diff --git a/.codex/config.toml b/.codex/config.toml index 416877cd0..9ed12c069 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,3 +1,27 @@ [mcp_servers.github-mcp-server] url = "https://api.githubcopilot.com/mcp/" bearer_token_env_var = "GITHUB_PERSONAL_ACCESS_TOKEN" +http_headers = { "X-MCP-Readonly" = "true" } + +[mcp_servers.zai-vision] +command = "zai-mcp-vision" +args = [] +env_vars = ["ZAI_API_KEY"] + +[mcp_servers.zai-web-search] +command = "zai-mcp-remote" +args = ["web-search"] +env_vars = ["ZAI_API_KEY"] + +[shell_environment_policy] +filters = { GITHUB_PERSONAL_ACCESS_TOKEN = "exclude", ZAI_API_KEY = "exclude", Z_AI_API_KEY = "exclude" } + +[mcp_servers.zai-web-reader] +command = "zai-mcp-remote" +args = ["web-reader"] +env_vars = ["ZAI_API_KEY"] + +[mcp_servers.zai-zread] +command = "zai-mcp-remote" +args = ["zread"] +env_vars = ["ZAI_API_KEY"] diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json index 3ac48fadf..1b7ee0999 100644 --- a/.config/dotnet-tools.json +++ b/.config/dotnet-tools.json @@ -3,28 +3,28 @@ "isRoot": true, "tools": { "csharpier": { - "version": "1.3.0", + "version": "1.4.1", "commands": [ "csharpier" ], "rollForward": false }, "coverlet.console": { - "version": "6.0.4", + "version": "10.1.1", "commands": [ "coverlet" ], "rollForward": false }, "dotnet-reportgenerator-globaltool": { - "version": "5.5.11", + "version": "5.6.1", "commands": [ "reportgenerator" ], "rollForward": false }, - "ilspycmd": { - "version": "9.1.0.7988", + "ilspycmd.any": { + "version": "11.2.0.10050", "commands": [ "ilspycmd" ], diff --git a/.cursorrules b/.cursorrules index ce4ee47a3..b3ee8a18f 100644 --- a/.cursorrules +++ b/.cursorrules @@ -1,36 +1 @@ -# Cursor Rules for NovaSharp - -**Complete documentation: [`.llm/context.md`](.llm/context.md)** - -## Quick Reference - -| Priority | Concern | Never Sacrifice For Lower Priority | -| -------- | ------- | ---------------------------------- | -| 1. CORRECTNESS | Lua Spec Compliance | Performance, memory, clarity | -| 2. SPEED | Runtime Performance | Memory, clarity | -| 3. MEMORY | Minimal Allocations | Clarity | -| 4. UNITY | Platform Compatibility | Clarity | -| 5. CLARITY | Maintainability | - | - -## Critical Rules - -1. **NEVER `git add` or `git commit`** - Leave version control to humans -2. **NEVER use absolute paths** - Relative paths from repo root only -3. **NEVER discard output** - No `>/dev/null` or `2>/dev/null` -4. **Lua Spec = Source of Truth** - Fix NovaSharp, never tests -5. **Multi-Version Testing** - All tests run on Lua 5.1-5.5 -6. **Mandatory post-work improvement gate** - After every large change or investigation, and before declaring it complete, follow [`.llm/skills/post-work-reflection/SKILL.md`](.llm/skills/post-work-reflection/SKILL.md). Fix discovered defects, capture reusable techniques or durable knowledge in the appropriate `.llm` artifact, and obtain an independent review when agents are available. - -## Build & Test - -```bash -./scripts/build/quick.sh # Build interpreter -./scripts/test/quick.sh # Run all tests -./scripts/test/quick.sh Floor # Filter by pattern -``` - -Do NOT use raw `dotnet build` or `dotnet test`. - -## Skills - -See [`.llm/skills/`](.llm/skills/) for task-specific guides. +Read and apply the shared NovaSharp engineering policy in [AGENTS.md](AGENTS.md). diff --git a/.devcontainer/.dockerignore b/.devcontainer/.dockerignore new file mode 100644 index 000000000..8e00860f1 --- /dev/null +++ b/.devcontainer/.dockerignore @@ -0,0 +1,3 @@ +# Host-generated runtime credentials must never enter the image build context. +.mcp.env +.mcp.env.* diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index d640ccbac..a279aa550 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -12,7 +12,7 @@ ARG TARGETARCH=amd64 # Pinned checksum for Microsoft package repository bootstrap package. ARG MS_PACKAGES_DEB_SHA256=8434dcb8c346dc95fbd63dbece056c343704590b58b6a5c323d39acf52bf0b48 # Keep this in sync with global.json. scripts/lint/check-tooling-consistency.py enforces it. -ARG DOTNET_SDK_MAJOR_MINOR=9.0 +ARG DOTNET_SDK_MAJOR_MINOR=10.0 # Pinned Lua source version and checksum. ARG LUA55_VERSION=5.5.0 ARG LUA55_SHA256=57ccc32bbbd005cab75bcc52444052535af691789dba2b9016d5c50640d68b3d @@ -177,6 +177,11 @@ RUN git config --system init.defaultBranch main \ && git config --system core.autocrlf input \ && git config --system core.eol lf +# Seed the NuGet cache mount point so Docker initializes new named volumes with +# vscode ownership instead of root:root. Existing volumes are repaired by +# ensure-nuget-cache.sh before any lifecycle command invokes dotnet. +RUN install -d -m 0755 -o vscode -g vscode /home/vscode/.nuget + # Initialize zoxide for bash (add to bashrc for interactive shells). RUN echo 'eval "$(zoxide init bash)"' >> /etc/bash.bashrc @@ -219,4 +224,9 @@ RUN echo "=== Environment Verification ===" \ && actionlint -version && yamllint --version \ && echo "=== Verification Complete ===" +COPY --chmod=0755 zai-mcp-vision.sh /usr/local/bin/zai-mcp-vision +COPY --chmod=0755 zai-mcp-remote.sh /usr/local/bin/zai-mcp-remote +# Installed Claude launchers always use container-owned files, including on NTFS mounts. +COPY mcp_credentials.py /usr/local/bin/read-claude-mcp-key.py + USER vscode diff --git a/.devcontainer/README.md b/.devcontainer/README.md index 2a7ea8276..9752e9c91 100644 --- a/.devcontainer/README.md +++ b/.devcontainer/README.md @@ -1,5 +1,21 @@ # NovaSharp devcontainer maintenance +Host initialization requires Bash. From PowerShell in the checkout, start the +container and open an interactive login shell with: + +```powershell +npx --yes --package=@devcontainers/cli -- devcontainer up --workspace-folder "$PWD" +npx --yes --package=@devcontainers/cli -- devcontainer exec --workspace-folder "$PWD" zsh -il +``` + +Run the second command after the first succeeds. The host hook runs relative to +the workspace, so either WSL Bash or Git Bash can find it on a Windows drive. +Docker receives its env-file path in the host's native format. + +When cloning with Git for Windows, enable symlink support and use +`git clone -c core.symlinks=true` with the repository URL. This preserves the +two skill-directory links checked by the project's pre-commit hook. + The devcontainer installs the current npm `latest` dist-tag for these coding tools: @@ -7,6 +23,9 @@ tools: - `opencode-ai` - `@openai/codex` - `@anthropic-ai/claude-code` +- `@github/copilot` +- `mcp-remote` +- `@z_ai/mcp-server` The image build installs the current Node.js LTS through the base image's NVM setup, then installs the tools as the `vscode` user. Container creation and every @@ -31,12 +50,11 @@ Tool refreshes use a dedicated cache under the user's cache directory. A successful update clears downloaded CLI tarballs without deleting the cache used by ordinary project-level npm commands. -Image builds and first-create refreshes fail if npm cannot provide the requested -latest releases. Restart checks are deliberately bounded: if npm is temporarily -unavailable but all four image-baked tools are intact, startup emits a warning -and continues with those versions. This keeps an existing development container -usable during a registry or network outage without silently treating the tools -as current. +Image builds require npm to supply the requested latest releases. Container +creation and subsequent starts use bounded retries. If the registry is +unreachable or a published tarball cannot be installed, startup warns and +validates all seven installed tools before continuing. A missing or broken +installation still fails startup. Run the refresh manually with: @@ -51,10 +69,12 @@ Anthropic backends. The setup hook also installs opt-in `codex-zai` and `claude-zai` launchers. Switching is per process; no command rewrites the native configuration. -Provide the Z.ai credential through a private environment or secret store: +To use the optional integrations, add the credentials you need before +rebuilding. A checkout can start without `.env.local`: ```bash -export ZAI_API_KEY="..." +[ -e .env.local ] || cp .env.local.example .env.local +# Add or update ZAI_API_KEY and GITHUB_PERSONAL_ACCESS_TOKEN. codex-zai claude-zai ``` @@ -70,9 +90,18 @@ Optional per-process overrides are `CODEX_ZAI_MODEL`, `ZAI_API_TIMEOUT_MS` (default: five minutes), and `CLAUDE_ZAI_CONFIG_DIR`. Claude's `haiku`, `sonnet`, and `opus` aliases map to Z.ai's recommended GLM models; override them with `CLAUDE_ZAI_HAIKU_MODEL`, -`CLAUDE_ZAI_SONNET_MODEL`, and `CLAUDE_ZAI_OPUS_MODEL`. Harness shell and MCP -subprocesses do not inherit the model-server credential. Reinstall the launchers -manually after moving the checkout: +`CLAUDE_ZAI_SONNET_MODEL`, and `CLAUDE_ZAI_OPUS_MODEL`. Ordinary shell and +unrelated MCP children do not inherit the model-server credential. The trusted +Z.ai MCP servers receive only their required credential. For Claude, their +wrappers use `CLAUDE_PROJECT_DIR` to select a private, workspace-specific copy +of the Z.ai key in the container user's home directory. Codex explicitly +forwards only `ZAI_API_KEY` through its stdio MCP allowlist. +The wrappers scrub the canonical key and unrelated tokens before starting the +MCP process. +After moving a managed checkout, recreate its devcontainer from the new +workspace path. Creation stages the credential for that path and reinstalls +the launchers. For a standalone POSIX checkout, reinstall the launchers from +the new repository root: ```bash bash .devcontainer/ai-backends.sh install @@ -85,14 +114,15 @@ to create a user and mount namespace even with AppArmor profiles reject. In an existing devcontainer, `claude-zai` therefore defaults `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=0` and relies on the outer container as the process boundary. Controlled Bash and stdio MCP probes verified that -Claude still removes the model-server credential from those children. +Claude still removes the model-server credential from ordinary shell children +while deliberately authenticating the selected Z.ai MCP servers. Outside a container, the launcher retains the stronger scrubber by default. Set -`CLAUDE_ZAI_SUBPROCESS_ENV_SCRUB=1` to request it explicitly; the launcher runs a -real bubblewrap preflight and exits with actionable guidance before starting a -model session when the runtime cannot support it. Do not add `SYS_ADMIN`, run a -privileged container, or globally weaken host AppArmor merely to make this -optional second sandbox work. +`CLAUDE_ZAI_SUBPROCESS_ENV_SCRUB=1` to request it explicitly; the launcher +runs a real bubblewrap preflight and exits with actionable guidance before +starting a model session when the runtime cannot support it. Do not add +`SYS_ADMIN`, run a privileged container, or globally weaken host AppArmor merely +to make this optional second sandbox work. ## Agent network reliability @@ -205,31 +235,107 @@ run authenticated streaming and read-only tool workloads in both clients. Record attempt counts, latency, and failure class without recording credentials or response bodies. -## GitHub MCP - -GitHub's hosted MCP server is configured for every agent harness used by this -repository: - -- `.vscode/mcp.json` configures VS Code and Copilot Chat with GitHub OAuth. +## Project MCP servers + +The devcontainer exposes GitHub's hosted MCP server plus every MCP currently +listed by the Z.ai Coding Plan: Vision Understanding, Web Search Prime, Web +Reader, and Zread. The Vision package is installed in the image and refreshed +with the other npm agent tools; the three remote Z.ai servers use their official +HTTPS endpoints. + +Claude Code 2.1.260 cannot consume the SSE-framed MCP initialization response +currently returned by those three endpoints. Codex 0.153.2 completes the +response but loses the transport while sending the subsequent `initialized` +notification. Direct HTTP probes and OpenCode succeed from the same container, +so `claude-zai` and Codex use the installed `mcp-remote` stdio bridge only for +those three servers. Vision remains direct stdio and GitHub remains native HTTP. +Re-test native HTTP after either client upgrades before removing its bridge. + +In Claude Code 2.1.260, `claude-zai mcp list` ignores this per-session strict +catalog and health-checks `.mcp.json`, so it can falsely report the three native +HTTP failures. The authoritative check is the `system/init` event from an actual +`claude-zai --print --output-format stream-json --verbose` session: its +`mcp_servers` array must show all five entries as `connected`. + +Keep model access separate from MCP health. In the 2026-09-04 live probe, all +five MCPs connected before Z.ai's model API returned HTTP 429, code `1310`, for +an exhausted weekly/monthly subscription allowance. Claude retries that response +and can look hung. A rebuild, key rotation, or MCP change cannot repair quota; +interrupt the retries, check the Z.ai plan's usage/reset time, and retry after +capacity is available. + +The same catalog is configured for every agent frontend used by this repository: + +- `.vscode/mcp.json` configures VS Code and Copilot Chat. - `.codex/config.toml` configures the Codex CLI and Codex extension. - `.mcp.json` configures Claude Code, Copilot CLI, and Nanocoder. - `opencode.json` configures OpenCode. -No credential is stored in the repository or image. Before opening the -devcontainer, export a least-privilege GitHub token on the host so VS Code can -forward it to the terminal harnesses: +Nanocoder receives the catalog's absolute path, so launching it below the +repository root still discovers every server. + +No credential is committed or stored in an image layer. Before container +creation, the host preflight reads only the two allowlisted values from the +ignored `.env.local` and atomically publishes an ignored Docker env file. +The preflight restricts access to both files with an owner-only Windows ACL on +Windows drives and mode `0600` on POSIX filesystems. Each credential is optional. +A failed preflight stops the launch and preserves the last published contents. +Docker captures the environment at creation. After adding, changing, or removing +a credential, recreate the container with **Dev Containers: Rebuild Container** +or `devcontainer up --workspace-folder . --remove-existing-container`. + +```bash +[ -e .env.local ] || cp .env.local.example .env.local +# Add or update GITHUB_PERSONAL_ACCESS_TOKEN and ZAI_API_KEY, then: +code . +# Select “Dev Containers: Rebuild Container” if one already exists. +``` + +Use a least-privilege GitHub token. Every project definition sends +`X-MCP-Readonly: true` by default, so unattended/YOLO sessions cannot invoke +GitHub write tools. Remove that header only when intentional GitHub mutations +are required; the token's permissions then define the available writes. The two +keys enter the trusted container process environment and remain readable from +the mounted workspace, so do not run untrusted repository code or agents. +The isolated `claude-zai` launcher pre-approves only the five audited names; +native Claude Code still asks before trusting project MCP definitions. Codex +loads them only after the repository itself is trusted. The project entry +replaces Copilot CLI's built-in read-only GitHub definition instead of creating +a duplicate. + +Sources: [Z.ai Coding Plan MCP overview](https://docs.z.ai/devpack/overview), +[Claude Code MCP configuration](https://code.claude.com/docs/en/mcp), +[Codex MCP configuration](https://developers.openai.com/codex/mcp/), +[Claude Code native SSE failure](https://github.com/anthropics/claude-code/issues/58759), +[`mcp-remote`](https://github.com/geelen/mcp-remote), +[GitHub MCP server](https://github.com/github/github-mcp-server), and +[Dev Container environment files](https://code.visualstudio.com/remote/advancedcontainers/environment-variables). + +## NuGet cache volume ownership + +`novasharp-nuget-cache` is mounted at `/home/vscode/.nuget`. Docker only +copies ownership from the image when it initializes an empty named volume. If +the mount point is absent from the image, Docker creates the volume as +`root:root`, and the non-root `vscode` user cannot create +`~/.nuget/NuGet/NuGet.Config`. NuGet reports that failure as +`Failed to read NuGet.Config due to unauthorized access`. + +The image seeds `/home/vscode/.nuget` with `vscode` ownership so new volumes +start correct. `ensure-nuget-cache.sh` then runs before every lifecycle step +that invokes `dotnet`; it repairs an existing volume whose owner no longer +matches the current runtime UID, including after `updateRemoteUserUID` or when +the volume predates the image seed. The repair uses only the current UID/GID +and is skipped when the cache is already writable. + +If passwordless `sudo` is unavailable, or the volume is mounted read-only, stop +the container and recreate the disposable cache volume, then rebuild so the +image seed applies: ```bash -export GITHUB_PERSONAL_ACCESS_TOKEN="$(gh auth token)" +docker volume rm novasharp-nuget-cache ``` -If the container is already open, run the same command in its terminal before -starting Codex, Claude Code, Copilot CLI, OpenCode, or Nanocoder. In VS Code, -open `.vscode/mcp.json`, select **Start**, and then select **Auth** to complete -GitHub OAuth. Copilot CLI also includes a read-only GitHub MCP server by default; -the project entry is deliberately named `github-mcp-server` so the authenticated -project configuration replaces that built-in definition instead of duplicating -it. +`docker volume rm` fails while a container is still using the volume. ## Generated artifact retention diff --git a/.devcontainer/ai-backends.sh b/.devcontainer/ai-backends.sh index 6e6372263..679a717ca 100755 --- a/.devcontainer/ai-backends.sh +++ b/.devcontainer/ai-backends.sh @@ -3,9 +3,16 @@ set -euo pipefail +# Prevent an imported lowercase variable from retaining its export attribute +# when a function-local variable temporarily holds the real credential. +export -n zai_key 2>/dev/null || true + readonly PROFILE_NAME="devcontainer-zai" readonly ZAI_RESPONSES_URL="https://api.z.ai/api/v1" readonly ZAI_ANTHROPIC_URL="https://api.z.ai/api/anthropic" +AI_BACKENDS_SOURCE_DIR="$(dirname "$(realpath "${BASH_SOURCE[0]}")")" +readonly AI_BACKENDS_SOURCE_DIR +readonly CLAUDE_ZAI_MCP_CONFIG="${AI_BACKENDS_SOURCE_DIR}/claude-zai.mcp.json" die() { printf '[ai-backends] ERROR: %s\n' "$*" >&2 @@ -162,7 +169,9 @@ launch_codex_zai() { local catalog_file codex_home model reasoning_effort zai_key command -v codex >/dev/null 2>&1 || die "codex is not installed." zai_key="$(resolve_zai_key)" + export -n zai_key 2>/dev/null || true export ZAI_API_KEY="${zai_key}" + zai_key="" codex_home="${CODEX_HOME:-${HOME}/.codex}" catalog_file="${codex_home}/${PROFILE_NAME}-models.json" @@ -186,10 +195,11 @@ launch_codex_zai() { } launch_claude_zai() { - local config_dir container_mode subprocess_scrub timeout_ms zai_key + local claude_settings config_dir container_mode subprocess_scrub timeout_ms zai_key local -a claude_args=() command -v claude >/dev/null 2>&1 || die "claude is not installed." zai_key="$(resolve_zai_key)" + export -n zai_key 2>/dev/null || true config_dir="${CLAUDE_ZAI_CONFIG_DIR:-${HOME}/.claude-zai}" timeout_ms="${ZAI_API_TIMEOUT_MS:-300000}" case "${timeout_ms}" in @@ -198,6 +208,9 @@ launch_claude_zai() { esac mkdir -p "${config_dir}" chmod 700 "${config_dir}" + [ -f "${CLAUDE_ZAI_MCP_CONFIG}" ] \ + || die "Claude Z.ai MCP config is missing: ${CLAUDE_ZAI_MCP_CONFIG}" + claude_args+=(--mcp-config "${CLAUDE_ZAI_MCP_CONFIG}" --strict-mcp-config) container_mode="${AI_BACKENDS_CONTAINER_MODE:-auto}" case "${container_mode}" in @@ -237,14 +250,17 @@ launch_claude_zai() { || die "Claude subprocess isolation cannot create its nested sandbox. Set CLAUDE_ZAI_SUBPROCESS_ENV_SCRUB=0 to rely on the outer devcontainer boundary." fi + claude_settings='{"enabledMcpjsonServers":["github-mcp-server","zai-vision","zai-web-search","zai-web-reader","zai-zread"]}' if [ "${container_mode}" = "yes" ]; then # The outer devcontainer is the primary isolation boundary. Anthropic's # weaker mode still needs blocked namespaces, so keep the inner sandbox # off unless the caller explicitly opts into the scrubber and preflight. - claude_args+=(--settings '{"sandbox":{"enabled":false,"enableWeakerNestedSandbox":true}}') + claude_settings='{"enabledMcpjsonServers":["github-mcp-server","zai-vision","zai-web-search","zai-web-reader","zai-zread"],"sandbox":{"enabled":false,"enableWeakerNestedSandbox":true}}' fi + claude_args+=(--settings "${claude_settings}") unset ANTHROPIC_API_KEY \ + CLAUDE_CODE_OAUTH_TOKEN \ ANTHROPIC_MODEL \ ANTHROPIC_DEFAULT_MODEL \ ANTHROPIC_DEFAULT_HAIKU_MODEL \ @@ -259,7 +275,8 @@ launch_claude_zai() { CLAUDE_CODE_USE_MANTLE \ CLAUDE_CODE_USE_GATEWAY export ANTHROPIC_AUTH_TOKEN="${zai_key}" - unset ZAI_API_KEY Z_AI_API_KEY + zai_key="" + unset ZAI_API_KEY Z_AI_API_KEY ZAI_MCP_API_KEY export ANTHROPIC_BASE_URL="${ZAI_ANTHROPIC_URL}" export ANTHROPIC_DEFAULT_HAIKU_MODEL="${CLAUDE_ZAI_HAIKU_MODEL:-glm-5.3-flash[1m]}" export ANTHROPIC_DEFAULT_SONNET_MODEL="${CLAUDE_ZAI_SONNET_MODEL:-glm-5.3[1m]}" diff --git a/.devcontainer/check-mcp-env.sh b/.devcontainer/check-mcp-env.sh new file mode 100755 index 000000000..e24749d88 --- /dev/null +++ b/.devcontainer/check-mcp-env.sh @@ -0,0 +1,128 @@ +#!/usr/bin/env bash +# Filter and validate host-side credentials before Docker consumes .mcp.env. + +set +x +set -euo pipefail + +workspace_dir="${1:-$(pwd -P)}" +env_file="${workspace_dir}/.env.local" +generated_file="${workspace_dir}/.devcontainer/.mcp.env" +temporary_file="" + +fail() { + printf '[devcontainer:mcp] ERROR: %s\n' "$*" >&2 + exit 1 +} + +cleanup_temporary_file() { + if [ -n "${temporary_file}" ] && [ -f "${temporary_file}" ]; then + rm -f -- "${temporary_file}" + fi +} + +protect_posix_file() { + local path="$1" stat_option mode_format link_format + case "${OSTYPE}" in + darwin*|*bsd*) stat_option=-f; mode_format=%Lp; link_format=%l ;; + *) stat_option=-c; mode_format=%a; link_format=%h ;; + esac + [ -O "${path}" ] || fail "Credential file must belong to the current host user." + [ "$(stat "${stat_option}" "${link_format}" "${path}")" = 1 ] \ + || fail "Refusing to change a multiply-linked credential file." + chmod 600 "${path}" || fail "Could not restrict credential file permissions." + [ "$(stat "${stat_option}" "${mode_format}" "${path}")" = 600 ] \ + || fail "Credential filesystem did not enforce mode 0600." +} + +[ -d "${workspace_dir}" ] || fail "Workspace directory does not exist." +[ -d "${workspace_dir}/.devcontainer" ] && [ ! -L "${workspace_dir}/.devcontainer" ] \ + || fail ".devcontainer must be a real directory inside the workspace." +trap cleanup_temporary_file EXIT +[ ! -L "${generated_file}" ] \ + || fail "Refusing to replace a symlinked .devcontainer/.mcp.env." +if [ -e "${generated_file}" ] && [ ! -f "${generated_file}" ]; then + fail ".devcontainer/.mcp.env must be a regular file." +fi +# Keep the previous file available to other launches until the replacement is +# ready. A failed preflight stops the current launch without changing that file. +[ ! -L "${env_file}" ] \ + || fail "Refusing to read a symlinked .env.local." + +# A WSL distro can have both Windows and Linux filesystems. Select the +# permission mechanism by the workspace mount, not simply by the host OS. +windows_path_tool="" +case "${OSTYPE}" in + msys*|cygwin*) windows_path_tool=cygpath ;; + linux*) + if command -v wslpath >/dev/null; then + workspace_fs="$(findmnt -n -o FSTYPE --target "${workspace_dir}")" \ + || fail "Could not identify the WSL workspace filesystem." + case "${workspace_fs}" in + drvfs|9p) windows_path_tool=wslpath ;; + esac + fi + ;; +esac +if [ -n "${windows_path_tool}" ]; then + acl_script="$(dirname "${BASH_SOURCE[0]}")/mcp-env-windows.ps1" + windows_helper=(powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass + -File "$("${windows_path_tool}" -aw "${acl_script}")" -Workspace "$("${windows_path_tool}" -aw "${workspace_dir}")") + MSYS2_ARG_CONV_EXCL='*' "${windows_helper[@]}" -Action Protect \ + || fail "Could not protect Windows MCP credential paths." +fi + +unset github_token zai_token value +github_token="" +zai_token="" +if [ -e "${env_file}" ]; then + [ -f "${env_file}" ] || fail ".env.local must be a regular file." + if [ -z "${windows_path_tool}" ]; then + protect_posix_file "${env_file}" + fi + + for key in GITHUB_PERSONAL_ACCESS_TOKEN ZAI_API_KEY; do + definition_count="$({ grep -Ec "^${key}=" "${env_file}" || [ "$?" = "1" ]; })" + case "${definition_count}" in + 0) continue ;; + 1) ;; + *) fail "${key} must appear at most once in .env.local." ;; + esac + value="$(sed -n "s/^${key}=//p" "${env_file}")" + value="${value%$'\r'}" + case "${value}" in + *[[:space:]\"\']*) + fail "${key} must use Docker env-file syntax without quotes or whitespace." + ;; + esac + case "${key}" in + GITHUB_PERSONAL_ACCESS_TOKEN) github_token="${value}" ;; + ZAI_API_KEY) zai_token="${value}" ;; + esac + done +fi + +write_filtered_env() { + if [ -n "${github_token}" ]; then + printf 'GITHUB_PERSONAL_ACCESS_TOKEN=%s\n' "${github_token}" + fi + if [ -n "${zai_token}" ]; then + printf 'ZAI_API_KEY=%s\n' "${zai_token}" + fi +} + +if [ -n "${windows_path_tool}" ]; then + # An EOF alone can mean the producer was interrupted partway through. + { write_filtered_env && printf '\0'; } | MSYS2_ARG_CONV_EXCL='*' "${windows_helper[@]}" -Action Publish \ + || fail "Could not publish the private Windows MCP environment file." +else + umask 077 + temporary_file="$(mktemp "${generated_file}.XXXXXX")" \ + || fail "Could not create the filtered MCP environment file." + protect_posix_file "${temporary_file}" + write_filtered_env >"${temporary_file}" + mv -f "${temporary_file}" "${generated_file}" + [ ! -e "${temporary_file}" ] && [ -f "${generated_file}" ] \ + || fail "Atomic replacement did not create the filtered MCP environment file." +fi +trap - EXIT +printf '[devcontainer:mcp] Filtered MCP environment generated.\n' diff --git a/.devcontainer/claude-zai.mcp.json b/.devcontainer/claude-zai.mcp.json new file mode 100644 index 000000000..0cf6ea693 --- /dev/null +++ b/.devcontainer/claude-zai.mcp.json @@ -0,0 +1,32 @@ +{ + "mcpServers": { + "github-mcp-server": { + "type": "http", + "url": "https://api.githubcopilot.com/mcp/", + "headers": { + "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}", + "X-MCP-Readonly": "true" + } + }, + "zai-vision": { + "type": "stdio", + "command": "zai-mcp-vision", + "args": [] + }, + "zai-web-search": { + "type": "stdio", + "command": "zai-mcp-remote", + "args": ["web-search"] + }, + "zai-web-reader": { + "type": "stdio", + "command": "zai-mcp-remote", + "args": ["web-reader"] + }, + "zai-zread": { + "type": "stdio", + "command": "zai-mcp-remote", + "args": ["zread"] + } + } +} diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 9cdb1c612..90232051a 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -11,16 +11,20 @@ "--no-cache" ] }, - // Forward a host-provided PAT to terminal harnesses without storing it in the image. - // VS Code authenticates its GitHub MCP connection separately through OAuth. + // Bash inherits the workspace as its working directory, including under WSL. + "initializeCommand": ["bash", ".devcontainer/check-mcp-env.sh"], + // Inject credentials only at container runtime; they never enter image layers. + "runArgs": ["--env-file", "${localWorkspaceFolder}/.devcontainer/.mcp.env"], + // Nanocoder otherwise resolves .mcp.json only from the launch directory. "remoteEnv": { - "GITHUB_PERSONAL_ACCESS_TOKEN": "${localEnv:GITHUB_PERSONAL_ACCESS_TOKEN}" + "NANOCODER_MCPSERVERS_FILE": "${containerWorkspaceFolder}/.mcp.json" }, // Block attach until onCreate finishes so extension activation sees a restored solution. "waitFor": "onCreateCommand", // Mount configuration for better performance "mounts": [ - // Cache NuGet packages in a named volume for persistence across rebuilds + // Cache NuGet packages in a named volume. The Dockerfile seeds the mount + // point with vscode ownership; ensure-nuget-cache.sh repairs old volumes. "source=novasharp-nuget-cache,target=/home/vscode/.nuget,type=volume" ], // VS Code customizations diff --git a/.devcontainer/ensure-nuget-cache.sh b/.devcontainer/ensure-nuget-cache.sh new file mode 100755 index 000000000..d1d971827 --- /dev/null +++ b/.devcontainer/ensure-nuget-cache.sh @@ -0,0 +1,105 @@ +#!/usr/bin/env bash +# Ensure the persistent NuGet cache is writable by the current lifecycle user. +# +# Docker initializes an empty named volume from the image only when the mount +# point exists. Volumes created before the image seeded /home/vscode/.nuget, or +# volumes created before a UID remap, can therefore be root-owned and make +# `dotnet restore` fail with "Failed to read NuGet.Config due to unauthorized +# access" before any lifecycle script can run. + +set -euo pipefail + +nuget_dir="${HOME:?HOME must be set}/.nuget" + +case "${nuget_dir}" in + /*) ;; + *) + printf '[devcontainer:nuget] ERROR: refusing to repair a relative path: %s\n' "${nuget_dir}" >&2 + exit 1 + ;; +esac + +if [ -L "${nuget_dir}" ]; then + printf '[devcontainer:nuget] ERROR: %s must not be a symbolic link.\n' "${nuget_dir}" >&2 + exit 1 +fi + +config_file="${nuget_dir}/NuGet/NuGet.Config" + +cache_is_writable() { + [ -d "${nuget_dir}" ] || return 1 + [ -w "${nuget_dir}" ] && [ -x "${nuget_dir}" ] || return 1 + + local child + for child in NuGet packages; do + if [ -e "${nuget_dir}/${child}" ]; then + [ -d "${nuget_dir}/${child}" ] || return 1 + [ -w "${nuget_dir}/${child}" ] && [ -x "${nuget_dir}/${child}" ] || return 1 + fi + done + + if [ -e "${config_file}" ] && { [ ! -f "${config_file}" ] || [ ! -r "${config_file}" ]; }; then + return 1 + fi +} + +recovery_message() { + printf '[devcontainer:nuget] ERROR: %s is not writable.\n' "${nuget_dir}" >&2 + printf '[devcontainer:nuget] Stop the container, recreate the disposable cache volume, and rebuild:\n' >&2 + printf '[devcontainer:nuget] docker volume rm novasharp-nuget-cache\n' >&2 + printf '[devcontainer:nuget] A read-only mount cannot be repaired in place.\n' >&2 +} + +if [ -e "${config_file}" ] && [ ! -f "${config_file}" ]; then + printf '[devcontainer:nuget] ERROR: NuGet.Config must be a regular file: %s\n' "${config_file}" >&2 + recovery_message + exit 1 +fi + +if cache_is_writable; then + exit 0 +fi + +# A missing cache directory under a writable HOME does not need privilege. +if [ ! -d "${nuget_dir}" ]; then + mkdir -p "${nuget_dir}" 2>/dev/null || true + if cache_is_writable; then + exit 0 + fi +fi + +if [ "$(id -u)" != "0" ]; then + if ! command -v sudo >/dev/null 2>&1; then + printf '[devcontainer:nuget] ERROR: %s is not writable and sudo is unavailable.\n' "${nuget_dir}" >&2 + recovery_message + exit 1 + fi + if ! sudo -n true >/dev/null 2>&1; then + printf '[devcontainer:nuget] ERROR: passwordless sudo is unavailable.\n' >&2 + recovery_message + exit 1 + fi +fi + +elevate() { + if [ "$(id -u)" = "0" ]; then + "$@" + else + sudo -n "$@" + fi +} + +if ! elevate mkdir -p "${nuget_dir}" \ + || ! elevate chown -R "$(id -u):$(id -g)" "${nuget_dir}" \ + || ! elevate chmod -R u+rwX "${nuget_dir}"; then + recovery_message + exit 1 +fi + +if ! cache_is_writable; then + recovery_message + exit 1 +fi + +printf '[devcontainer:nuget] Repaired ownership of %s for uid %s.\n' \ + "${nuget_dir}" "$(id -u)" diff --git a/.devcontainer/install-npm-tools.sh b/.devcontainer/install-npm-tools.sh index 4dee8c76b..7a0d8db28 100755 --- a/.devcontainer/install-npm-tools.sh +++ b/.devcontainer/install-npm-tools.sh @@ -4,18 +4,23 @@ set -euo pipefail offline_ok=0 +install_attempts="${NOVA_NPM_INSTALL_ATTEMPTS:-5}" case "${1:-}" in "") ;; - --offline-ok) offline_ok=1 ;; + --offline-ok) + offline_ok=1 + install_attempts="${NOVA_NPM_START_ATTEMPTS:-${NOVA_NPM_INSTALL_ATTEMPTS:-2}}" + export NPM_CONFIG_FETCH_RETRIES="${NOVA_NPM_START_FETCH_RETRIES:-1}" + export NPM_CONFIG_FETCH_TIMEOUT="${NOVA_NPM_START_FETCH_TIMEOUT_MS:-10000}" + ;; *) echo "Usage: $0 [--offline-ok]" >&2 exit 2 ;; esac -install_attempts="${NOVA_NPM_INSTALL_ATTEMPTS:-5}" if ! [[ "${install_attempts}" =~ ^[1-9][0-9]*$ ]]; then - echo "❌ NOVA_NPM_INSTALL_ATTEMPTS must be a positive integer." >&2 + echo "❌ npm install attempts must be a positive integer." >&2 exit 2 fi @@ -24,12 +29,18 @@ readonly NPM_TOOL_PACKAGES=( "opencode-ai@latest" "@openai/codex@latest" "@anthropic-ai/claude-code@latest" + "@github/copilot@latest" + "mcp-remote@latest" + "@z_ai/mcp-server@latest" ) readonly NPM_TOOL_COMMANDS=( "nanocoder" "opencode" "codex" "claude" + "copilot" + "mcp-remote" + "zai-mcp-server" ) run_with_retries() { @@ -130,7 +141,7 @@ echo " Node.js: $(node --version); npm: $(npm --version); prefix: ${npm_prefix installed_tree="$(read_installed_tree)" packages_to_install=() -registry_unverified=0 +using_fallback=0 clean_tool_cache=0 for package_index in "${!NPM_TOOL_PACKAGES[@]}"; do package_spec="${NPM_TOOL_PACKAGES[package_index]}" @@ -148,7 +159,7 @@ for package_index in "${!NPM_TOOL_PACKAGES[@]}"; do if ! latest_version="$(run_with_retries "${install_attempts}" npm view "${package_spec}" version)"; then if [ "${offline_ok}" = "1" ] && [ -n "${installed_version}" ] && [ -x "${expected_command}" ]; then echo "⚠️ npm registry unavailable; keeping ${package_name}@${installed_version}." >&2 - registry_unverified=1 + using_fallback=1 continue fi echo "❌ Unable to resolve ${package_spec} from npm." >&2 @@ -195,9 +206,10 @@ if [ "${#packages_to_install[@]}" -gt 0 ]; then exit "${install_exit_code}" fi done - echo "⚠️ npm update failed; continuing with the intact installed tool versions." >&2 + using_fallback=1 + echo "⚠️ npm update failed; validating the installed tool versions before continuing." >&2 fi -elif [ "${registry_unverified}" = "1" ]; then +elif [ "${using_fallback}" = "1" ]; then echo " No npm changes applied; latest status could not be verified." else echo " All npm coding tools are current." @@ -214,10 +226,30 @@ for package_index in "${!NPM_TOOL_COMMANDS[@]}"; do echo "❌ Expected ${command_name} from ${expected_command}, but PATH resolved ${resolved_command:-nothing}." >&2 exit 1 fi - if ! tool_version="$(timeout 30 "${resolved_command}" --version 2>&1)"; then - echo "❌ ${command_name} is installed but failed its version check:" >&2 - echo "${tool_version}" >&2 - exit 1 + if [ "${command_name}" = "zai-mcp-server" ]; then + # The stdio server has no version command. After a failed refresh, + # launch it with EOF to catch a broken payload without any real keys. + if [ "${using_fallback}" = "1" ]; then + if ! probe_output="$( + probe_home="$(mktemp -d)" || exit 1 + trap 'rm -rf -- "${probe_home}"' EXIT + env -i PATH="${PATH}" HOME="${probe_home}" Z_AI_API_KEY=devcontainer-health-check Z_AI_MODE=ZAI \ + timeout 30 "${resolved_command}" &1 + )"; then + printf '❌ %s failed its stdio startup check:\n%s\n' "${command_name}" "${probe_output}" >&2 + exit 1 + fi + fi + tool_version="$( + node -e 'process.stdout.write(require(process.argv[1]).version)' \ + "${npm_prefix}/lib/node_modules/@z_ai/mcp-server/package.json" + )" + else + if ! tool_version="$(timeout 30 "${resolved_command}" --version 2>&1)"; then + echo "❌ ${command_name} is installed but failed its version check:" >&2 + echo "${tool_version}" >&2 + exit 1 + fi fi tool_versions+=("${tool_version}") done @@ -226,6 +258,9 @@ printf " %-11s %s\n" "nanocoder:" "${tool_versions[0]}" printf " %-11s %s\n" "opencode:" "${tool_versions[1]}" printf " %-11s %s\n" "codex:" "${tool_versions[2]}" printf " %-11s %s\n" "claude:" "${tool_versions[3]}" +printf " %-11s %s\n" "copilot:" "${tool_versions[4]}" +printf " %-11s %s\n" "mcp-remote:" "${tool_versions[5]}" +printf " %-11s %s\n" "zai-mcp:" "${tool_versions[6]}" if [ "${clean_tool_cache}" = "1" ] || [ "${NOVA_NPM_CLEAN_CACHE:-0}" = "1" ]; then npm cache clean --force diff --git a/.devcontainer/mcp-env-windows.ps1 b/.devcontainer/mcp-env-windows.ps1 new file mode 100644 index 000000000..739101ab6 --- /dev/null +++ b/.devcontainer/mcp-env-windows.ps1 @@ -0,0 +1,123 @@ +# Windows PowerShell 5.1 host helper. Bash supplies only the validated Docker +# env-file bytes and a NUL completion marker on stdin. NTFS security is applied +# before any bytes are written. +param( + [Parameter(Mandatory)][string] $Workspace, + [Parameter(Mandatory)][ValidateSet('Protect', 'Publish')][string] $Action +) +$ErrorActionPreference = 'Stop' +$identity = [Security.Principal.WindowsIdentity]::GetCurrent() +$userSid = $identity.User +function New-PrivateAcl([bool] $SetOwner) { + $acl = [Security.AccessControl.FileSecurity]::new() + if ($SetOwner) { $acl.SetOwner($userSid) } + $acl.SetAccessRuleProtection($true, $false) + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + $userSid, 'FullControl', 'Allow')) + return $acl +} + +function Test-RegularPath([string] $Path, [bool] $Directory) { + try { + $attributes = [IO.File]::GetAttributes($Path) + } catch [IO.FileNotFoundException] { + return $false + } + if (($attributes -band [IO.FileAttributes]::ReparsePoint) -or + ([bool]($attributes -band [IO.FileAttributes]::Directory) -ne $Directory)) { + throw "Refusing redirected or unexpected MCP credential path: $Path" + } + if (-not $Directory -and (Get-Item -LiteralPath $Path -Force).LinkType -eq 'HardLink') { + throw "Refusing a multiply-linked credential file: $Path" + } + return $true +} + +function Assert-PrivateAcl([Security.AccessControl.FileSecurity] $Acl) { + $rules = $Acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) + if ($Acl.GetOwner([Security.Principal.SecurityIdentifier]) -ne $userSid -or + -not $Acl.AreAccessRulesProtected -or $rules.Count -ne 1 -or + $rules[0].IdentityReference -ne $userSid -or + $rules[0].AccessControlType -ne 'Allow' -or $rules[0].FileSystemRights -ne 'FullControl') { + throw 'NTFS did not enforce a private, current-user-only credential ACL.' + } +} + +function Protect-ExistingFile([string] $Path) { + if (Test-RegularPath $Path $false) { + $owner = [IO.File]::GetAccessControl($Path).GetOwner([Security.Principal.SecurityIdentifier]) + if ($owner -ne $userSid -and $owner -ne $identity.Owner) { + throw "Credential file must belong to the current host user: $Path" + } + [IO.File]::SetAccessControl($Path, (New-PrivateAcl ($owner -ne $userSid))) + Assert-PrivateAcl ([IO.File]::GetAccessControl($Path)) + } +} + +# Windows link/ACL queries can briefly deny rename sharing. Keep these queries +# and the rename mutually exclusive for simultaneous preflights of this checkout. +function Invoke-WithCredentialLock([scriptblock] $Operation) { + $hasher = [Security.Cryptography.SHA256]::Create() + try { + $pathBytes = [Text.Encoding]::UTF8.GetBytes([IO.Path]::GetFullPath($Workspace).TrimEnd('\').ToUpperInvariant()) + $name = 'Local\NovaSharp.McpEnv.' + [BitConverter]::ToString($hasher.ComputeHash($pathBytes)) + } finally { + $hasher.Dispose() + } + $mutex = [Threading.Mutex]::new($false, $name) + try { + try { $null = $mutex.WaitOne() } catch [Threading.AbandonedMutexException] { + # The previous owner exited. WaitOne granted us ownership. + } + try { & $Operation } finally { $mutex.ReleaseMutex() } + } finally { + $mutex.Dispose() + } +} + +$directory = [IO.Path]::Combine($Workspace, '.devcontainer') +if (-not (Test-RegularPath $Workspace $true) -or -not (Test-RegularPath $directory $true)) { + throw 'Workspace and .devcontainer must be real directories.' +} +$destination = [IO.Path]::Combine($directory, '.mcp.env') +if ($Action -eq 'Protect') { + Invoke-WithCredentialLock { + Protect-ExistingFile $destination + Protect-ExistingFile ([IO.Path]::Combine($Workspace, '.env.local')) + } + return +} + +# File.Replace inherits the old destination ACL. A same-volume Windows rename +# preserves the verified ACL of the new file and works for both first publish +# and concurrent replacement. +Add-Type -Namespace NovaSharp -Name NativeFile -MemberDefinition @' +[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)] +public static extern bool MoveFileEx(string existing, string replacement, uint flags); +'@ +$temporary = "$destination.$([Guid]::NewGuid().ToString('N'))" +$stream = [IO.FileStream]::new($temporary, [IO.FileMode]::CreateNew, + [Security.AccessControl.FileSystemRights]::FullControl, [IO.FileShare]::None, + 4096, [IO.FileOptions]::None, (New-PrivateAcl $true)) +try { + try { + Assert-PrivateAcl ($stream.GetAccessControl()) + [Console]::OpenStandardInput().CopyTo($stream) + if ($stream.Length -eq 0) { throw 'Incomplete credential input.' } + $stream.Position = $stream.Length - 1 + if ($stream.ReadByte() -ne 0) { throw 'Incomplete credential input.' } + $stream.SetLength($stream.Length - 1) + } finally { + $stream.Dispose() + } + Invoke-WithCredentialLock { + $null = Test-RegularPath $destination $false + if (-not [NovaSharp.NativeFile]::MoveFileEx($temporary, $destination, 1)) { + throw [ComponentModel.Win32Exception]::new([Runtime.InteropServices.Marshal]::GetLastWin32Error()) + } + if (-not (Test-RegularPath $destination $false)) { throw 'The published credential file is missing.' } + Assert-PrivateAcl ([IO.File]::GetAccessControl($destination)) + } +} finally { + [IO.File]::Delete($temporary) +} diff --git a/.devcontainer/mcp_credentials.py b/.devcontainer/mcp_credentials.py new file mode 100644 index 000000000..593b0d719 --- /dev/null +++ b/.devcontainer/mcp_credentials.py @@ -0,0 +1,100 @@ +"""Stage and read the project-specific Z.ai credential used by Claude MCP.""" + +import hashlib +import os +from pathlib import Path +import stat +import sys +import tempfile + + +def validate_key(key): + if not key or any(byte in b" \t\r\n\v\f\"'\0" for byte in key): + raise ValueError("Filtered MCP credentials contain an invalid ZAI_API_KEY.") + return key + + +def private_file(workspace, *, create): + project = workspace.resolve(strict=True) + if not project.is_dir(): + raise ValueError("The Claude workspace must be a directory.") + home = Path.home() + home_info = home.stat() + if home_info.st_uid != os.geteuid() or home_info.st_mode & 0o022: + raise ValueError("The runtime user's home directory must be owned and writable only by its user.") + directory = home / ".novasharp-mcp" + if create: + directory.mkdir(mode=0o700, exist_ok=True) + directory_info = directory.lstat() + if ( + not stat.S_ISDIR(directory_info.st_mode) + or directory_info.st_uid != os.geteuid() + or stat.S_IMODE(directory_info.st_mode) != 0o700 + ): + raise ValueError("The private MCP directory must be user-owned with mode 700.") + return directory / hashlib.sha256(os.fsencode(project)).hexdigest() + + +def stage(workspace): + destination = private_file(workspace, create=True) + key = os.environb.get(b"ZAI_API_KEY", b"") + if key: + validate_key(key) + # Publish an empty file on removal as well. Readers see a complete snapshot. + staging = tempfile.NamedTemporaryFile(dir=destination.parent, delete=False) + try: + with staging: + os.fchmod(staging.fileno(), 0o600) + if key: + staging.write(b"ZAI_API_KEY=" + key + b"\n") + os.replace(staging.name, destination) + finally: + Path(staging.name).unlink(missing_ok=True) + + +def read_key(path, *, standalone): + # Check the open file itself, including refusals for symlinks and pipes. + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as file: + info = os.fstat(file.fileno()) + # An atomic replacement may already have unlinked the open snapshot. + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_nlink > 1: + raise ValueError("Filtered MCP credentials must be a user-owned regular file.") + if stat.S_IMODE(info.st_mode) != 0o600: + raise ValueError("Filtered MCP credentials must have mode 600; rebuild the devcontainer.") + prefix = b"ZAI_API_KEY=" + keys = [] + for line in file: + if line.startswith(prefix): + keys.append(line[len(prefix):].removesuffix(b"\n").removesuffix(b"\r")) + elif not standalone: + raise ValueError("Unexpected assignment in the private Claude credential file.") + if len(keys) != 1: + raise ValueError("Filtered MCP credentials contain an invalid ZAI_API_KEY.") + return validate_key(keys[0]) + + +def main(*, standalone=False): + if len(sys.argv) != 3 or sys.argv[1] not in ("stage", "read"): + sys.exit("Expected a stage or read operation and a workspace directory.") + workspace = Path(sys.argv[2]) + try: + if sys.argv[1] == "stage": + stage(workspace) + else: + if standalone: + parent = workspace / ".devcontainer" + if parent.is_symlink(): + raise ValueError("Filtered MCP credentials must have a real parent directory.") + path = parent / ".mcp.env" + else: + path = private_file(workspace, create=False) + sys.stdout.buffer.write(read_key(path, standalone=standalone)) + except FileNotFoundError: + sys.exit("Filtered MCP credentials are missing; rebuild the devcontainer.") + except (OSError, ValueError) as error: + sys.exit(f"Cannot {sys.argv[1]} the Claude MCP credential: {error}") + + +if __name__ == "__main__": + main() diff --git a/.devcontainer/on-create.sh b/.devcontainer/on-create.sh index 449047397..fc91d5c8c 100755 --- a/.devcontainer/on-create.sh +++ b/.devcontainer/on-create.sh @@ -19,6 +19,18 @@ fi cd "${WORKSPACE_DIR}" +# Docker Desktop can present a trusted host checkout as root-owned to vscode. +if [ -e .git ] && { [ ! -O . ] || [ ! -O .git ]; }; then + workspace_path="$(pwd -P)" + git config --global --fixed-value --replace-all safe.directory "${workspace_path}" "${workspace_path}" +fi + +# Use Docker's creation-time environment before extensions can launch Claude MCP. +python3 .devcontainer/mcp_credentials.py stage . + +# Repair the persistent NuGet cache before any dotnet command can read it. +bash .devcontainer/ensure-nuget-cache.sh + run_with_retries() { local max_attempts="$1" shift @@ -115,7 +127,7 @@ bash .devcontainer/cleanup-artifacts.sh "${WORKSPACE_DIR}" --all # ============================================================================ echo "" echo "🤖 Step 2/4: Refreshing npm coding tools..." -bash .devcontainer/install-npm-tools.sh +bash .devcontainer/install-npm-tools.sh --offline-ok bash .devcontainer/ai-backends.sh install # ============================================================================ diff --git a/.devcontainer/post-create.sh b/.devcontainer/post-create.sh index c4c6461c9..9ab78d048 100755 --- a/.devcontainer/post-create.sh +++ b/.devcontainer/post-create.sh @@ -19,6 +19,9 @@ fi cd "${WORKSPACE_DIR}" +# Repair the persistent NuGet cache before any dotnet command can read it. +bash .devcontainer/ensure-nuget-cache.sh + run_with_retries() { local max_attempts="$1" shift diff --git a/.devcontainer/post-start.sh b/.devcontainer/post-start.sh index 4afa7d337..98c0cb23d 100755 --- a/.devcontainer/post-start.sh +++ b/.devcontainer/post-start.sh @@ -7,10 +7,8 @@ workspace_dir="${1:-$(pwd)}" retention_days="${NOVA_ARTIFACT_RETENTION_DAYS:-7}" cd "${workspace_dir}" -NOVA_NPM_INSTALL_ATTEMPTS="${NOVA_NPM_START_ATTEMPTS:-2}" \ - NPM_CONFIG_FETCH_RETRIES="${NOVA_NPM_START_FETCH_RETRIES:-1}" \ - NPM_CONFIG_FETCH_TIMEOUT="${NOVA_NPM_START_FETCH_TIMEOUT_MS:-10000}" \ - bash .devcontainer/install-npm-tools.sh --offline-ok +bash .devcontainer/ensure-nuget-cache.sh +bash .devcontainer/install-npm-tools.sh --offline-ok bash .devcontainer/ai-backends.sh install bash .devcontainer/cleanup-artifacts.sh "${workspace_dir}" --older-than-days "${retention_days}" diff --git a/.devcontainer/read-claude-mcp-key.py b/.devcontainer/read-claude-mcp-key.py new file mode 100644 index 000000000..69d42bd05 --- /dev/null +++ b/.devcontainer/read-claude-mcp-key.py @@ -0,0 +1,6 @@ +"""Standalone checkout entry point. The image installs its private reader here.""" + +from mcp_credentials import main + +if __name__ == "__main__": + main(standalone=True) diff --git a/.devcontainer/update-content.sh b/.devcontainer/update-content.sh index 11f403ba6..d7195c98d 100755 --- a/.devcontainer/update-content.sh +++ b/.devcontainer/update-content.sh @@ -44,5 +44,9 @@ run_with_retries() { } cd "${WORKSPACE_DIR}" + +# Repair the persistent NuGet cache before any dotnet command can read it. +bash .devcontainer/ensure-nuget-cache.sh + run_with_retries 5 dotnet tool restore --verbosity minimal run_with_retries 5 dotnet restore src/NovaSharp.sln --verbosity minimal diff --git a/.devcontainer/zai-mcp-remote.sh b/.devcontainer/zai-mcp-remote.sh new file mode 100755 index 000000000..81c6fa1ce --- /dev/null +++ b/.devcontainer/zai-mcp-remote.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Bridge Z.ai's SSE-formatted Streamable HTTP responses to stdio for Claude and Codex. + +set +x +set -euo pipefail + +fail() { + printf '[zai-mcp-remote] ERROR: %s\n' "$*" >&2 + exit 1 +} + +server_alias="${1:-}" +case "${server_alias}" in + web-search) endpoint="https://api.z.ai/api/mcp/web_search_prime/mcp" ;; + web-reader) endpoint="https://api.z.ai/api/mcp/web_reader/mcp" ;; + zread) endpoint="https://api.z.ai/api/mcp/zread/mcp" ;; + *) fail "Expected one of: web-search, web-reader, zread." ;; +esac + +[ "$#" = "1" ] || fail "Unexpected arguments for ${server_alias}." +command -v mcp-remote >/dev/null 2>&1 \ + || fail "mcp-remote is not installed; rebuild the devcontainer." + +unset token zai_mcp_token +if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then + launcher_dir="$(dirname "$(realpath "${BASH_SOURCE[0]}")")" + zai_mcp_token="$(python3 -EsB "${launcher_dir}/read-claude-mcp-key.py" read "${CLAUDE_PROJECT_DIR}")" +elif [ -n "${ZAI_API_KEY:-}" ]; then + # Codex explicitly forwards only this key through the server's env_vars. + zai_mcp_token="${ZAI_API_KEY}" +else + fail "A filtered Claude runtime credential or Codex-forwarded ZAI_API_KEY is required." +fi +zai_mcp_token="${zai_mcp_token%$'\r'}" +[ -n "${zai_mcp_token}" ] || fail "Filtered MCP credentials contain an invalid ZAI_API_KEY." +case "${zai_mcp_token}" in + *[[:space:]\"\']*) fail "Filtered MCP credentials contain an invalid ZAI_API_KEY." ;; +esac + +# The bridge receives the credential through an anonymous file descriptor. The +# handoff creates no additional persistent/header file and keeps the value out +# of argv and the bridge process environment. +unset ZAI_MCP_API_KEY \ + ANTHROPIC_AUTH_TOKEN \ + ANTHROPIC_API_KEY \ + CLAUDE_CODE_OAUTH_TOKEN \ + ZAI_API_KEY \ + Z_AI_API_KEY \ + GITHUB_PERSONAL_ACCESS_TOKEN \ + GITHUB_PAT \ + GITHUB_TOKEN \ + GH_TOKEN \ + OPENAI_API_KEY \ + CODEX_API_KEY +exec mcp-remote "${endpoint}" --header-file \ + <(printf 'Authorization: Bearer %s\n' "${zai_mcp_token}") diff --git a/.devcontainer/zai-mcp-vision.sh b/.devcontainer/zai-mcp-vision.sh new file mode 100755 index 000000000..3db7b0d04 --- /dev/null +++ b/.devcontainer/zai-mcp-vision.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Adapt the canonical project key name to the Z.ai Vision MCP package. + +set +x +set -euo pipefail + +unset zai_api_key +if [ -n "${CLAUDE_PROJECT_DIR:-}" ]; then + launcher_dir="$(dirname "$(realpath "${BASH_SOURCE[0]}")")" + zai_api_key="$(python3 -EsB "${launcher_dir}/read-claude-mcp-key.py" read "${CLAUDE_PROJECT_DIR}")" +else + zai_api_key="${ZAI_API_KEY:-${Z_AI_API_KEY:-}}" +fi +if [ -z "${zai_api_key}" ]; then + printf 'zai-mcp-vision: ZAI_API_KEY is missing; update .env.local and rebuild the devcontainer.\n' >&2 + exit 1 +fi +if ! command -v zai-mcp-server >/dev/null 2>&1; then + printf 'zai-mcp-vision: zai-mcp-server is missing; rebuild the devcontainer.\n' >&2 + exit 1 +fi + +unset ZAI_API_KEY \ + Z_AI_API_KEY \ + ZAI_MCP_API_KEY \ + ANTHROPIC_AUTH_TOKEN \ + ANTHROPIC_API_KEY \ + CLAUDE_CODE_OAUTH_TOKEN \ + GITHUB_PERSONAL_ACCESS_TOKEN \ + GITHUB_PAT \ + GITHUB_TOKEN \ + GH_TOKEN \ + OPENAI_API_KEY \ + CODEX_API_KEY +export Z_AI_API_KEY="${zai_api_key}" +export Z_AI_MODE=ZAI +unset zai_api_key +exec zai-mcp-server "$@" diff --git a/.env.local.example b/.env.local.example new file mode 100644 index 000000000..a2e609036 --- /dev/null +++ b/.env.local.example @@ -0,0 +1,3 @@ +# Copy this file to .env.local, fill whichever values you need without quotes, and rebuild. +GITHUB_PERSONAL_ACCESS_TOKEN= +ZAI_API_KEY= diff --git a/.gitattributes b/.gitattributes index 5254f0d4b..7d2816b11 100644 --- a/.gitattributes +++ b/.gitattributes @@ -12,6 +12,10 @@ .devcontainer/Dockerfile text eol=lf .devcontainer/devcontainer.json text eol=lf +# yamllint runs against the working copy inside the Linux devcontainer. +*.yml text eol=lf +*.yaml text eol=lf + # Keep C# sources on CRLF to match .editorconfig and keep CSharpier happy on Linux agents. *.cs text eol=crlf diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ccf5cc406..e2bb7ddaa 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,40 +1,21 @@ -# GitHub Copilot Instructions for NovaSharp + -**Complete documentation: [`../.llm/context.md`](../.llm/context.md)** +# NovaSharp engineering policy -## Quick Reference - -| Priority | Concern | Never Sacrifice For Lower Priority | -| -------------- | ---------------------- | ---------------------------------- | -| 1. CORRECTNESS | Lua Spec Compliance | Performance, memory, clarity | -| 2. SPEED | Runtime Performance | Memory, clarity | -| 3. MEMORY | Minimal Allocations | Clarity | -| 4. UNITY | Platform Compatibility | Clarity | -| 5. CLARITY | Maintainability | - | - -## Critical Rules - -1. **Scoped Git Operations Allowed When Requested** - If the user asks for commits, pushes, or PR/CI work, agents may run `git add`, `git commit`, and `git push` after reviewing the diff. Use small scoped commits and never use destructive git commands unless explicitly requested. -1. **NEVER use absolute paths** - Relative paths from repo root only -1. **Do not discard diagnostic output in ad-hoc commands** - Repo helper scripts may intentionally quiet noisy tools, but failures must surface actionable output. -1. **Lua Spec = Source of Truth** - Fix NovaSharp, never tests -1. **Multi-Version Testing** - All tests run on Lua 5.1-5.5 -1. **Lua Fixture Metadata** - ONLY `@lua-versions`, `@novasharp-only`, `@expects-error` -1. **Pre-Commit Validation Allowed** - `bash ./scripts/dev/pre-commit.sh` is expected before commits and may restage files it auto-formats or regenerates. -1. **No false green-lighting** - Only say `green`, `verified`, `passes`, or `complete` after the exact local checks and PR CI were observed passing. Otherwise report the check as `not run` or failing residual risk. -1. **Mandatory post-work improvement gate** - After every large change or investigation, and before declaring it complete, follow [`../.llm/skills/post-work-reflection/SKILL.md`](../.llm/skills/post-work-reflection/SKILL.md). Fix discovered defects, capture reusable techniques or durable knowledge in the appropriate `.llm` artifact, and obtain an independent review when agents are available. - -## Build & Test +1. Preserve exact Lua 5.1–5.5 behavior first, then runtime speed, allocations, Unity compatibility (Mono and IL2CPP/AOT), and clarity, in that order. Resolve semantic disputes with the matching reference Lua. Fix the implementation when it differs from the oracle. +1. Host APIs may change. Update repository-owned callers atomically and remove superseded APIs without compatibility shims. +1. Use repository-relative paths. Preserve actionable diagnostics. Investigate every test failure. +1. Scope material work to one falsifiable slice targeting a shippable PR in under two hours. Record unfinished work in the [execution queue](../PLAN.md). +1. For material changes, follow the [evidence-driven workflow](../.llm/workflows/evidence-driven-change.md). Always add both C# tests and Lua fixtures and regenerate the corpus when adding either C# or Lua regression coverage or changing runtime or interop code. At the top of each fixture use only the hand-authored tags `@lua-versions`, `@novasharp-only`, and `@expects-error`. Run tests across Lua 5.1–5.5. Compare Lua behavior changes against the matching reference interpreters. +1. Run builds and tests through the quick scripts. Before closing behavior or CI changes, run focused checks, the quick build, full quick tests, formatting, and applicable Lua comparisons. Poll PR CI through success or diagnosis. Claim overall success only after observing all required local and PR checks pass. Identify every unrun or failing gate. +1. When commits, pushes, or PR work are requested, review the diff and use small scoped commits. Run `bash ./scripts/dev/pre-commit.sh` before committing (it may format and restage files). Destructive Git operations require an explicit request. +1. After material changes or investigations, apply [post-work reflection](../.llm/skills/post-work-reflection/SKILL.md) and seek independent review when available. ```bash -./scripts/build/quick.sh # Build interpreter -./scripts/test/quick.sh # Run all tests -./scripts/test/quick.sh Floor # Filter by pattern +./scripts/build/quick.sh # Interpreter build; use --all for the full solution +./scripts/test/quick.sh # Full tests +./scripts/test/quick.sh Floor # Filter by method +./scripts/test/quick.sh -c Math # Filter by class ``` -Do NOT use raw `dotnet build` or `dotnet test`. -Before closing behavior or CI work, run the relevant targeted tests, `./scripts/build/quick.sh`, `./scripts/test/quick.sh`, formatting, Lua comparison when behavior changes, then poll PR CI until green or document the newly diagnosed failure. - -## Skills - -See [`../.llm/skills/`](../.llm/skills/) for task-specific guides. +For source locations, project conventions, or skill discovery, consult the [repository guide](../.llm/context.md). diff --git a/.github/workflows/nuget-publish.yml b/.github/workflows/nuget-publish.yml index c4c55424c..e1267d4bb 100644 --- a/.github/workflows/nuget-publish.yml +++ b/.github/workflows/nuget-publish.yml @@ -69,12 +69,13 @@ jobs: run: dotnet build src/NovaSharp.sln -c Release -p:Version=${{ steps.version.outputs.version }} - name: Run tests + env: + DOTNET_ROLL_FORWARD: Major run: | - dotnet test \ + dotnet test --project \ src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj \ -c Release \ --no-build \ - -- \ --report-trx --report-trx-filename "test-results.trx" - name: Pack NuGet packages diff --git a/.github/workflows/openai-review.yml b/.github/workflows/openai-review.yml new file mode 100644 index 000000000..c8b8100bc --- /dev/null +++ b/.github/workflows/openai-review.yml @@ -0,0 +1,29 @@ +name: OpenAI Review + +on: + pull_request: + types: [opened, synchronize, reopened, ready_for_review, converted_to_draft] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + review: + if: >- + ${{ !github.event.pull_request.draft && + github.event.pull_request.head.repo.full_name == github.repository && + github.event.pull_request.user.type != 'Bot' }} + uses: Ambiguous-Interactive/review-tools/.github/workflows/openai-review.yml@5aabfe60ec294f8160b70d0a712c561db5e3fa29 # v1.1.2 + with: + model: ${{ vars.OPENAI_REVIEW_MODEL || 'gpt-6.1-terra' }} + effort: ${{ vars.OPENAI_REVIEW_EFFORT }} + timeout-minutes: 15 + secrets: + OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} + permissions: + contents: read + pull-requests: write diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 30560cf5d..61b5a9e23 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -87,6 +87,13 @@ jobs: run: | python3 tools/LlmSkillIndexer/test_llm_skill_indexer.py python3 tools/LlmSkillIndexer/llm_skill_indexer.py --check + - name: Validate skills with the Agent Skills reference implementation + shell: bash + run: | + python -m pip install -r tools/LlmSkillIndexer/requirements-reference.txt + for skill in .llm/skills/*/; do + skills-ref validate "$skill" + done - name: Setup .NET (formatting gate) uses: actions/setup-dotnet@v6 @@ -148,6 +155,10 @@ jobs: fetch-depth: 0 # Lint checks already passed in the 'lint' job (this job has needs: lint). # Skip redundant branding/namespace/naming/spelling/documentation/fixture-catalog steps. + - name: Check Windows devcontainer host initialization + if: runner.os == 'Windows' + shell: bash + run: pwsh -NoProfile -File scripts/lint/test-devcontainer-windows-preflight.ps1 - name: Setup .NET uses: actions/setup-dotnet@v6 with: diff --git a/.gitignore b/.gitignore index 264cff539..8e900bded 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,10 @@ *.suo *.user *.sln.docstates +/.env.local* +!/.env.local.example +/.devcontainer/.mcp.env +/.devcontainer/.mcp.env.* tools/LuaCorpusExtractor/__pycache__/** tools/LuaCorpusExtractor/__pycache__ @@ -242,4 +246,3 @@ manual-review.txt # Unity Package Manager sample source templates use a literal Samples~ directory. !src/unity/com.wallstop-studios.novasharp/Samples~/ !src/unity/com.wallstop-studios.novasharp/Samples~/** -GOAL.md diff --git a/.llm/context.md b/.llm/context.md index 283908fe7..e4153e4cd 100644 --- a/.llm/context.md +++ b/.llm/context.md @@ -1,52 +1,4 @@ -# AI Assistant Guidelines for NovaSharp - -## 🔴 Priority Hierarchy (NEVER Violate) - -NovaSharp follows a strict priority order. **NEVER sacrifice a higher priority for a lower one:** - -| Priority | Concern | Description | -| ------------------ | ---------------------- | --------------------------------------------- | -| **1. CORRECTNESS** | Lua Spec Compliance | Behavior MUST match reference Lua exactly | -| **2. SPEED** | Runtime Performance | Execute Lua code as fast as possible | -| **3. MEMORY** | Minimal Allocations | Zero-allocation hot paths, aggressive pooling | -| **4. UNITY** | Platform Compatibility | IL2CPP/AOT, Mono, no runtime code generation | -| **5. CLARITY** | Maintainability | Clean architecture, readability | - -**The Iron Rule**: A performance optimization that breaks Lua spec compliance is REJECTED. A memory optimization that slows down hot paths is REJECTED. See [correctness-then-performance](skills/correctness-then-performance/SKILL.md) for the complete decision framework. - -### ⛔ "Close Enough" is NEVER Acceptable - -NovaSharp's goal is **exact Lua spec compliance**, not "something like Lua." When discrepancies are found: - -1. **ASSUME NovaSharp is WRONG** — Reference Lua behavior is the source of truth -1. **Investigate deeply** — Never dismiss differences as "acceptable variations" -1. **Fix production code** — Never adjust tests to match NovaSharp's bugs -1. **Verify with `lua5.X`** — Every expected result must be confirmed against reference Lua -1. **"Close enough" = BUG** — Approximate behavior, formatting differences, or edge case mismatches are all bugs - -______________________________________________________________________ - -## 🔴 Critical Rules - -1. **Scoped Git Operations Allowed When Requested** — If the user asks for commits, pushes, or PR/CI work, agents may run `git add`, `git commit`, and `git push` after reviewing the diff. Use small scoped commits and never use destructive git commands unless explicitly requested. -1. **NEVER use absolute paths** — Relative to repo root only -1. **Do not discard diagnostic output in ad-hoc commands** — Repo helper scripts may intentionally quiet noisy tools, but failures must surface actionable output. -1. **Lua Spec Compliance is HIGHEST PRIORITY** — Fix production code, never tests -1. **No Legacy Host API Compatibility** — NovaSharp is pre-adoption with no external consumers. Freely make breaking host-facing API changes when they improve the project; update repository-owned callers atomically and remove superseded APIs instead of adding shims, forwarding wrappers, obsolete aliases, migration adapters, deprecation windows, or compatibility layers. This does not relax Lua-version behavior or supported-platform compatibility. -1. **Zero-Flaky Test Policy** — Every failure is a real bug -1. **Always create BOTH C# tests AND `.lua` fixtures** — Regenerate corpus after -1. **Multi-Version Testing** — Run tests against Lua 5.1-5.5 -1. **Lua Fixture Metadata** — Use ONLY `@lua-versions`, `@novasharp-only`, `@expects-error` **at TOP of file** -1. **Pre-Commit Validation Allowed** — Run `./scripts/dev/pre-commit.sh` after changes; it may restage files it auto-formats or regenerates. -1. **No False Green-Light** — Only say `green`, `verified`, `passes`, or `complete` after the exact local checks and PR CI were observed passing; otherwise report `not run` or residual risk. -1. **Evidence-Driven Material Changes** — Use the [evidence-driven change workflow](workflows/evidence-driven-change.md) for material behavior, architecture, performance, reliability, CI, or LLM-system work. Require observed red→green evidence and risk-selected gates. -1. **Lean Execution Plan** — Keep `PLAN.md` limited to in-progress and intentionally queued work. Route reusable guidance to skills/workflows, stable facts to knowledge or domain docs, completed evidence to `progress/`, and unselected backlog detail to issues. Use [plan-maintenance](skills/plan-maintenance/SKILL.md) and remove completed items in the same change that records their session result. -1. **Session Length Target: Under 2 Hours** — Scope each session to one shippable green PR that completes a falsifiable slice of a `PLAN.md` item. If the full slice will not fit, stop at a green checkpoint and hand off remainders through `PLAN.md`, `progress/`, and issues. See [plan-maintenance](skills/plan-maintenance/SKILL.md#session-scoping). -1. **Mandatory Post-Work Improvement Gate** — After every large change or investigation, complete [post-work-reflection](skills/post-work-reflection/SKILL.md) before reporting completion. Resolve findings at their root, update the appropriate LLM guidance or knowledge when evidence supports a durable lesson, and independently review the result when agents are available. - -See individual skills for detailed guidance. - -______________________________________________________________________ +# NovaSharp repository guide ## Project Overview @@ -60,63 +12,16 @@ ______________________________________________________________________ ## Where to Find Things -### Quick Navigation by Task - -| I want to... | Look in | -| ------------------------------- | --------------------------------------------------- | -| Fix Lua behavior bug | `src/runtime/.../CoreLib/` (stdlib modules) | -| Fix parser/lexer issue | `src/runtime/.../Tree/Lexer/` or `.../Tree/Parser/` | -| Fix VM execution bug | `src/runtime/.../Execution/VM/` | -| Add/modify a data type | `src/runtime/.../DataTypes/` | -| Fix C# interop issue | `src/runtime/.../Interop/` | -| Add a new test | `src/tests/.../Tests.TUnit/` | -| Add a Lua test fixture | `src/tests/.../Tests/Fixtures/` | -| Check Lua spec | `docs/lua-spec/lua5X-manual.md` | -| Find pooling utilities | `src/runtime/.../DataStructs/CollectionPools.cs` | -| Find string building utilities | `src/runtime/.../DataStructs/ZStringBuilder.cs` | -| Check/add performance patterns | `.llm/skills/high-performance-csharp/SKILL.md` | -| Investigate comparison failures | `.llm/skills/lua-comparison-harness/SKILL.md` | -| Debug cross-platform issues | `.llm/skills/test-failure-investigation/SKILL.md` | -| Plan or review architecture | `.llm/skills/architecture-review/SKILL.md` | -| Verify a behavior change | `.llm/skills/change-path-verification/SKILL.md` | -| Run an independent hardening | `.llm/skills/adversarial-handoff/SKILL.md` | -| Capture durable repository fact | `.llm/knowledge/` | -| Create or maintain the plan | `.llm/skills/plan-maintenance/SKILL.md` | - -### Key Files - -- `Api/LuaValue.cs` — Core Lua value type -- `DataTypes/Table.cs` — Lua table implementation -- `Execution/VM/Processor.cs` — Main VM execution loop -- `CoreLib/*Module.cs` — Standard library implementations -- `DataStructs/CollectionPools.cs` — ListPool, HashSetPool, etc. - -______________________________________________________________________ - -## Commands - -```bash -# Build (interpreter only) -./scripts/build/quick.sh +Runtime paths below are relative to `src/runtime/WallstopStudios.NovaSharp.Interpreter/`. -# Build full solution -./scripts/build/quick.sh --all - -# Run all tests -./scripts/test/quick.sh - -# Run tests by pattern -./scripts/test/quick.sh Floor # Method name -./scripts/test/quick.sh -c MathModule # Class name - -# Format code -dotnet tool restore -dotnet tool run csharpier format . -``` - -Before closing behavior or CI work, run the relevant targeted tests, `./scripts/build/quick.sh`, `./scripts/test/quick.sh`, formatting, Lua comparison when behavior changes, then poll PR CI until green or document the newly diagnosed failure. If any required check was not run, say exactly that and do not present the work as complete. - -______________________________________________________________________ +| Task | Start here | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Investigate Lua behavior | `CoreLib/`, then the matching [Lua manual](../docs/lua-spec/) | +| Trace parsing | `Tree/Lexer/`, `Tree/Expressions/`, `Tree/Statements/` | +| Trace execution | `Execution/VM/Processor/` | +| Inspect host interop or values | `Interop/`, `Api/LuaValue.cs`, `DataTypes/Table.cs` | +| Find pools and string builders | `DataStructs/CollectionPools.cs`, `DataStructs/ZStringBuilder.cs` | +| Write a regression | [TUnit tests](../src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/) and [Lua fixtures](../src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/) | ## Coding Style @@ -156,37 +61,16 @@ ______________________________________________________________________ ______________________________________________________________________ -## Skills Index - -Skills are in `.llm/skills/`. Run `python3 tools/LlmSkillIndexer/llm_skill_indexer.py` to see all available skills. - -### Core Skills - -| Category | Key Skills | -| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **Priority** | [correctness-then-performance](skills/correctness-then-performance/SKILL.md), [lua-spec-verification](skills/lua-spec-verification/SKILL.md) | -| **Performance** | [high-performance-csharp](skills/high-performance-csharp/SKILL.md), [zstring-migration](skills/zstring-migration/SKILL.md), [data-structures](skills/data-structures/SKILL.md) | -| **Testing** | [tunit-test-writing](skills/tunit-test-writing/SKILL.md), [lua-fixture-creation](skills/lua-fixture-creation/SKILL.md), [test-failure-investigation](skills/test-failure-investigation/SKILL.md) | -| **Workflow** | [systematic-investigation](skills/systematic-investigation/SKILL.md), [architecture-review](skills/architecture-review/SKILL.md), [adversarial-handoff](skills/adversarial-handoff/SKILL.md), [plan-maintenance](skills/plan-maintenance/SKILL.md) | -| **Verification** | [change-path-verification](skills/change-path-verification/SKILL.md), [deterministic-testing](skills/deterministic-testing/SKILL.md), [post-work-reflection](skills/post-work-reflection/SKILL.md) | -| **Unity** | [unity-gc-patterns](skills/unity-gc-patterns/SKILL.md), [aggressive-inlining](skills/aggressive-inlining/SKILL.md) | -| **Lua** | [lua-comparison-harness](skills/lua-comparison-harness/SKILL.md), [adding-opcodes](skills/adding-opcodes/SKILL.md) | -| **Quality** | [defensive-programming](skills/defensive-programming/SKILL.md), [documentation-and-changelog](skills/documentation-and-changelog/SKILL.md) | - -______________________________________________________________________ - -## Key Utilities +## Skill discovery -| Utility | Usage | -| ---------------- | ----------------------------------------- | -| **Pooling** | `using var lease = ListPool.Get();` | -| **ZString** | `using var sb = ZStringBuilder.Create();` | -| **Enum strings** | `TokenTypeStrings.GetName(token)` | -| **Hash codes** | `HashCodeHelper.HashCode(a, b, c)` | +Use your client’s skill selector or list the canonical names from the repository root: -See [use-extension-methods](skills/use-extension-methods/SKILL.md) for full list. +```bash +python3 -c 'import json; import sys; print("\n".join(skill["name"] for skill in json.load(sys.stdin.buffer)["skills"]))' < .llm/skills-index.json +``` -______________________________________________________________________ +Open a matching skill for its procedure and consult its references as needed. +The [authoring guide](skills/adding-skills/SKILL.md) covers changes to the catalog. ## Resources diff --git a/.llm/knowledge/devcontainer-ai-backends.md b/.llm/knowledge/devcontainer-ai-backends.md index e5406d432..334035ef1 100644 --- a/.llm/knowledge/devcontainer-ai-backends.md +++ b/.llm/knowledge/devcontainer-ai-backends.md @@ -12,10 +12,9 @@ environment, custom `CODEX_HOME`, key absence, argument forwarding, and file permissions. - **Implication:** Never implement a backend toggle by rewriting native config. - Credentials belong in exported process environment variables, never generated - files or an intermediate command's arguments. - Model-server credentials must also be filtered from shell, hook, and stdio MCP - subprocesses. + Do not put credentials in generated profiles or an intermediate command's + arguments. Ordinary shell, hook, and unrelated MCP children must not receive + model credentials; a trusted MCP may receive only its required key. - **Fact:** Claude Code 2.1.259's experimental Linux subprocess scrubber forces the strong bubblewrap path. `sandbox.enableWeakerNestedSandbox=true` only changes `/proc` handling and still requests `--unshare-user`; it cannot repair @@ -48,6 +47,86 @@ After any `latest` CLI upgrade, rerun the fake-CLI suite and a controlled local connection-refusal smoke test to verify provider/model parsing without billing. +## Project MCP catalogs and runtime secrets + +- **Fact:** As verified on 2026-09-03, GitHub plus Z.ai Vision, Web Search Prime, + Web Reader, and Zread are projected into each frontend's native project format. + Nanocoder requires `NANOCODER_MCPSERVERS_FILE` because it does not search parent + directories for `.mcp.json`. +- **Fact:** A host preflight allowlists `GITHUB_PERSONAL_ACCESS_TOKEN` and + `ZAI_API_KEY` from ignored `.env.local` into an ignored Docker env file. + The workspace-relative host hook uses native Windows ACLs on Windows drives + and mode `0600` on POSIX storage. It atomically publishes after validation so a concurrent launch + can open the previous file. A failed preflight stops that launch. A missing + source publishes an empty file, allowing credential-free devcontainer startup. +- **Fact:** The GitHub server sends `X-MCP-Readonly: true` in every frontend. + The Vision wrapper maps only the required Z.ai alias and scrubs the canonical + Z.ai key and GitHub token before executing the package. +- **Evidence:** Cross-repository hostile preflight tests, real frontend parsers, + authenticated MCP initialization, cwd-shift probes, and a Claude tool-list + oracle showing no GitHub write tools. +- **Implication:** Keep `.env.local*` and generated runtime variants ignored and + excluded from Docker build contexts. Treat the mounted repository and agent + process as trusted: runtime keys are not a sandbox boundary. Remove the + read-only header only for a deliberate, least-privilege mutation workflow. + +## Claude and Codex remote MCP need a version-scoped compatibility bridge + +- **Fact:** As verified with Claude Code 2.1.260 on 2026-09-04, Claude's native + HTTP MCP client rejects the SSE-framed initialization result returned by + Z.ai's Web Search Prime, Web Reader, and Zread endpoints. The same key and + endpoint succeed through raw HTTP initialization, OpenCode, and `mcp-remote`. +- **Fact:** Codex 0.153.2 reaches the same servers and accepts initialization, + but its Streamable HTTP transport closes while sending the subsequent + `initialized` notification. A fresh session using the stdio bridge produced + no MCP startup errors and proceeded to the independently failing model quota. +- **Fact:** Claude 2.1.260 also does not forward its reserved Anthropic auth + variable to the configured stdio MCP child. The Z.ai wrappers therefore parse + a private credential file selected by the canonical `CLAUDE_PROJECT_DIR`. + The managed image stages only the Docker-injected Z.ai key on its Linux + filesystem during creation. Windows bind mounts can report mode `0777` even + for host files protected by a private NTFS ACL. +- **Fact:** `claude-zai` uses a private MCP catalog and Codex uses its project + catalog to bridge only the three affected remote servers through `mcp-remote`. + Vision remains direct stdio and GitHub remains native HTTP. Codex forwards only + `ZAI_API_KEY` through the documented per-server `env_vars` allowlist; the + wrapper validates it and scrubs all credentials before starting the bridge. + Standalone POSIX wrappers read the filtered runtime file below `CLAUDE_PROJECT_DIR`. + The presence of `CLAUDE_PROJECT_DIR` makes that file authoritative: an absent, + malformed, symlinked, or over-readable file fails closed and never falls back + to an ambient key. + Its isolated settings approve exactly the five audited project server names. +- **Fact:** In 2.1.260, the `claude mcp list` management subcommand ignores the + launcher's per-session strict MCP catalog and instead health-checks project + `.mcp.json`. It can therefore report native HTTP failures while a real session + has all five private-catalog servers connected. Treat the streamed + `system/init.mcp_servers` result as the runtime oracle. +- **Evidence:** Authenticated HTTP/2 initialization returned status 200 and MCP + protocol `2024-11-05`; OpenCode connected to all five servers; native Claude + reported Zod `invalid_union` failures for the three remote Z.ai servers; + Claude debug output showed the missing child credential; and the bridge then + connected to the same endpoints. See [Claude MCP configuration](https://code.claude.com/docs/en/mcp), + [the upstream native SSE failure](https://github.com/anthropics/claude-code/issues/58759), + and [`mcp-remote`](https://github.com/geelen/mcp-remote). +- **Implication:** Do not diagnose this signature as container networking or + rotate a working key. Keep native HTTP in clients where the authenticated + handshake succeeds. After each Claude or Codex upgrade, run a real + authenticated native-HTTP session through the `initialized` notification; + an HTTP 200 initialization response alone is insufficient. Remove that + client's bridge only after full session startup succeeds. After each + `mcp-remote@latest` upgrade, repeat the bridged session probe. Preserve hostile + wrapper tests for argv/log leakage, source precedence, key scrubbing, symlink + rejection, and missing credentials. See + [Codex MCP configuration](https://developers.openai.com/codex/mcp/). +- **Fact:** MCP transport health and model-plan capacity are independent. The + 2026-09-04 Totem session initialized all five MCPs before the Z.ai model API + returned HTTP 429/code `1310` for exhausted weekly/monthly allowance. Claude's + retries made the prompt look hung. +- **Implication:** For `1310`, stop the retry loop and inspect the Z.ai plan's + reset/capacity. Do not rebuild the container, rotate a working key, or change + MCP transport. Diagnose native MCP parsing, actual session MCP status, and + model quota as three separate failure domains. + ## Endpoint and model contracts can change - **Fact:** Z.ai's Codex integration currently uses the Responses endpoint diff --git a/.llm/skills/adding-skills/SKILL.md b/.llm/skills/adding-skills/SKILL.md index 3016071dd..51aaf8e2e 100644 --- a/.llm/skills/adding-skills/SKILL.md +++ b/.llm/skills/adding-skills/SKILL.md @@ -10,7 +10,7 @@ metadata: Keep skill content compatible with the [Agent Skills specification](https://agentskills.io/specification) and discoverable -by Codex, Claude Code, and GitHub Copilot. +by Codex, Claude Code, OpenCode, and GitHub Copilot. ## Canonical layout @@ -92,4 +92,4 @@ related-skill references, both client discovery symlinks, and the committed - [ ] Resources are linked directly and paths resolve from the skill directory - [ ] Added scripts were executed successfully - [ ] Indexer tests, generation, and strict check succeeded -- [ ] `.llm/context.md` routing changed if the skill is commonly used +- [ ] Confirm the description distinguishes the skill from nearby tasks diff --git a/.llm/skills/ci-workflow/references/REFERENCE.md b/.llm/skills/ci-workflow/references/REFERENCE.md index a62822fa8..586368a2a 100644 --- a/.llm/skills/ci-workflow/references/REFERENCE.md +++ b/.llm/skills/ci-workflow/references/REFERENCE.md @@ -39,16 +39,13 @@ NovaSharp uses TUnit on Microsoft.Testing.Platform. ``` -### Platform Options Separator +### Microsoft.Testing.Platform options -Options for the test platform MUST come after `--`: +Run a specific project with `--project` and pass runner options directly to +`dotnet test`. When using `dotnet run`, place runner options after `--`. ```bash -# WRONG -dotnet test --results-directory ./results --report-trx - -# CORRECT -dotnet test -- --results-directory ./results --report-trx +dotnet test --project path/to/TestProject.csproj --results-directory ./results --report-trx ``` ______________________________________________________________________ diff --git a/.llm/skills/plan-maintenance/SKILL.md b/.llm/skills/plan-maintenance/SKILL.md index 9524bf4d3..dc5af6e07 100644 --- a/.llm/skills/plan-maintenance/SKILL.md +++ b/.llm/skills/plan-maintenance/SKILL.md @@ -37,7 +37,7 @@ issue entry, and hand off cleanly instead of leaving a half-finished branch. | Information | Canonical destination | | ---------------------------------------------------------------------- | ----------------------------------- | -| Always-applicable priority or closure gate | `.llm/context.md` | +| Always-applicable priority or closure gate | `AGENTS.md` | | Reusable method or decision process | `.llm/skills/` or `.llm/workflows/` | | Stable verified repository fact | `.llm/knowledge/` | | Architecture, proposal, benchmark, or domain detail | Relevant file under `docs/` | diff --git a/.llm/skills/post-work-reflection/SKILL.md b/.llm/skills/post-work-reflection/SKILL.md index c9e18377f..cbb16eb95 100644 --- a/.llm/skills/post-work-reflection/SKILL.md +++ b/.llm/skills/post-work-reflection/SKILL.md @@ -86,7 +86,7 @@ ______________________________________________________________________ | Defect or incomplete work | Fix production code, tests, tooling, or docs before completion | | Reusable problem-solving technique | Create or update one focused `.llm/skills//SKILL.md` skill | | Stable repository fact or useful trivia | Add it to the relevant topic under `.llm/knowledge/` | -| Always-applicable policy or priority | Update `.llm/context.md`; mirror only the essential rule in `AGENTS.md` | +| Always-applicable policy or priority | Update the shared startup policy in `AGENTS.md` | | Navigation or task-routing information | Update `.llm/context.md` or the relevant skill links/triggers | | Repeated mechanical failure | Prefer an automated check, helper, or template plus concise guidance | | Task-specific or transient observation | Keep it in the final report; do not persist it as guidance | diff --git a/.llm/skills/tunit-test-writing/references/REFERENCE.md b/.llm/skills/tunit-test-writing/references/REFERENCE.md index bff4db4ec..376887ff2 100644 --- a/.llm/skills/tunit-test-writing/references/REFERENCE.md +++ b/.llm/skills/tunit-test-writing/references/REFERENCE.md @@ -97,7 +97,7 @@ ______________________________________________________________________ ## Running Tests -See [context.md Quick Scripts](../../../context.md) for test commands (`./scripts/test/quick.sh`). +See [the shared build and test commands](../../../../AGENTS.md) for test commands (`./scripts/test/quick.sh`). ______________________________________________________________________ diff --git a/.llm/workflows/README.md b/.llm/workflows/README.md index cb9be84f7..2b460acde 100644 --- a/.llm/workflows/README.md +++ b/.llm/workflows/README.md @@ -34,13 +34,13 @@ evidence that its intended behavior exists. ## Single-Source-of-Truth Rules -- Put universal priorities in `.llm/context.md`. +- Put universal priorities in `AGENTS.md`. - Put reusable procedures in `.llm/skills/`. - Put orchestration and gates here. - Put verified stable facts in `.llm/knowledge/`. - Keep task receipts out of source control unless a project document requires them. PR descriptions and CI artifacts are suitable receipt locations. -- Front-end adapters should link to `.llm/context.md`; generated adapters must +- Front-end adapters should load `AGENTS.md`; generated adapters must identify their canonical template and generator. Do not encode the same dispatch predicate in both prose and metadata. Metadata is diff --git a/.llm/workflows/evidence-driven-change.md b/.llm/workflows/evidence-driven-change.md index 7281bf9f3..4428e945e 100644 --- a/.llm/workflows/evidence-driven-change.md +++ b/.llm/workflows/evidence-driven-change.md @@ -47,7 +47,7 @@ record why and provide the strongest available differential evidence. ## 4. Implement Make the smallest complete change within the accepted scope. Preserve the -priority hierarchy in `.llm/context.md`. The implementer owns production changes +priority hierarchy in `AGENTS.md`. The implementer owns production changes and fixes; reviewers report findings and do not silently expand scope. ## 5. Green Gate @@ -57,7 +57,7 @@ Use [change-path-verification](../skills/change-path-verification/SKILL.md) and observation and prove it now passes. Run risk-selected targeted checks, then every applicable repository closure gate. Behavior or CI changes require the build, full tests, formatting, applicable reference-Lua comparison, and PR CI -described in `.llm/context.md`. Mark an irrelevant gate `N/A` with a concrete +described in [the shared policy](../../AGENTS.md). Mark an irrelevant gate `N/A` with a concrete semantic-risk rationale; report unavailable applicable gates as unrun residual risk. diff --git a/.mcp.json b/.mcp.json index 5b81add2a..f310912bd 100644 --- a/.mcp.json +++ b/.mcp.json @@ -5,8 +5,34 @@ "transport": "http", "url": "https://api.githubcopilot.com/mcp/", "headers": { - "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" + "Authorization": "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}", + "X-MCP-Readonly": "true" } + }, + "zai-vision": { + "type": "stdio", + "transport": "stdio", + "command": "zai-mcp-vision", + "args": [], + "env": { "ZAI_API_KEY": "${ZAI_API_KEY}" } + }, + "zai-web-search": { + "type": "http", + "transport": "http", + "url": "https://api.z.ai/api/mcp/web_search_prime/mcp", + "headers": { "Authorization": "Bearer ${ZAI_API_KEY}" } + }, + "zai-web-reader": { + "type": "http", + "transport": "http", + "url": "https://api.z.ai/api/mcp/web_reader/mcp", + "headers": { "Authorization": "Bearer ${ZAI_API_KEY}" } + }, + "zai-zread": { + "type": "http", + "transport": "http", + "url": "https://api.z.ai/api/mcp/zread/mcp", + "headers": { "Authorization": "Bearer ${ZAI_API_KEY}" } } } } diff --git a/.vscode/mcp.json b/.vscode/mcp.json index 3cac80046..f3ebbf09e 100644 --- a/.vscode/mcp.json +++ b/.vscode/mcp.json @@ -2,7 +2,32 @@ "servers": { "github-mcp-server": { "type": "http", - "url": "https://api.githubcopilot.com/mcp/" + "url": "https://api.githubcopilot.com/mcp/", + "headers": { + "Authorization": "Bearer ${env:GITHUB_PERSONAL_ACCESS_TOKEN}", + "X-MCP-Readonly": "true" + } + }, + "zai-vision": { + "type": "stdio", + "command": "zai-mcp-vision", + "args": [], + "env": { "ZAI_API_KEY": "${env:ZAI_API_KEY}" } + }, + "zai-web-search": { + "type": "http", + "url": "https://api.z.ai/api/mcp/web_search_prime/mcp", + "headers": { "Authorization": "Bearer ${env:ZAI_API_KEY}" } + }, + "zai-web-reader": { + "type": "http", + "url": "https://api.z.ai/api/mcp/web_reader/mcp", + "headers": { "Authorization": "Bearer ${env:ZAI_API_KEY}" } + }, + "zai-zread": { + "type": "http", + "url": "https://api.z.ai/api/mcp/zread/mcp", + "headers": { "Authorization": "Bearer ${env:ZAI_API_KEY}" } } } } diff --git a/AGENTS.md b/AGENTS.md index f22316c1e..3e13c64cc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,40 +1,19 @@ -# NovaSharp AI Assistant Guidelines +# NovaSharp engineering policy -**Complete documentation: [`.llm/context.md`](.llm/context.md)** - -## Quick Reference - -| Priority | Concern | Never Sacrifice For Lower Priority | -| -------------- | ---------------------- | ---------------------------------- | -| 1. CORRECTNESS | Lua Spec Compliance | Performance, memory, clarity | -| 2. SPEED | Runtime Performance | Memory, clarity | -| 3. MEMORY | Minimal Allocations | Clarity | -| 4. UNITY | Platform Compatibility | Clarity | -| 5. CLARITY | Maintainability | - | - -## Critical Rules - -1. **Scoped Git Operations Allowed When Requested** - If the user asks for commits, pushes, or PR/CI work, agents may run `git add`, `git commit`, and `git push` after reviewing the diff. Use small scoped commits and never use destructive git commands unless explicitly requested. -1. **NEVER use absolute paths** - Relative paths from repo root only -1. **Do not discard diagnostic output in ad-hoc commands** - Repo helper scripts may intentionally quiet noisy tools, but failures must surface actionable output. -1. **Lua Spec = Source of Truth** - Fix NovaSharp, never tests -1. **No Legacy Host API Compatibility** - Freely improve or remove public APIs; update repository-owned callers atomically and do not add shims, obsolete aliases, migration adapters, deprecation windows, or other legacy API layers. Lua-version behavior and supported-platform compatibility remain required. -1. **Pre-Commit Validation Allowed** - `bash ./scripts/dev/pre-commit.sh` is expected before commits and may restage files it auto-formats or regenerates. -1. **No false green-lighting** - Only say `green`, `verified`, `passes`, or `complete` after the exact local checks and PR CI were observed passing. Otherwise report the check as `not run` or failing residual risk. -1. **Session length target: under 2 hours** - Scope each session to one shippable, green PR covering a falsifiable slice; hand off remainders via `PLAN.md`, `progress/`, and issues instead of over-running. See [`.llm/skills/plan-maintenance/SKILL.md`](.llm/skills/plan-maintenance/SKILL.md). -1. **Mandatory post-work improvement gate** - After every large change or investigation, and before declaring it complete, follow [`.llm/skills/post-work-reflection/SKILL.md`](.llm/skills/post-work-reflection/SKILL.md). Fix discovered defects, capture reusable techniques or durable knowledge in the appropriate `.llm` artifact, and obtain an independent review when agents are available. - -## Build & Test +1. Preserve exact Lua 5.1–5.5 behavior first, then runtime speed, allocations, Unity compatibility (Mono and IL2CPP/AOT), and clarity, in that order. Resolve semantic disputes with the matching reference Lua. Fix the implementation when it differs from the oracle. +1. Host APIs may change. Update repository-owned callers atomically and remove superseded APIs without compatibility shims. +1. Use repository-relative paths. Preserve actionable diagnostics. Investigate every test failure. +1. Scope material work to one falsifiable slice targeting a shippable PR in under two hours. Record unfinished work in the [execution queue](PLAN.md). +1. For material changes, follow the [evidence-driven workflow](.llm/workflows/evidence-driven-change.md). Always add both C# tests and Lua fixtures and regenerate the corpus when adding either C# or Lua regression coverage or changing runtime or interop code. At the top of each fixture use only the hand-authored tags `@lua-versions`, `@novasharp-only`, and `@expects-error`. Run tests across Lua 5.1–5.5. Compare Lua behavior changes against the matching reference interpreters. +1. Run builds and tests through the quick scripts. Before closing behavior or CI changes, run focused checks, the quick build, full quick tests, formatting, and applicable Lua comparisons. Poll PR CI through success or diagnosis. Claim overall success only after observing all required local and PR checks pass. Identify every unrun or failing gate. +1. When commits, pushes, or PR work are requested, review the diff and use small scoped commits. Run `bash ./scripts/dev/pre-commit.sh` before committing (it may format and restage files). Destructive Git operations require an explicit request. +1. After material changes or investigations, apply [post-work reflection](.llm/skills/post-work-reflection/SKILL.md) and seek independent review when available. ```bash -./scripts/build/quick.sh # Build interpreter -./scripts/test/quick.sh # Run all tests -./scripts/test/quick.sh Floor # Filter by pattern +./scripts/build/quick.sh # Interpreter build; use --all for the full solution +./scripts/test/quick.sh # Full tests +./scripts/test/quick.sh Floor # Filter by method ./scripts/test/quick.sh -c Math # Filter by class ``` -Before closing behavior or CI work, run the relevant targeted tests, `./scripts/build/quick.sh`, `./scripts/test/quick.sh`, formatting, Lua comparison when behavior changes, then poll PR CI until green or document the newly diagnosed failure. - -## Skills - -See [`.llm/skills/`](.llm/skills/) for task-specific guides. +For source locations, project conventions, or skill discovery, consult the [repository guide](.llm/context.md). diff --git a/CLAUDE.md b/CLAUDE.md index 1aebc4010..43c994c2d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,49 +1 @@ -# CLAUDE.md - -**Complete documentation: [`.llm/context.md`](.llm/context.md)** - -## Quick Reference - -| Priority | Concern | Never Sacrifice For Lower Priority | -| -------------- | ---------------------- | ---------------------------------- | -| 1. CORRECTNESS | Lua Spec Compliance | Performance, memory, clarity | -| 2. SPEED | Runtime Performance | Memory, clarity | -| 3. MEMORY | Minimal Allocations | Clarity | -| 4. UNITY | Platform Compatibility | Clarity | -| 5. CLARITY | Maintainability | - | - -## Critical Rules - -1. **Scoped Git Operations Allowed When Requested** - If the user asks for commits, pushes, or PR/CI work, agents may run `git add`, `git commit`, and `git push` after reviewing the diff. Use small scoped commits and never use destructive git commands unless explicitly requested. -1. **NEVER use absolute paths** - Relative paths from repo root only -1. **Do not discard diagnostic output in ad-hoc commands** - Repo helper scripts may intentionally quiet noisy tools, but failures must surface actionable output. -1. **Lua Spec = Source of Truth** - Fix NovaSharp, never tests -1. **Multi-Version Testing** - All tests run on Lua 5.1-5.5 -1. **Lua Fixture Metadata** - ONLY `@lua-versions`, `@novasharp-only`, `@expects-error` -1. **Pre-Commit Validation Allowed** - `bash ./scripts/dev/pre-commit.sh` is expected before commits and may restage files it auto-formats or regenerates. -1. **No false green-lighting** - Only say `green`, `verified`, `passes`, or `complete` after the exact local checks and PR CI were observed passing. Otherwise report the check as `not run` or failing residual risk. -1. **Mandatory post-work improvement gate** - After every large change or investigation, and before declaring it complete, follow [`.llm/skills/post-work-reflection/SKILL.md`](.llm/skills/post-work-reflection/SKILL.md). Fix discovered defects, capture reusable techniques or durable knowledge in the appropriate `.llm` artifact, and obtain an independent review when agents are available. - -## Build & Test - -```bash -./scripts/build/quick.sh # Build interpreter -./scripts/build/quick.sh --all # Build full solution -./scripts/test/quick.sh # Run all tests -./scripts/test/quick.sh Floor # Filter by method pattern -./scripts/test/quick.sh -c Math # Filter by class -./scripts/test/quick.sh -c Math -m Floor # Combined filter -./scripts/test/quick.sh --no-build Floor # Skip build -``` - -Do NOT use raw `dotnet build` or `dotnet test` - use quick scripts. -Before closing behavior or CI work, run the relevant targeted tests, `./scripts/build/quick.sh`, `./scripts/test/quick.sh`, formatting, Lua comparison when behavior changes, then poll PR CI until green or document the newly diagnosed failure. - -## Skills - -See [`.llm/skills/`](.llm/skills/) for task-specific guides: - -- [correctness-then-performance](.llm/skills/correctness-then-performance/SKILL.md) - Priority hierarchy -- [high-performance-csharp](.llm/skills/high-performance-csharp/SKILL.md) - Zero-allocation patterns -- [tunit-test-writing](.llm/skills/tunit-test-writing/SKILL.md) - Writing tests -- [lua-fixture-creation](.llm/skills/lua-fixture-creation/SKILL.md) - Creating .lua fixtures +@AGENTS.md diff --git a/GOAL.md b/GOAL.md new file mode 100644 index 000000000..c2e7fbfed --- /dev/null +++ b/GOAL.md @@ -0,0 +1,75 @@ +# Goal + +Advance [PLAN.md](PLAN.md) through a green PR and merge it. + +## Objective + +- Carry forward any in-progress work. +- Address any [Open Issues](https://github.com/wallstop/NovaSharp/issues), paginated, to get a full list. If you only get 50, you have not gotten everything, ordered by most-gameplay impacting first. +- Drive any open dependency to green (incorporate) if relevant. +- Ensure main CI is green; if it is not, RCA the issue and implement a comprehensive fix. +- See if there were any draft/in-progress PRs from previous sessions and drive those to completion. +- Drive `PLAN.md` improvements as far forward as possible towards accomplishing the full work for the next achievable milestone(s) - do not over-scope, keep the target goal within reason. Then, open a PR that achieves a fully green state (all CI checks passing, all reviewer feedback addressed), then merge it. Do not explicitly trigger reviews. +- Aggregate all of one session's work into one PR, do not stack PRs. +- Prefer vscode's github connector extension, then git, then gh for github interactions. Do not change org policies. We have reader and write apps available. +- Open detailed issues for any issues or follow-up items. + +## API Evolution Policy + +- Treat NovaSharp as pre-adoption: there are no external consumers whose host API + compatibility must be preserved. +- Freely rename, move, redesign, or remove public APIs when doing so improves Lua + correctness, performance, memory use, Unity support, or the resulting API. +- Do not add or retain legacy APIs, compatibility shims, forwarding wrappers, + obsolete aliases, migration adapters, or deprecation windows. Update all + repository-owned callers, tests, samples, tooling, and documentation atomically. +- This freedom applies to NovaSharp's host-facing APIs. It does not relax exact Lua + version behavior or supported-platform compatibility requirements. + +## Work Style + +- **Task-based, red-green, data-backed, exploratory, science-driven.** +- **Session length target: under 2 hours.** Scope each session to one shippable + PR that completes a falsifiable slice (see [plan-maintenance](.llm/skills/plan-maintenance/SKILL.md)). + If the remaining work cannot finish in time, stop at a green checkpoint and + hand off through `PLAN.md`, `progress/`, and issues instead of over-running. +- Commit and push freely. Small, coherent commits. +- Address all non-trivial reviewer feedback and CI failures before moving to the next task. +- When CodeRabbit reports a rate limit, proceed with the merge as soon as CI passes on the final commit and all actionable review feedback is addressed. If an earlier CodeRabbit change request still blocks the merge, verify its fixes, resolve its threads, and dismiss that review with links to the fixes and validation. + +## Fix Philosophy + +| Failure type | Fix target | +| --------------------------- | -------------------- | +| Production bug | Production code | +| Test bug | Test code | +| Fragile / unnecessary check | Remove or rewrite it | + +- Prefer **data-driven tests** over repeated similar test cases. +- Add **diagnostics** when an issue is hard to understand without them. +- When a bug is found, **sweep the codebase** for the same class of problem and fix all affected paths. +- **Simplify aggressively.** Do not add tests, scripts, or abstractions unless they prevent a real, recurring issue. + +## Quality Bar + +Every change must be: + +- **Robust and reliable** not fragile or coupled to implementation details. +- **Complete** the whole class of problem is addressed, not just the one example. +- **Non-bloating** no unnecessary files, tests, or scaffolding. + +Target: consensus among all reviewers that the result needs zero revisions. + +## Progress Tracking + +- Log work in `progress/session-NNN-brief-description.md` (literal `progress/` at repo root). +- Unified formatting; descriptive names for easy discovery. +- Keep `PLAN.md` current: remove completed or obsolete items after each session. + +## Sub-agent Loop + +1. Use sub-agents for parallel or specialized work. +1. After a sub-agent completes, have an **adversarial sub-agent** review it critically. +1. If recommendations exist, have another sub-agent evaluate and implement them. +1. Repeat until all sub-agents agree the result is exceptional with zero issues (minor or otherwise). +1. If not using sub-agents, apply this adversarial review loop on the main thread. diff --git a/PLAN.md b/PLAN.md index 13c8fdaee..0963b688b 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1,18 +1,18 @@ # NovaSharp Plan This file is the execution queue. Repository priorities and closure gates live in -[`.llm/context.md`](.llm/context.md); planning rules — including the under-2-hour +[`AGENTS.md`](AGENTS.md); planning rules — including the under-2-hour session scoping target — live in the [plan-maintenance skill](.llm/skills/plan-maintenance/SKILL.md). Design evidence belongs in domain documentation, completed work in `progress/`, and the full -backlog in [GitHub issues](https://github.com/wallstop/NovaSharp/issues). +backlog in [GitHub issues](https://github.com/Ambiguous-Interactive/NovaSharp/issues). ## Now 1. Advance Phase A5 call paths in - [#108](https://github.com/wallstop/NovaSharp/issues/108): + [#108](https://github.com/Ambiguous-Interactive/NovaSharp/issues/108): - Migrate each remaining legacy CoreLib registration in its own scoped change: - Table, Load, Utf8, OsSystem, StringPack, MetaTable, ErrorHandling, + Load, Utf8, OsSystem, StringPack, MetaTable, ErrorHandling, TableIterators, OsTime, Json, and Dynamic. - Add the return-buffer writer and confine tuple arrays to escaped varargs or multi-return values. @@ -24,8 +24,8 @@ backlog in [GitHub issues](https://github.com/wallstop/NovaSharp/issues). after warmup, `new Script()` retains less than 100 KiB, and coroutine create/resume is near-zero allocation. 1. Close the post-`LuaValue` table measurements in - [#93](https://github.com/wallstop/NovaSharp/issues/93), then ratchet the hosted - allocation baseline in [#92](https://github.com/wallstop/NovaSharp/issues/92). + [#93](https://github.com/Ambiguous-Interactive/NovaSharp/issues/93), then ratchet the hosted + allocation baseline in [#92](https://github.com/Ambiguous-Interactive/NovaSharp/issues/92). 1. Finish the [B1 source-generator MVP](docs/proposals/roslyn-hardwire-generator.md): async suspension output, the NS0002 code fix after adapter contracts settle, @@ -49,7 +49,7 @@ backlog in [GitHub issues](https://github.com/wallstop/NovaSharp/issues). 1. A4.5: evaluate table-field inline caches, specialized arithmetic, fast builtins, and safe global-import caching independently against the scoreboard. 1. A6/A7: profile strings and cold compilation, including the cached-compilation - work tracked in [#118](https://github.com/wallstop/NovaSharp/issues/118), then + work tracked in [#118](https://github.com/Ambiguous-Interactive/NovaSharp/issues/118), then optimize only measured bottlenecks; exit with string-heavy workloads within 2–3x of native Lua, cold `LoadString` within 5–10x, and cold-load allocations reduced at least 5x. Do not rewrite the parser without a demonstrated loading @@ -59,6 +59,7 @@ backlog in [GitHub issues](https://github.com/wallstop/NovaSharp/issues). ## Later or gated +1. Run the [paired agent guidance pilot](tools/LlmSkillIndexer/pilot.md) once authenticated, isolated sessions are available for all three frontends. Require held-out task correctness before adopting further skill consolidations. 1. B3/B4: async/coroutine hosting, capability-based mod isolation, deterministic providers, hot reload, supply-chain controls, and a Unity mod-host sample; close the remaining [sandbox threat-model](docs/security/sandbox-threat-model.md) @@ -72,10 +73,12 @@ backlog in [GitHub issues](https://github.com/wallstop/NovaSharp/issues). Lua-CSharp; evaluate the gated [stackless/fuel model](docs/proposals/runtime-research-gates.md#stacklessfuel-execution-model) in the same study. -1. Lua parity backlog: [call-context error names](https://github.com/wallstop/NovaSharp/issues/124), - [optional-argument validation](https://github.com/wallstop/NovaSharp/issues/125), - [residual number/string parity nits](https://github.com/wallstop/NovaSharp/issues/138), - other error formats, [Lua 5.5 const loop-variable enforcement](https://github.com/wallstop/NovaSharp/issues/130), +1. Lua parity backlog: [call-context error names](https://github.com/Ambiguous-Interactive/NovaSharp/issues/124), + [optional-argument validation](https://github.com/Ambiguous-Interactive/NovaSharp/issues/125), + [residual number/string parity nits](https://github.com/Ambiguous-Interactive/NovaSharp/issues/138), + [table library exports](https://github.com/Ambiguous-Interactive/NovaSharp/issues/159), + [table.insert arity and results](https://github.com/Ambiguous-Interactive/NovaSharp/issues/160), + other error formats, [Lua 5.5 const loop-variable enforcement](https://github.com/Ambiguous-Interactive/NovaSharp/issues/130), `__gc`, Lua 5.4 garbage collector options, version-migration docs, and explicit compatibility-version matrix coverage; retain the [host-GC and byte-fidelity constraints](docs/proposals/runtime-research-gates.md#host-gc-and-string-fidelity). diff --git a/docs/Contributing.md b/docs/Contributing.md index a0d241137..3c05af60a 100644 --- a/docs/Contributing.md +++ b/docs/Contributing.md @@ -4,7 +4,7 @@ This project keeps the build/test tooling and documentation in lockstep. Use thi ## Environment & Tooling -- Install the .NET SDK pinned by `global.json` (currently 9.0.100 with latest-minor roll-forward). +- Install the .NET SDK pinned by `global.json` (currently 10.0.100 with latest-minor roll-forward). - Install Python 3.10+ (CI uses 3.12) and restore the shared tooling dependencies once per clone: ```bash python -m pip install -r requirements.tooling.txt @@ -22,8 +22,11 @@ This project keeps the build/test tooling and documentation in lockstep. Use thi - Full solution build: `dotnet build src/NovaSharp.sln -c Release` - Interpreter-only build: `dotnet build src/runtime/WallstopStudios.NovaSharp.Interpreter/WallstopStudios.NovaSharp.Interpreter.csproj` -- Interpreter tests (Release):\ - `dotnet test src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj -c Release -- --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx` +- Interpreter tests (Release): `./scripts/test/quick.sh` + +To inspect a built assembly, run `dotnet tool run ilspycmd -- path/to/assembly.dll`. +The manifest selects the managed ILSpy package so the command also runs on Debian 12. +The native Linux x64 package requires glibc 2.38 or later. ## Coverage diff --git a/docs/Testing.md b/docs/Testing.md index 9a0c12647..7c35d7171 100644 --- a/docs/Testing.md +++ b/docs/Testing.md @@ -11,7 +11,9 @@ NovaSharp ships with a comprehensive test suite that blends historical Lua fixtu ## Running the Tests Locally ```bash -dotnet test src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj -c Release -- --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx +DOTNET_ROLL_FORWARD=Major dotnet test \ + --project src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj \ + -c Release --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx ``` - Produces a standards-based TRX file under `TestResults/` (or the supplied `--results-directory`) so failures can be inspected with the test explorer of your choice. @@ -19,9 +21,9 @@ dotnet test src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Wallstop ### Microsoft.Testing.Platform runner -- `global.json` pins `test.runner` to `Microsoft.Testing.Platform`, so every `dotnet test` invocation must pass an explicit target path, solution, or test module. Use the positional project path shown above; test-platform options still go after the `--` separator. +- The .NET 10 SDK selects Microsoft.Testing.Platform through `global.json`. Use `--project` when selecting a test project from the repository root and pass runner options directly to `dotnet test`. - The interpreter TUnit suite completes quickly on a many-core workstation; expect a slower first run when a clean build is required because the Microsoft.Testing.Platform entry point is re-generated. -- Visual Studio and Rider inherit the same configuration because the runner is set in `global.json`; if a local command fails with “VSTest target is no longer supported”, re-run it with the explicit target path shown above so the Microsoft.Testing.Platform mode is engaged. +- IDEs that honor the SDK test runner configuration use the Microsoft.Testing.Platform setting in `global.json`. ### TUnit-first policy @@ -59,9 +61,7 @@ bash ./scripts/build/build.sh pwsh ./scripts/coverage/coverage.ps1 ``` -- If the host only has .NET 9 installed (common on new Ubuntu images), set `DOTNET_ROLL_FORWARD=Major` when invoking the script (PowerShell or Bash) so the .NET 9 runtime can execute the net8.0 testhost. - -- Restores local tools, builds the solution in Release, and drives `dotnet test` through the `coverlet.console` wrapper so the TUnit suites execute exactly as they do in CI. +- Restores local tools, builds the solution in Release, and runs the TUnit test application through the `coverlet.console` wrapper. - Emits LCOV, Cobertura, and OpenCover artefacts under `artifacts/coverage`, with the TRX test logs in `artifacts/coverage/test-results`. @@ -69,7 +69,7 @@ pwsh ./scripts/coverage/coverage.ps1 - Pass `-SkipBuild` to reuse existing binaries and `-Configuration Debug` to collect non-Release stats. -- On macOS/Linux without PowerShell, run `bash ./scripts/coverage/coverage.sh` (identical flags/behaviour). Both scripts automatically set `DOTNET_ROLL_FORWARD=Major` when it isn’t already defined so .NET 9 runtimes can execute the net8.0 testhost; override the variable if you need different roll-forward behaviour. +- On macOS/Linux without PowerShell, run `bash ./scripts/coverage/coverage.sh` (identical flags/behaviour). Both scripts automatically set `DOTNET_ROLL_FORWARD=Major` when it isn’t already defined so newer .NET runtimes can execute the .NET 8 test host. Set the variable explicitly to use a different roll-forward policy. - Both coverage helpers honour gating settings: set `COVERAGE_GATING_MODE` to `monitor` (warn) or `enforce` (fail), and override the per-metric targets via `COVERAGE_GATING_TARGET_LINE`, `COVERAGE_GATING_TARGET_BRANCH`, and `COVERAGE_GATING_TARGET_METHOD`. CI now exports `COVERAGE_GATING_MODE=enforce` with **80 % line / 80 % branch / 80 % method** thresholds so coverage dips fail fast; set the mode to `monitor` locally if you need a warning-only rehearsal. To mirror the enforced gate (the default in CI), export the same settings before rerunning the script: @@ -191,7 +191,8 @@ Validation checklist: ```powershell dotnet build src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/WallstopStudios.NovaSharp.VsCodeDebugger.csproj -c Release -nologo dotnet build src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/WallstopStudios.NovaSharp.RemoteDebugger.csproj -c Release -nologo -dotnet test src/tests/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit.csproj -c Release --filter "FullyQualifiedName~RemoteDebugger" +$env:DOTNET_ROLL_FORWARD = 'Major' +dotnet test --project src/tests/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit/WallstopStudios.NovaSharp.RemoteDebugger.Tests.TUnit.csproj -c Release ``` Document new suppressions or analyzer exclusions in the closest authoritative analyzer documentation (with the CA rule, justification, and follow-up owner) before merging. diff --git a/docs/audits/documentation_audit.log b/docs/audits/documentation_audit.log index 0a962f3da..4e57cc3d2 100644 --- a/docs/audits/documentation_audit.log +++ b/docs/audits/documentation_audit.log @@ -10,20 +10,20 @@ Found 185 undocumented public/internal type declarations. - src/runtime/WallstopStudios.NovaSharp.Interpreter/CompiledScript.cs - line 621: missing XML docs for `ExecuteValues()` - src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/DebugModule.cs - - line 1620: missing XML docs for `Value` - - line 1625: missing XML docs for `Function` - - line 1626: missing XML docs for `Mask` - - line 1627: missing XML docs for `Count` - - line 1640: missing XML docs for `Upvalue` - - line 1642: missing XML docs for `ReferenceId` - - line 1644: missing XML docs for `ToString()` - - line 1655: missing XML docs for `Name` - - line 1657: missing XML docs for `Type` - - line 1659: missing XML docs for `TryIndex()` - - line 1671: missing XML docs for `SetIndex()` - - line 1682: missing XML docs for `AsString()` - - line 1692: missing XML docs for `TryMetaIndex()` - - line 1698: missing XML docs for `IsTypeCompatible()` + - line 1617: missing XML docs for `Value` + - line 1622: missing XML docs for `Function` + - line 1623: missing XML docs for `Mask` + - line 1624: missing XML docs for `Count` + - line 1637: missing XML docs for `Upvalue` + - line 1639: missing XML docs for `ReferenceId` + - line 1641: missing XML docs for `ToString()` + - line 1652: missing XML docs for `Name` + - line 1654: missing XML docs for `Type` + - line 1656: missing XML docs for `TryIndex()` + - line 1668: missing XML docs for `SetIndex()` + - line 1679: missing XML docs for `AsString()` + - line 1689: missing XML docs for `TryMetaIndex()` + - line 1695: missing XML docs for `IsTypeCompatible()` - src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/IO/FileUserDataDescriptor.cs - line 22: missing XML docs for `Name` - line 24: missing XML docs for `Type` @@ -105,8 +105,8 @@ Found 185 undocumented public/internal type declarations. - line 281: missing XML docs for `GetStatistics()` - line 286: missing XML docs for `Trim()` - src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/CallbackFunction.cs - - line 24: missing XML docs for `class SharedState` - - line 26: missing XML docs for `AdditionalData` + - line 25: missing XML docs for `class SharedState` + - line 27: missing XML docs for `AdditionalData` - src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/Closure.cs - line 459: missing XML docs for `CallValues()` - src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/Coroutine.cs @@ -157,9 +157,9 @@ Found 185 undocumented public/internal type declarations. - src/runtime/WallstopStudios.NovaSharp.Interpreter/Script.cs - line 626: missing XML docs for `BeginDefaultOptionsScope()` - line 734: missing XML docs for `RegisterCoroutineForMemoryStatistics()` - - line 4817: missing XML docs for `GetTrackedCoroutineCountForMemoryStatisticsForTests()` - - line 4825: missing XML docs for `GetEstimatedScriptRetainedBytesForMemoryStatisticsForTests()` - - line 4952: missing XML docs for `Dispose()` + - line 4811: missing XML docs for `GetTrackedCoroutineCountForMemoryStatisticsForTests()` + - line 4819: missing XML docs for `GetEstimatedScriptRetainedBytesForMemoryStatisticsForTests()` + - line 4946: missing XML docs for `Dispose()` - src/runtime/WallstopStudios.NovaSharp.Interpreter/Utilities/OneOf/FastOneOf2.cs - line 198: missing XML docs for `FromT0()` - line 211: missing XML docs for `FromT1()` @@ -210,15 +210,15 @@ Found 185 undocumented public/internal type declarations. - line 110: missing XML docs for `DeleteFile()` - line 112: missing XML docs for `MoveFile()` - line 114: missing XML docs for `ExecuteCommand()` - - line 212: missing XML docs for `ExitFast()` - - line 252: missing XML docs for `class Program` - - line 393: missing XML docs for `Main()` - - line 1058: missing XML docs for `CanRead` - - line 1060: missing XML docs for `CanSeek` - - line 1062: missing XML docs for `CanWrite` - - line 1064: missing XML docs for `Length` - - line 1072: missing XML docs for `Flush()` - - line 1074: missing XML docs for `Write()` - - line 1079: missing XML docs for `Read()` - - line 1084: missing XML docs for `Seek()` - - line 1089: missing XML docs for `SetLength()` + - line 211: missing XML docs for `ExitFast()` + - line 251: missing XML docs for `class Program` + - line 392: missing XML docs for `Main()` + - line 1057: missing XML docs for `CanRead` + - line 1059: missing XML docs for `CanSeek` + - line 1061: missing XML docs for `CanWrite` + - line 1063: missing XML docs for `Length` + - line 1071: missing XML docs for `Flush()` + - line 1073: missing XML docs for `Write()` + - line 1078: missing XML docs for `Read()` + - line 1083: missing XML docs for `Seek()` + - line 1088: missing XML docs for `SetLength()` diff --git a/docs/audits/naming_audit.log b/docs/audits/naming_audit.log index bf7c2d327..e2113cb5c 100644 --- a/docs/audits/naming_audit.log +++ b/docs/audits/naming_audit.log @@ -6,7 +6,7 @@ All inspected files/types follow naming expectations (PascalCase for types/metho ## Namespace Prefix Summary -- WallstopStudios.NovaSharp: 770 (96.37% of 799) -- NovaSharp: 26 (3.25% of 799) -- : 3 (0.38% of 799) -- : 799 \ No newline at end of file +- WallstopStudios.NovaSharp: 772 (96.38% of 801) +- NovaSharp: 26 (3.25% of 801) +- : 3 (0.37% of 801) +- : 801 \ No newline at end of file diff --git a/docs/audits/spelling_audit.log b/docs/audits/spelling_audit.log index 492a8bc98..fa4d02a51 100644 --- a/docs/audits/spelling_audit.log +++ b/docs/audits/spelling_audit.log @@ -2,7 +2,7 @@ _Generated via tools/SpellingAudit/spelling_audit.py_ -Scan targets: .agents, .claude, .claudeignore, .codex, .codexignore, .config, .csharpierignore, .cursorrules, .devcontainer, .dockerignore, .editorconfig, .gitattributes, .githooks, .github, .gitignore, .llm, .markdown-link-check.json, .mcp.json, .opencode, .vscode, .yamllint.yml, _config.yml, AGENTS.md, CLAUDE.md, csharpier.json, Directory.Build.props, Directory.Build.targets, docs, global.json, LICENSE, opencode.json, PLAN.md, progress, README.md, requirements.tooling.txt, scripts, src, tools +Scan targets: .agents, .claude, .claudeignore, .codex, .codexignore, .config, .csharpierignore, .cursorrules, .devcontainer, .dockerignore, .editorconfig, .env.local.example, .gitattributes, .githooks, .github, .gitignore, .llm, .markdown-link-check.json, .mcp.json, .opencode, .vscode, .yamllint.yml, _config.yml, AGENTS.md, CLAUDE.md, csharpier.json, Directory.Build.props, Directory.Build.targets, docs, global.json, GOAL.md, LICENSE, opencode.json, PLAN.md, progress, README.md, requirements.tooling.txt, scripts, src, tools Skip globs: .git, .git/*, .git\*, .vs, .vs/*, .vs\*, src/.vs, src/.vs/*, src\.vs\*, artifacts, artifacts/*, artifacts\*, docs/coverage, docs/coverage/*, docs\coverage, docs\coverage\*, docs/testing/lua-error-ratchet.json, docs\testing\lua-error-ratchet.json, build, coverage-html.tgz, *.dll, *.exe, *.bin, *.pdb, *.obj, *.lock, *.log, *.vsidx, *.png, *.jpg, *.jpeg, *.gif, *.bmp, *.ico, *.svg, *.ttf, *.woff, *.woff2, *.eot, *.pdf, *.zip, *.tar, *.tar.gz, *.tgz, *.gz, *.7z, *.nupkg, *.luac, *.snap, src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/Resources/theme.css, src\debuggers\WallstopStudios.NovaSharp.RemoteDebugger\Resources\theme.css, */bin/*, *\bin\*, */obj/*, *\obj\*, */packages/*, *\packages\* Allowlisted words: Lua, LuaJIT, NovaSharp, userdata, metatable, metatables, NuGet, Interop, interop, alo, isnt, aNumber, aString, anObject, anArray, aNegativeNumber, afterAll, abd, Hel, varN diff --git a/docs/testing/real-world-scripts.md b/docs/testing/real-world-scripts.md index afe6e75c3..fc9473a07 100644 --- a/docs/testing/real-world-scripts.md +++ b/docs/testing/real-world-scripts.md @@ -21,7 +21,7 @@ NovaSharp executes a curated set of third-party Lua scripts to spot regressions - Add new scripts under `src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/Fixtures/RealWorld/` with the upstream `LICENSE`. - Extend `RealWorldScriptTests` with a descriptive `TestCaseData` entry that exercises a behaviour NovaSharp must support. - Update the table above (and `docs/ThirdPartyLicenses.md`) with the script name, tag/commit, license, and source URL. -- Re-run `dotnet test src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.csproj -c Release --filter RealWorld` after every corpus change. +- Re-run `./scripts/test/quick.sh -c RealWorld` after every corpus change. ## Completed Setup diff --git a/global.json b/global.json index bbd55e413..c93bc05eb 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "9.0.100", + "version": "10.0.100", "rollForward": "latestMinor", "allowPrerelease": false }, diff --git a/opencode.json b/opencode.json index 90243b14d..e12c0f785 100644 --- a/opencode.json +++ b/opencode.json @@ -2,10 +2,7 @@ "$schema": "https://opencode.ai/config.json", "provider": { "zai-coding-plan": { - "options": { - "timeout": 300000, - "chunkTimeout": 45000 - } + "options": { "timeout": 300000, "chunkTimeout": 45000 } } }, "mcp": { @@ -15,8 +12,36 @@ "enabled": true, "oauth": false, "headers": { - "Authorization": "Bearer {env:GITHUB_PERSONAL_ACCESS_TOKEN}" + "Authorization": "Bearer {env:GITHUB_PERSONAL_ACCESS_TOKEN}", + "X-MCP-Readonly": "true" } + }, + "zai-vision": { + "type": "local", + "command": ["zai-mcp-vision"], + "enabled": true, + "environment": { "ZAI_API_KEY": "{env:ZAI_API_KEY}" } + }, + "zai-web-search": { + "type": "remote", + "url": "https://api.z.ai/api/mcp/web_search_prime/mcp", + "enabled": true, + "oauth": false, + "headers": { "Authorization": "Bearer {env:ZAI_API_KEY}" } + }, + "zai-web-reader": { + "type": "remote", + "url": "https://api.z.ai/api/mcp/web_reader/mcp", + "enabled": true, + "oauth": false, + "headers": { "Authorization": "Bearer {env:ZAI_API_KEY}" } + }, + "zai-zread": { + "type": "remote", + "url": "https://api.z.ai/api/mcp/zread/mcp", + "enabled": true, + "oauth": false, + "headers": { "Authorization": "Bearer {env:ZAI_API_KEY}" } } } } diff --git a/progress/session-187-devcontainer-nuget-volume-ownership.md b/progress/session-187-devcontainer-nuget-volume-ownership.md new file mode 100644 index 000000000..3fd799acf --- /dev/null +++ b/progress/session-187-devcontainer-nuget-volume-ownership.md @@ -0,0 +1,64 @@ +# Session 187: Devcontainer NuGet volume ownership + +## Goal + +Make devcontainer startup reliable for fresh checkouts and existing NuGet +volumes. Keep the GitHub and Z.ai integrations optional and their credentials +out of image layers, shell traces, and unrelated MCP child processes. Validate +the startup paths and land the change through PR CI. Track the Docker-backed +regression harness in [#150](https://github.com/wallstop/NovaSharp/issues/150). + +## Root cause + +`devcontainer.json` mounts the `novasharp-nuget-cache` named volume at +`/home/vscode/.nuget`, but the image did not create that path. Docker initializes +an empty named volume from the image only when the mount point exists; otherwise +it creates the volume as `root:root 0755`. Lifecycle commands run as `vscode`, so +NuGet could not create/read `~/.nuget/NuGet/NuGet.Config` and reported `Failed to +read NuGet.Config due to unauthorized access`. Both `onCreateCommand` and +`updateContentCommand` then retried a permanent permissions failure. + +## Fix + +Defense in depth, matching Docker's named-volume first-use semantics: + +- `.devcontainer/Dockerfile` now seeds `/home/vscode/.nuget` with `vscode` + ownership, so fresh volumes are initialized correctly. The devcontainer CLI's + UID-remap layer also chowns `/home/vscode`, so the seed survives + `updateRemoteUserUID`. +- `.devcontainer/ensure-nuget-cache.sh` repairs an existing volume whose mount + is not writable by the runtime user. It uses the dynamic UID/GID (not a + hardcoded `1000`), only escalates through `sudo -n` when needed, creates a + missing directory without privilege when `$HOME` is writable, and prints the + volume-recreation remediation when passwordless sudo or the mount is + unavailable. It is idempotent when the cache is healthy. +- The guard runs before every lifecycle step that invokes `dotnet`: + `on-create.sh`, `update-content.sh`, `post-create.sh`, and `post-start.sh`. +- `check-tooling-consistency.py` now enforces the image seed's `vscode` + ownership, the uncommented mount path, and command-position guard ordering. + `test-devcontainer-lifecycle.sh` covers healthy, repair, unreadable-config, + dynamic-UID, missing-directory-without-sudo, and denied-sudo paths. + +## MCP startup + +The host preflight generates a private runtime env file containing only the +configured GitHub and Z.ai keys. A checkout without credentials gets an empty +file. The old copy remains readable until the replacement is ready, so another +launch can consume it during preflight. An invalid input stops the current +launch. The Claude and Codex Z.ai wrappers bridge the affected remote servers +through stdio. Native GitHub requests continue to request read-only access. + +## Evidence + +- A temporary root-owned cache made real NuGet report unauthorized access. + Running the guard as UID 1000 restored access. The second guard run exited + silently without additional repair. +- Focused regression cases initially rejected credential-free startup and + accepted a directory in place of `NuGet.Config`. The fixes preserve optional + startup and diagnose the malformed cache before restore. +- A loopback MCP server received the synthetic authorization header through + `mcp-remote` 0.16.7. The fake token stayed out of its diagnostics and scratch + configuration files. +- The interpreter build and quick test suite succeeded (15,716 tests). +- Docker was unavailable for this session's local end-to-end startup test. + The container-level follow-up is tracked in [#150](https://github.com/wallstop/NovaSharp/issues/150). diff --git a/progress/session-188-windows-devcontainer-startup.md b/progress/session-188-windows-devcontainer-startup.md new file mode 100644 index 000000000..9d1370080 --- /dev/null +++ b/progress/session-188-windows-devcontainer-startup.md @@ -0,0 +1,56 @@ +# Session 188 — Windows devcontainer startup + +## Root causes + +- The Windows CLI passed drive-letter paths to WSL Bash. On the same checkout, + `bash -n` failed on the expanded script path and found the relative script. + The old lint test required the broken path literally. +- A synthetic run of the old preflight reported success after `chmod 600`. + WSL and Docker both saw mode `0777` on this NTFS mount. The native ACL still + granted local users read access, and Claude's credential reader required `0600`. +- Docker Desktop presented the checkout as root-owned. Git refused to operate + as `vscode`, including during hook installation. +- During a second clean creation, npm advertised `@openai/codex@0.172.0` + while its tarball returned HTTP 404 on five attempts. The creation hook + aborted even though the image already contained the tools. The same tarball + subsequently returned HTTP 200. + +## Changes + +The host hook uses the workspace working directory. Bash filters the two +optional credentials and publishes them with native access controls on Windows. +The managed Claude launchers read a project-specific Z.ai credential staged +on the container filesystem at creation. Git trusts the mounted checkout when +its ownership differs from the container user's. + +Creation and restart now share the bounded npm refresh. On registry failure, +startup checks all seven installed tools before continuing. Building a fresh +image still requires the requested packages. + +The Windows CI fixture launches the configured hook under a path containing +spaces and checks the native ACL. The opt-in Docker test covers the real +lifecycle and uses local MCP test doubles. See the [test instructions](../scripts/test/README.md). + +## Local evidence + +- Windows 11 build 26300, Dev Containers CLI `0.91.0`, Docker Desktop client + and engine `29.9.3`. Bash resolved to WSL on the reported launch. The native + ACL regression also ran under Git for Windows Bash. +- `devcontainer exec --workspace-folder . zsh -il` opened a PTY in the checkout + as `vscode`, with both the login and interactive shell options set. +- `python scripts/test/devcontainer-smoke.py --temp-parent .. --image novasharp-windows-smoke:session188` + exited zero on a Windows drive. The clean checkout restored the solution. + Recreating with synthetic keys repaired a root-owned NuGet volume and both + managed launchers delivered the expected key to local MCP doubles. The next + start preserved cache ownership. Recreating after key removal cleared the + Docker environment and the staged credential. Docker's exported build context + and the captured diagnostics contained no synthetic keys. +- `python scripts/test/devcontainer-smoke.py --temp-parent ..` repeated all four + lifecycle stages from a fresh image build after the npm fix and exited zero. + In a separate network-isolated container, a loopback npm registry advertised + a newer Codex release and returned 404 for its tarball. The actual npm client + exhausted its retries, the startup check exited zero, and the baked Codex + `0.171.0` still ran `--version` and `--help`. +- The Linux interpreter build and quick test suite completed with 15,716 tests + and zero failures. The Release solution build reported zero warnings and + errors. CSharpier checked 828 files. diff --git a/progress/session-190-agent-guidance.md b/progress/session-190-agent-guidance.md new file mode 100644 index 000000000..6ed405692 --- /dev/null +++ b/progress/session-190-agent-guidance.md @@ -0,0 +1,47 @@ +# Session 190 — Shared agent guidance + +The two root policies diverged on host API compatibility. The navigation guide +also recommended running the index generator to list skills. Against the old +files, both new discovery tests failed. Against the shared policy and read-only +inventory, all 21 indexer tests succeeded. The inventory matched the canonical +directories and preserved the index bytes. + +Claude imports the root policy. OpenCode and Codex use the same repository +policy and canonical skill tree. The upstream reference validator accepted all +32 packages and rejected a control missing its description. Repository metadata +and index freshness remain separate checks. + +On the initial candidate (`eac0f9dd`), the root policy changed from 3,201 to 2,044 bytes and the optional repository +guide from 14,060 to 4,534 bytes (LF). These are file measurements. Session +token consumption and task success require paired frontend runs. + +The [Agent Skills specification](https://agentskills.io/specification) informed +the distinction between package validation and discovery. The +[upstream evaluation guide](https://agentskills.io/skill-creation/evaluating-skills) +informed paired task grading. Keep the current set of skills until held-out +outcomes justify changing their triggers or grouping. + +The quick build succeeded and the full quick suite reported 15,716 successful +tests. Across baseline and candidate, OpenCode 1.19.6 and Claude +Code 2.1.331 each advertised the 32 project skills. Codex 0.172.0's candidate +prompt contained the shared policy and all 32 names. Claude's local context +diagnostic estimated 1.1k memory tokens on baseline and 685 for the initial +candidate (4 for the import and 681 for the shared policy). + +All three [pilot inputs](../tools/LlmSkillIndexer/pilot.md) could be prepared. +The inventory task produced no scored model pair. The Claude model request +reported a missing login. OpenCode's configured provider returned a server +error. Both managed Z.ai launchers reported a missing API key. Codex's baseline +trial timed out after 120 seconds. Its candidate trial attempted the inventory, +but Linux denied namespace creation before the command executed. The same +namespace restriction and unavailable trial container prevented isolated +historical model runs. Task correctness, cost, and end-to-end token savings +remain unmeasured. + +The maintainer waived further Claude Code and OpenCode task trials for this PR. +The follow-up review fixes restored the fixture requirements, kept the Copilot +policy mirror under a drift check, and removed the inventory test's dependency +on jq. All 22 indexer tests ran successfully. The Codex prompt diagnostic +confirmed the full shared policy and all 32 skill names. The blinded task +results and trial limitations are recorded in +[issue #157](https://github.com/Ambiguous-Interactive/NovaSharp/issues/157). diff --git a/progress/session-191-a5-table-callback-views.md b/progress/session-191-a5-table-callback-views.md new file mode 100644 index 000000000..c14e17eb2 --- /dev/null +++ b/progress/session-191-a5-table-callback-views.md @@ -0,0 +1,93 @@ +# Session 191 — A5 table callback views + +Phase A5 [#108](https://github.com/Ambiguous-Interactive/NovaSharp/issues/108) +moves each remaining table callback, including Lua 5.1 global `unpack`, to the +stack-only argument view. The old public CLR callback methods and their module +types leave the host API. The migration preserves Lua registration names +and version gates. The callbacks use the existing built-in delegate registration. +A method-level preservation attribute keeps the private entry points visible +to the Unity linker without a UnityEngine dependency. +Load is the next module in the Phase A5 queue. + +The base was `877c0731`, the merged guidance PR +[#158](https://github.com/Ambiguous-Interactive/NovaSharp/pull/158). Its Tests, +CSharpier, and Benchmarks workflows succeeded on main. The paginated issue +inventory contained 29 open issues and the open PR list contained six tooling +bumps. Current tool pins suffice for the migration. + +## Evidence + +- The new registration test failed in all five Lua profiles on the base + because the registered callbacks used legacy arguments. The test checks + available functions through the Lua-visible table, including registration + variants and the separately registered global. The first candidate run + exposed a test bug: the raw pair enumeration returned a nil tombstone for + the version-gated `move` entry. The test now enumerates non-nil entries and + checks the version-gated names separately. +- The paired fixture exercises the registered functions across Lua 5.1–5.5, + including range return counts, nil in a multi-return argument, and an + overlapping move. Curating its version header ensures the corpus includes + all five lanes. Automatic inference intersects function-version requirements + across branches without evaluating their runtime version guards. +- The paired fixture found that Lua 5.1 and 5.2 `table.maxn` counted removed + keys and skipped fractions. After removing a sequence entry, assigning key + 3.5, and removing it, stock Lua returned `2,3.5,2` on both versions. + The base returned `3,2,2`. The scan now visits live entries and considers + every positive numeric key. +- The Linux x64 Release interpreter built with the .NET 9.0.321 SDK. On each + Lua profile, the same preloaded Lua loop accumulated the result of unpacking + the single value 42 from a reused table 100,000 times. Five warmups followed + by eleven samples, with tiered compilation disabled, yielded a median of + 312.00048 B per call on the base and 48.00048 B on the candidate. Every + sample returned 4,200,000. Bytes include the Lua loop and the amortized + allocation at the host entry point. +- Independent verification matched base and pre-correction candidate outputs for all five + profiles, including version exposure, trailing argument expansion, coercion, + comparator reentrancy and failure, mutation, and range behavior. Its separate + explicit-bound unpack probe measured the same 264 B reduction per call. +- The reference export inventory showed an existing difference in every + version. [#159](https://github.com/Ambiguous-Interactive/NovaSharp/issues/159) + records the CLR-derived names and the missing Lua 5.1 and 5.5 entries for a + separate parity change. [#160](https://github.com/Ambiguous-Interactive/NovaSharp/issues/160) + tracks two separate pre-existing `table.insert` divergences verified + across all five Lua versions. +- The adversarial review identified the loss of Unity linker roots when the + public callbacks became private. The replacement uses Unity's documented + third-party attribute contract and preserves each of the nine entry points. + [Unity PreserveAttribute](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Scripting.PreserveAttribute.html) + +## Hosted CI findings + +The first benchmark job reported 16 fresh-compile allocation regressions. +The fresh-compile benchmark constructs a new Script each time. An isolated +probe reproduced the same increase for construction on its own, 896 B per +operation in the Lua 5.1 and 5.4 profiles and 1,024 B in the Lua 5.2 profile. +Each newly migrated name had created an unused 64 B CLR delegate during +registration. The CLR getter now creates and caches the adapter on demand, +preserving delegate identity across callers. In Lua 5.4 the fresh-compile +probe moved from 350,714 B on the base to 351,610 B in the first candidate +and 334,842 B after the change. The one-result unpack allocation remained +48.00048 B per call. + +The Windows Lua 5.2 job exposed that its reference build omits +`LUA_COMPAT_MAXN`. The original fixture failed against a local Lua 5.2.4 +build with the Windows job's compatibility flags and no `LUA_COMPAT_ALL`. +The revised fixture passed both build variants. It checks `maxn` behavior +when the reference exports it. TUnit still verifies its presence in the +NovaSharp 5.1 and 5.2 profiles and its absence in later profiles. + +## Local checks + +The quick build, 216 TableModule tests, 57 ModuleRegister tests, and all +15,721 quick tests passed with zero failures or skips. Regenerating the +corpus retained one comparable fixture in all five lanes. + +Unity player execution was unavailable. Independent inspection of the +Release assembly confirmed nine method-level preservation annotations. + +## Release note + +Removed the public `TableModule` and `TableModuleGlobals` CLR callback surface. +The stack-only callback path reduces allocation on single-result +`unpack` calls. Lua 5.1 and 5.2 `table.maxn` now ignores removed entries +and includes fractional numeric keys. diff --git a/requirements.tooling.txt b/requirements.tooling.txt index 3f9128ebb..94effb08d 100644 --- a/requirements.tooling.txt +++ b/requirements.tooling.txt @@ -1,10 +1,10 @@ mdformat==1.0.0 mdformat-gfm==1.0.0 -markdown-it-py==4.2.0 +markdown-it-py==4.3.0 requests==2.34.2 codespell==2.4.3 yamllint==1.38.0 # Read `_config.yml`'s exclude list in scripts/ci/check_jekyll_liquid.py. Also a # transitive dependency of yamllint; pinned here so the guard does not rely on # that staying true. -PyYAML==6.0.3 +PyYAML==6.0.4 diff --git a/scripts/README.md b/scripts/README.md index 1ad1fc611..bb032b484 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -22,7 +22,7 @@ For fast iterative development, use the quick build and test scripts: - `coverage/` — Coverlet + ReportGenerator wrappers (`coverage.ps1` / `coverage.sh`) that build the solution, run the interpreter tests, and publish Markdown/HTML/JSON summaries into `artifacts/coverage` + `docs/coverage/latest`. - `benchmarks/` — Helpers for running the runtime + same-run comparison BenchmarkDotNet suites (`run-benchmarks.ps1` / `run-benchmarks.sh`), emitting the Phase A0 scoreboard (`run-phase-a0-scoreboard.ps1` / `run-phase-a0-scoreboard.sh`), adding reference `lua` CLI wall-time context (`run-lua-cli-context.py`), keeping `docs/Performance.md` up to date, and rendering `artifacts/benchmark-deltas.md` with external runtime and optional self-baseline deltas. CI integration via `.github/workflows/benchmarks.yml` stores historical benchmark data and posts the aggregate delta comment on benchmark PRs. - `build/` — Cross-platform build helpers including `quick.sh` for fast development builds and `build.ps1` / `build.sh` for CI. -- `test/` — Quick test runner (`quick.sh`) with filtering support for fast iterative testing. +- `test/` — Filtered interpreter tests and the [Docker-backed devcontainer startup check](test/README.md). - `tests/` — Lua specification parity harnesses, the aggregate Lua comparison report renderer (`render-lua-comparison-report.py`), and test utilities. - `packaging/` — NuGet and Unity package builders (`build-unity-package.ps1` / `build-unity-package.sh`) that produce UPM-compatible packages. CI integration via `.github/workflows/nuget-publish.yml` handles NuGet.org and GitHub Packages publishing. - `ci/` — Repository health guards (e.g., README/link enforcement, GitHub Pages Liquid syntax) that run locally or in CI before builds/tests execute. diff --git a/scripts/build/README.md b/scripts/build/README.md index a59cfbf3b..eb77ddaa8 100644 --- a/scripts/build/README.md +++ b/scripts/build/README.md @@ -40,7 +40,7 @@ Use `quick.sh` for fast iterative development with incremental compilation: - `--skip-tests` / `-SkipTests`: Build only; do not execute tests. - `--skip-tool-restore` / `-SkipToolRestore`: Assume `dotnet tool restore` already ran for this checkout. -Both scripts automatically set `DOTNET_ROLL_FORWARD=Major` when the variable is unset so environments with only .NET 9 installed can still run the net8 test runner. Test logs are written to `artifacts/test-results`, matching the CI layout. +Both scripts automatically set `DOTNET_ROLL_FORWARD=Major` when the variable is unset so newer .NET runtimes can run the .NET 8 test host. Test logs are written to `artifacts/test-results`, matching the CI layout. ### Examples diff --git a/scripts/build/build.ps1 b/scripts/build/build.ps1 index 10ae48d1e..80dbb1318 100644 --- a/scripts/build/build.ps1 +++ b/scripts/build/build.ps1 @@ -51,7 +51,7 @@ else { if ([string]::IsNullOrWhiteSpace($env:DOTNET_ROLL_FORWARD)) { $env:DOTNET_ROLL_FORWARD = "Major" - Write-Host "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so .NET 9 hosts can run the net8 test runner." + Write-Host "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so newer .NET runtimes can run the .NET 8 test host." } # Suppress TUnit ASCII banner and telemetry messages @@ -96,9 +96,8 @@ NovaSharp test results were not generated. This placeholder file ensures CI arti Set-Content -Path $placeholderPath -Value $placeholderContent Write-Host "Running tests for $TestProject..." - # Microsoft.Testing.Platform options (--report-trx, --results-directory) must be passed after -- - dotnet test $TestProject -c $Configuration --no-build ` - -- --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx ` + dotnet test --project $TestProject -c $Configuration --no-build ` + --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx ` --results-directory $resultsDir if ($LASTEXITCODE -ne 0) { throw "dotnet test $TestProject failed with exit code $LASTEXITCODE." diff --git a/scripts/build/build.sh b/scripts/build/build.sh index 0ce4dbc72..9cdb5e320 100755 --- a/scripts/build/build.sh +++ b/scripts/build/build.sh @@ -83,7 +83,7 @@ EOF if [[ -z "${DOTNET_ROLL_FORWARD:-}" ]]; then export DOTNET_ROLL_FORWARD="Major" - echo "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so .NET 9 hosts can run the net8 test runner." + echo "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so newer .NET runtimes can run the .NET 8 test host." fi # Suppress TUnit ASCII banner and telemetry messages @@ -113,14 +113,8 @@ dotnet build "$solution" -c "$configuration" -m "${build_restore_flag[@]}" if (( run_tests )); then echo "Running tests for $test_project..." - test_restore_flag=() - if (( ! restore_packages )); then - test_restore_flag=(--no-restore) - fi - # Microsoft.Testing.Platform options (--report-trx, --results-directory) must be passed after -- - dotnet test "$test_project" -c "$configuration" --no-build \ - "${test_restore_flag[@]}" \ - -- --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx \ + dotnet test --project "$test_project" -c "$configuration" --no-build \ + --report-trx --report-trx-filename NovaSharpInterpreterTUnit.trx \ --results-directory "$test_results_dir" rm -f "$test_results_placeholder" fi diff --git a/scripts/coverage/coverage.ps1 b/scripts/coverage/coverage.ps1 index 18a2b7855..ee33ded58 100644 --- a/scripts/coverage/coverage.ps1 +++ b/scripts/coverage/coverage.ps1 @@ -120,7 +120,7 @@ else { if ([string]::IsNullOrWhiteSpace($env:DOTNET_ROLL_FORWARD)) { $env:DOTNET_ROLL_FORWARD = "Major" - Write-Host "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so .NET 9 runtimes can host net8 test runners." + Write-Host "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so newer .NET runtimes can run .NET 8 test hosts." } # Suppress TUnit ASCII banner and telemetry messages @@ -221,8 +221,7 @@ try { $tunitCoverageDir = Join-Path $coverageRoot "tunit" New-Item -ItemType Directory -Force -Path $tunitCoverageDir | Out-Null $tunitCoverageBase = Join-Path $tunitCoverageDir "coverage" - # Use 'dotnet run' instead of 'dotnet test' because Microsoft.Testing.Platform - # (configured in global.json) does not support 'dotnet test --project' syntax. + # Launch the TUnit test application directly through coverlet. $tunitTargetArgs = "run --project `"$tunitRunnerProject`" -c $Configuration --no-build" $remoteDebuggerTargetArgs = diff --git a/scripts/coverage/coverage.sh b/scripts/coverage/coverage.sh index 699ddce2a..c3b5da76e 100755 --- a/scripts/coverage/coverage.sh +++ b/scripts/coverage/coverage.sh @@ -165,7 +165,7 @@ trap 'popd >/dev/null' EXIT if [[ -z "${DOTNET_ROLL_FORWARD:-}" ]]; then export DOTNET_ROLL_FORWARD=Major - log "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so .NET 9 runtimes can host net8 test runners." + log "DOTNET_ROLL_FORWARD not set; defaulting to 'Major' so newer .NET runtimes can run .NET 8 test hosts." fi # Suppress TUnit ASCII banner and telemetry messages @@ -252,8 +252,7 @@ mkdir -p "$tunit_coverage_dir" tunit_coverage_base="$tunit_coverage_dir/coverage" tunit_coverage_json="${tunit_coverage_base}.json" -# Use 'run' instead of 'test' because Microsoft.Testing.Platform -# (configured in global.json) does not support 'dotnet test ' syntax. +# Launch the TUnit test application directly through coverlet. tunit_target_args=( run --project "$tunit_runner_project" -c "$configuration" diff --git a/scripts/lint/README.md b/scripts/lint/README.md index 6338e4439..090e55475 100644 --- a/scripts/lint/README.md +++ b/scripts/lint/README.md @@ -115,6 +115,11 @@ Z.ai backend starts, custom `CODEX_HOME` profiles are installed with restrictive permissions, missing credentials fail closed, arguments are forwarded verbatim, and existing non-symlink launchers are never replaced. +The managed credential tests also exercise the installed Claude wrappers with +project-specific credentials. On Windows, run +`pwsh -File scripts/lint/test-devcontainer-windows-preflight.ps1` to exercise +the configured host command from a spaced path and check the native ACLs. + ```bash python scripts/lint/check-tooling-consistency.py ``` diff --git a/scripts/lint/check-shell-python-invocation.py b/scripts/lint/check-shell-python-invocation.py index f6b8044b1..0f3dba222 100644 --- a/scripts/lint/check-shell-python-invocation.py +++ b/scripts/lint/check-shell-python-invocation.py @@ -72,6 +72,9 @@ def check_script(path: Path) -> list[tuple[int, str]]: # Skip comments and empty lines if not stripped or stripped.startswith("#"): continue + # Copying a Python file as fixture data does not execute it. + if re.fullmatch(r"cp\s+[^;&|`<>\n()]+", stripped): + continue # Check if this line directly executes a .py file without python if stripped.endswith(".py") or stripped.endswith('.py"') or stripped.endswith(".py'"): # Make sure it's not prefixed with python diff --git a/scripts/lint/check-tooling-consistency.py b/scripts/lint/check-tooling-consistency.py index 2606d8d56..f3abc4c53 100644 --- a/scripts/lint/check-tooling-consistency.py +++ b/scripts/lint/check-tooling-consistency.py @@ -24,7 +24,10 @@ DEVCONTAINER_NPM_INSTALLER = REPO_ROOT / ".devcontainer" / "install-npm-tools.sh" DEVCONTAINER_ARTIFACT_CLEANER = REPO_ROOT / ".devcontainer" / "cleanup-artifacts.sh" DEVCONTAINER_ON_CREATE = REPO_ROOT / ".devcontainer" / "on-create.sh" +DEVCONTAINER_UPDATE_CONTENT = REPO_ROOT / ".devcontainer" / "update-content.sh" +DEVCONTAINER_POST_CREATE = REPO_ROOT / ".devcontainer" / "post-create.sh" DEVCONTAINER_POST_START = REPO_ROOT / ".devcontainer" / "post-start.sh" +DEVCONTAINER_NUGET_CACHE_GUARD = REPO_ROOT / ".devcontainer" / "ensure-nuget-cache.sh" DEVCONTAINER_LIFECYCLE_TEST = REPO_ROOT / "scripts" / "lint" / "test-devcontainer-lifecycle.sh" DEVCONTAINER_BUILD_CACHE_TEST = REPO_ROOT / "scripts" / "lint" / "test-devcontainer-build-cache.sh" DEVCONTAINER_AI_BACKENDS_TEST = REPO_ROOT / "scripts" / "lint" / "test-ai-backends.sh" @@ -41,6 +44,9 @@ "@nanocollective/nanocoder@latest", "opencode-ai@latest", "@openai/codex@latest", + "@github/copilot@latest", + "mcp-remote@latest", + "@z_ai/mcp-server@latest", ) @@ -244,7 +250,6 @@ def check_devcontainer_npm_tooling(violations: list[str]) -> None: installer = read_text(DEVCONTAINER_NPM_INSTALLER) dockerfile = read_text(DEVCONTAINER_DOCKERFILE) devcontainer = read_text(DEVCONTAINER_JSON) - on_create = read_text(DEVCONTAINER_ON_CREATE) for package in LATEST_NPM_TOOLS: if package not in installer: @@ -277,7 +282,7 @@ def check_devcontainer_npm_tooling(violations: list[str]) -> None: ) image_installer = "RUN NOVA_NPM_CLEAN_CACHE=1 novasharp-install-npm-tools" - image_install_position = dockerfile.find(image_installer) + image_install_position = dockerfile.find(image_installer + "\n") last_user_before_install = dockerfile.rfind("USER ", 0, image_install_position) install_user_line = ( dockerfile[last_user_before_install:].splitlines()[0] if last_user_before_install >= 0 else "" @@ -285,7 +290,7 @@ def check_devcontainer_npm_tooling(violations: list[str]) -> None: if image_install_position < 0 or install_user_line != "USER vscode": violations.append( f"{repo_path(DEVCONTAINER_DOCKERFILE)} must run the image npm installer as the vscode user " - "during the image build." + "in strict mode during the image build." ) if "CODEX_CLI_VERSION" in dockerfile: @@ -307,11 +312,12 @@ def check_devcontainer_npm_tooling(violations: list[str]) -> None: "through UID remapping and exercise every parent under a synthetic UID." ) - workspace_installer = ".devcontainer/install-npm-tools.sh" - if workspace_installer not in on_create: - violations.append( - f"{repo_path(DEVCONTAINER_ON_CREATE)} must refresh the npm CLIs when a container is created." - ) + for hook in (DEVCONTAINER_ON_CREATE, DEVCONTAINER_POST_START): + command = r"^\s*bash\s+\.devcontainer/install-npm-tools\.sh\s+--offline-ok\s*$" + if not hook.is_file() or not re.search(command, read_text(hook), re.MULTILINE): + violations.append( + f"{repo_path(hook)} must allow startup with validated image tools when an npm refresh fails." + ) if ".devcontainer/post-start.sh" not in devcontainer: violations.append( @@ -367,17 +373,91 @@ def check_devcontainer_artifact_cleanup(violations: list[str]) -> None: return post_start = read_text(DEVCONTAINER_POST_START) - if ".devcontainer/install-npm-tools.sh" not in post_start or "--offline-ok" not in post_start: - violations.append( - f"{repo_path(DEVCONTAINER_POST_START)} must refresh the latest npm CLIs with the " - "tested offline fallback on every start." - ) if ".devcontainer/cleanup-artifacts.sh" not in post_start or "--older-than-days" not in post_start: violations.append( f"{repo_path(DEVCONTAINER_POST_START)} must prune expired generated artifacts on every start." ) +def strip_jsonc_comments(text: str) -> str: + return "\n".join( + line for line in text.splitlines() if not line.lstrip().startswith("//") + ) + + +def first_command_line(text: str, pattern: str) -> int: + compiled = re.compile(pattern) + for index, line in enumerate(text.splitlines()): + if line.lstrip().startswith("#"): + continue + if compiled.search(line): + return index + return -1 + + +def check_devcontainer_nuget_cache(violations: list[str]) -> None: + if not DEVCONTAINER_NUGET_CACHE_GUARD.is_file(): + violations.append( + f"{repo_path(DEVCONTAINER_NUGET_CACHE_GUARD)} is missing. " + "The NuGet cache volume must be repaired before any lifecycle command uses dotnet." + ) + return + + guard = read_text(DEVCONTAINER_NUGET_CACHE_GUARD) + if "$(id -u)" not in guard or "$(id -g)" not in guard: + violations.append( + f"{repo_path(DEVCONTAINER_NUGET_CACHE_GUARD)} must use the runtime UID/GID " + "so ownership repair survives updateRemoteUserUID." + ) + + dockerfile = read_text(DEVCONTAINER_DOCKERFILE) + dockerfile_instructions = "\n".join( + line for line in dockerfile.splitlines() if not line.lstrip().startswith("#") + ) + seed_pattern = ( + r"^\s*RUN\s+install\s+-d\b" + r"(?=[^\n]*\s-o\s+vscode\b)" + r"(?=[^\n]*\s-g\s+vscode\b)" + r"[^\n]*/home/vscode/\.nuget\b" + ) + if not re.search(seed_pattern, dockerfile_instructions, flags=re.MULTILINE): + violations.append( + f"{repo_path(DEVCONTAINER_DOCKERFILE)} must seed /home/vscode/.nuget with " + "vscode ownership so Docker initializes new named volumes correctly." + ) + + devcontainer = strip_jsonc_comments(read_text(DEVCONTAINER_JSON)) + if not re.search(r'\btarget=/home/vscode/\.nuget(?:,|")', devcontainer): + violations.append( + f"{repo_path(DEVCONTAINER_JSON)} must keep the NuGet cache volume at " + "/home/vscode/.nuget so the image seed applies." + ) + + guard_pattern = r"^\s*(?:bash\s+)?(?:\./)?\.devcontainer/ensure-nuget-cache\.sh(?:\s|$)" + dotnet_pattern = r"(?:^\s*(?:run_with_retries\s+\d+\s+)?|\$\(\s*)dotnet\b" + for lifecycle_path in ( + DEVCONTAINER_ON_CREATE, + DEVCONTAINER_UPDATE_CONTENT, + DEVCONTAINER_POST_CREATE, + DEVCONTAINER_POST_START, + ): + lifecycle = read_text(lifecycle_path) + guard_line = first_command_line(lifecycle, guard_pattern) + if guard_line < 0: + violations.append( + f"{repo_path(lifecycle_path)} must run " + f"{repo_path(DEVCONTAINER_NUGET_CACHE_GUARD)} before using dotnet." + ) + continue + + dotnet_line = first_command_line(lifecycle, dotnet_pattern) + if dotnet_line >= 0 and guard_line > dotnet_line: + violations.append( + f"{repo_path(lifecycle_path)} must repair the NuGet cache volume " + f"before its first dotnet command." + ) + + def check_devcontainer_lifecycle_behavior(violations: list[str]) -> None: if not DEVCONTAINER_LIFECYCLE_TEST.is_file(): violations.append(f"{repo_path(DEVCONTAINER_LIFECYCLE_TEST)} is missing.") @@ -456,6 +536,7 @@ def check_github_mcp_configs(violations: list[str]) -> None: return expected_authorization = f"Bearer ${{{GITHUB_MCP_TOKEN_ENV}}}" + expected_vscode_authorization = f"Bearer ${{env:{GITHUB_MCP_TOKEN_ENV}}}" expected_opencode_authorization = f"Bearer {{env:{GITHUB_MCP_TOKEN_ENV}}}" codex = load_toml(CODEX_MCP_CONFIG) @@ -466,6 +547,8 @@ def check_github_mcp_configs(violations: list[str]) -> None: violations.append( f"{repo_path(CODEX_MCP_CONFIG)} must read its GitHub token from {GITHUB_MCP_TOKEN_ENV}." ) + if codex_server.get("http_headers", {}).get("X-MCP-Readonly") != "true": + violations.append(f"{repo_path(CODEX_MCP_CONFIG)} must keep GitHub MCP read-only by default.") shared = load_json(SHARED_MCP_CONFIG) shared_server = shared.get("mcpServers", {}).get(GITHUB_MCP_SERVER_NAME, {}) @@ -480,15 +563,19 @@ def check_github_mcp_configs(violations: list[str]) -> None: violations.append( f"{repo_path(SHARED_MCP_CONFIG)} must reference {GITHUB_MCP_TOKEN_ENV}; never store a PAT." ) + if shared_server.get("headers", {}).get("X-MCP-Readonly") != "true": + violations.append(f"{repo_path(SHARED_MCP_CONFIG)} must keep GitHub MCP read-only by default.") vscode = load_json(VSCODE_MCP_CONFIG) vscode_server = vscode.get("servers", {}).get(GITHUB_MCP_SERVER_NAME, {}) if vscode_server.get("url") != GITHUB_MCP_URL: violations.append(f"{repo_path(VSCODE_MCP_CONFIG)} must configure the hosted GitHub MCP URL.") - if "headers" in vscode_server: + if vscode_server.get("headers", {}).get("Authorization") != expected_vscode_authorization: violations.append( - f"{repo_path(VSCODE_MCP_CONFIG)} must use VS Code OAuth instead of a committed token header." + f"{repo_path(VSCODE_MCP_CONFIG)} must reference {GITHUB_MCP_TOKEN_ENV}; never store a PAT." ) + if vscode_server.get("headers", {}).get("X-MCP-Readonly") != "true": + violations.append(f"{repo_path(VSCODE_MCP_CONFIG)} must keep GitHub MCP read-only by default.") opencode = load_json(OPENCODE_CONFIG) opencode_server = opencode.get("mcp", {}).get(GITHUB_MCP_SERVER_NAME, {}) @@ -505,13 +592,13 @@ def check_github_mcp_configs(violations: list[str]) -> None: violations.append( f"{repo_path(OPENCODE_CONFIG)} must reference {GITHUB_MCP_TOKEN_ENV}; never store a PAT." ) + if opencode_server.get("headers", {}).get("X-MCP-Readonly") != "true": + violations.append(f"{repo_path(OPENCODE_CONFIG)} must keep GitHub MCP read-only by default.") devcontainer = read_text(DEVCONTAINER_JSON) - token_forwarding = f'"{GITHUB_MCP_TOKEN_ENV}": "${{localEnv:{GITHUB_MCP_TOKEN_ENV}}}"' - if token_forwarding not in devcontainer: + if '"--env-file", "${localWorkspaceFolder}/.devcontainer/.mcp.env"' not in devcontainer: violations.append( - f"{repo_path(DEVCONTAINER_JSON)} must forward a host {GITHUB_MCP_TOKEN_ENV} to the " - "remote user environment." + f"{repo_path(DEVCONTAINER_JSON)} must load the filtered runtime MCP environment." ) gitignore = read_text(REPO_ROOT / ".gitignore") @@ -627,6 +714,7 @@ def main() -> int: check_devcontainer_uses_local_tools(violations) check_devcontainer_npm_tooling(violations) check_devcontainer_artifact_cleanup(violations) + check_devcontainer_nuget_cache(violations) check_devcontainer_lifecycle_behavior(violations) check_devcontainer_build_cache_behavior(violations) check_devcontainer_ai_backends(violations) diff --git a/scripts/lint/test-ai-backends.sh b/scripts/lint/test-ai-backends.sh index 874ef2f97..4ae3943f1 100755 --- a/scripts/lint/test-ai-backends.sh +++ b/scripts/lint/test-ai-backends.sh @@ -29,6 +29,7 @@ cat >"${test_bin}/codex" <<'STUB' set -euo pipefail { printf 'zai_key=%s\n' "${ZAI_API_KEY:+set}" + printf 'lowercase_zai_key=%s\n' "${zai_key-unset}" printf 'arg=%s\n' "$@" } >"${STUB_LOG:?}" STUB @@ -40,7 +41,10 @@ set -euo pipefail printf 'auth_token=%s\n' "${ANTHROPIC_AUTH_TOKEN:+set}" printf 'zai_key=%s\n' "${ZAI_API_KEY-unset}" printf 'zai_key_alias=%s\n' "${Z_AI_API_KEY-unset}" + printf 'zai_mcp_key=%s\n' "${ZAI_MCP_API_KEY-unset}" printf 'native_key=%s\n' "${ANTHROPIC_API_KEY-unset}" + printf 'native_oauth=%s\n' "${CLAUDE_CODE_OAUTH_TOKEN-unset}" + printf 'lowercase_zai_key=%s\n' "${zai_key-unset}" printf 'base_url=%s\n' "${ANTHROPIC_BASE_URL-unset}" printf 'timeout=%s\n' "${API_TIMEOUT_MS-unset}" printf 'config_dir=%s\n' "${CLAUDE_CONFIG_DIR-unset}" @@ -115,9 +119,11 @@ HOME="${test_home}" \ CODEX_HOME="${codex_home}" \ STUB_LOG="${codex_log}" \ ZAI_API_KEY="test-secret" \ +zai_key="ambient-lowercase-secret" \ CODEX_ZAI_MODEL="glm-test" \ "${launcher_bin}/codex-zai" exec "hello world" grep -Eq '^zai_key=set$' "${codex_log}" || fail "Codex did not receive the Z.ai key" +grep -Eq '^lowercase_zai_key=unset$' "${codex_log}" || fail "Codex leaked its internal Z.ai key variable" grep -Eq '^arg=--profile$' "${codex_log}" || fail "Codex profile was not selected" grep -Eq '^arg=devcontainer-zai$' "${codex_log}" || fail "Codex profile name was not forwarded" grep -Eq '^arg=glm-test$' "${codex_log}" || fail "Codex model override was not forwarded" @@ -133,7 +139,10 @@ PATH="${test_bin}:${launcher_bin}:/usr/bin:/bin" \ HOME="${test_home}" \ STUB_LOG="${claude_log}" \ Z_AI_API_KEY="test-secret" \ +ZAI_MCP_API_KEY="stale-mcp-secret" \ ANTHROPIC_API_KEY="native-secret" \ +CLAUDE_CODE_OAUTH_TOKEN="native-oauth-secret" \ +zai_key="ambient-lowercase-secret" \ CLAUDE_CODE_USE_BEDROCK=1 \ CLAUDE_CODE_USE_VERTEX=1 \ CLAUDE_CODE_USE_FOUNDRY=1 \ @@ -152,7 +161,10 @@ ZAI_API_TIMEOUT_MS="123456" \ grep -Eq '^auth_token=set$' "${claude_log}" || fail "Claude did not receive the Z.ai token" grep -Eq '^zai_key=unset$' "${claude_log}" || fail "Claude retained the canonical Z.ai key" grep -Eq '^zai_key_alias=unset$' "${claude_log}" || fail "Claude retained the Z.ai key alias" +grep -Eq '^zai_mcp_key=unset$' "${claude_log}" || fail "Claude retained the ambient MCP key alias" grep -Eq '^native_key=unset$' "${claude_log}" || fail "Claude native key was not isolated" +grep -Eq '^native_oauth=unset$' "${claude_log}" || fail "Claude native OAuth token was not isolated" +grep -Eq '^lowercase_zai_key=unset$' "${claude_log}" || fail "Claude leaked its internal Z.ai key variable" grep -Eq '^base_url=https://api.z.ai/api/anthropic$' "${claude_log}" \ || fail "Claude Z.ai endpoint is incorrect" grep -Eq '^timeout=123456$' "${claude_log}" || fail "Claude timeout override was not forwarded" @@ -178,8 +190,13 @@ grep -Eq '^opus_model=glm-5.3\[1m\]$' "${claude_log}" \ grep -Eq '^arg=--print$' "${claude_log}" || fail "Claude arguments were not forwarded" grep -Eq '^arg=--settings$' "${claude_log}" \ || fail "Claude nested-container settings were not forwarded" -grep -Fq 'arg={"sandbox":{"enabled":false,"enableWeakerNestedSandbox":true}}' "${claude_log}" \ - || fail "Claude inner sandbox was not disabled inside the devcontainer" +grep -Eq '^arg=--mcp-config$' "${claude_log}" \ + || fail "Claude Z.ai MCP catalog was not selected" +grep -Eq '^arg=--strict-mcp-config$' "${claude_log}" \ + || fail "Claude Z.ai did not isolate its MCP catalog" +grep -Fq 'arg={"enabledMcpjsonServers":["github-mcp-server","zai-vision","zai-web-search","zai-web-reader","zai-zread"],"sandbox":{"enabled":false,"enableWeakerNestedSandbox":true}}' \ + "${claude_log}" \ + || fail "Claude Z.ai did not approve only its known project MCP servers" if grep -Eq 'test-secret|native-secret' "${claude_log}"; then fail "Claude credential leaked into arguments" fi @@ -242,4 +259,540 @@ fi grep -Eq 'Set ZAI_API_KEY' "${missing_key_output}" \ || fail "Missing-key failure did not provide setup guidance" -printf 'PASS: isolated AI backend launchers\n' +# Every supported frontend must discover the same project-scoped MCP catalog, +# while credentials remain in the ignored host-side .env.local file. +mcp_env_check="${repo_root}/.devcontainer/check-mcp-env.sh" +vision_launcher="${repo_root}/.devcontainer/zai-mcp-vision.sh" +remote_launcher="${repo_root}/.devcontainer/zai-mcp-remote.sh" +for required_file in \ + "${repo_root}/.mcp.json" \ + "${repo_root}/.vscode/mcp.json" \ + "${repo_root}/.codex/config.toml" \ + "${repo_root}/opencode.json" \ + "${repo_root}/.devcontainer/claude-zai.mcp.json" \ + "${repo_root}/.env.local.example" \ + "${mcp_env_check}" \ + "${vision_launcher}" \ + "${remote_launcher}"; do + [ -f "${required_file}" ] || fail "missing MCP configuration: ${required_file#"${repo_root}/"}" +done +for executable_file in "${mcp_env_check}" "${vision_launcher}" "${remote_launcher}"; do + [ -x "${executable_file}" ] \ + || fail "MCP helper is not executable: ${executable_file#"${repo_root}/"}" +done + +python3 - "${repo_root}" <<'PY' || fail "project MCP catalogs are inconsistent" +import json +from pathlib import Path +import sys +import tomllib + +root = Path(sys.argv[1]) +names = { + "github-mcp-server", + "zai-vision", + "zai-web-search", + "zai-web-reader", + "zai-zread", +} +urls = { + "github-mcp-server": "https://api.githubcopilot.com/mcp/", + "zai-web-search": "https://api.z.ai/api/mcp/web_search_prime/mcp", + "zai-web-reader": "https://api.z.ai/api/mcp/web_reader/mcp", + "zai-zread": "https://api.z.ai/api/mcp/zread/mcp", +} + +portable = json.loads((root / ".mcp.json").read_text()) +assert set(portable["mcpServers"]) == names +assert portable["mcpServers"]["zai-vision"]["command"] == "zai-mcp-vision" +assert portable["mcpServers"]["zai-vision"]["args"] == [] +assert portable["mcpServers"]["zai-vision"]["env"] == {"ZAI_API_KEY": "${ZAI_API_KEY}"} +for name, url in urls.items(): + server = portable["mcpServers"][name] + assert server["type"] == "http" and server["transport"] == "http" + assert server["url"] == url + token = "GITHUB_PERSONAL_ACCESS_TOKEN" if name == "github-mcp-server" else "ZAI_API_KEY" + assert server["headers"]["Authorization"] == f"Bearer ${{{token}}}" +assert portable["mcpServers"]["github-mcp-server"]["headers"]["X-MCP-Readonly"] == "true" + +vscode = json.loads((root / ".vscode/mcp.json").read_text()) +assert set(vscode["servers"]) == names +assert vscode["servers"]["zai-vision"]["command"] == "zai-mcp-vision" +assert vscode["servers"]["zai-vision"]["env"] == {"ZAI_API_KEY": "${env:ZAI_API_KEY}"} +for name, url in urls.items(): + server = vscode["servers"][name] + assert server["type"] == "http" and server["url"] == url + token = "GITHUB_PERSONAL_ACCESS_TOKEN" if name == "github-mcp-server" else "ZAI_API_KEY" + assert server["headers"]["Authorization"] == f"Bearer ${{env:{token}}}" +assert vscode["servers"]["github-mcp-server"]["headers"]["X-MCP-Readonly"] == "true" + +opencode = json.loads((root / "opencode.json").read_text()) +assert set(opencode["mcp"]) == names +assert opencode["mcp"]["zai-vision"]["type"] == "local" +assert opencode["mcp"]["zai-vision"]["command"] == ["zai-mcp-vision"] +assert opencode["mcp"]["zai-vision"]["environment"] == {"ZAI_API_KEY": "{env:ZAI_API_KEY}"} +for name, url in urls.items(): + server = opencode["mcp"][name] + assert server["type"] == "remote" and server["url"] == url + assert server["enabled"] is True and server["oauth"] is False + token = "GITHUB_PERSONAL_ACCESS_TOKEN" if name == "github-mcp-server" else "ZAI_API_KEY" + assert server["headers"]["Authorization"] == f"Bearer {{env:{token}}}" +assert opencode["mcp"]["github-mcp-server"]["headers"]["X-MCP-Readonly"] == "true" + +with (root / ".codex/config.toml").open("rb") as stream: + codex_config = tomllib.load(stream) +codex = codex_config["mcp_servers"] +assert set(codex) == names +assert codex["zai-vision"]["command"] == "zai-mcp-vision" +assert codex["zai-vision"]["args"] == [] +assert codex["zai-vision"]["env_vars"] == ["ZAI_API_KEY"] +github = codex["github-mcp-server"] +assert github["url"] == urls["github-mcp-server"] +assert github["bearer_token_env_var"] == "GITHUB_PERSONAL_ACCESS_TOKEN" +assert codex["github-mcp-server"]["http_headers"]["X-MCP-Readonly"] == "true" +for name, alias in { + "zai-web-search": "web-search", + "zai-web-reader": "web-reader", + "zai-zread": "zread", +}.items(): + server = codex[name] + assert server["command"] == "zai-mcp-remote" + assert server["args"] == [alias] + assert server["env_vars"] == ["ZAI_API_KEY"] +assert codex_config["shell_environment_policy"]["filters"] == { + "GITHUB_PERSONAL_ACCESS_TOKEN": "exclude", + "ZAI_API_KEY": "exclude", + "Z_AI_API_KEY": "exclude", +} + +claude_zai = json.loads((root / ".devcontainer/claude-zai.mcp.json").read_text())["mcpServers"] +assert set(claude_zai) == names +assert claude_zai["zai-vision"]["command"] == "zai-mcp-vision" +assert "env" not in claude_zai["zai-vision"] +github = claude_zai["github-mcp-server"] +assert github["type"] == "http" and github["url"] == urls["github-mcp-server"] +assert github["headers"]["Authorization"] == "Bearer ${GITHUB_PERSONAL_ACCESS_TOKEN}" +assert claude_zai["github-mcp-server"]["headers"]["X-MCP-Readonly"] == "true" +for name, alias in { + "zai-web-search": "web-search", + "zai-web-reader": "web-reader", + "zai-zread": "zread", +}.items(): + server = claude_zai[name] + assert server["type"] == "stdio" + assert server["command"] == "zai-mcp-remote" + assert server["args"] == [alias] + assert "env" not in server +PY + +grep -R -Fq '@z_ai/mcp-server@latest' "${repo_root}/.devcontainer" \ + || fail "devcontainer does not install the Z.ai Vision MCP package" +grep -R -Fq '@github/copilot@latest' "${repo_root}/.devcontainer" \ + || fail "devcontainer does not install GitHub Copilot CLI" +grep -R -Fq 'mcp-remote@latest' "${repo_root}/.devcontainer" \ + || fail "devcontainer does not install the Claude/Z.ai transport bridge" +grep -Fq '/usr/local/bin/zai-mcp-vision' "${repo_root}/.devcontainer/Dockerfile" \ + || fail "devcontainer does not install the cwd-independent Vision wrapper" +grep -Fq '/usr/local/bin/zai-mcp-remote' "${repo_root}/.devcontainer/Dockerfile" \ + || fail "devcontainer does not install the cwd-independent remote MCP wrapper" +dockerignore_has_mcp_env=0 +for dockerignore in "${repo_root}/.dockerignore" "${repo_root}/.devcontainer/.dockerignore"; do + if [ -f "${dockerignore}" ] && grep -Fq '.mcp.env' "${dockerignore}"; then + dockerignore_has_mcp_env=1 + fi +done +[ "${dockerignore_has_mcp_env}" = "1" ] \ + || fail "filtered MCP credentials can enter the Docker build context" +if grep -Eq '"context"[[:space:]]*:[[:space:]]*"\.\."' \ + "${repo_root}/.devcontainer/devcontainer.json"; then + grep -Eq '^\.env\.(local\*|\*)$' "${repo_root}/.dockerignore" \ + || fail ".env.local backup files can enter the Docker build context" +fi +grep -Fq '"--env-file"' "${repo_root}/.devcontainer/devcontainer.json" \ + || fail "devcontainer does not load an environment file" +grep -Fq '"${localWorkspaceFolder}/.devcontainer/.mcp.env"' "${repo_root}/.devcontainer/devcontainer.json" \ + || fail "devcontainer does not load the filtered MCP environment" +grep -Fq '"NANOCODER_MCPSERVERS_FILE"' "${repo_root}/.devcontainer/devcontainer.json" \ + || fail "Nanocoder MCP discovery depends on the frontend launch directory" +git -C "${repo_root}" check-ignore -q .env.local \ + || fail ".env.local is not ignored by Git" +git -C "${repo_root}" check-ignore -q .env.local.bak \ + || fail ".env.local backup files are not ignored by Git" +git -C "${repo_root}" check-ignore -q .devcontainer/.mcp.env \ + || fail "generated MCP environment is not ignored by Git" +git -C "${repo_root}" check-ignore -q .devcontainer/.mcp.env.interrupted \ + || fail "temporary MCP environment files are not ignored by Git" + +preflight_workspace="${test_root}/preflight workspace" +mkdir -p "${preflight_workspace}/.devcontainer" +cp "${mcp_env_check}" "${preflight_workspace}/.devcontainer/" +python3 - "${repo_root}" "${preflight_workspace}" <<'PY' +import json +from pathlib import Path +import subprocess +import sys + +root, workspace = map(Path, sys.argv[1:]) +config = (root / ".devcontainer/devcontainer.json").read_text(encoding="utf-8") +config = json.loads("\n".join(line for line in config.splitlines() if not line.lstrip().startswith("//"))) +argv = [arg.replace("${localWorkspaceFolder}", r"X:\checkout with spaces") for arg in config["initializeCommand"]] +subprocess.run(argv, cwd=workspace, check=True) +assert (workspace / ".devcontainer/.mcp.env").read_bytes() == b"" +PY +parent_symlink_workspace="${test_root}/parent-symlink-workspace" +parent_symlink_target="${test_root}/outside-devcontainer" +mkdir -p "${parent_symlink_workspace}" "${parent_symlink_target}" +printf 'sentinel\n' >"${parent_symlink_target}/.mcp.env" +ln -s "${parent_symlink_target}" "${parent_symlink_workspace}/.devcontainer" +if bash "${mcp_env_check}" "${parent_symlink_workspace}" \ + >"${test_root}/preflight-parent-symlink.log" 2>&1; then + fail "MCP credential preflight accepted a symlinked .devcontainer directory" +fi +grep -Fxq sentinel "${parent_symlink_target}/.mcp.env" \ + || fail "MCP credential preflight cleanup escaped through a symlinked parent directory" +printf 'ZAI_API_KEY=stale-test-key\n' >"${preflight_workspace}/.devcontainer/.mcp.env" +bash "${mcp_env_check}" "${preflight_workspace}" \ + || fail "A checkout without .env.local must be able to start" +[ -f "${preflight_workspace}/.devcontainer/.mcp.env" ] \ + && [ ! -s "${preflight_workspace}/.devcontainer/.mcp.env" ] \ + || fail "A missing .env.local must replace stale credentials with an empty env file" +[ "$(stat -c '%a' "${preflight_workspace}/.devcontainer/.mcp.env")" = "600" ] \ + || fail "Empty MCP environment permissions are not 600" +printf 'ZAI_API_KEY=zai-test\n' >"${preflight_workspace}/.env.local" +bash "${mcp_env_check}" "${preflight_workspace}" +[ "$(cat "${preflight_workspace}/.devcontainer/.mcp.env")" = 'ZAI_API_KEY=zai-test' ] \ + || fail "Configuring Z.ai alone must not require or inject a GitHub token" +rm -- "${preflight_workspace}/.env.local" +source_symlink_target="${test_root}/source-credentials" +printf 'GITHUB_PERSONAL_ACCESS_TOKEN=github-test\nZAI_API_KEY=zai-test\n' \ + >"${source_symlink_target}" +chmod 644 "${source_symlink_target}" +ln -s "${source_symlink_target}" "${preflight_workspace}/.env.local" +if bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-source-symlink.log" 2>&1; then + fail "MCP credential preflight accepted a symlinked .env.local" +fi +[ "$(stat -c '%a' "${source_symlink_target}")" = "644" ] \ + || fail "MCP credential preflight chmodded a symlink target" +[ "$(cat "${preflight_workspace}/.devcontainer/.mcp.env")" = 'ZAI_API_KEY=zai-test' ] \ + || fail "symlinked source changed the last published MCP environment" +rm -f -- "${preflight_workspace}/.env.local" +printf 'GITHUB_PERSONAL_ACCESS_TOKEN=github-test\r\nZAI_API_KEY=zai-test\r\nUNRELATED_SECRET=must-not-propagate\r\n' \ + >"${preflight_workspace}/.env.local" +chmod 644 "${preflight_workspace}/.env.local" +credential_probe_bin="${test_root}/credential-probe-bin" +mkdir -p "${credential_probe_bin}" +cat >"${credential_probe_bin}/sed" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +[ -z "${github_token:-}" ] && [ -z "${zai_token:-}" ] && [ -z "${value:-}" ] || exit 97 +[ -f "${NOVA_TEST_PREVIOUS_MCP_ENV:?}" ] || exit 98 +exec /bin/sed "$@" +STUB +chmod 755 "${credential_probe_bin}/sed" +printf 'ZAI_API_KEY=previous-key\n' >"${preflight_workspace}/.devcontainer/.mcp.env" +PATH="${credential_probe_bin}:${PATH}" \ +NOVA_TEST_PREVIOUS_MCP_ENV="${preflight_workspace}/.devcontainer/.mcp.env" \ +github_token=ambient zai_token=ambient value=ambient \ + bash -x "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-trace.log" 2>&1 +if grep -Eq 'github-test|zai-test|must-not-propagate' "${test_root}/preflight-trace.log"; then + fail "MCP credential preflight leaked a secret to shell tracing" +fi +cp "${preflight_workspace}/.devcontainer/.mcp.env" "${test_root}/previous-mcp.env" +[ "$(stat -c '%a' "${preflight_workspace}/.env.local")" = "600" ] \ + || fail "MCP credential preflight did not restrict .env.local permissions" +[ "$(stat -c '%a' "${preflight_workspace}/.devcontainer/.mcp.env")" = "600" ] \ + || fail "generated MCP environment permissions are not 600" +[ "$(wc -l <"${preflight_workspace}/.devcontainer/.mcp.env")" = "2" ] \ + || fail "generated MCP environment contains unexpected assignments" +grep -Fxq 'GITHUB_PERSONAL_ACCESS_TOKEN=github-test' \ + "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "generated MCP environment omitted the GitHub credential" +grep -Fxq 'ZAI_API_KEY=zai-test' "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "generated MCP environment omitted the Z.ai credential" +if grep -Fq 'must-not-propagate' "${preflight_workspace}/.devcontainer/.mcp.env"; then + fail "generated MCP environment propagated an unrelated secret" +fi +printf 'ZAI_API_KEY=\n' >>"${preflight_workspace}/.env.local" +if bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-duplicate.log" 2>&1; then + fail "MCP credential preflight accepted a duplicate key" +fi +[ "$(stat -c '%a' "${preflight_workspace}/.env.local")" = "600" ] \ + || fail "MCP credential preflight rejected content before restricting source permissions" +if grep -Fq 'zai-test' "${test_root}/preflight-duplicate.log"; then + fail "MCP credential preflight leaked a secret value" +fi +cmp -s "${test_root}/previous-mcp.env" "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "invalid source changed the last published MCP environment" +printf 'GITHUB_PERSONAL_ACCESS_TOKEN=github-test\nZAI_API_KEY=zai-test\n' \ + >"${preflight_workspace}/.env.local" +preflight_bin="${test_root}/preflight-bin" +mkdir -p "${preflight_bin}" +cat >"${preflight_bin}/mv" <<'STUB' +#!/usr/bin/env bash +exit 73 +STUB +chmod 755 "${preflight_bin}/mv" +if PATH="${preflight_bin}:${PATH}" \ + bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-move.log" 2>&1; then + fail "MCP credential preflight ignored an atomic replacement failure" +fi +if find "${preflight_workspace}/.devcontainer" -maxdepth 1 -name '.mcp.env.*' -print -quit \ + | grep -q .; then + fail "MCP credential preflight left a secret-bearing temporary file" +fi +cmp -s "${test_root}/previous-mcp.env" "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "atomic replacement failure changed the last published MCP environment" + +cat >"${preflight_bin}/mv" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +/bin/mv "$@" +kill -TERM "${PPID}" +exit 0 +STUB +chmod 755 "${preflight_bin}/mv" +if PATH="${preflight_bin}:${PATH}" \ + bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-post-move-signal.log" 2>&1; then + fail "MCP credential preflight reported success after post-rename termination" +fi +cmp -s "${test_root}/previous-mcp.env" "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "post-rename termination removed the atomically published MCP environment" + +cat >"${preflight_bin}/mv" <<'STUB' +#!/usr/bin/env bash +kill -TERM "${PPID}" +exit 0 +STUB +chmod 755 "${preflight_bin}/mv" +if PATH="${preflight_bin}:${PATH}" \ + bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-signal.log" 2>&1; then + fail "MCP credential preflight reported success after a termination signal" +fi +cmp -s "${test_root}/previous-mcp.env" "${preflight_workspace}/.devcontainer/.mcp.env" \ + || fail "terminated preflight changed the last published MCP environment" +if find "${preflight_workspace}/.devcontainer" -maxdepth 1 -name '.mcp.env.*' -print -quit \ + | grep -q .; then + fail "terminated preflight left a secret-bearing temporary file" +fi + +symlink_target="${test_root}/must-not-overwrite" +printf 'sentinel\n' >"${symlink_target}" +rm -- "${preflight_workspace}/.devcontainer/.mcp.env" +ln -s "${symlink_target}" "${preflight_workspace}/.devcontainer/.mcp.env" +if bash "${mcp_env_check}" "${preflight_workspace}" >"${test_root}/preflight-symlink.log" 2>&1; then + fail "MCP credential preflight accepted a symlinked generated file" +fi +[ -L "${preflight_workspace}/.devcontainer/.mcp.env" ] \ + || fail "MCP credential preflight followed or replaced a generated-file symlink" +grep -Fxq sentinel "${symlink_target}" \ + || fail "MCP credential preflight overwrote a symlink target" +rm -f -- "${preflight_workspace}/.devcontainer/.mcp.env" + +cat >"${test_bin}/zai-mcp-server" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +{ + printf 'alias=%s\n' "${Z_AI_API_KEY:+set}" + printf 'canonical=%s\n' "${ZAI_API_KEY-unset}" + printf 'github=%s\n' "${GITHUB_PERSONAL_ACCESS_TOKEN-unset}" + printf 'bridge=%s\n' "${ZAI_MCP_API_KEY-unset}" + printf 'anthropic_auth=%s\n' "${ANTHROPIC_AUTH_TOKEN-unset}" + printf 'anthropic_api=%s\n' "${ANTHROPIC_API_KEY-unset}" + printf 'claude_oauth=%s\n' "${CLAUDE_CODE_OAUTH_TOKEN-unset}" + printf 'github_pat=%s\n' "${GITHUB_PAT-unset}" + printf 'github_token=%s\n' "${GITHUB_TOKEN-unset}" + printf 'gh_token=%s\n' "${GH_TOKEN-unset}" + printf 'openai=%s\n' "${OPENAI_API_KEY-unset}" + printf 'codex=%s\n' "${CODEX_API_KEY-unset}" + printf 'lowercase_vision_key=%s\n' "${zai_api_key-unset}" + printf 'mode=%s\n' "${Z_AI_MODE-unset}" + printf 'arg=%s\n' "$@" +} >"${STUB_LOG:?}" +STUB +chmod 755 "${test_bin}/zai-mcp-server" +vision_log="${test_root}/vision.log" +PATH="${test_bin}:/usr/bin:/bin" \ +STUB_LOG="${vision_log}" \ +ZAI_API_KEY="vision-test-secret" \ +GITHUB_PERSONAL_ACCESS_TOKEN="github-test-secret" \ +ZAI_MCP_API_KEY="bridge-test-secret" \ +ANTHROPIC_AUTH_TOKEN="anthropic-auth-test-secret" \ +ANTHROPIC_API_KEY="anthropic-api-test-secret" \ +CLAUDE_CODE_OAUTH_TOKEN="claude-oauth-test-secret" \ +GITHUB_PAT="github-pat-test-secret" \ +GITHUB_TOKEN="github-token-test-secret" \ +GH_TOKEN="gh-token-test-secret" \ +OPENAI_API_KEY="openai-test-secret" \ +CODEX_API_KEY="codex-test-secret" \ +zai_api_key="ambient-lowercase-secret" \ + bash "${vision_launcher}" --probe +grep -Eq '^alias=set$' "${vision_log}" || fail "Vision MCP did not receive the Z.ai key alias" +grep -Eq '^canonical=unset$' "${vision_log}" || fail "Vision MCP retained the canonical Z.ai key" +grep -Eq '^github=unset$' "${vision_log}" || fail "Vision MCP received the unrelated GitHub credential" +for scrubbed in bridge anthropic_auth anthropic_api claude_oauth github_pat github_token gh_token openai codex lowercase_vision_key; do + grep -Fxq "${scrubbed}=unset" "${vision_log}" \ + || fail "Vision MCP exposed ${scrubbed} to the server" +done +grep -Eq '^mode=ZAI$' "${vision_log}" || fail "Vision MCP did not receive Z.ai mode" +grep -Eq '^arg=--probe$' "${vision_log}" || fail "Vision MCP wrapper did not forward arguments" +if grep -Eq 'vision-test-secret|github-test-secret' "${vision_log}"; then + fail "Vision MCP wrapper leaked the secret" +fi + +runtime_workspace="${test_root}/runtime-workspace" +mkdir -p "${runtime_workspace}/.devcontainer" +printf 'GITHUB_PERSONAL_ACCESS_TOKEN=unused\nZAI_API_KEY=bridge-test-secret\n' \ + >"${runtime_workspace}/.devcontainer/.mcp.env" +chmod 600 "${runtime_workspace}/.devcontainer/.mcp.env" +PATH="${test_bin}:/usr/bin:/bin" \ +STUB_LOG="${vision_log}" \ +CLAUDE_PROJECT_DIR="${runtime_workspace}" \ + env -u ZAI_API_KEY -u Z_AI_API_KEY bash "${vision_launcher}" --runtime-probe +grep -Eq '^alias=set$' "${vision_log}" \ + || fail "Vision MCP did not load the filtered runtime credential" + +cat >"${test_bin}/mcp-remote" <<'STUB' +#!/usr/bin/env bash +set -euo pipefail +endpoint="${1:?}" +[ "${2:-}" = "--header-file" ] || exit 91 +header_file="${3:?}" +if [ "$(sed -n '1p' "${header_file}")" = 'Authorization: Bearer bridge-test-secret' ]; then + header_status=valid +else + header_status=invalid +fi +{ + printf 'endpoint=%s\n' "${endpoint}" + printf 'header=%s\n' "${header_status}" + printf 'bridge_key=%s\n' "${ZAI_MCP_API_KEY-unset}" + printf 'auth=%s\n' "${ANTHROPIC_AUTH_TOKEN-unset}" + printf 'canonical=%s\n' "${ZAI_API_KEY-unset}" + printf 'alias=%s\n' "${Z_AI_API_KEY-unset}" + printf 'github=%s\n' "${GITHUB_PERSONAL_ACCESS_TOKEN-unset}" + printf 'claude_oauth=%s\n' "${CLAUDE_CODE_OAUTH_TOKEN-unset}" + printf 'github_pat=%s\n' "${GITHUB_PAT-unset}" + printf 'github_token=%s\n' "${GITHUB_TOKEN-unset}" + printf 'gh_token=%s\n' "${GH_TOKEN-unset}" + printf 'openai=%s\n' "${OPENAI_API_KEY-unset}" + printf 'codex=%s\n' "${CODEX_API_KEY-unset}" + printf 'lowercase_token=%s\n' "${token-unset}" + printf 'internal_token=%s\n' "${zai_mcp_token-unset}" + printf 'header_arg=%s\n' "${header_file}" +} >"${STUB_LOG:?}" +STUB +chmod 755 "${test_bin}/mcp-remote" +for mapping in \ + 'web-search|https://api.z.ai/api/mcp/web_search_prime/mcp' \ + 'web-reader|https://api.z.ai/api/mcp/web_reader/mcp' \ + 'zread|https://api.z.ai/api/mcp/zread/mcp'; do + alias_name="${mapping%%|*}" + expected_endpoint="${mapping#*|}" + remote_log="${test_root}/remote-${alias_name}.log" + PATH="${test_bin}:/usr/bin:/bin" \ + STUB_LOG="${remote_log}" \ + CLAUDE_PROJECT_DIR="${runtime_workspace}" \ + ZAI_MCP_API_KEY="hostile-bridge-secret" \ + ANTHROPIC_AUTH_TOKEN="model-test-secret" \ + ZAI_API_KEY="canonical-test-secret" \ + Z_AI_API_KEY="alias-test-secret" \ + GITHUB_PERSONAL_ACCESS_TOKEN="github-test-secret" \ + CLAUDE_CODE_OAUTH_TOKEN="claude-oauth-test-secret" \ + GITHUB_PAT="github-pat-test-secret" \ + GITHUB_TOKEN="github-token-test-secret" \ + GH_TOKEN="gh-token-test-secret" \ + OPENAI_API_KEY="openai-test-secret" \ + CODEX_API_KEY="codex-test-secret" \ + token="ambient-lowercase-secret" \ + zai_mcp_token="ambient-internal-secret" \ + bash "${remote_launcher}" "${alias_name}" + grep -Fxq "endpoint=${expected_endpoint}" "${remote_log}" \ + || fail "Remote MCP wrapper mapped ${alias_name} to the wrong endpoint" + grep -Fxq 'header=valid' "${remote_log}" \ + || fail "Remote MCP wrapper did not provide its authorization header" + for scrubbed in bridge_key auth canonical alias github claude_oauth github_pat github_token gh_token openai codex lowercase_token internal_token; do + grep -Fxq "${scrubbed}=unset" "${remote_log}" \ + || fail "Remote MCP wrapper exposed ${scrubbed} to the bridge" + done + if grep -Eq 'bridge-test-secret|model-test-secret|canonical-test-secret|alias-test-secret|github-test-secret' \ + "${remote_log}"; then + fail "Remote MCP wrapper leaked a credential" + fi +done + +runtime_remote_log="${test_root}/remote-runtime.log" +PATH="${test_bin}:/usr/bin:/bin" \ +STUB_LOG="${runtime_remote_log}" \ +CLAUDE_PROJECT_DIR="${runtime_workspace}" \ + env -u ZAI_MCP_API_KEY -u ZAI_API_KEY -u Z_AI_API_KEY \ + bash "${remote_launcher}" web-search +grep -Fxq 'header=valid' "${runtime_remote_log}" \ + || fail "Remote MCP wrapper did not load the filtered runtime credential" + +codex_remote_log="${test_root}/remote-codex-env.log" +PATH="${test_bin}:/usr/bin:/bin" \ +STUB_LOG="${codex_remote_log}" \ +ZAI_API_KEY="bridge-test-secret" \ + env -u CLAUDE_PROJECT_DIR -u Z_AI_API_KEY -u ZAI_MCP_API_KEY \ + bash "${remote_launcher}" web-search +grep -Fxq 'header=valid' "${codex_remote_log}" \ + || fail "Remote MCP wrapper did not accept Codex's explicitly forwarded credential" +grep -Fxq 'canonical=unset' "${codex_remote_log}" \ + || fail "Remote MCP wrapper exposed Codex's credential to the bridge environment" +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${codex_remote_log}" \ + ZAI_API_KEY='quoted secret' \ + env -u CLAUDE_PROJECT_DIR -u Z_AI_API_KEY -u ZAI_MCP_API_KEY \ + bash "${remote_launcher}" web-search >"${test_root}/remote-codex-malformed.log" 2>&1; then + fail "Remote MCP wrapper accepted a malformed Codex-forwarded credential" +fi + +chmod 644 "${runtime_workspace}/.devcontainer/.mcp.env" +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${vision_log}" \ + CLAUDE_PROJECT_DIR="${runtime_workspace}" env -u ZAI_API_KEY -u Z_AI_API_KEY \ + bash "${vision_launcher}" >"${test_root}/vision-mode.log" 2>&1; then + fail "Vision MCP accepted an over-readable runtime credential file" +fi +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${runtime_remote_log}" \ + CLAUDE_PROJECT_DIR="${runtime_workspace}" \ + bash "${remote_launcher}" web-search >"${test_root}/remote-mode.log" 2>&1; then + fail "Remote MCP accepted an over-readable runtime credential file" +fi +chmod 600 "${runtime_workspace}/.devcontainer/.mcp.env" +printf 'GITHUB_PERSONAL_ACCESS_TOKEN=unused\nZAI_API_KEY="quoted secret"\n' \ + >"${runtime_workspace}/.devcontainer/.mcp.env" +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${vision_log}" \ + CLAUDE_PROJECT_DIR="${runtime_workspace}" env -u ZAI_API_KEY -u Z_AI_API_KEY \ + bash "${vision_launcher}" >"${test_root}/vision-malformed.log" 2>&1; then + fail "Vision MCP accepted a malformed runtime credential" +fi +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${runtime_remote_log}" \ + CLAUDE_PROJECT_DIR="${runtime_workspace}" \ + bash "${remote_launcher}" web-search >"${test_root}/remote-malformed.log" 2>&1; then + fail "Remote MCP accepted a malformed runtime credential" +fi + +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${runtime_remote_log}" \ + env -u CLAUDE_PROJECT_DIR -u ZAI_MCP_API_KEY -u ZAI_API_KEY -u Z_AI_API_KEY \ + bash "${remote_launcher}" web-search >"${test_root}/remote-missing.log" 2>&1; then + fail "Remote MCP wrapper accepted a missing key" +fi +grep -Fq 'A filtered Claude runtime credential or Codex-forwarded ZAI_API_KEY is required.' \ + "${test_root}/remote-missing.log" \ + || fail "Remote MCP missing-key failure did not come from credential validation" +missing_runtime_workspace="${test_root}/missing-runtime-workspace" +mkdir -p "${missing_runtime_workspace}" +if PATH="${test_bin}:/usr/bin:/bin" STUB_LOG="${runtime_remote_log}" \ + CLAUDE_PROJECT_DIR="${missing_runtime_workspace}" \ + ZAI_API_KEY="bridge-test-secret" \ + bash "${remote_launcher}" web-search >"${test_root}/remote-claude-no-fallback.log" 2>&1; then + fail "Remote MCP wrapper fell back to an ambient key for missing Claude runtime credentials" +fi +grep -Fq 'Filtered MCP credentials are missing' "${test_root}/remote-claude-no-fallback.log" \ + || fail "Remote MCP Claude source-precedence failure was not actionable" +if PATH="${test_bin}:/usr/bin:/bin" ZAI_MCP_API_KEY=placeholder \ + bash "${remote_launcher}" unknown >"${test_root}/remote-unknown.log" 2>&1; then + fail "Remote MCP wrapper accepted an unknown endpoint alias" +fi + +bash "${repo_root}/scripts/lint/test-devcontainer-runtime-credentials.sh" +printf 'PASS: isolated AI backends and project MCP catalogs\n' diff --git a/scripts/lint/test-devcontainer-lifecycle.sh b/scripts/lint/test-devcontainer-lifecycle.sh index 681de969f..f8a25f166 100755 --- a/scripts/lint/test-devcontainer-lifecycle.sh +++ b/scripts/lint/test-devcontainer-lifecycle.sh @@ -52,6 +52,9 @@ setup_npm_fixture() { local prefix="${fixture}/prefix" mkdir -p "${fake_bin}" "${prefix}/bin" "${prefix}/lib/node_modules/@openai/codex" \ "${prefix}/lib/node_modules/@anthropic-ai/claude-code" \ + "${prefix}/lib/node_modules/@github/copilot" \ + "${prefix}/lib/node_modules/mcp-remote" \ + "${prefix}/lib/node_modules/@z_ai/mcp-server" \ "${prefix}/lib/node_modules/@nanocollective" "${fixture}/cache" printf '%s\n' "1.0.0" > "${fixture}/installed-version" @@ -86,7 +89,7 @@ setup_npm_fixture() { ' list)' \ ' if [ "${NOVA_TEST_SCENARIO}" = "list-invalid" ]; then printf "not-json\n"; exit 1; fi' \ ' version="$(<"${NOVA_TEST_FIXTURE}/installed-version")"' \ - ' printf "{\"dependencies\":{\"@nanocollective/nanocoder\":{\"version\":\"%s\"},\"opencode-ai\":{\"version\":\"%s\"},\"@openai/codex\":{\"version\":\"%s\"},\"@anthropic-ai/claude-code\":{\"version\":\"%s\"}}}\n" "${version}" "${version}" "${version}" "${version}"' \ + ' printf "{\"dependencies\":{\"@nanocollective/nanocoder\":{\"version\":\"%s\"},\"opencode-ai\":{\"version\":\"%s\"},\"@openai/codex\":{\"version\":\"%s\"},\"@anthropic-ai/claude-code\":{\"version\":\"%s\"},\"@github/copilot\":{\"version\":\"%s\"},\"mcp-remote\":{\"version\":\"%s\"},\"@z_ai/mcp-server\":{\"version\":\"%s\"}}}\n" "${version}" "${version}" "${version}" "${version}" "${version}" "${version}" "${version}"' \ ' if [ "${NOVA_TEST_SCENARIO}" = "list-nonzero" ]; then exit 1; fi' \ ' ;;' \ ' view)' \ @@ -98,13 +101,15 @@ setup_npm_fixture() { ' fi' \ ' ;;' \ ' install)' \ - ' if [ "${NOVA_TEST_SCENARIO}" = "install-fail" ] || [ "${NOVA_TEST_SCENARIO}" = "broken-fallback" ]; then' \ - ' if [ "${NOVA_TEST_SCENARIO}" = "broken-fallback" ]; then' \ - ' unlink "${NOVA_TEST_FIXTURE}/prefix/bin/nanocoder"' \ - ' printf "#!/usr/bin/env bash\necho broken native payload >&2\nexit 88\n" > "${NOVA_TEST_FIXTURE}/prefix/bin/nanocoder"' \ - ' chmod +x "${NOVA_TEST_FIXTURE}/prefix/bin/nanocoder"' \ + ' if [[ "${NOVA_TEST_SCENARIO}" =~ ^(install-fail|broken-fallback|broken-mcp-fallback|missing-fallback)$ ]]; then' \ + ' if [[ "${NOVA_TEST_SCENARIO}" = broken-* ]]; then' \ + ' tool=nanocoder; if [ "${NOVA_TEST_SCENARIO}" = "broken-mcp-fallback" ]; then tool=zai-mcp-server; fi' \ + ' unlink "${NOVA_TEST_FIXTURE}/prefix/bin/${tool}"' \ + ' printf "#!/usr/bin/env bash\necho broken native payload >&2\nexit 88\n" > "${NOVA_TEST_FIXTURE}/prefix/bin/${tool}"' \ + ' chmod +x "${NOVA_TEST_FIXTURE}/prefix/bin/${tool}"' \ ' fi' \ - ' echo "simulated install failure" >&2' \ + ' if [ "${NOVA_TEST_SCENARIO}" = "missing-fallback" ]; then unlink "${NOVA_TEST_FIXTURE}/prefix/bin/codex"; fi' \ + ' echo "npm error E404: published tarball unavailable" >&2' \ ' exit 73' \ ' fi' \ ' echo 2.0.0 > "${NOVA_TEST_FIXTURE}/installed-version"' \ @@ -116,8 +121,12 @@ setup_npm_fixture() { # shellcheck disable=SC2016 write_executable "${prefix}/bin/fake-cli" \ '#!/usr/bin/env bash' \ + 'if [ "$(basename "$0")" = "zai-mcp-server" ]; then' \ + ' [[ $# = 0 && -n "${Z_AI_API_KEY:-}" && -z "${NOVA_TEST_FIXTURE:-}" ]] || exit 89' \ + ' exit 0' \ + 'fi' \ 'printf "%s %s\n" "$(basename "$0")" "$(<"${NOVA_TEST_FIXTURE}/installed-version")"' - for command_name in nanocoder opencode codex claude; do + for command_name in nanocoder opencode codex claude copilot mcp-remote zai-mcp-server; do ln -s fake-cli "${prefix}/bin/${command_name}" done @@ -167,12 +176,13 @@ result="$(run_installer resolution-fail --offline-ok)" assert_contains "${result}" "latest status could not be verified" result="$(run_installer resolution-fail)" -[ "${result%%$'\n'*}" != "0" ] || fail "strict create/build refresh should fail offline" +[ "${result%%$'\n'*}" != "0" ] || fail "strict build refresh should fail offline" assert_contains "${result}" "Unable to resolve" result="$(run_installer install-fail --offline-ok)" [ "${result%%$'\n'*}" = "0" ] || fail "offline start should survive install-stage failure" -assert_contains "${result}" "continuing with the intact installed tool versions" +assert_contains "${result}" "validating the installed tool versions before continuing" +assert_contains "${result}" "npm error E404" result="$(run_installer install-fail)" [ "${result%%$'\n'*}" = "73" ] || fail "strict install should preserve npm's failure code" @@ -181,6 +191,14 @@ result="$(run_installer broken-fallback --offline-ok)" [ "${result%%$'\n'*}" != "0" ] || fail "a non-runnable fallback must fail startup" assert_contains "${result}" "failed its version check" +result="$(run_installer broken-mcp-fallback --offline-ok)" +[ "${result%%$'\n'*}" != "0" ] || fail "a broken stdio MCP payload must fail startup" +assert_contains "${result}" "zai-mcp-server failed its stdio startup check" + +result="$(run_installer missing-fallback --offline-ok)" +[ "${result%%$'\n'*}" = "73" ] || fail "a missing fallback must preserve npm's install failure" +assert_contains "${result}" "installed @openai/codex fallback is not intact" + result="$(run_installer root)" [ "${result%%$'\n'*}" != "0" ] || fail "root npm installation must be rejected" assert_contains "${result}" "Refusing to install npm tools as root" @@ -364,4 +382,130 @@ bash "${REPO_ROOT}/.devcontainer/cleanup-artifacts.sh" "${workspace}" --all >/de [ ! -e "${workspace}/BenchmarkDotNet.Artifacts/build-cache" ] || fail "full cleanup exempted benchmark output" [ -f "${workspace}/src/source.cs" ] || fail "full cleanup deleted source" +# ============================================================================ +# NuGet cache ownership guard +# ============================================================================ +nuget_guard="${REPO_ROOT}/.devcontainer/ensure-nuget-cache.sh" +grep -F -- '$(id -u)' "${nuget_guard}" >/dev/null || + fail "NuGet cache guard must use the runtime UID" +grep -F -- '$(id -g)' "${nuget_guard}" >/dev/null || + fail "NuGet cache guard must use the runtime GID" + +nuget_home="${TEST_ROOT}/nuget-home" +mkdir -p "${nuget_home}/.nuget" + +nuget_healthy_bin="${TEST_ROOT}/nuget-healthy-bin" +mkdir -p "${nuget_healthy_bin}" +write_executable "${nuget_healthy_bin}/sudo" \ + '#!/usr/bin/env bash' \ + 'echo "healthy NuGet cache must not invoke sudo" >&2' \ + 'exit 98' +if ! HOME="${nuget_home}" PATH="${nuget_healthy_bin}:${PATH}" \ + bash "${nuget_guard}" 2>&1; then + fail "healthy NuGet cache should pass without sudo" +fi + +nuget_malformed_home="${TEST_ROOT}/nuget-malformed-home" +mkdir -p "${nuget_malformed_home}/.nuget/NuGet/NuGet.Config" +if nuget_malformed_output="$( + HOME="${nuget_malformed_home}" PATH="${nuget_healthy_bin}:${PATH}" bash "${nuget_guard}" 2>&1 +)"; then + fail "a directory in place of NuGet.Config must fail before restore" +fi +assert_contains "${nuget_malformed_output}" "NuGet.Config must be a regular file" +assert_contains "${nuget_malformed_output}" "docker volume rm novasharp-nuget-cache" + +if [ "$(id -u)" = "0" ]; then + echo "Skipping non-root NuGet cache cases because the test suite is running as root." +else + chmod 0555 "${nuget_home}/.nuget" + nuget_sudo_log="${TEST_ROOT}/nuget-sudo.log" + nuget_repair_bin="${TEST_ROOT}/nuget-repair-bin" + mkdir -p "${nuget_repair_bin}" + # shellcheck disable=SC2016 + write_executable "${nuget_repair_bin}/sudo" \ + '#!/usr/bin/env bash' \ + 'printf "%s\n" "$*" >> "${NOVA_TEST_SUDO_LOG}"' \ + 'if [ "${1:-}" = "-n" ]; then shift; fi' \ + 'command_name="${1:-}"' \ + 'if [ -z "${command_name}" ]; then exit 96; fi' \ + 'shift' \ + 'exec "$(command -v "${command_name}")" "$@"' + if ! HOME="${nuget_home}" PATH="${nuget_repair_bin}:${PATH}" \ + NOVA_TEST_SUDO_LOG="${nuget_sudo_log}" bash "${nuget_guard}" 2>&1; then + fail "root-owned-equivalent NuGet cache should be repaired" + fi + [ -w "${nuget_home}/.nuget" ] || fail "NuGet cache was not made writable" + assert_contains "$(<"${nuget_sudo_log}")" "chown -R $(id -u):$(id -g) ${nuget_home}/.nuget" + assert_contains "$(<"${nuget_sudo_log}")" "chmod -R u+rwX ${nuget_home}/.nuget" + + # Simulate sudo exposing a malformed config while repairing its parent. + write_executable "${nuget_repair_bin}/chown" \ + '#!/usr/bin/env bash' \ + 'chmod u+rwx "$3/NuGet"' + chmod 000 "${nuget_malformed_home}/.nuget/NuGet" + if nuget_malformed_output="$( + HOME="${nuget_malformed_home}" PATH="${nuget_repair_bin}:${PATH}" \ + NOVA_TEST_SUDO_LOG="${nuget_sudo_log}" bash "${nuget_guard}" 2>&1 + )"; then + fail "malformed NuGet.Config must still fail after its parent becomes accessible" + fi + [ -x "${nuget_malformed_home}/.nuget/NuGet" ] || + fail "test sudo must make the malformed configuration visible" + rm -- "${nuget_repair_bin}/chown" + assert_contains "${nuget_malformed_output}" "docker volume rm novasharp-nuget-cache" + + # An unreadable config file inside a writable cache still needs repair. + mkdir -p "${nuget_home}/.nuget/NuGet" + printf '\n' > "${nuget_home}/.nuget/NuGet/NuGet.Config" + chmod 000 "${nuget_home}/.nuget/NuGet/NuGet.Config" + if ! HOME="${nuget_home}" PATH="${nuget_repair_bin}:${PATH}" \ + NOVA_TEST_SUDO_LOG="${nuget_sudo_log}" bash "${nuget_guard}" 2>&1; then + fail "unreadable NuGet.Config should trigger a repair" + fi + [ -r "${nuget_home}/.nuget/NuGet/NuGet.Config" ] || + fail "NuGet.Config was not made readable" + chmod 0644 "${nuget_home}/.nuget/NuGet/NuGet.Config" + + nuget_no_sudo_bin="${TEST_ROOT}/nuget-no-sudo-bin" + mkdir -p "${nuget_no_sudo_bin}" + for command_name in id mkdir chown chmod; do + ln -s "$(command -v "${command_name}")" "${nuget_no_sudo_bin}/${command_name}" + done + bash_path="$(command -v bash)" + chmod 0555 "${nuget_home}/.nuget" + if nuget_no_sudo_output="$( + HOME="${nuget_home}" PATH="${nuget_no_sudo_bin}" "${bash_path}" "${nuget_guard}" 2>&1 + )"; then + fail "unwritable NuGet cache without sudo must fail" + fi + assert_contains "${nuget_no_sudo_output}" "sudo is unavailable" + + # A missing cache under a writable HOME must not require sudo. + nuget_empty_home="${TEST_ROOT}/nuget-empty-home" + mkdir -p "${nuget_empty_home}" + if ! HOME="${nuget_empty_home}" PATH="${nuget_no_sudo_bin}" \ + "${bash_path}" "${nuget_guard}" 2>&1; then + fail "missing NuGet cache under a writable HOME should not require sudo" + fi + [ -d "${nuget_empty_home}/.nuget" ] || fail "NuGet cache directory was not created" + + # Passwordless sudo being unavailable must produce the remediation message. + nuget_denied_bin="${TEST_ROOT}/nuget-denied-bin" + mkdir -p "${nuget_denied_bin}" + write_executable "${nuget_denied_bin}/sudo" \ + '#!/usr/bin/env bash' \ + 'echo "sudo: a password is required" >&2' \ + 'exit 1' + chmod 0555 "${nuget_home}/.nuget" + if nuget_denied_output="$( + HOME="${nuget_home}" PATH="${nuget_denied_bin}:${PATH}" bash "${nuget_guard}" 2>&1 + )"; then + fail "password-required sudo must fail the repair" + fi + assert_contains "${nuget_denied_output}" "passwordless sudo is unavailable" + assert_contains "${nuget_denied_output}" "docker volume rm novasharp-nuget-cache" + chmod 0755 "${nuget_home}/.nuget" +fi + echo "Devcontainer lifecycle behavior checks passed." diff --git a/scripts/lint/test-devcontainer-runtime-credentials.sh b/scripts/lint/test-devcontainer-runtime-credentials.sh new file mode 100755 index 000000000..52aecad96 --- /dev/null +++ b/scripts/lint/test-devcontainer-runtime-credentials.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# Exercise the image's installed Claude wrappers with synthetic credentials. +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +fixture="$(mktemp -d "${TMPDIR:-/tmp}/novasharp-runtime-credentials.XXXXXX")" +trap 'rm -rf -- "${fixture:?}"' EXIT +workspace="${fixture}/workspace with spaces" +private_home="${fixture}/home" +launchers="${fixture}/bin" +mkdir -p "${workspace}/.devcontainer" "${private_home}" "${launchers}" +chmod 0700 "${private_home}" +cp "${repo_root}/.devcontainer/zai-mcp-vision.sh" "${launchers}/zai-mcp-vision" +cp "${repo_root}/.devcontainer/zai-mcp-remote.sh" "${launchers}/zai-mcp-remote" +cp "${repo_root}/.devcontainer/mcp_credentials.py" "${launchers}/read-claude-mcp-key.py" +printf 'ZAI_API_KEY=host-mount-sentinel\n' >"${workspace}/.devcontainer/.mcp.env" +chmod 0777 "${workspace}/.devcontainer/.mcp.env" + +cat >"${launchers}/zai-mcp-server" <<'STUB' +#!/usr/bin/env bash +set -eu +[[ ${Z_AI_API_KEY:?} = "$(<"${EXPECTED_FILE:?}")" && -z ${ZAI_API_KEY+x} && -z ${GITHUB_PERSONAL_ACCESS_TOKEN+x} ]] +STUB +cat >"${launchers}/mcp-remote" <<'STUB' +#!/usr/bin/env bash +set -eu +[[ $# = 3 && $2 = --header-file && $(<"$3") = "Authorization: Bearer $(<"${EXPECTED_FILE:?}")" ]] +[[ -z ${ZAI_API_KEY+x} && -z ${Z_AI_API_KEY+x} && -z ${GITHUB_PERSONAL_ACCESS_TOKEN+x} ]] +STUB +chmod +x "${launchers}/zai-mcp-server" "${launchers}/mcp-remote" + +stage() { + env HOME="${private_home}" ZAI_API_KEY="$1" GITHUB_PERSONAL_ACCESS_TOKEN=synthetic-github \ + python3 -EsB "${repo_root}/.devcontainer/mcp_credentials.py" stage "${workspace}" +} + +launch() { + local project="$1" + shift + env HOME="${private_home}" PATH="${launchers}:${PATH}" EXPECTED_FILE="${fixture}/expected" \ + CLAUDE_PROJECT_DIR="${project}" ZAI_API_KEY=ambient-sentinel Z_AI_API_KEY=alias-sentinel \ + GITHUB_PERSONAL_ACCESS_TOKEN=synthetic-github bash "${launchers}/$1" "${@:2}" +} + +reject_both() { + local project="$1" expected_error="$2" launcher + for launcher in zai-mcp-vision zai-mcp-remote; do + if launch "${project}" "${launcher}" web-search >"${fixture}/failure" 2>&1; then + echo "${launcher} accepted an unsafe or missing credential" >&2 + exit 1 + fi + if ! grep -Fq "${expected_error}" "${fixture}/failure"; then + cat "${fixture}/failure" >&2 + exit 1 + fi + done +} + +for sentinel in synthetic-first synthetic-rotated; do + stage "${sentinel}" + printf '%s\n' "${sentinel}" >"${fixture}/expected" + launch "${workspace}/." zai-mcp-vision + launch "${workspace}" zai-mcp-remote web-search +done + +files=("${private_home}/.novasharp-mcp/"*) +[[ ${#files[@]} -eq 1 && -f ${files[0]} ]] +credential="${files[0]}" +[[ $(stat -c '%a' "${private_home}/.novasharp-mcp") = 700 && $(stat -c '%a' "${credential}") = 600 ]] +[[ $(<"${credential}") = 'ZAI_API_KEY=synthetic-rotated' ]] + +# Rotate after the reader has opened the previous inode but before it checks it. +python3 -EsB - "${repo_root}/.devcontainer" "${credential}" <<'PY' +import os +from pathlib import Path +import sys +from unittest.mock import patch + +sys.path.insert(0, sys.argv[1]) +from mcp_credentials import read_key + +path = Path(sys.argv[2]) +replacement = path.with_suffix(".replacement") +replacement.write_bytes(path.read_bytes()) +replacement.chmod(0o600) +open_file = os.open + +def open_then_replace(path, flags): + fd = open_file(path, flags) + os.replace(replacement, path) + return fd + +with patch("mcp_credentials.os.open", open_then_replace): + assert read_key(path, standalone=False) == b"synthetic-rotated" +PY + +mkdir "${fixture}/another project" +reject_both "${fixture}/another project" "credentials are missing" +chmod 0755 "${private_home}/.novasharp-mcp" +reject_both "${workspace}" "mode 700" +chmod 0700 "${private_home}/.novasharp-mcp" +chmod 0644 "${credential}" +reject_both "${workspace}" "mode 600" +chmod 0600 "${credential}" +printf 'UNRELATED=sentinel\n' >>"${credential}" +reject_both "${workspace}" "Unexpected assignment" +rm -- "${credential}" +ln -s "${workspace}/.devcontainer/.mcp.env" "${credential}" +reject_both "${workspace}" "Cannot read" + +stage "" +[[ -f ${credential} && ! -L ${credential} && ! -s ${credential} ]] +reject_both "${workspace}" "invalid ZAI_API_KEY" +printf 'PASS: private devcontainer Claude MCP credential storage\n' diff --git a/scripts/lint/test-devcontainer-windows-preflight.ps1 b/scripts/lint/test-devcontainer-windows-preflight.ps1 new file mode 100644 index 000000000..7e15a75f7 --- /dev/null +++ b/scripts/lint/test-devcontainer-windows-preflight.ps1 @@ -0,0 +1,100 @@ +# Exercise the host command with the Windows path expansion performed by the CLI. +$ErrorActionPreference = 'Stop' +$repo = Get-Item (Join-Path $PSScriptRoot '../..') +$config = Get-Content -LiteralPath (Join-Path $repo '.devcontainer/devcontainer.json') -Raw | ConvertFrom-Json +$fixture = [IO.Directory]::CreateTempSubdirectory('NovaSharp preflight ') +$workspace = $fixture.CreateSubdirectory('checkout with spaces') +$helpers = $workspace.CreateSubdirectory('.devcontainer') +$sourceFile = Join-Path $workspace '.env.local' +$envFile = Join-Path $helpers '.mcp.env' +$currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + +function Assert-PrivateAcl($path) { + $acl = Get-Acl -LiteralPath $path + if (!$acl.AreAccessRulesProtected) { throw "Inherited permissions on $path" } + if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $currentSid) { + throw "Wrong owner on $path" + } + $rules = $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) + if ($rules.Count -ne 1 -or $rules[0].IdentityReference.Value -ne $currentSid -or + $rules[0].AccessControlType -ne 'Allow' -or $rules[0].FileSystemRights -ne 'FullControl') { + throw "Expected a single access rule granting the current user full control of $path" + } +} + +function Invoke-Preflight([switch]$ShouldFail) { + $command, [string[]] $arguments = $config.initializeCommand | ForEach-Object { + $_.Replace('${localWorkspaceFolder}', $workspace.FullName) + } + $output = & $command @arguments 2>&1 + $result = $LASTEXITCODE + if (($output -join "`n") -match 'synthetic-(zai|github|unrelated)') { + throw 'Host preflight logged a credential' + } + if (($result -ne 0) -ne $ShouldFail.IsPresent) { + throw "Unexpected preflight exit $result. $output" + } +} + +try { + Copy-Item (Join-Path $repo '.devcontainer/check-mcp-env.sh') $helpers.FullName + Copy-Item (Join-Path $repo '.devcontainer/mcp-env-windows.ps1') $helpers.FullName + Push-Location -LiteralPath $workspace.FullName + try { + Invoke-Preflight + if ((Get-Item -LiteralPath $envFile).Length -ne 0) { throw 'Expected an empty Docker env file' } + + $expected = @('GITHUB_PERSONAL_ACCESS_TOKEN=synthetic-github', 'ZAI_API_KEY=synthetic-zai') + [IO.File]::WriteAllLines($sourceFile, $expected + 'OTHER=synthetic-unrelated') + $acl = Get-Acl -LiteralPath $sourceFile + $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new( + [Security.Principal.SecurityIdentifier]::new('S-1-5-32-545'), 'Read', 'Allow')) + Set-Acl -LiteralPath $sourceFile -AclObject $acl + Invoke-Preflight + Assert-PrivateAcl $sourceFile + Assert-PrivateAcl $envFile + if ((Get-Content -LiteralPath $envFile) -join "`n" -cne ($expected -join "`n")) { + throw 'Docker env file contains the wrong assignments' + } + + [IO.File]::AppendAllText($sourceFile, "ZAI_API_KEY=duplicate`n") + Invoke-Preflight -ShouldFail + if ((Get-Content -LiteralPath $envFile) -join "`n" -cne ($expected -join "`n")) { + throw 'Invalid input changed the last published file' + } + Remove-Item -LiteralPath $sourceFile + Invoke-Preflight + if ((Get-Item -LiteralPath $envFile).Length -ne 0) { throw 'Removed credentials survived' } + + $outsideFile = Join-Path $fixture 'outside' + [IO.File]::WriteAllText($outsideFile, 'sentinel') + $originalAcl = (Get-Acl -LiteralPath $outsideFile).Sddl + foreach ($linkedPath in @($sourceFile, $envFile)) { + if ([IO.File]::Exists($linkedPath)) { [IO.File]::Delete($linkedPath) } + New-Item -ItemType HardLink -Path $linkedPath -Target $outsideFile | Out-Null + Invoke-Preflight -ShouldFail + if ((Get-Acl -LiteralPath $outsideFile).Sddl -ne $originalAcl -or + [IO.File]::ReadAllText($outsideFile) -cne 'sentinel') { throw 'Preflight modified a hardlink' } + [IO.File]::Delete($linkedPath) + } + + # A junction does not require Windows developer mode or symlink privileges. + $target = Join-Path $fixture 'redirected' + Move-Item -LiteralPath $helpers.FullName -Destination $target + New-Item -ItemType Junction -Path $helpers.FullName -Target $target | Out-Null + try { + [IO.File]::WriteAllText($envFile, 'sentinel') + Invoke-Preflight -ShouldFail + if ([IO.File]::ReadAllText($envFile) -cne 'sentinel') { throw 'Preflight followed a junction' } + } finally { + [IO.Directory]::Delete($helpers.FullName) + } + } finally { + Pop-Location + } +} finally { + if ($fixture.Parent.FullName -ne (Get-Item ([IO.Path]::GetTempPath())).FullName.TrimEnd('\') -or + !$fixture.Name.StartsWith('NovaSharp preflight ')) { throw 'Unexpected fixture location' } + Remove-Item -Recurse -Force -LiteralPath $fixture.FullName +} +Write-Output 'Windows host command, credential filtering and native ACL checks passed.' diff --git a/scripts/test/README.md b/scripts/test/README.md index fbac1a601..17b1be1d7 100644 --- a/scripts/test/README.md +++ b/scripts/test/README.md @@ -2,6 +2,15 @@ This folder contains quick test execution utilities for NovaSharp development. +## Devcontainer startup + +With Docker running and `devcontainer` on PATH, run +`python scripts/test/devcontainer-smoke.py` to build the current committed +checkout and exercise the configured lifecycle. Use `--image IMAGE` to reuse +a local devcontainer image built from that commit with its features. On Windows, +`--temp-parent ..` places the disposable checkout on the same drive as the repo. +The test uses isolated containers, a named NuGet volume, and synthetic credentials. + ## quick.sh - Quick Test Runner Optimized script for fast iterative test execution with filtering support. diff --git a/scripts/test/devcontainer-smoke.py b/scripts/test/devcontainer-smoke.py new file mode 100644 index 000000000..3ae8789a4 --- /dev/null +++ b/scripts/test/devcontainer-smoke.py @@ -0,0 +1,272 @@ +"""Exercise a committed NovaSharp checkout using the Dev Containers CLI and Docker.""" + +import argparse +from contextlib import ExitStack +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import uuid + + +ROOT = Path(__file__).resolve().parents[2] +GITHUB = "GITHUB_PERSONAL_ACCESS_TOKEN" +ZAI = "ZAI_API_KEY" +UNRELATED = "NOVASHARP_SMOKE_UNRELATED" + + +def require(condition, message): + if not condition: + raise RuntimeError(message) + + +def cli_command(): + executable = shutil.which("devcontainer") + require(executable, "Install @devcontainers/cli and put devcontainer on PATH.") + # npm's Windows batch wrapper reparses command-line metacharacters. + if os.name == "nt" and Path(executable).suffix.lower() in {".cmd", ".bat"}: + for root in (Path(executable).parent, Path(executable).parent.parent): + for modules in (root / "node_modules", root): + entry = modules / "@devcontainers" / "cli" / "devcontainer.js" + if entry.is_file(): + return ["node", str(entry)] + raise RuntimeError("Cannot locate devcontainer.js beside the npm launcher.") + return [executable] + + +def sha(value): + return hashlib.sha256(value.encode()).hexdigest() + + +# Run as the devcontainer user. The installed wrappers launch these local stdio +# MCP doubles. Neither the test command line nor the MCP replies contain keys. +MCP_PROBE = r''' +import hashlib, json, os, pathlib, subprocess, sys, tempfile + +def sha(value): + return hashlib.sha256(value.encode()).hexdigest() + +github, zai = sys.argv[1:3] +assert sha(os.environ["GITHUB_PERSONAL_ACCESS_TOKEN"]) == github +assert sha(os.environ["ZAI_API_KEY"]) == zai +assert "NOVASHARP_SMOKE_UNRELATED" not in os.environ +request = {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": "2025-03-26", "capabilities": {}, "clientInfo": {"name": "smoke", "version": "1"}}} +server = r"""#!/usr/bin/env python3 +import hashlib, json, os, pathlib, sys +request = json.loads(input()) +assert request['method'] == 'initialize' +for key in ('GITHUB_PERSONAL_ACCESS_TOKEN', 'ZAI_API_KEY', 'NOVASHARP_SMOKE_UNRELATED'): + assert key not in os.environ +if pathlib.Path(sys.argv[0]).name == 'zai-mcp-server': + key = os.environ['Z_AI_API_KEY'] +else: + assert sys.argv[1] == 'https://api.z.ai/api/mcp/web_search_prime/mcp' + assert 'Z_AI_API_KEY' not in os.environ and sys.argv[2] == '--header-file' + header = pathlib.Path(sys.argv[3]).read_bytes() + assert header.startswith(b'Authorization: Bearer ') and header.endswith(b'\n') and header.count(b'\n') == 1 + key = header.removeprefix(b'Authorization: Bearer ').removesuffix(b'\n').decode() +assert hashlib.sha256(key.encode()).hexdigest() == os.environ['EXPECTED_DIGEST'] +print(json.dumps({'jsonrpc':'2.0','id':request['id'],'result':{ + 'protocolVersion':request['params']['protocolVersion'],'capabilities':{},'serverInfo':{'name':'smoke','version':'1'}}})) +""" +with tempfile.TemporaryDirectory() as folder: + for binary in ("mcp-remote", "zai-mcp-server"): + path = pathlib.Path(folder, binary) + path.write_text(server) + path.chmod(0o700) + env = dict(os.environ, PATH=folder + ":" + os.environ["PATH"], EXPECTED_DIGEST=zai) + env.pop("CLAUDE_PROJECT_DIR", None) + for claude in (False, True): + if claude: + env.pop("ZAI_API_KEY") + env["CLAUDE_PROJECT_DIR"] = os.getcwd() + for command in (["zai-mcp-vision"], ["zai-mcp-remote", "web-search"]): + result = subprocess.run(command, env=env, input=json.dumps(request) + "\n", + text=True, stdout=subprocess.PIPE, check=True) + reply = json.loads(result.stdout) + assert reply["id"] == 1 and reply["result"]["serverInfo"]["name"] == "smoke" +''' + + +def smoke(image, temp_parent): + name = "novasharp-smoke-" + uuid.uuid4().hex + secrets = {key: uuid.uuid4().hex for key in (GITHUB, ZAI, UNRELATED)} + clean_env = {key: value for key, value in os.environ.items() if key not in secrets} + cli = cli_command() + label = "novasharp.smoke=" + name + + def run(*args, input_text=None, cwd=None): + result = subprocess.run( + list(map(str, args)), cwd=cwd, env=clean_env, + input=input_text.encode("utf-8") if input_text is not None else None, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + # Text-mode stdin on Windows would translate LF into CRLF inside + # Dockerfiles and Bash programs executed by the Linux container. + result.stdout = result.stdout.decode("utf-8", errors="replace") + result.stderr = result.stderr.decode("utf-8", errors="replace") + log = result.stdout + result.stderr + require(not any(value in log for value in secrets.values()), + f"{args[0]} {args[1]} disclosed a synthetic credential in its output.") + if result.returncode: + raise RuntimeError(f"{args[0]} {args[1]} exited {result.returncode}\n{log}") + return result + + print("Dev Containers CLI", run(*cli, "--version").stdout.strip(), flush=True) + print("Docker client/server", run("docker", "version", "--format", + "{{.Client.Version}}/{{.Server.Version}}").stdout.strip(), flush=True) + with tempfile.TemporaryDirectory(prefix="novasharp-smoke-", dir=temp_parent) as tmp, ExitStack() as cleanup: + scratch = Path(tmp).resolve() + workspace = scratch / "NovaSharp smoke" + print(f"Cloning committed HEAD into {workspace}", flush=True) + run("git", "clone", "--quiet", "--no-hardlinks", "-c", "core.longpaths=true", "--", ROOT, workspace) + config_file = workspace / ".devcontainer" / "devcontainer.json" + config = json.loads("\n".join( + line for line in config_file.read_text(encoding="utf-8").splitlines() + if not line.lstrip().startswith("//") + )) + mount = "source=novasharp-nuget-cache,target=/home/vscode/.nuget,type=volume" + require(mount in config["mounts"], "Cannot isolate the project's NuGet volume.") + config["mounts"][config["mounts"].index(mount)] = mount.replace("novasharp-nuget-cache", name) + config_file.write_text(json.dumps(config), encoding="utf-8") + context = (config_file.parent / config["build"]["context"]).resolve() + ws_args = ["--workspace-folder", str(workspace), "--id-label", label] + + runtime = name + ":runtime" + if image: + # Avoid tagging or deleting a caller-owned image when given an ID. + image_info = json.loads(run("docker", "image", "inspect", image).stdout)[0] + source = next(iter(image_info["RepoTags"] or image_info["RepoDigests"] or [image_info["Id"]])) + else: + source = name + ":project" + print("Building the project image and configured features", flush=True) + run(*cli, "build", "--workspace-folder", workspace, "--image-name", source) + cleanup.callback(run, "docker", "image", "rm", "--no-prune", source) + # Prebuilt images can carry the original workspace mount and lifecycle in + # their metadata. Apply the isolated fixture's config exactly once. + empty = scratch / "empty" + empty.mkdir() + run("docker", "build", "-t", runtime, "-f", "-", empty, + input_text=f'FROM {source}\nLABEL devcontainer.metadata="[]"\n') + cleanup.callback(run, "docker", "image", "rm", "--no-prune", runtime) + del config["build"] + config.pop("features", None) + config["image"] = runtime + config_file.write_text(json.dumps(config), encoding="utf-8") + run("docker", "volume", "create", "--label", label, name) + cleanup.callback(run, "docker", "volume", "rm", name) + + def remove_containers(): + ids = run("docker", "ps", "-aq", "--filter", f"label={label}").stdout.split() + if ids: + run("docker", "rm", "-fv", *ids) + + cleanup.callback(remove_containers) + + def up(stage): + print(stage, flush=True) + result = run(*cli, "up", *ws_args) + info = json.loads(result.stdout.strip().splitlines()[-1]) + require(info["outcome"] == "success", f"{stage} failed.") + container = info["containerId"] + source_name = run("docker", "inspect", "--format", + '{{range .Mounts}}{{if eq .Destination "/home/vscode/.nuget"}}{{.Name}}{{end}}{{end}}', + container).stdout.strip() + require(source_name == name, "Wrong NuGet volume mounted.") + require(info["remoteUser"] == "vscode", "Unexpected devcontainer user.") + run(*cli, "exec", *ws_args, "zsh", "-ilc", + '[[ -o interactive && -o login && "$PWD" == "$1" && "$(id -un)" == vscode ' + '&& "$(git rev-parse --show-toplevel)" == "$PWD" ]]', + "smoke", info["remoteWorkspaceFolder"]) + run("docker", "exec", "-w", info["remoteWorkspaceFolder"], "-u", info["remoteUser"], + container, "bash", "-ec", + 'test -w "$HOME/.nuget"; test -s src/runtime/WallstopStudios.NovaSharp.Interpreter/obj/project.assets.json') + return info, result.stdout + result.stderr + + def exec_script(info, *command, script): + run("docker", "exec", "-i", "-u", info["remoteUser"], "-w", info["remoteWorkspaceFolder"], + info["containerId"], *command, input_text=script) + + no_keys = r""" +test -z "${GITHUB_PERSONAL_ACCESS_TOKEN+x}${ZAI_API_KEY+x}${NOVASHARP_SMOKE_UNRELATED+x}" +for runtime_credential in "$HOME"/.novasharp-mcp/*; do + test -f "$runtime_credential" && test ! -s "$runtime_credential" || exit 1 +done +bin=$(mktemp -d) +trap 'rm -rf -- "$bin"' EXIT +ln -s /bin/true "$bin/zai-mcp-server" +ln -s /bin/true "$bin/mcp-remote" +export PATH="$bin:$PATH" CLAUDE_PROJECT_DIR="$PWD" ZAI_API_KEY=unexpected-ambient-fallback +assert_refuses() { + if output=$("$@" 2>&1); then + echo "MCP launcher accepted a removed credential: $1" >&2 + exit 1 + fi + case "$output" in + *ZAI_API_KEY*) ;; + *) printf '%s\n' "$output" >&2; exit 1 ;; + esac +} +assert_refuses zai-mcp-vision +assert_refuses zai-mcp-remote web-search +""" + source_env = workspace / ".env.local" + filtered = config_file.parent / ".mcp.env" + require(not source_env.exists(), "Fresh checkout unexpectedly includes .env.local.") + fresh, _ = up("Starting with a fresh cache and no credentials") + require(filtered.read_bytes() == b"", "Expected an empty filtered environment.") + exec_script(fresh, "bash", "-e", script=no_keys) + run("docker", "exec", "-u", "0", fresh["containerId"], "bash", "-ec", + 'cd /home/vscode/.nuget; touch .ownership-probe; chown 0:0 . .ownership-probe; chmod 700 .') + remove_containers() + source_env.write_bytes("".join(f"{key}={value}\r\n" for key, value in secrets.items()).encode()) + repaired, log = up("Recreating with a root-owned cache and synthetic credentials") + require("Repaired ownership" in log, "The cache repair did not run.") + expected = {f"{key}={secrets[key]}" for key in (GITHUB, ZAI)} + require(set(filtered.read_text().splitlines()) == expected, "Wrong Docker env-file contents.") + exec_script(repaired, "python3", "-", sha(secrets[GITHUB]), sha(secrets[ZAI]), script=MCP_PROBE) + + # Docker itself applies .dockerignore. Inspect the result of COPY over + # the whole configured build context, including dotfiles, in scratch. + exported = scratch / "exported-context" + (filtered.parent / ".mcp.env.interrupted").write_bytes(filtered.read_bytes()) + run("docker", "build", "-f", "-", "--output", f"type=local,dest={exported}", context, + input_text="FROM scratch\nCOPY . /\n") + require((exported / "check-mcp-env.sh").is_file(), "Wrong Docker build context.") + for path in exported.rglob("*"): + if path.is_file(): + content = path.read_bytes() + require(not any(secret.encode() in content for secret in secrets.values()), + "Docker included a synthetic credential in a COPY layer.") + run("docker", "history", "--no-trunc", runtime) + run("docker", "logs", repaired["containerId"]) + + def owner_stamp(info): + return run("docker", "exec", info["containerId"], "stat", "-c", "%u:%g %z", + "/home/vscode/.nuget/.ownership-probe").stdout + + stamp = owner_stamp(repaired) + require(not stamp.startswith("0:"), "Cache probe is still root-owned after restore.") + run("docker", "stop", repaired["containerId"]) + restarted, log = up("Restarting the repaired container and checking cache ownership") + require(restarted["containerId"] == repaired["containerId"], "Restart replaced the container.") + require("Repaired ownership" not in log and owner_stamp(restarted) == stamp, + "Restart changed existing cache ownership.") + remove_containers() + source_env.unlink() + cleared, _ = up("Recreating after removing credentials") + require(filtered.read_bytes() == b"", "Stale credentials survived removal.") + exec_script(cleared, "bash", "-e", script=no_keys) + print("Devcontainer startup smoke test passed.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--image", help="Reuse a local project image built from this commit with its features.") + parser.add_argument("--temp-parent", type=Path, help="Create the disposable checkout on this filesystem.") + args = parser.parse_args() + smoke(args.image, args.temp_parent) diff --git a/scripts/test/quick.sh b/scripts/test/quick.sh index 00e8d16be..008a265d4 100755 --- a/scripts/test/quick.sh +++ b/scripts/test/quick.sh @@ -122,7 +122,7 @@ export DOTNET_CLI_TELEMETRY_OPTOUT=1 export DOTNET_NOLOGO=1 export TESTINGPLATFORM_NOBANNER=1 -# Ensure .NET 9 can run .NET 8 test host +# Allow newer .NET runtimes to run the .NET 8 test host if [[ -z "${DOTNET_ROLL_FORWARD:-}" ]]; then export DOTNET_ROLL_FORWARD="Major" fi diff --git a/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugServer.cs b/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugServer.cs index df42d91b3..debf12c17 100644 --- a/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugServer.cs +++ b/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugServer.cs @@ -680,9 +680,8 @@ private static string GetWatchElementName(WatchType watchType) return known; } - return WatchElementNameCache.GetOrAdd( - watchType, - static wt => InvariantString.ToLowerInvariantIfNeeded(wt.ToString()) + return WatchElementNameCache.GetOrAdd(watchType, static wt => + InvariantString.ToLowerInvariantIfNeeded(wt.ToString()) ); } } diff --git a/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugWebHost.cs b/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugWebHost.cs index 417f6eaa9..96c10c83e 100644 --- a/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugWebHost.cs +++ b/src/debuggers/WallstopStudios.NovaSharp.RemoteDebugger/DebugWebHost.cs @@ -47,10 +47,9 @@ private static byte[] GetResourceData(string resourceName) { Assembly assembly = Assembly.GetExecutingAssembly(); - using Stream stream = - assembly.GetManifestResourceStream( - "WallstopStudios.NovaSharp.RemoteDebugger.Resources." + resourceName - ) + using Stream stream = assembly.GetManifestResourceStream( + "WallstopStudios.NovaSharp.RemoteDebugger.Resources." + resourceName + ) ?? throw new InvalidOperationException( $"Embedded resource '{resourceName}' could not be located." ); diff --git a/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/NovaSharpVsCodeDebugServer.cs b/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/NovaSharpVsCodeDebugServer.cs index ab2e0225b..4e9976c04 100644 --- a/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/NovaSharpVsCodeDebugServer.cs +++ b/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/NovaSharpVsCodeDebugServer.cs @@ -362,42 +362,39 @@ private void ListenThread(TcpListener serverSocket) clientSocket.RemoteEndPoint ); - SpawnThread( - "VsCodeDebugSession_" + sessionId, - () => + SpawnThread("VsCodeDebugSession_" + sessionId, () => + { + using (NetworkStream networkStream = new NetworkStream(clientSocket)) { - using (NetworkStream networkStream = new NetworkStream(clientSocket)) + try + { + RunSession(sessionId, networkStream); + } + catch (InterpreterException ex) + { + Log( + "[{0}] : Interpreter error : {1}", + sessionId, + ex.DecoratedMessage ?? ex.Message + ); + } + catch (IOException ex) { - try - { - RunSession(sessionId, networkStream); - } - catch (InterpreterException ex) - { - Log( - "[{0}] : Interpreter error : {1}", - sessionId, - ex.DecoratedMessage ?? ex.Message - ); - } - catch (IOException ex) - { - Log("[{0}] : IO error : {1}", sessionId, ex.Message); - } - catch (InvalidOperationException ex) - { - Log("[{0}] : Session error : {1}", sessionId, ex.Message); - } + Log("[{0}] : IO error : {1}", sessionId, ex.Message); } + catch (InvalidOperationException ex) + { + Log("[{0}] : Session error : {1}", sessionId, ex.Message); + } + } #if DOTNET_CORE - clientSocket.Dispose(); + clientSocket.Dispose(); #else - clientSocket.Close(); + clientSocket.Close(); #endif - Log("[{0}] : Client connection closed", sessionId); - } - ); + Log("[{0}] : Client connection closed", sessionId); + }); } } catch (SocketException e) diff --git a/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/SDK/Utilities.cs b/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/SDK/Utilities.cs index 8d94586ba..b75b02c66 100644 --- a/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/SDK/Utilities.cs +++ b/src/debuggers/WallstopStudios.NovaSharp.VsCodeDebugger/SDK/Utilities.cs @@ -63,24 +63,21 @@ public static string ExpandVariables( variables = new { }; } Type type = variables.GetType(); - return Variable.Replace( - format, - match => + return Variable.Replace(format, match => + { + string name = match.Groups[1].Value; + if (!underscoredOnly || name.StartsWith('_')) { - string name = match.Groups[1].Value; - if (!underscoredOnly || name.StartsWith('_')) + PropertyInfo property = Framework.Do.GetProperty(type, name); + if (property != null) { - PropertyInfo property = Framework.Do.GetProperty(type, name); - if (property != null) - { - object value = property.GetValue(variables, null); - return value.ToString(); - } - return '{' + name + ": not found}"; + object value = property.GetValue(variables, null); + return value.ToString(); } - return match.Groups[0].Value; + return '{' + name + ": not found}"; } - ); + return match.Groups[0].Value; + }); } /** diff --git a/src/interop/WallstopStudios.NovaSharp.Interop.Generator/LuaInteropSourceGenerator.cs b/src/interop/WallstopStudios.NovaSharp.Interop.Generator/LuaInteropSourceGenerator.cs index a2054af2f..f9b42b71f 100644 --- a/src/interop/WallstopStudios.NovaSharp.Interop.Generator/LuaInteropSourceGenerator.cs +++ b/src/interop/WallstopStudios.NovaSharp.Interop.Generator/LuaInteropSourceGenerator.cs @@ -31,13 +31,11 @@ public void Initialize(IncrementalGeneratorInitializationContext context) ) .Where(static model => model != null); - context.RegisterSourceOutput( - luaObjects, - static (sourceContext, model) => - sourceContext.AddSource( - model.HintName, - SourceText.From(EmitSource(model), Encoding.UTF8) - ) + context.RegisterSourceOutput(luaObjects, static (sourceContext, model) => + sourceContext.AddSource( + model.HintName, + SourceText.From(EmitSource(model), Encoding.UTF8) + ) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Api/LuaEngineAdapters.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Api/LuaEngineAdapters.cs index 0948f534e..36c20962a 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Api/LuaEngineAdapters.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Api/LuaEngineAdapters.cs @@ -78,8 +78,8 @@ internal sealed class LuaRandomProviderAdapter : IRandomProvider /// public LuaRandomProviderAdapter(ILuaRandomProvider randomProvider) { - _randomProvider = - randomProvider ?? throw new ArgumentNullException(nameof(randomProvider)); + _randomProvider = randomProvider + ?? throw new ArgumentNullException(nameof(randomProvider)); } /// diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Compatibility/PreserveAttribute.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Compatibility/PreserveAttribute.cs new file mode 100644 index 000000000..167c5ee39 --- /dev/null +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Compatibility/PreserveAttribute.cs @@ -0,0 +1,10 @@ +namespace WallstopStudios.NovaSharp.Interpreter.Compatibility +{ + using System; + + /// + /// Roots a reflection-bound method in the Unity linker without a UnityEngine dependency. + /// + [AttributeUsage(AttributeTargets.Method, Inherited = false)] + internal sealed class PreserveAttribute : Attribute { } +} diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/CoroutineModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/CoroutineModule.cs index 249f1e872..ac63dbb1d 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/CoroutineModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/CoroutineModule.cs @@ -82,9 +82,8 @@ CallbackArgumentsView args } LuaValue handle = Create(executionContext, args); - return LuaValue.NewCallbackView( - executionContext.Script, - callArgs => ResumeCoroutineWithArguments(handle.Coroutine, callArgs, 0) + return LuaValue.NewCallbackView(executionContext.Script, callArgs => + ResumeCoroutineWithArguments(handle.Coroutine, callArgs, 0) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/DebugModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/DebugModule.cs index 46c3a9647..919c099c4 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/DebugModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/DebugModule.cs @@ -1597,16 +1597,13 @@ out CallStackItem frame private static LuaValue GetUpvalueIdentifier(Script script, UpvalueCell upvalueSlot) { return UpvalueIdentifiers - .GetValue( - upvalueSlot, - slot => new UpvalueIdentifierValue( - UserData.Create( - script, - new UpvalueIdentifier(slot), - UpvalueIdentifierDescriptorInstance - ) + .GetValue(upvalueSlot, slot => new UpvalueIdentifierValue( + UserData.Create( + script, + new UpvalueIdentifier(slot), + UpvalueIdentifierDescriptorInstance ) - ) + )) .Value; } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/IoModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/IoModule.cs index 9759a6a61..fa9986cbc 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/IoModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/IoModule.cs @@ -243,9 +243,8 @@ private static LuaValue Close( CallbackArgumentsView args ) { - FileUserDataBase outp = - args[0] - .CheckUserDataType("close", 0, TypeValidationOptions.AllowNil) + FileUserDataBase outp = args[0] + .CheckUserDataType("close", 0, TypeValidationOptions.AllowNil) ?? GetDefaultFile(executionContext, StandardFileType.StdOut); return outp.Close(executionContext, args); } @@ -277,9 +276,8 @@ private static LuaValue Flush( CallbackArgumentsView args ) { - FileUserDataBase outp = - args[0] - .CheckUserDataType("close", 0, TypeValidationOptions.AllowNil) + FileUserDataBase outp = args[0] + .CheckUserDataType("close", 0, TypeValidationOptions.AllowNil) ?? GetDefaultFile(executionContext, StandardFileType.StdOut); outp.Flush(); return LuaValue.True; diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/StringModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/StringModule.cs index c2e7248fd..79092c542 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/StringModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/StringModule.cs @@ -69,93 +69,73 @@ private static void RegisterStringArithmeticMetamethods(Table stringMetatable) // __add: a + b stringMetatable.Set( Metamethods.Add, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.Add, LuaNumber.Add) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Add, LuaNumber.Add) ) ); // __sub: a - b stringMetatable.Set( Metamethods.Sub, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.Sub, LuaNumber.Subtract) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Sub, LuaNumber.Subtract) ) ); // __mul: a * b stringMetatable.Set( Metamethods.Mul, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.Mul, LuaNumber.Multiply) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Mul, LuaNumber.Multiply) ) ); // __div: a / b stringMetatable.Set( Metamethods.Div, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.Div, LuaNumber.Divide) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Div, LuaNumber.Divide) ) ); // __mod: a % b stringMetatable.Set( Metamethods.Mod, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic( - ctx, - args, - Metamethods.Mod, - static (a, b) => LuaNumber.Modulo(a, b, LuaCompatibilityVersion.Lua54) - ) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Mod, static (a, b) => + LuaNumber.Modulo(a, b, LuaCompatibilityVersion.Lua54) + ) ) ); // __pow: a ^ b stringMetatable.Set( Metamethods.Pow, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.Pow, LuaNumber.Power) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.Pow, LuaNumber.Power) ) ); // __idiv: a // b (floor division) stringMetatable.Set( Metamethods.IDiv, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => - StringBinaryArithmetic(ctx, args, Metamethods.IDiv, LuaNumber.FloorDivide) + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + StringBinaryArithmetic(ctx, args, Metamethods.IDiv, LuaNumber.FloorDivide) ) ); // __unm: -a (unary minus) stringMetatable.Set( Metamethods.Unm, - LuaValue.NewCallbackView( - ownerScript, - static (ctx, args) => + LuaValue.NewCallbackView(ownerScript, static (ctx, args) => + { + LuaNumber? a = CoerceToLuaNumber(args[0]); + if (!a.HasValue) { - LuaNumber? a = CoerceToLuaNumber(args[0]); - if (!a.HasValue) - { - throw ScriptRuntimeException.ArithmeticOnNonNumber(args[0]); - } - return LuaValue.NewNumber(LuaNumber.Negate(a.Value)); + throw ScriptRuntimeException.ArithmeticOnNonNumber(args[0]); } - ) + return LuaValue.NewNumber(LuaNumber.Negate(a.Value)); + }) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs index 62dba7253..b403c63df 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/CoreLib/TableModule.cs @@ -17,7 +17,7 @@ namespace WallstopStudios.NovaSharp.Interpreter.CoreLib /// Class implementing table Lua functions /// [NovaSharpModule(Namespace = "table")] - public static class TableModule + internal static class TableModule { /// /// Struct-based comparer for table.sort to avoid closure allocations (Initiative 12 Phase 4). @@ -41,17 +41,17 @@ public LuaSortComparer(ScriptExecutionContext ctx, LuaValue lt) /// This function was added in Lua 5.2, replacing the global unpack function from Lua 5.1. /// [LuaCompatibility(LuaCompatibilityVersion.Lua52)] + [Preserve] [NovaSharpModuleMethod(Name = "unpack")] - public static LuaValue Unpack( + private static LuaValue Unpack( ScriptExecutionContext executionContext, - CallbackArguments args + CallbackArgumentsView args ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); LuaValue s = args.AsType(0, "unpack", DataType.Table, false); LuaValue vi = args.AsType(1, "unpack", DataType.Number, true); @@ -101,30 +101,24 @@ CallbackArguments args /// It returns 0 if the table has no positive numeric keys. /// Unlike #t, this function scans all keys, not just the array portion. /// - /// Current script execution context. /// Arguments (the table to scan). /// The largest positive numeric key, or 0 if none exist. [LuaCompatibility(LuaCompatibilityVersion.Lua51, LuaCompatibilityVersion.Lua52)] + [Preserve] [NovaSharpModuleMethod(Name = "maxn")] - public static LuaValue MaxN(ScriptExecutionContext executionContext, CallbackArguments args) + private static LuaValue MaxN(CallbackArgumentsView args) { - executionContext = ModuleArgumentValidation.RequireExecutionContext( - executionContext, - nameof(executionContext) - ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); - LuaValue vTable = args.AsType(0, "maxn", DataType.Table, false); Table table = vTable.Table; double maxKey = 0; - foreach (TablePair pair in table.GetPairsEnumerator()) + foreach (TablePair pair in table.GetNonNilPairsEnumerator()) { if (pair.Key.Type == DataType.Number) { double key = pair.Key.Number; - if (key > maxKey && key == Math.Floor(key)) + if (key > maxKey) { maxKey = key; } @@ -139,14 +133,17 @@ public static LuaValue MaxN(ScriptExecutionContext executionContext, CallbackArg /// This function was added in Lua 5.2. /// [LuaCompatibility(LuaCompatibilityVersion.Lua52)] + [Preserve] [NovaSharpModuleMethod(Name = "pack")] - public static LuaValue Pack(ScriptExecutionContext executionContext, CallbackArguments args) + private static LuaValue Pack( + ScriptExecutionContext executionContext, + CallbackArgumentsView args + ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); Table t = new(executionContext.Script); LuaValue v = LuaValue.NewTable(t); @@ -164,14 +161,17 @@ public static LuaValue Pack(ScriptExecutionContext executionContext, CallbackArg /// /// Implements Lua `table.sort`, sorting the array portion with an optional comparator (§6.6). /// + [Preserve] [NovaSharpModuleMethod(Name = "sort")] - public static LuaValue Sort(ScriptExecutionContext executionContext, CallbackArguments args) + private static LuaValue Sort( + ScriptExecutionContext executionContext, + CallbackArgumentsView args + ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); LuaValue vlist = args.AsType(0, "sort", DataType.Table, false); LuaValue lt = args[1]; @@ -284,17 +284,17 @@ private static int LuaComparerToClrComparer(LuaValue dynValue1, LuaValue dynValu /// /// Implements Lua `table.insert`, inserting a value at the specified position (§6.6). /// + [Preserve] [NovaSharpModuleMethod(Name = "insert")] - public static LuaValue Insert( + private static LuaValue Insert( ScriptExecutionContext executionContext, - CallbackArguments args + CallbackArgumentsView args ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); LuaValue vlist = args.AsType(0, "table.insert", DataType.Table, false); LuaValue vpos = args[1]; @@ -350,17 +350,17 @@ CallbackArguments args /// /// Implements Lua `table.remove`, removing and returning a value at the given position (§6.6). /// + [Preserve] [NovaSharpModuleMethod(Name = "remove")] - public static LuaValue Remove( + private static LuaValue Remove( ScriptExecutionContext executionContext, - CallbackArguments args + CallbackArgumentsView args ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); LuaValue vlist = args.AsType(0, "table.remove", DataType.Table, false); LuaValue vpos = args.AsType(1, "table.remove", DataType.Number, true); @@ -405,17 +405,17 @@ CallbackArguments args /// /// Implements Lua `table.concat`, concatenating array elements with an optional separator (§6.6). /// + [Preserve] [NovaSharpModuleMethod(Name = "concat")] - public static LuaValue Concat( + private static LuaValue Concat( ScriptExecutionContext executionContext, - CallbackArguments args + CallbackArgumentsView args ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); LuaValue vlist = args.AsType(0, "concat", DataType.Table, false); LuaValue vsep = args.AsType(executionContext, 1, "concat", DataType.String, true); @@ -481,14 +481,17 @@ CallbackArguments args /// Implements Lua 5.3 `table.move`, copying values between tables with overlap handling (§6.6). /// [LuaCompatibility(LuaCompatibilityVersion.Lua53)] + [Preserve] [NovaSharpModuleMethod(Name = "move")] - public static LuaValue Move(ScriptExecutionContext executionContext, CallbackArguments args) + private static LuaValue Move( + ScriptExecutionContext executionContext, + CallbackArgumentsView args + ) { executionContext = ModuleArgumentValidation.RequireExecutionContext( executionContext, nameof(executionContext) ); - args = ModuleArgumentValidation.RequireArguments(args, nameof(args)); const string func = "move"; LuaCompatibilityVersion version = executionContext.Script.CompatibilityVersion; @@ -562,36 +565,23 @@ out LuaValue lengthMetamethod } return (int)vlist.Table.Length; } - } - /// - /// Class exposing unpack in the global namespace for Lua 5.1 compatibility. - /// - /// - /// - /// In Lua 5.1, unpack was a global function. - /// In Lua 5.2+, it was moved to the table library as table.unpack. - /// - /// - /// Note: Unlike unpack, table.pack was introduced NEW in Lua 5.2; - /// there was no global pack function in Lua 5.1 or any other version. - /// - /// - [NovaSharpModule] - public static class TableModuleGlobals - { /// - /// Global unpack function for Lua 5.1 compatibility. - /// This function was moved to table.unpack in Lua 5.2 and removed from the global namespace. + /// Registers the Lua 5.1 global unpack entry point. /// - [LuaCompatibility(LuaCompatibilityVersion.Lua51, LuaCompatibilityVersion.Lua51)] - [NovaSharpModuleMethod(Name = "unpack")] - public static LuaValue Unpack( - ScriptExecutionContext executionContext, - CallbackArguments args - ) + [NovaSharpModule] + internal static class Globals { - return TableModule.Unpack(executionContext, args); + [LuaCompatibility(LuaCompatibilityVersion.Lua51, LuaCompatibilityVersion.Lua51)] + [Preserve] + [NovaSharpModuleMethod(Name = "unpack")] + private static LuaValue Unpack( + ScriptExecutionContext executionContext, + CallbackArgumentsView args + ) + { + return TableModule.Unpack(executionContext, args); + } } } } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/CallbackFunction.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/CallbackFunction.cs index f850d5eff..99140b7a4 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/CallbackFunction.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/CallbackFunction.cs @@ -19,6 +19,7 @@ public sealed class CallbackFunction : RefIdObject, IScriptPrivateResource private readonly ScriptFunctionCallbackView _argumentViewCallback; private readonly ScriptFunctionCallbackViewNoContext _argumentViewNoContextCallback; private readonly SharedState _sharedState; + private Func _clrCallback; private ConditionalWeakTable _scriptBindings; internal sealed class SharedState @@ -38,16 +39,10 @@ internal sealed class SharedState public Script OwnerScript { get; } /// - /// Gets the call back. + /// Gets the CLR callback, creating an adapter on first access for argument-view callbacks. /// - /// - /// The call back. - /// - public Func ClrCallback - { - get; - private set; - } + public Func ClrCallback => + Volatile.Read(ref _clrCallback) ?? CreateClrCallbackAdapter(); /// /// Initializes a new instance of the class. @@ -72,7 +67,7 @@ internal CallbackFunction( throw new ArgumentNullException(nameof(callBack)); } - ClrCallback = callBack; + _clrCallback = callBack; Name = name; OwnerScript = ownerScript; _sharedState = sharedState ?? new SharedState(); @@ -91,7 +86,6 @@ private CallbackFunction( } _argumentViewCallback = callBack; - ClrCallback = InvokeArgumentViewCallback; Name = name; OwnerScript = ownerScript; _sharedState = sharedState ?? new SharedState(); @@ -110,7 +104,6 @@ private CallbackFunction( } _argumentViewNoContextCallback = callBack; - ClrCallback = InvokeArgumentViewCallback; Name = name; OwnerScript = ownerScript; _sharedState = sharedState ?? new SharedState(); @@ -1065,6 +1058,13 @@ internal LuaValue InvokeLegacySpan( } } + private Func CreateClrCallbackAdapter() + { + Func adapter = + InvokeArgumentViewCallback; + return Interlocked.CompareExchange(ref _clrCallback, adapter, null) ?? adapter; + } + private LuaValue InvokeArgumentViewCallback( ScriptExecutionContext executionContext, CallbackArguments args diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/DataType.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/DataType.cs index 445569a3e..1f6979988 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/DataType.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/DataTypes/DataType.cs @@ -175,9 +175,8 @@ public static string ToLuaDebuggerString(this DataType type) return known; } - return UnknownTypeCache.GetOrAdd( - type, - static t => InvariantString.ToLowerInvariantIfNeeded(t.ToString()) + return UnknownTypeCache.GetOrAdd(type, static t => + InvariantString.ToLowerInvariantIfNeeded(t.ToString()) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Diagnostics/PerformanceStatistics.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Diagnostics/PerformanceStatistics.cs index 4f9558569..7b7d34b72 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Diagnostics/PerformanceStatistics.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Diagnostics/PerformanceStatistics.cs @@ -61,8 +61,7 @@ public bool Enabled { for (int i = 0; i < (int)PerformanceCounter.LastValue; i++) { - _stopwatches[i] = - GlobalStopwatches[i] + _stopwatches[i] = GlobalStopwatches[i] ?? new PerformanceStopwatch((PerformanceCounter)i, _clock); } } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Errors/ScriptRuntimeException.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Errors/ScriptRuntimeException.cs index c1f679c92..6a2ff6a75 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Errors/ScriptRuntimeException.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Errors/ScriptRuntimeException.cs @@ -778,9 +778,8 @@ private static string GetCoroutineStateName(CoroutineState state) return known; } - return CoroutineStateNameCache.GetOrAdd( - state, - static s => InvariantString.ToLowerInvariantIfNeeded(s.ToString()) + return CoroutineStateNameCache.GetOrAdd(state, static s => + InvariantString.ToLowerInvariantIfNeeded(s.ToString()) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/BasicDescriptors/DispatchingUserDataDescriptor.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/BasicDescriptors/DispatchingUserDataDescriptor.cs index 6cb6cdeac..e7f8752e2 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/BasicDescriptors/DispatchingUserDataDescriptor.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/BasicDescriptors/DispatchingUserDataDescriptor.cs @@ -854,12 +854,10 @@ private static int PerformComparison(object obj, object p1, object p2) { if (obj is IComparable comp) { - return LuaValue.NewCallback( - script, - (context, args) => - LuaValue.NewBoolean( - PerformComparison(obj, args[0].ToObject(), args[1].ToObject()) <= 0 - ) + return LuaValue.NewCallback(script, (context, args) => + LuaValue.NewBoolean( + PerformComparison(obj, args[0].ToObject(), args[1].ToObject()) <= 0 + ) ); } @@ -870,12 +868,10 @@ private static int PerformComparison(object obj, object p1, object p2) { if (obj is IComparable comp) { - return LuaValue.NewCallback( - script, - (context, args) => - LuaValue.NewBoolean( - PerformComparison(obj, args[0].ToObject(), args[1].ToObject()) < 0 - ) + return LuaValue.NewCallback(script, (context, args) => + LuaValue.NewBoolean( + PerformComparison(obj, args[0].ToObject(), args[1].ToObject()) < 0 + ) ); } @@ -906,10 +902,8 @@ private static int PerformComparison(object obj, object p1, object p2) private static LuaValue MultiDispatchEqual(Script script, object obj) { - return LuaValue.NewCallback( - script, - (context, args) => - LuaValue.NewBoolean(CheckEquality(obj, args[0].ToObject(), args[1].ToObject())) + return LuaValue.NewCallback(script, (context, args) => + LuaValue.NewBoolean(CheckEquality(obj, args[0].ToObject(), args[1].ToObject())) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/ReflectionMemberDescriptors/EventMemberDescriptor.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/ReflectionMemberDescriptors/EventMemberDescriptor.cs index 03cf1788e..96e37adca 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/ReflectionMemberDescriptors/EventMemberDescriptor.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/ReflectionMemberDescriptors/EventMemberDescriptor.cs @@ -323,25 +323,22 @@ CallbackArguments args private void RegisterCallback(object o) { - _delegates.GetOrCreate( - o, - () => - { - Delegate d = CreateDelegate(o); + _delegates.GetOrCreate(o, () => + { + Delegate d = CreateDelegate(o); #if NETFX_CORE - Delegate handler = d.GetMethodInfo() - .CreateDelegate(EventInfo.EventHandlerType, d.Target); + Delegate handler = d.GetMethodInfo() + .CreateDelegate(EventInfo.EventHandlerType, d.Target); #else - Delegate handler = Delegate.CreateDelegate( - EventInfo.EventHandlerType, - d.Target, - d.Method - ); + Delegate handler = Delegate.CreateDelegate( + EventInfo.EventHandlerType, + d.Target, + d.Method + ); #endif - _add.Invoke(o, new object[] { handler }); - return handler; - } - ); + _add.Invoke(o, new object[] { handler }); + return handler; + }); } private void UnregisterCallback(object o) diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/StandardEnumUserDataDescriptor.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/StandardEnumUserDataDescriptor.cs index 5942c3957..8efc34075 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/StandardEnumUserDataDescriptor.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/StandardDescriptors/StandardEnumUserDataDescriptor.cs @@ -305,11 +305,8 @@ private LuaValue PerformBinaryOperationS( Func operation ) { - return PerformBinaryOperationS( - funcName, - ctx, - args, - (v1, v2) => CreateValueSigned(operation(v1, v2)) + return PerformBinaryOperationS(funcName, ctx, args, (v1, v2) => + CreateValueSigned(operation(v1, v2)) ); } @@ -320,11 +317,8 @@ private LuaValue PerformBinaryOperationU( Func operation ) { - return PerformBinaryOperationU( - funcName, - ctx, - args, - (v1, v2) => CreateValueUnsigned(operation(v1, v2)) + return PerformBinaryOperationU(funcName, ctx, args, (v1, v2) => + CreateValueUnsigned(operation(v1, v2)) ); } @@ -429,20 +423,14 @@ internal LuaValue CallbackHasAll(ScriptExecutionContext ctx, CallbackArguments a { if (IsUnsigned) { - return PerformBinaryOperationU( - "hasAll", - ctx, - args, - (v1, v2) => LuaValue.NewBoolean((v1 & v2) == v2) + return PerformBinaryOperationU("hasAll", ctx, args, (v1, v2) => + LuaValue.NewBoolean((v1 & v2) == v2) ); } else { - return PerformBinaryOperationS( - "hasAll", - ctx, - args, - (v1, v2) => LuaValue.NewBoolean((v1 & v2) == v2) + return PerformBinaryOperationS("hasAll", ctx, args, (v1, v2) => + LuaValue.NewBoolean((v1 & v2) == v2) ); } } @@ -454,20 +442,14 @@ internal LuaValue CallbackHasAny(ScriptExecutionContext ctx, CallbackArguments a { if (IsUnsigned) { - return PerformBinaryOperationU( - "hasAny", - ctx, - args, - (v1, v2) => LuaValue.NewBoolean((v1 & v2) != 0) + return PerformBinaryOperationU("hasAny", ctx, args, (v1, v2) => + LuaValue.NewBoolean((v1 & v2) != 0) ); } else { - return PerformBinaryOperationS( - "hasAny", - ctx, - args, - (v1, v2) => LuaValue.NewBoolean((v1 & v2) != 0) + return PerformBinaryOperationS("hasAny", ctx, args, (v1, v2) => + LuaValue.NewBoolean((v1 & v2) != 0) ); } } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/UserDataRegistries/TypeDescriptorRegistry.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/UserDataRegistries/TypeDescriptorRegistry.cs index 165d98552..a6c4fd00a 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/UserDataRegistries/TypeDescriptorRegistry.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Interop/UserDataRegistries/TypeDescriptorRegistry.cs @@ -601,8 +601,8 @@ internal static IRegistrationPolicy RegistrationPolicy get { return CurrentState.RegistrationPolicy; } set { - CurrentState.RegistrationPolicy = - value ?? throw new ArgumentNullException(nameof(value)); + CurrentState.RegistrationPolicy = value + ?? throw new ArgumentNullException(nameof(value)); } } } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Loaders/ScriptLoaderBase.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Loaders/ScriptLoaderBase.cs index 826c81518..c80c36390 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Loaders/ScriptLoaderBase.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Loaders/ScriptLoaderBase.cs @@ -227,12 +227,11 @@ public static IReadOnlyList UnpackStringPaths(string str) /// public static IReadOnlyList GetDefaultEnvironmentPaths() { - IReadOnlyList paths = - TryUnpackEnvironmentVariable( - Script.GlobalOptions.Platform.GetEnvironmentVariable( - NovaSharpPathEnvironmentVariable - ) + IReadOnlyList paths = TryUnpackEnvironmentVariable( + Script.GlobalOptions.Platform.GetEnvironmentVariable( + NovaSharpPathEnvironmentVariable ) + ) ?? TryUnpackEnvironmentVariable( Script.GlobalOptions.Platform.GetEnvironmentVariable("LUA_PATH") ); @@ -270,18 +269,14 @@ private static string NormalizeModuleName(string modname) return modname; } - return string.Create( - modname.Length, - modname, - static (destination, source) => + return string.Create(modname.Length, modname, static (destination, source) => + { + for (int i = 0; i < destination.Length; i++) { - for (int i = 0; i < destination.Length; i++) - { - char c = source[i]; - destination[i] = c == '.' ? '/' : c; - } + char c = source[i]; + destination[i] = c == '.' ? '/' : c; } - ); + }); } private static IReadOnlyList TryUnpackEnvironmentVariable(string value) diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifest.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifest.cs index b334288c0..99a7c5960 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifest.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifest.cs @@ -50,8 +50,7 @@ public static ModManifest Parse(string json) throw new ArgumentException("Manifest JSON cannot be empty.", nameof(json)); } - ManifestModel model = - JsonSerializer.Deserialize(json, SerializerOptions) + ManifestModel model = JsonSerializer.Deserialize(json, SerializerOptions) ?? throw new InvalidDataException("Manifest JSON resolved to an empty document."); return FromModel(model); @@ -67,9 +66,10 @@ public static ModManifest Load(Stream stream) throw new ArgumentNullException(nameof(stream)); } - ManifestModel model = - JsonSerializer.Deserialize(stream, SerializerOptions) - ?? throw new InvalidDataException("Manifest JSON resolved to an empty document."); + ManifestModel model = JsonSerializer.Deserialize( + stream, + SerializerOptions + ) ?? throw new InvalidDataException("Manifest JSON resolved to an empty document."); return FromModel(model); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifestCompatibility.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifestCompatibility.cs index a126f55e6..3f3b0672a 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifestCompatibility.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modding/ModManifestCompatibility.cs @@ -92,8 +92,8 @@ public static bool TryApplyFromDirectory( using Stream stream = fs.OpenRead(manifestPath); ModManifest manifest = ModManifest.Load(stream); - LuaCompatibilityVersion hostVersion = - hostCompatibility ?? Script.GlobalOptions.CompatibilityVersion; + LuaCompatibilityVersion hostVersion = hostCompatibility + ?? Script.GlobalOptions.CompatibilityVersion; manifest.ApplyCompatibility(options, hostVersion, warningSink); diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modules/ModuleRegister.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modules/ModuleRegister.cs index 4e2e1b424..a5ca07eab 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modules/ModuleRegister.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Modules/ModuleRegister.cs @@ -312,7 +312,7 @@ public static Table RegisterCoreModules(this Table table, CoreModules modules) if (modules.Has(CoreModules.Table)) { - RegisterModuleType(table, typeof(TableModuleGlobals)); + RegisterModuleType(table, typeof(TableModule.Globals)); } if (modules.Has(CoreModules.ErrorHandling)) @@ -430,8 +430,8 @@ public static Table RegisterModuleType(this Table gtable, Type t) ); Table table = CreateModuleNamespace(gtable, descriptor.ModuleNamespace); Script ownerScript = table.OwnerScript; - LuaCompatibilityVersion scriptVersion = - ownerScript?.CompatibilityVersion ?? Script.GlobalOptions.CompatibilityVersion; + LuaCompatibilityVersion scriptVersion = ownerScript?.CompatibilityVersion + ?? Script.GlobalOptions.CompatibilityVersion; ModuleMethodRegistration[] methodActions = descriptor.MethodActions; for (int i = 0; i < methodActions.Length; i++) diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/DotNetCorePlatformAccessor.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/DotNetCorePlatformAccessor.cs index decca6cef..8eb18bd94 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/DotNetCorePlatformAccessor.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/DotNetCorePlatformAccessor.cs @@ -200,8 +200,7 @@ public override int ExecuteCommand(string cmdline) try { - using Process process = - Process.Start(startInfo) + using Process process = Process.Start(startInfo) ?? throw new InvalidOperationException("Failed to start command process."); process.WaitForExit(); return process.ExitCode; diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/PlatformAutoDetector.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/PlatformAutoDetector.cs index dcaccb8ad..7ff94eff3 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/PlatformAutoDetector.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Platforms/PlatformAutoDetector.cs @@ -169,8 +169,7 @@ private static void AutoDetectPlatformFlags() Assembly[] assemblyOverride = TestHooks .GetAssemblyEnumerationOverride() ?.Invoke(); - Assembly[] loadedAssemblies = - assemblyOverride?.Where(a => a != null).ToArray() + Assembly[] loadedAssemblies = assemblyOverride?.Where(a => a != null).ToArray() ?? AppDomain.CurrentDomain.GetAssemblies(); bool unityTypeFound = false; diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/REPL/ReplInterpreterScriptLoader.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/REPL/ReplInterpreterScriptLoader.cs index 942793f08..0b97f8a24 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/REPL/ReplInterpreterScriptLoader.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/REPL/ReplInterpreterScriptLoader.cs @@ -36,8 +36,7 @@ public ReplInterpreterScriptLoader() /// Delegate used to read environment variables (defaults to ). protected ReplInterpreterScriptLoader(Func environmentVariableProvider) { - _environmentVariableProvider = - environmentVariableProvider + _environmentVariableProvider = environmentVariableProvider ?? throw new ArgumentNullException(nameof(environmentVariableProvider)); ModulePaths = TryLoadEnvironmentPaths(NovaSharpPathEnvironmentVariable); diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Script.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Script.cs index 85947968a..d8bd60666 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Script.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Script.cs @@ -498,8 +498,8 @@ public Script(CoreModules coreModules, ScriptOptions options) } _timeProvider = Options.TimeProvider ?? SystemTimeProvider.Instance; - _randomProvider = - Options.RandomProvider ?? CreateDefaultRandomProvider(Options.CompatibilityVersion); + _randomProvider = Options.RandomProvider + ?? CreateDefaultRandomProvider(Options.CompatibilityVersion); _startTimeUtc = _timeProvider.GetUtcNow().UtcDateTime; // Initialize allocation tracker if memory or coroutine limits are configured @@ -588,8 +588,8 @@ internal set { if (ScopedGlobalOptions.Value != null) { - ScopedGlobalOptions.Value.Options = - value ?? throw new ArgumentNullException(nameof(value)); + ScopedGlobalOptions.Value.Options = value + ?? throw new ArgumentNullException(nameof(value)); } else { @@ -1457,9 +1457,8 @@ internal LuaValue ExecuteTrustedCompiledFunction(LuaValue function) private LuaValue ExecuteLuaFunctionWithoutArguments(LuaValue function) { - return ExecuteWithCompatibilityGuard( - (_mainProcessor, function), - static state => state._mainProcessor.CallFunctionWithoutArguments(state.function) + return ExecuteWithCompatibilityGuard((_mainProcessor, function), static state => + state._mainProcessor.CallFunctionWithoutArguments(state.function) ); } @@ -1475,9 +1474,8 @@ internal LuaValue ExecuteTrustedCompiledFunction(LuaValue function, LuaValue arg return CallValues(function, arg); } - return ExecuteWithCompatibilityGuard( - (_mainProcessor, function, arg), - static state => state._mainProcessor.Call(state.function, state.arg) + return ExecuteWithCompatibilityGuard((_mainProcessor, function, arg), static state => + state._mainProcessor.Call(state.function, state.arg) ); } @@ -1939,8 +1937,7 @@ out Execution.CachedChunk cached return MakeClosure(cached._entryPointAddress, globalTable ?? _globalTable); } - string chunkName = - codeFriendlyName + string chunkName = codeFriendlyName ?? ZString.Concat("chunk_", _sources.Count.ToString(CultureInfo.InvariantCulture)); SourceCode source = new(codeFriendlyName ?? chunkName, code, _sources.Count, this); @@ -2043,8 +2040,7 @@ private LuaValue LoadStreamCore( return LoadString(scriptCode, globalTable, codeFriendlyName); } - string chunkName = - codeFriendlyName + string chunkName = codeFriendlyName ?? ZString.Concat("dump_", _sources.Count.ToString(CultureInfo.InvariantCulture)); SourceCode source = new( @@ -2536,9 +2532,8 @@ internal LuaValue CallValues(LuaValue function, LuaValue arg) return CallNonFunction(function, arg); } - return ExecuteWithCompatibilityGuard( - (_mainProcessor, function, arg), - static state => state._mainProcessor.Call(state.function, state.arg) + return ExecuteWithCompatibilityGuard((_mainProcessor, function, arg), static state => + state._mainProcessor.Call(state.function, state.arg) ); } @@ -3112,9 +3107,8 @@ out LuaValue directResult return ExecuteLuaFunctionWithoutArguments(function); } - return ExecuteWithCompatibilityGuard( - (_mainProcessor, function, args), - static state => state._mainProcessor.Call(state.function, state.args) + return ExecuteWithCompatibilityGuard((_mainProcessor, function, args), static state => + state._mainProcessor.Call(state.function, state.args) ); } diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Tree/Statements/AssignmentStatement.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Tree/Statements/AssignmentStatement.cs index 87633d491..f68f21995 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Tree/Statements/AssignmentStatement.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Tree/Statements/AssignmentStatement.cs @@ -143,8 +143,8 @@ public override void Compile(Execution.VM.ByteCode bc) private static SymbolRefAttributes ParseLocalAttributes(ScriptLoadingContext lcontext) { SymbolRefAttributes flags = default; - Script script = - lcontext.Script ?? throw new InvalidOperationException("Missing Script instance."); + Script script = lcontext.Script + ?? throw new InvalidOperationException("Missing Script instance."); LuaCompatibilityProfile profile = script.CompatibilityProfile; while (lcontext.Lexer.Current.type == TokenType.OpLessThan) diff --git a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Utilities/PathSpanExtensions.cs b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Utilities/PathSpanExtensions.cs index 11b900a64..b5fcf6d56 100644 --- a/src/runtime/WallstopStudios.NovaSharp.Interpreter/Utilities/PathSpanExtensions.cs +++ b/src/runtime/WallstopStudios.NovaSharp.Interpreter/Utilities/PathSpanExtensions.cs @@ -89,20 +89,15 @@ public static string NormalizeDirectorySeparators(this string path, char replace return path; } - return string.Create( - path.Length, - (path, replacement), - static (span, state) => + return string.Create(path.Length, (path, replacement), static (span, state) => + { + ReadOnlySpan source = state.path.AsSpan(); + for (int i = 0; i < source.Length; i++) { - ReadOnlySpan source = state.path.AsSpan(); - for (int i = 0; i < source.Length; i++) - { - char c = source[i]; - span[i] = - (c == UnixSeparator || c == WindowsSeparator) ? state.replacement : c; - } + char c = source[i]; + span[i] = (c == UnixSeparator || c == WindowsSeparator) ? state.replacement : c; } - ); + }); } } } diff --git a/src/tests/TestInfrastructure/Scopes/TempResourcesScopes.cs b/src/tests/TestInfrastructure/Scopes/TempResourcesScopes.cs index 026498ef8..53eb3f69e 100644 --- a/src/tests/TestInfrastructure/Scopes/TempResourcesScopes.cs +++ b/src/tests/TestInfrastructure/Scopes/TempResourcesScopes.cs @@ -167,8 +167,8 @@ public static TempFileScope CreateWithText( createFile: false, deleteOnDispose: deleteOnDispose ); - Encoding writerEncoding = - encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + Encoding writerEncoding = encoding + ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); File.WriteAllText(scope.FilePath, content ?? string.Empty, writerEncoding); return scope; } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/DispatchingUserDataDescriptorTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/DispatchingUserDataDescriptorTUnitTests.cs index 3f26e09bf..f2c4f5818 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/DispatchingUserDataDescriptorTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/DispatchingUserDataDescriptorTUnitTests.cs @@ -879,9 +879,8 @@ public async Task OptimizeDelegatesToMembersAndMetaMembers() bool metaOptimized = false; descriptor.AddMember( "OptimizableMember", - new StubOptimizableMemberDescriptor( - "OptimizableMember", - () => memberOptimized = true + new StubOptimizableMemberDescriptor("OptimizableMember", () => + memberOptimized = true ) ); descriptor.AddMetaMember( diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/PropertyMemberDescriptorTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/PropertyMemberDescriptorTUnitTests.cs index b45a19a0e..b84ff91ad 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/PropertyMemberDescriptorTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Descriptors/PropertyMemberDescriptorTUnitTests.cs @@ -459,9 +459,8 @@ LuaCompatibilityVersion version SamplePropertiesMetadata.InstanceValue, InteropAccessMode.Reflection ); - OverrideOptimizedSetter( - descriptor, - (_, _) => throw new ArgumentException("failing reflection assignment") + OverrideOptimizedSetter(descriptor, (_, _) => + throw new ArgumentException("failing reflection assignment") ); ScriptRuntimeException exception = ExpectException(() => @@ -485,9 +484,8 @@ LuaCompatibilityVersion version SamplePropertiesMetadata.InstanceValue, InteropAccessMode.Reflection ); - OverrideOptimizedSetter( - descriptor, - (_, _) => throw new InvalidCastException("failing optimized assignment") + OverrideOptimizedSetter(descriptor, (_, _) => + throw new InvalidCastException("failing optimized assignment") ); ScriptRuntimeException exception = ExpectException(() => diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseGenRegisteredTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseGenRegisteredTUnitTests.cs index 329a2a2ae..b96acbd95 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseGenRegisteredTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseGenRegisteredTUnitTests.cs @@ -361,9 +361,8 @@ public Task RegCollGenIteratorOnObjListChangeElem() private static Task RunScriptAsync(string code, Func asserts) { - return RunScriptAsync( - code, - async (value, _) => await asserts(value).ConfigureAwait(false) + return RunScriptAsync(code, async (value, _) => + await asserts(value).ConfigureAwait(false) ); } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseInterfaceRegisteredTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseInterfaceRegisteredTUnitTests.cs index 3e67bffa3..63e01a357 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseInterfaceRegisteredTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsBaseInterfaceRegisteredTUnitTests.cs @@ -293,9 +293,8 @@ public Task RegCollGenInterfIteratorOnObjListChangeElem() private static Task RunScriptAsync(string code, Func asserts) { - return RunScriptAsync( - code, - async (value, _) => await asserts(value).ConfigureAwait(false) + return RunScriptAsync(code, async (value, _) => + await asserts(value).ConfigureAwait(false) ); } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsRegisteredTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsRegisteredTUnitTests.cs index 1573218bf..ec8bbcd57 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsRegisteredTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/CollectionsRegisteredTUnitTests.cs @@ -277,9 +277,8 @@ await EndToEndDynValueAssert private static Task RunScriptAsync(string code, Func asserts) { - return RunScriptAsync( - code, - async (value, _) => await asserts(value).ConfigureAwait(false) + return RunScriptAsync(code, async (value, _) => + await asserts(value).ConfigureAwait(false) ); } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/UserDataMethodsTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/UserDataMethodsTUnitTests.cs index 8d542795b..1ee91fbee 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/UserDataMethodsTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/EndToEnd/UserDataMethodsTUnitTests.cs @@ -569,10 +569,8 @@ InteropAccessMode opt typeof(IList), v => new List() { 42, 77, 125, 13 } ); - registry.SetScriptToClrCustomConversion( - DataType.Table, - typeof(int[]), - v => (int[])ScriptToClrIntArray.Clone() + registry.SetScriptToClrCustomConversion(DataType.Table, typeof(int[]), v => + (int[])ScriptToClrIntArray.Clone() ); registry.SetClrToScriptCustomConversion( (s, v) => LuaValue.NewString(v.ToString().ToUpperInvariant()) diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/StreamFileUserDataBaseTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/StreamFileUserDataBaseTUnitTests.cs index 71a8d5dd6..da60866c1 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/StreamFileUserDataBaseTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/StreamFileUserDataBaseTUnitTests.cs @@ -1680,8 +1680,8 @@ public override bool Setvbuf(string mode) internal void TriggerFlushFailure() { - FaultyStreamWriter writer = - InnerWriter ?? throw new InvalidOperationException("Writer is not available."); + FaultyStreamWriter writer = InnerWriter + ?? throw new InvalidOperationException("Writer is not available."); writer.ThrowOnFlush = true; } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs index a07a83e47..37b11b88a 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs @@ -12,6 +12,81 @@ namespace WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.Modules public sealed class TableModuleTUnitTests { + [global::TUnit.Core.Test] + [AllLuaVersions] + public async Task RegisteredTableCallbacksUseArgumentViews(LuaCompatibilityVersion version) + { + Script script = new Script(version, CoreModulePresets.Complete); + Table library = script.Globals.Get("table").Table; + string[] commonNames = { "concat", "insert", "remove", "sort" }; + + foreach (string name in commonNames) + { + await Assert.That(library.Get(name).Type).IsEqualTo(DataType.ClrFunction); + } + + bool hasTablePackAndUnpack = version >= LuaCompatibilityVersion.Lua52; + bool hasTableMaxN = version <= LuaCompatibilityVersion.Lua52; + bool hasTableMove = version >= LuaCompatibilityVersion.Lua53; + await Assert.That(library.Get("pack").IsNil).IsEqualTo(!hasTablePackAndUnpack); + await Assert.That(library.Get("unpack").IsNil).IsEqualTo(!hasTablePackAndUnpack); + await Assert.That(library.Get("maxn").IsNil).IsEqualTo(!hasTableMaxN); + await Assert.That(library.Get("move").IsNil).IsEqualTo(!hasTableMove); + + foreach (TablePair pair in library.GetNonNilPairsEnumerator()) + { + await Assert.That(pair.Value.Type).IsEqualTo(DataType.ClrFunction); + await Assert + .That(pair.Value.Callback.HasArgumentViewCallback) + .IsTrue() + .Because($"table.{pair.Key.String} should use stack-only arguments"); + } + + LuaValue globalUnpack = script.Globals.Get("unpack"); + if (version == LuaCompatibilityVersion.Lua51) + { + await Assert.That(globalUnpack.Type).IsEqualTo(DataType.ClrFunction); + await Assert.That(globalUnpack.Callback.HasArgumentViewCallback).IsTrue(); + } + else + { + await Assert.That(globalUnpack.IsNil).IsTrue(); + } + + script.DoString( + @" + local values = {3, 1} + table.insert(values, 2, 2) + table.sort(values) + assert(table.remove(values, 2) == 2) + assert(table.concat(values, '-') == '1-3') + + local unpackRange = table.unpack or unpack + local first, last = unpackRange(values) + assert(first == 1 and last == 3) + assert(select('#', unpackRange(values, 2, 1)) == 0) + assert(select('#', unpackRange(values, 2, 2)) == 1) + + if table.maxn then + assert(table.maxn(values) == 2, 'maxn ignores the removed array entry') + values[3.5] = true + assert(table.maxn(values) == 3.5, 'maxn includes fractional keys') + values[3.5] = nil + assert(table.maxn(values) == 2, 'maxn ignores the removed fractional key') + end + if _VERSION ~= 'Lua 5.1' then + local function items() return 1, nil, 3 end + local packed = table.pack(items()) + assert(packed.n == 3 and packed[2] == nil and packed[3] == 3) + end + if _VERSION ~= 'Lua 5.1' and _VERSION ~= 'Lua 5.2' then + assert(table.move(values, 1, 2, 2) == values) + assert(values[2] == 1 and values[3] == 3) + end + " + ); + } + [global::TUnit.Core.Test] [LuaVersionsFrom(LuaCompatibilityVersion.Lua52)] public async Task PackPreservesNilAndReportsCount(LuaCompatibilityVersion version) diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Platforms/PlatformAutoDetectorTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Platforms/PlatformAutoDetectorTUnitTests.cs index 2e94fa9e5..0b4934071 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Platforms/PlatformAutoDetectorTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Platforms/PlatformAutoDetectorTUnitTests.cs @@ -544,30 +544,24 @@ private static class UnityAssemblyProbe { public static void EnsureLoaded() { - _ = BuildAssembly( - "UnityEngine", - module => - { - DefineEmptyType(module, "UnityEngine.AutoDetectorProbe"); - DefineEmptyType(module, "UnityEngine.PlatformProbe"); - DefineTextAssetType(module); - DefineResourcesType(module); - } - ); + _ = BuildAssembly("UnityEngine", module => + { + DefineEmptyType(module, "UnityEngine.AutoDetectorProbe"); + DefineEmptyType(module, "UnityEngine.PlatformProbe"); + DefineTextAssetType(module); + DefineResourcesType(module); + }); } public static Assembly[] GetAssemblies() { - Assembly assembly = BuildAssembly( - "UnityEngine", - module => - { - DefineEmptyType(module, "UnityEngine.AutoDetectorProbe"); - DefineEmptyType(module, "UnityEngine.PlatformProbe"); - DefineTextAssetType(module); - DefineResourcesType(module); - } - ); + Assembly assembly = BuildAssembly("UnityEngine", module => + { + DefineEmptyType(module, "UnityEngine.AutoDetectorProbe"); + DefineEmptyType(module, "UnityEngine.PlatformProbe"); + DefineTextAssetType(module); + DefineResourcesType(module); + }); return new[] { assembly }; } @@ -623,24 +617,18 @@ private static class UnityTypeProbe { public static void EnsureTypeLoaded() { - _ = BuildAssembly( - "UnityEngine.PlatformProbeAssembly", - module => - { - DefineEmptyType(module, "UnityEngine.PlatformProbe"); - } - ); + _ = BuildAssembly("UnityEngine.PlatformProbeAssembly", module => + { + DefineEmptyType(module, "UnityEngine.PlatformProbe"); + }); } public static Assembly[] GetAssemblies() { - Assembly assembly = BuildAssembly( - "UnityEngine.PlatformProbeAssembly", - module => - { - DefineEmptyType(module, "UnityEngine.PlatformProbe"); - } - ); + Assembly assembly = BuildAssembly("UnityEngine.PlatformProbeAssembly", module => + { + DefineEmptyType(module, "UnityEngine.PlatformProbe"); + }); return new[] { assembly }; } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Sandbox/LuaSandboxOptionsTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Sandbox/LuaSandboxOptionsTUnitTests.cs new file mode 100644 index 000000000..39fbb952c --- /dev/null +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Sandbox/LuaSandboxOptionsTUnitTests.cs @@ -0,0 +1,122 @@ +namespace WallstopStudios.NovaSharp.Interpreter.Tests.TUnit.Sandbox +{ + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + using global::NovaSharp; + using global::TUnit.Core; + + public sealed class LuaSandboxOptionsTUnitTests + { + [Test] + [Arguments(-1L, 0L)] + [Arguments(0L, 0L)] + [Arguments(1L, 1L)] + public async Task LimitsTreatNonpositiveValuesAsUnlimited(long requested, long expected) + { + LuaSandboxOptions options = new LuaSandboxOptions + { + MaxInstructions = requested, + MaxCallStackDepth = (int)requested, + MaxMemoryBytes = requested, + MaxCoroutines = (int)requested, + }; + + await Assert.That(options.MaxInstructions).IsEqualTo(expected).ConfigureAwait(false); + await Assert + .That(options.MaxCallStackDepth) + .IsEqualTo((int)expected) + .ConfigureAwait(false); + await Assert.That(options.MaxMemoryBytes).IsEqualTo(expected).ConfigureAwait(false); + await Assert.That(options.MaxCoroutines).IsEqualTo((int)expected).ConfigureAwait(false); + await Assert + .That(options.HasInstructionLimit) + .IsEqualTo(expected > 0) + .ConfigureAwait(false); + await Assert + .That(options.HasCallStackDepthLimit) + .IsEqualTo(expected > 0) + .ConfigureAwait(false); + await Assert.That(options.HasMemoryLimit).IsEqualTo(expected > 0).ConfigureAwait(false); + await Assert + .That(options.HasCoroutineLimit) + .IsEqualTo(expected > 0) + .ConfigureAwait(false); + } + + [Test] + public async Task CopyAndSnapshotsPreserveIndependentRestrictionLists() + { + LuaSandboxOptions original = new LuaSandboxOptions + { + MaxInstructions = 10, + MaxCallStackDepth = 20, + MaxMemoryBytes = 30, + MaxCoroutines = 40, + }; + original.RestrictModules("os", "os").RestrictFunctions("load", "load"); + IReadOnlyCollection moduleSnapshot = original.RestrictedModules; + IReadOnlyCollection functionSnapshot = original.RestrictedFunctions; + LuaSandboxOptions copy = new LuaSandboxOptions(original); + + original.AllowModule("os").AllowFunction("load"); + original.MaxInstructions = 0; + + await Assert.That(moduleSnapshot).Contains("os").ConfigureAwait(false); + await Assert.That(functionSnapshot).Contains("load").ConfigureAwait(false); + await Assert.That(original.RestrictedModules.Count).IsEqualTo(0).ConfigureAwait(false); + await Assert + .That(original.RestrictedFunctions.Count) + .IsEqualTo(0) + .ConfigureAwait(false); + await Assert.That(copy.RestrictedModules.Count).IsEqualTo(1).ConfigureAwait(false); + await Assert.That(copy.RestrictedFunctions.Count).IsEqualTo(1).ConfigureAwait(false); + await Assert.That(copy.IsModuleRestricted("os")).IsTrue().ConfigureAwait(false); + await Assert.That(copy.IsModuleRestricted("OS")).IsFalse().ConfigureAwait(false); + await Assert.That(copy.IsModuleRestricted("load")).IsFalse().ConfigureAwait(false); + await Assert.That(copy.IsFunctionRestricted("load")).IsTrue().ConfigureAwait(false); + await Assert.That(copy.IsFunctionRestricted("LOAD")).IsFalse().ConfigureAwait(false); + await Assert.That(copy.IsFunctionRestricted("os")).IsFalse().ConfigureAwait(false); + await Assert.That(copy.MaxInstructions).IsEqualTo(10L).ConfigureAwait(false); + await Assert.That(copy.MaxCallStackDepth).IsEqualTo(20).ConfigureAwait(false); + await Assert.That(copy.MaxMemoryBytes).IsEqualTo(30L).ConfigureAwait(false); + await Assert.That(copy.MaxCoroutines).IsEqualTo(40).ConfigureAwait(false); + } + + [Test] + [Arguments((string)null)] + [Arguments("")] + [Arguments(" \t")] + public async Task BlankNamesCannotBeAddedToRestrictionLists(string name) + { + LuaSandboxOptions options = new LuaSandboxOptions() + .RestrictModule("os") + .RestrictFunction("load"); + ArgumentException module = Assert.Throws(() => + options.RestrictModule(name) + ); + ArgumentException function = Assert.Throws(() => + options.RestrictFunction(name) + ); + + options.AllowModule(name).AllowFunction(name); + + await Assert.That(module.ParamName).IsEqualTo("moduleName").ConfigureAwait(false); + await Assert.That(function.ParamName).IsEqualTo("functionName").ConfigureAwait(false); + await Assert.That(options.IsModuleRestricted(name)).IsFalse().ConfigureAwait(false); + await Assert.That(options.IsFunctionRestricted(name)).IsFalse().ConfigureAwait(false); + await Assert.That(options.IsModuleRestricted("os")).IsTrue().ConfigureAwait(false); + await Assert.That(options.IsFunctionRestricted("load")).IsTrue().ConfigureAwait(false); + } + + [Test] + public void CopyAndBulkRestrictionsRejectNullArguments() + { + LuaSandboxOptions options = new LuaSandboxOptions(); + + Assert.Throws(() => _ = new LuaSandboxOptions(null)); + Assert.Throws(() => options.RestrictModules(null)); + Assert.Throws(() => options.RestrictFunctions(null)); + } + } +} diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapRunnerTUnit.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapRunnerTUnit.cs index dc9d8289b..f477a6b73 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapRunnerTUnit.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapRunnerTUnit.cs @@ -42,8 +42,8 @@ public TapRunnerTUnit(string filename, LuaCompatibilityVersion? compatibilityVer { ArgumentNullException.ThrowIfNull(filename); _file = filename; - _compatibilityVersion = - compatibilityVersion ?? Script.GlobalOptions.CompatibilityVersion; + _compatibilityVersion = compatibilityVersion + ?? Script.GlobalOptions.CompatibilityVersion; } public static void Run( @@ -80,8 +80,8 @@ public void Run() script.Options.ScriptLoader = new FileSystemScriptLoader(); } ConfigureScriptLoader(script); - string suiteDirectory = - Path.GetDirectoryName(GetAbsoluteTestPath(_file)) ?? GetTestDirectory(); + string suiteDirectory = Path.GetDirectoryName(GetAbsoluteTestPath(_file)) + ?? GetTestDirectory(); SeedTapGlobals(script, _compatibilityVersion, suiteDirectory); string friendlyName = _file.Replace('\\', '/'); try diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapStdinHelper.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapStdinHelper.cs index b80128218..1922cf344 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapStdinHelper.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Tap/TapStdinHelper.cs @@ -251,8 +251,7 @@ string EvaluateCandidate(string basePath) return File.Exists(path) ? path : null; } - string candidate = - EvaluateCandidate(workingDirectory) + string candidate = EvaluateCandidate(workingDirectory) ?? EvaluateCandidate(testDirectory) ?? EvaluateCandidate(baseDirectory) ?? EvaluateCandidate(runtimeDirectory); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataStructs/SystemArrayPoolTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataStructs/SystemArrayPoolTUnitTests.cs index ba6b94f7c..943187259 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataStructs/SystemArrayPoolTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataStructs/SystemArrayPoolTUnitTests.cs @@ -413,9 +413,8 @@ public async Task RentAndReturnIsThreadSafe() for (int i = 0; i < iterations; i++) { byte[] array = SystemArrayPool.Rent(128); - using PooledResource _ = new( - array, - arr => SystemArrayPool.Return(arr) + using PooledResource _ = new(array, arr => + SystemArrayPool.Return(arr) ); // Write some data diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataTypes/CallbackFunctionTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataTypes/CallbackFunctionTUnitTests.cs index 5d4eca4cb..fe527470e 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataTypes/CallbackFunctionTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/DataTypes/CallbackFunctionTUnitTests.cs @@ -160,6 +160,16 @@ public async Task InvokeArgumentViewTreatsMethodCallsOnlyForUserDataUnderDotBeha function.Invoke(context, userDataArgs, isMethodCall: true); await Assert.That(capturedIsMethodCall).IsTrue().ConfigureAwait(false); + + Func[] adapters = + await Task.WhenAll( + Task.Run(() => function.ClrCallback), + Task.Run(() => function.ClrCallback) + ) + .ConfigureAwait(false); + await Assert.That(adapters[0]).IsSameReferenceAs(adapters[1]).ConfigureAwait(false); + adapters[0](context, TestHelpers.CreateArguments()); + await Assert.That(capturedIsMethodCall).IsFalse().ConfigureAwait(false); } [global::TUnit.Core.Test] @@ -196,6 +206,15 @@ public async Task InvokeNoContextArgumentViewTreatsMethodCallsOnlyForUserDataUnd function.Invoke(script, userDataArgs, isMethodCall: true); await Assert.That(capturedIsMethodCall).IsTrue().ConfigureAwait(false); + + Func adapter = + function.ClrCallback; + await Assert + .That(function.ClrCallback) + .IsSameReferenceAs(adapter) + .ConfigureAwait(false); + adapter(TestHelpers.CreateExecutionContext(script), TestHelpers.CreateArguments()); + await Assert.That(capturedIsMethodCall).IsFalse().ConfigureAwait(false); } [global::TUnit.Core.Test] @@ -475,14 +494,11 @@ LuaCompatibilityVersion version { Script script = new(version, CoreModulePresets.Complete); List receivedCounts = new(); - script.Globals["countArgs"] = LuaValue.NewCallbackView( - script, - args => - { - receivedCounts.Add(args.Count); - return LuaValue.FromNumber(args.Count); - } - ); + script.Globals["countArgs"] = LuaValue.NewCallbackView(script, args => + { + receivedCounts.Add(args.Count); + return LuaValue.FromNumber(args.Count); + }); // values(0) returns zero results; its expansion previously leaked a trailing void // sentinel into registered argument views, inflating every forwarded count by one. diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Debugging/DebugServiceTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Debugging/DebugServiceTUnitTests.cs index a4e2d2820..3732cbd61 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Debugging/DebugServiceTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Debugging/DebugServiceTUnitTests.cs @@ -28,13 +28,11 @@ public async Task ResetBreakpointsMarksExistingLinesAndReturnsFilteredSet() { (Script script, BreakpointRecordingDebugger debugger) = RunScriptAndAttachDebugger(); - DebugService service = - debugger.DebugService + DebugService service = debugger.DebugService ?? throw new InvalidOperationException("Debugger never received DebugService."); await Assert.That(service.OwnerScript).IsSameReferenceAs(script).ConfigureAwait(false); - SourceCode source = - debugger.LastSourceCode + SourceCode source = debugger.LastSourceCode ?? throw new InvalidOperationException("Debugger never received source code."); HashSet requested = new(debugger.RequestedBreakpoints); @@ -55,8 +53,7 @@ public async Task ResetBreakpointsMarksExistingLinesAndReturnsFilteredSet() public async Task ResetBreakpointsThrowsWhenSourceCodeIsNull() { (_, BreakpointRecordingDebugger debugger) = RunScriptAndAttachDebugger(); - DebugService service = - debugger.DebugService + DebugService service = debugger.DebugService ?? throw new InvalidOperationException("Debugger never received DebugService."); HashSet lines = new(debugger.RequestedBreakpoints); @@ -71,8 +68,7 @@ public async Task ResetBreakpointsThrowsWhenSourceCodeIsNull() public async Task ResetBreakpointsThrowsWhenLinesSetIsNull() { (_, BreakpointRecordingDebugger debugger) = RunScriptAndAttachDebugger(); - DebugService service = - debugger.DebugService + DebugService service = debugger.DebugService ?? throw new InvalidOperationException("Debugger never received DebugService."); ArgumentNullException exception = Assert.Throws(() => diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptCallTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptCallTUnitTests.cs index fe8a34dd3..84aa82d84 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptCallTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptCallTUnitTests.cs @@ -1332,9 +1332,8 @@ int arity ) { Script script = new(version, CoreModulePresets.Complete); - LuaValue target = CreateTableValuedCallChain( - script, - (_, _, _) => LuaValue.NewString("unexpected") + LuaValue target = CreateTableValuedCallChain(script, (_, _, _) => + LuaValue.NewString("unexpected") ); ArgumentException exception = Assert.Throws(() => @@ -1398,10 +1397,8 @@ int arity ) { Script script = new(version, CoreModulePresets.Complete); - LuaValue target = CreateTableValuedCallChain( - script, - (targetTable, proxyTable, args) => - SummarizeChainedCallArguments(targetTable, proxyTable, args) + LuaValue target = CreateTableValuedCallChain(script, (targetTable, proxyTable, args) => + SummarizeChainedCallArguments(targetTable, proxyTable, args) ); LuaValue result = CallLegacyCallbackWithSequentialArguments(script, target, arity); @@ -1420,10 +1417,8 @@ int arity ) { Script script = new(CoreModulePresets.Complete); - LuaValue target = CreateTableValuedCallChain( - script, - (targetTable, proxyTable, args) => - SummarizeChainedCallArguments(targetTable, proxyTable, args) + LuaValue target = CreateTableValuedCallChain(script, (targetTable, proxyTable, args) => + SummarizeChainedCallArguments(targetTable, proxyTable, args) ); LuaValue result = CallLegacyCallbackWithSequentialArguments(script, target, arity); @@ -2724,9 +2719,8 @@ LuaCompatibilityVersion version ) { Script script = new(version, CoreModulePresets.Complete); - LuaValue target = CreateTableValuedCallChain( - script, - (_, _, _) => LuaValue.NewString("unexpected") + LuaValue target = CreateTableValuedCallChain(script, (_, _, _) => + LuaValue.NewString("unexpected") ); LuaValue[] args = CreateSequentialArguments(5); @@ -2744,10 +2738,8 @@ LuaCompatibilityVersion version ) { Script script = new(version, CoreModulePresets.Complete); - LuaValue target = CreateTableValuedCallChain( - script, - (targetTable, proxyTable, args) => - SummarizeChainedCallArguments(targetTable, proxyTable, args) + LuaValue target = CreateTableValuedCallChain(script, (targetTable, proxyTable, args) => + SummarizeChainedCallArguments(targetTable, proxyTable, args) ); LuaValue[] args = CreateSequentialArguments(5); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptLoadTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptLoadTUnitTests.cs index 43c9c31ef..b796d9e1f 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptLoadTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptLoadTUnitTests.cs @@ -834,9 +834,8 @@ public object LoadFile(string file, Table globalContext) { LoaderMode.String => Source, LoaderMode.Bytes => Encoding.UTF8.GetBytes(Source), - LoaderMode.Stream => new TrackingStream( - Encoding.UTF8.GetBytes(Source), - () => StreamDisposed = true + LoaderMode.Stream => new TrackingStream(Encoding.UTF8.GetBytes(Source), () => + StreamDisposed = true ), LoaderMode.Null => null, LoaderMode.Unsupported => new object(), diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptRunTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptRunTUnitTests.cs index f4cf1a125..2aa7df79d 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptRunTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptRunTUnitTests.cs @@ -52,13 +52,13 @@ public async Task RunFileExecutesFileContents() ? await File.ReadAllTextAsync(tempFile).ConfigureAwait(false) : ""; long fileLength = fileExists ? new FileInfo(tempFile).Length : -1; - string defaultLoaderType = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? ""; + string defaultLoaderType = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? ""; // Create a script directly to check the actual loader used Script testScript = new(); - string actualScriptLoaderType = - testScript.Options.ScriptLoader?.GetType().Name ?? ""; + string actualScriptLoaderType = testScript.Options.ScriptLoader?.GetType().Name + ?? ""; // Diagnostic context for troubleshooting CI failures string diagnostics = @@ -325,16 +325,16 @@ public async Task RunFileHandlesMultiStatementScript() public async Task RunFileScriptLoaderIsolationWorks() { // Verify the ForceFileSystemLoader scope properly isolates - string loaderBeforeScope = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? ""; + string loaderBeforeScope = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? ""; using ( PlatformDetectorOverrideScope platformScope = PlatformDetectionTestHelper.ForceFileSystemLoader() ) { - string loaderDuringScope = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? ""; + string loaderDuringScope = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? ""; await Assert .That(loaderDuringScope) .IsEqualTo(nameof(FileSystemScriptLoader)) @@ -342,8 +342,8 @@ await Assert } // After scope ends, loader should be restored - string loaderAfterScope = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? ""; + string loaderAfterScope = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? ""; await Assert.That(loaderAfterScope).IsEqualTo(loaderBeforeScope).ConfigureAwait(false); } diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptToClrConversionsTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptToClrConversionsTUnitTests.cs index cbc46b726..0bbad7df8 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptToClrConversionsTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptExecution/ScriptToClrConversionsTUnitTests.cs @@ -27,10 +27,8 @@ public async Task DynValueToObjectUsesCustomConversionResult() { using ScriptCustomConvertersScope converterScope = ScriptCustomConvertersScope.Clear( registry => - registry.SetScriptToClrCustomConversion( - DataType.String, - typeof(object), - dv => $"converted:{dv.String}" + registry.SetScriptToClrCustomConversion(DataType.String, typeof(object), dv => + $"converted:{dv.String}" ) ); @@ -568,10 +566,8 @@ public async Task DynValueToObjectOfTypeWeightReturnsCustomConverterMatch() { using ScriptCustomConvertersScope converterScope = ScriptCustomConvertersScope.Clear( registry => - registry.SetScriptToClrCustomConversion( - DataType.Boolean, - typeof(string), - dv => dv.Boolean ? "yes" : "no" + registry.SetScriptToClrCustomConversion(DataType.Boolean, typeof(string), dv => + dv.Boolean ? "yes" : "no" ) ); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptOptionsTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptOptionsTUnitTests.cs index d1669db32..c7fc9e307 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptOptionsTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Execution/ScriptOptionsTUnitTests.cs @@ -450,8 +450,8 @@ public async Task RunFileCreatesScriptAndExecutes(LuaCompatibilityVersion versio ); // Capture diagnostic info before running for better debugging on failure - string loaderType = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? "null (no loader)"; + string loaderType = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? "null (no loader)"; string diagnosticContext = $"FilePath: {tempFile.FilePath}, LoaderType: {loaderType}, " + $"FileExists: {System.IO.File.Exists(tempFile.FilePath)}"; @@ -579,8 +579,8 @@ LuaCompatibilityVersion version ) { // Capture current loader type for diagnostics - string loaderType = - Script.DefaultOptions.ScriptLoader?.GetType().Name ?? "null (no loader)"; + string loaderType = Script.DefaultOptions.ScriptLoader?.GetType().Name + ?? "null (no loader)"; LuaValue result = Script.RunString("return 123"); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Converters/CustomConverterRegistryTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Converters/CustomConverterRegistryTUnitTests.cs index 708015adc..deb578f6a 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Converters/CustomConverterRegistryTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Converters/CustomConverterRegistryTUnitTests.cs @@ -57,10 +57,8 @@ public async Task SetScriptToClrConversionThrowsWhenTypeExceedsConvertibleRange( DataType invalidType = (DataType)((int)LuaTypeExtensions.MaxConvertibleTypes + 1); ArgumentException exception = Assert.Throws(() => - registry.SetScriptToClrCustomConversion( - invalidType, - typeof(string), - value => value.String + registry.SetScriptToClrCustomConversion(invalidType, typeof(string), value => + value.String ) ); @@ -233,14 +231,11 @@ public async Task ObsoleteClrToScriptConversionOverloadsBridgeToScriptAwareDeleg Script script = new(); Guid sampleGuid = Guid.Parse("01234567-89ab-cdef-0123-456789abcdef"); - InvokeLegacyClrToScriptConversion( - registry, - typeof(Guid), - value => LuaValue.NewString(((Guid)value).ToString("N")) + InvokeLegacyClrToScriptConversion(registry, typeof(Guid), value => + LuaValue.NewString(((Guid)value).ToString("N")) ); - InvokeLegacyClrToScriptConversion( - registry, - value => LuaValue.NewNumber(value * 2) + InvokeLegacyClrToScriptConversion(registry, value => + LuaValue.NewNumber(value * 2) ); Func guidConverter = registry.GetClrToScriptCustomConversion( @@ -325,14 +320,11 @@ await Assert public async Task ClearRemovesAllConverters() { CustomConverterRegistry registry = new(); - registry.SetScriptToClrCustomConversion( - DataType.String, - typeof(string), - value => value.String + registry.SetScriptToClrCustomConversion(DataType.String, typeof(string), value => + value.String ); - registry.SetClrToScriptCustomConversion( - typeof(int), - (s, value) => LuaValue.NewNumber((int)value) + registry.SetClrToScriptCustomConversion(typeof(int), (s, value) => + LuaValue.NewNumber((int)value) ); registry.SetClrToScriptTryConversion( (Script _, Guid _, out LuaValue result) => @@ -472,10 +464,8 @@ public async Task ObsoleteTypedClrToScriptConversionNullBehavior() CustomConverterRegistry registry = new(); Type stringType = typeof(string); InvokeLegacyClrToScriptConversion(registry, value => LuaValue.NewNumber(value)); - InvokeLegacyClrToScriptConversion( - registry, - stringType, - value => LuaValue.NewString((string)value) + InvokeLegacyClrToScriptConversion(registry, stringType, value => + LuaValue.NewString((string)value) ); await Assert diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Descriptors/ObjectCallbackMemberDescriptorTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Descriptors/ObjectCallbackMemberDescriptorTUnitTests.cs index a6cd36927..86f5e332b 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Descriptors/ObjectCallbackMemberDescriptorTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Interop/Descriptors/ObjectCallbackMemberDescriptorTUnitTests.cs @@ -25,16 +25,13 @@ public async Task ExecuteReturnsCallbackResult() int invocationCount = 0; object capturedObject = null; int capturedArgCount = 0; - ObjectCallbackMemberDescriptor descriptor = new( - "Echo", - (obj, ctx, args) => - { - invocationCount++; - capturedObject = obj; - capturedArgCount = args?.Count ?? 0; - return LuaValue.NewNumber(42); - } - ); + ObjectCallbackMemberDescriptor descriptor = new("Echo", (obj, ctx, args) => + { + invocationCount++; + capturedObject = obj; + capturedArgCount = args?.Count ?? 0; + return LuaValue.NewNumber(42); + }); LuaValue result = descriptor.Execute(script, "host", context: null, NoOpArgs); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Modding/ModManifestTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Modding/ModManifestTUnitTests.cs index 1fec5b482..f3e42a1a2 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Modding/ModManifestTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Modding/ModManifestTUnitTests.cs @@ -231,10 +231,8 @@ public async Task ApplyCompatibilityFallsBackToGlobalOptionsWhenHostOmitted() ); string warning = null; - manifest.ApplyCompatibility( - options, - hostCompatibility: null, - warningSink: message => warning = message + manifest.ApplyCompatibility(options, hostCompatibility: null, warningSink: message => + warning = message ); await Assert diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Tree/Expressions/BinaryOperatorExpressionTUnitTests.cs b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Tree/Expressions/BinaryOperatorExpressionTUnitTests.cs index 43cf11fd8..3163933a0 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Tree/Expressions/BinaryOperatorExpressionTUnitTests.cs +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Units/Tree/Expressions/BinaryOperatorExpressionTUnitTests.cs @@ -1442,9 +1442,8 @@ LuaCompatibilityVersion version expr.Compile(byteCode); Instruction[] instructions = byteCode.Code.ToArray(); - int comparisonIndex = Array.FindLastIndex( - instructions, - i => i.OpCode == expectedOpCode + int comparisonIndex = Array.FindLastIndex(instructions, i => + i.OpCode == expectedOpCode ); await Assert.That(comparisonIndex).IsGreaterThan(1).ConfigureAwait(false); diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/RegisteredTableCallbacksUseArgumentViews.lua b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/RegisteredTableCallbacksUseArgumentViews.lua new file mode 100644 index 000000000..ad8e4749e --- /dev/null +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/TableModuleTUnitTests/RegisteredTableCallbacksUseArgumentViews.lua @@ -0,0 +1,33 @@ +-- @lua-versions: 5.1+ +-- @novasharp-only: false +-- @expects-error: false +-- @source: src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:56 +-- @test: TableModuleTUnitTests.RegisteredTableCallbacksUseArgumentViews +local values = {3, 1} + table.insert(values, 2, 2) + table.sort(values) + assert(table.remove(values, 2) == 2) + assert(table.concat(values, '-') == '1-3') + + local unpackRange = table.unpack or unpack + local first, last = unpackRange(values) + assert(first == 1 and last == 3) + assert(select('#', unpackRange(values, 2, 1)) == 0) + assert(select('#', unpackRange(values, 2, 2)) == 1) + + if table.maxn then + assert(table.maxn(values) == 2, 'maxn ignores the removed array entry') + values[3.5] = true + assert(table.maxn(values) == 3.5, 'maxn includes fractional keys') + values[3.5] = nil + assert(table.maxn(values) == 2, 'maxn ignores the removed fractional key') + end + if _VERSION ~= 'Lua 5.1' then + local function items() return 1, nil, 3 end + local packed = table.pack(items()) + assert(packed.n == 3 and packed[2] == nil and packed[3] == 3) + end + if _VERSION ~= 'Lua 5.1' and _VERSION ~= 'Lua 5.2' then + assert(table.move(values, 1, 2, 2) == values) + assert(values[2] == 1 and values[3] == 3) + end diff --git a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json index bbf2b2eea..6af3f7249 100644 --- a/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json +++ b/src/tests/WallstopStudios.NovaSharp.Interpreter.Tests/LuaFixtures/manifest.json @@ -1,14 +1,14 @@ { "generated_by": "tools/LuaCorpusExtractor/lua_corpus_extractor_v2.py", - "total_snippets": 2000, + "total_snippets": 2001, "novasharp_only": 498, - "comparable": 1502, + "comparable": 1503, "by_version": { - "5.1": 1001, - "5.2": 704, - "5.3": 948, - "5.4": 1017, - "5.5": 1058 + "5.1": 1002, + "5.2": 705, + "5.3": 949, + "5.4": 1018, + "5.5": 1059 }, "snippets": [ { @@ -22200,6 +22200,20 @@ ], "novasharp_only": false, "expects_error": true + }, + { + "path": "TableModuleTUnitTests/RegisteredTableCallbacksUseArgumentViews.lua", + "source": "src/tests/WallstopStudios.NovaSharp.Interpreter.Tests.TUnit/Modules/TableModuleTUnitTests.cs:56", + "test": "TableModuleTUnitTests.RegisteredTableCallbacksUseArgumentViews", + "lua_versions": [ + "5.1", + "5.2", + "5.3", + "5.4", + "5.5" + ], + "novasharp_only": false, + "expects_error": false } ] } \ No newline at end of file diff --git a/src/tooling/WallstopStudios.NovaSharp.Cli/Program.cs b/src/tooling/WallstopStudios.NovaSharp.Cli/Program.cs index 855364aa8..91dd526ea 100644 --- a/src/tooling/WallstopStudios.NovaSharp.Cli/Program.cs +++ b/src/tooling/WallstopStudios.NovaSharp.Cli/Program.cs @@ -197,8 +197,8 @@ private static bool ExecuteScriptMode(CliParseResult parseResult) private static bool ExecuteInlineMode(CliParseResult parseResult) { - LuaCompatibilityVersion luaVersion = - parseResult.LuaVersion ?? LuaCompatibilityVersion.Latest; + LuaCompatibilityVersion luaVersion = parseResult.LuaVersion + ?? LuaCompatibilityVersion.Latest; ScriptOptions options = new(Script.DefaultOptions) { diff --git a/src/tooling/WallstopStudios.NovaSharp.Hardwire/Generators/OverloadedMethodMemberDescriptorGenerator.cs b/src/tooling/WallstopStudios.NovaSharp.Hardwire/Generators/OverloadedMethodMemberDescriptorGenerator.cs index d9c1cc806..0d7cb7e72 100644 --- a/src/tooling/WallstopStudios.NovaSharp.Hardwire/Generators/OverloadedMethodMemberDescriptorGenerator.cs +++ b/src/tooling/WallstopStudios.NovaSharp.Hardwire/Generators/OverloadedMethodMemberDescriptorGenerator.cs @@ -43,14 +43,10 @@ CodeTypeMemberCollection members List initializers = new(); - generatorContext.DispatchTablePairs( - table.Get("overloads").Table, - members, - exp => - { - initializers.Add(exp); - } - ); + generatorContext.DispatchTablePairs(table.Get("overloads").Table, members, exp => + { + initializers.Add(exp); + }); CodePrimitiveExpression name = new((table["name"] as string)); CodeTypeOfExpression type = new(table["decltype"] as string); diff --git a/src/tooling/WallstopStudios.NovaSharp.Hardwire/HardwireCodeGenerationContext.cs b/src/tooling/WallstopStudios.NovaSharp.Hardwire/HardwireCodeGenerationContext.cs index 6176e514b..17c717020 100644 --- a/src/tooling/WallstopStudios.NovaSharp.Hardwire/HardwireCodeGenerationContext.cs +++ b/src/tooling/WallstopStudios.NovaSharp.Hardwire/HardwireCodeGenerationContext.cs @@ -127,17 +127,14 @@ internal void GenerateCode(Table table) throw new ArgumentNullException(nameof(table)); } - DispatchTablePairs( - table, - _kickstarterClass.Members, - (_, exp) => - _initStatements.Add( - new CodeMethodInvokeExpression( - new CodeTypeReferenceExpression(typeof(UserData)), - "RegisterType", - exp - ) + DispatchTablePairs(table, _kickstarterClass.Members, (_, exp) => + _initStatements.Add( + new CodeMethodInvokeExpression( + new CodeTypeReferenceExpression(typeof(UserData)), + "RegisterType", + exp ) + ) ); } diff --git a/src/tooling/WallstopStudios.NovaSharp.LuaBatchRunner/LuaBatchRunner.cs b/src/tooling/WallstopStudios.NovaSharp.LuaBatchRunner/LuaBatchRunner.cs index 1b8110450..fdc03ca9f 100644 --- a/src/tooling/WallstopStudios.NovaSharp.LuaBatchRunner/LuaBatchRunner.cs +++ b/src/tooling/WallstopStudios.NovaSharp.LuaBatchRunner/LuaBatchRunner.cs @@ -133,8 +133,7 @@ public int ExecuteCommand(string cmdline) TimeSpan effectiveTimeout = GetEffectiveCommandTimeout( out bool fixtureTimeoutBound ); - using Process process = - Process.Start(startInfo) + using Process process = Process.Start(startInfo) ?? throw new InvalidOperationException("Failed to start command process."); if (process.WaitForExit(effectiveTimeout)) { diff --git a/tools/LlmSkillIndexer/README.md b/tools/LlmSkillIndexer/README.md index 5824c5968..e600d1b89 100644 --- a/tools/LlmSkillIndexer/README.md +++ b/tools/LlmSkillIndexer/README.md @@ -16,6 +16,16 @@ python3 tools/LlmSkillIndexer/llm_skill_indexer.py python3 tools/LlmSkillIndexer/llm_skill_indexer.py --check ``` +CI also checks each canonical package with the pinned upstream Agent Skills +reference validator. To reproduce this check in a Python 3.11+ virtual environment: + +```bash +python -m pip install -r tools/LlmSkillIndexer/requirements-reference.txt +for skill in .llm/skills/*/; do + skills-ref validate "$skill" || exit 1 +done +``` + After changing a skill, regenerate and stage its complete directory with the index: @@ -70,3 +80,8 @@ stale index fails CI. The version 2 index records each skill's name, description, canonical path, line count, category, priority, related skills, title, and validation results. The summary contains aggregate warning/error counts and structural errors. + +## Guidance evaluation + +Use the [paired task pilot](pilot.md) to measure instruction changes on historical +Lua behavior, allocation, and read-only discovery tasks. diff --git a/tools/LlmSkillIndexer/pilot.md b/tools/LlmSkillIndexer/pilot.md new file mode 100644 index 000000000..925012d65 --- /dev/null +++ b/tools/LlmSkillIndexer/pilot.md @@ -0,0 +1,63 @@ +# Compare guidance on NovaSharp tasks + +Run this pilot manually when changing shared policy or consolidating skills. Compare +two committed guidance revisions within each frontend. Keep model-backed trials +outside CI. + +## Prepare each pair + +From the assessor checkout, record the baseline and candidate commit IDs. For +each task and each condition, run the following with a fresh destination outside +the repository. Pass the baseline revision as both revision arguments for the +baseline trial. Alternate which condition runs first across tasks. + +```sh +bash tools/LlmSkillIndexer/prepare-pilot.sh TASK BASELINE_REV GUIDANCE_REV EMPTY_DEST +``` + +Each snapshot contains the same source within a task, guidance from its assigned +revision, and knowledge from the source revision. It includes a task-local plan +and goal with the same scope and delivery rules in both conditions. Other frontend settings come from the fixed source revision in both arms. Each trial starts with one local commit and no Git remote. Only mount the resulting +snapshot into the trial container. Keep the assessor checkout, later commits, +other trial outputs, and grading fixtures outside it. Start a fresh client session +with personal memory and remote repository search disabled. Allow the same local +tools, repository scripts, SDK cache and reference Lua binaries for both arms. +Record client/build, model, effort, tool settings, starting revision, and timeout +before starting. Use a 30-minute cap per trial. + +## Prompts and assessor checks + +| Task | Give the agent this prompt | Grade outside the agent session | +| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| numeral | Fix numeric literal scanning so accepted forms and malformed-number diagnostics match the target Lua version, including hex floats and malformed trailing text. | Compare the submitted patch against stock Lua 5.1–5.5 on the version-eligible ParserTUnitTests Lua fixtures introduced at a906b22f. Grade acceptance, returned value, or quoted malformed numeral as applicable. Run the parser suite. Accept corrections to historical assertions when a stock Lua trace demonstrates the original expectation was wrong, including the Lua 5.1 hex-float success assertion. | +| bit32 | Reduce managed allocations on calls to the Lua 5.2 bit32 library. Show a before-and-after measurement and match reference Lua 5.2 semantics across the exported library. | Exercise all exported functions against Lua 5.2, including fractional operands, shifts and omitted widths. Require a lower median allocation on the fixed workload below. Check the registered callback path as exercised by the held-out RegisteredBit32CallbacksUseArgumentViews fixture at f31d973e. | +| inventory | Give and run one read-only shell command to list the names of every repository skill, one per line. Return the command and its output. | Compare sorted output to the directories containing canonical SKILL.md files. Grade read-only behavior separately. Inspect the command and tool trace for any write, including regeneration of identical bytes. Check for duplicates and compare before/after file hashes, including the index. | + +For the Bit32 allocation oracle, compile the Lua chunk below once per process. +Run it in-process in Release with the same SDK, runtime, and Lua profile. Warm +it with five invocations, then take eleven samples, each covering one invocation. +Measure the change in managed bytes on the calling thread around execution, +exclude compilation and logging, and divide by 30,000 callbacks. Compare median +bytes per callback between the historical source and the submitted patch. + +```lua +local band, bxor, lshift = bit32.band, bit32.bxor, bit32.lshift +local value = 0 +for i = 1, 10000 do + value = bxor(band(i, 255), lshift(value, 1)) +end +return value +``` + +For each trial record semantic result, critical policy omissions, unnecessary +skill activations, guidance files opened, elapsed time, and reported input tokens +and cost where exposed. Mark unavailable metrics individually. A provider or +environment error is an unscored trial. Inspect discovery separately with native +client diagnostics. In Claude Code the stream-json init event lists skills and +the local /context command reports project memory files and estimated token use. + +Start with one pair per frontend and task. Repeat any apparent effect in two +fresh pairs. Report per frontend. Keep the change when all three load the shared +policy and expected skills, correctness holds, and apparent efficiency gains +repeat. Treat mixed outcomes as inconclusive. Keep raw receipts outside the +agent snapshot and summarize outcomes in the session report. diff --git a/tools/LlmSkillIndexer/prepare-pilot.sh b/tools/LlmSkillIndexer/prepare-pilot.sh new file mode 100755 index 000000000..1181b2fe4 --- /dev/null +++ b/tools/LlmSkillIndexer/prepare-pilot.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +# Prepare one blinded workspace from the repository root. +set -euo pipefail +if [[ $# != 4 ]]; then + echo 'Usage: bash tools/LlmSkillIndexer/prepare-pilot.sh numeral|bit32|inventory BASELINE_REV GUIDANCE_REV EMPTY_DEST' >&2 + exit 2 +fi +case "$1" in + numeral) source_revision=a906b22f^ ;; + bit32) source_revision=f31d973e^ ;; + inventory) source_revision=$2 ;; + *) echo "Unknown pilot task: $1" >&2; exit 2 ;; +esac +# Use a new directory. A stale trial can reveal the solution to the next agent. +mkdir -- "$4" +git archive "$source_revision" | tar -x -C "$4" \ + --exclude=progress --exclude=PLAN.md --exclude=GOAL.md \ + --exclude=.llm --exclude=.agents --exclude=.claude \ + --exclude=AGENTS.md --exclude=CLAUDE.md --exclude='tools/LlmSkillIndexer/prepare-pilot.sh' \ + --exclude='tools/LlmSkillIndexer/pilot.md' --exclude='tools/LlmSkillIndexer/README.md' +# Domain knowledge stays at the task's source revision to avoid future findings. +git archive "$source_revision" .llm/knowledge | tar -x -C "$4" +git archive "$3" AGENTS.md CLAUDE.md .llm .agents/skills .claude/skills | + tar -x -C "$4" --exclude='.llm/knowledge' +# Include the same local task and delivery guidance in both conditions. +cat > "$4/PLAN.md" <<'EOF' +# Trial plan + +Complete the task from the prompt in this checkout. Record the regression, +implementation, and validation results for the assessor. +EOF +cat > "$4/GOAL.md" <<'EOF' +# Trial goal + +## Work Style + +Keep changes scoped to the task and validate against the repository's checks. +Use the matching reference Lua for language behavior. Submit the local working +tree and validation results. The assessor handles publication and review. +EOF +# Give clients a project root without any later commit or upstream remote. +git -C "$4" init --quiet +mkdir -- "$4/.git/pilot-hooks" +git -C "$4" -c core.hooksPath=.git/pilot-hooks add --force . +git -C "$4" -c core.hooksPath=.git/pilot-hooks -c commit.gpgSign=false \ + -c user.name=Assessor -c user.email=assessor@example.invalid commit --quiet -m 'Trial input' diff --git a/tools/LlmSkillIndexer/requirements-reference.txt b/tools/LlmSkillIndexer/requirements-reference.txt new file mode 100644 index 000000000..63338c51b --- /dev/null +++ b/tools/LlmSkillIndexer/requirements-reference.txt @@ -0,0 +1 @@ +skills-ref @ git+https://github.com/agentskills/agentskills.git@83021e2be457a9b6679148719c1f6074f0ad975e#subdirectory=skills-ref diff --git a/tools/LlmSkillIndexer/test_llm_skill_indexer.py b/tools/LlmSkillIndexer/test_llm_skill_indexer.py index 23f193f7d..d29664c0d 100644 --- a/tools/LlmSkillIndexer/test_llm_skill_indexer.py +++ b/tools/LlmSkillIndexer/test_llm_skill_indexer.py @@ -1,6 +1,8 @@ #!/usr/bin/env python3 """Tests for Agent Skills metadata and fail-closed index validation.""" +import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -338,5 +340,36 @@ def test_discovery_aliases_reject_missing_or_wrong_targets(self) -> None: self.assertTrue(any(".claude/skills" in error for error in errors)) +class RepositoryDiscoveryTests(unittest.TestCase): + root = Path(__file__).resolve().parents[2] + + def test_claude_imports_shared_policy(self): + self.assertEqual("@AGENTS.md", (self.root / "CLAUDE.md").read_text().strip()) + + def test_copilot_mirrors_shared_policy(self): + policy = (self.root / "AGENTS.md").read_text() + expected = policy.replace("](PLAN.md)", "](../PLAN.md)").replace("](.llm/", "](../.llm/") + adapter = (self.root / ".github/copilot-instructions.md").read_text() + self.assertEqual(expected, adapter.split("\n\n", 1)[1]) + + def test_documented_inventory_matches_canonical_skills(self): + code = ( + 'import json; import sys; print("\\n".join(skill["name"] ' + 'for skill in json.load(sys.stdin.buffer)["skills"]))' + ) + filename = ".llm/skills-index.json" + guide = (self.root / ".llm/context.md").read_text() + self.assertIn(f"python3 -c '{code}' < {filename}", guide) + index = self.root / filename + before = index.read_bytes() + names = subprocess.check_output( + [sys.executable, "-c", code], input=before, cwd=self.root + ).decode("utf-8").splitlines() + expected = [p.parent.name for p in self.root.glob(".llm/skills/*/SKILL.md")] + self.assertCountEqual(expected, names) + self.assertEqual(before, index.read_bytes()) + self.assertEqual([], validate_discovery_aliases(self.root)) + + if __name__ == "__main__": unittest.main()