diff --git a/ci/conda-lock/linux-64-py3.11.txt b/ci/conda-lock/linux-64-py3.11.txt index 9e408888d7..684df44ea5 100644 --- a/ci/conda-lock/linux-64-py3.11.txt +++ b/ci/conda-lock/linux-64-py3.11.txt @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Generated by ci/lock.py; regenerate with: python ci/lock.py -# specs: ["python 3.11.*", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] +# specs: ["python 3.11.*", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pygments >=2.17,<3", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] # min-age-days: 7 # platform: linux-64 @EXPLICIT diff --git a/ci/conda-lock/linux-64-py3.12.txt b/ci/conda-lock/linux-64-py3.12.txt index 170dfe91fd..c91b827ea5 100644 --- a/ci/conda-lock/linux-64-py3.12.txt +++ b/ci/conda-lock/linux-64-py3.12.txt @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Generated by ci/lock.py; regenerate with: python ci/lock.py -# specs: ["python 3.12.*", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] +# specs: ["python 3.12.*", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pygments >=2.17,<3", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] # min-age-days: 7 # platform: linux-64 @EXPLICIT diff --git a/ci/conda-lock/linux-64-py3.13.txt b/ci/conda-lock/linux-64-py3.13.txt index c8c5667de8..c874924590 100644 --- a/ci/conda-lock/linux-64-py3.13.txt +++ b/ci/conda-lock/linux-64-py3.13.txt @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Generated by ci/lock.py; regenerate with: python ci/lock.py -# specs: ["python 3.13.* *_cp313", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] +# specs: ["python 3.13.* *_cp313", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pygments >=2.17,<3", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] # min-age-days: 7 # platform: linux-64 @EXPLICIT diff --git a/ci/conda-lock/linux-64-py3.14.txt b/ci/conda-lock/linux-64-py3.14.txt index 4106d9db25..730ef0fc9b 100644 --- a/ci/conda-lock/linux-64-py3.14.txt +++ b/ci/conda-lock/linux-64-py3.14.txt @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 # Generated by ci/lock.py; regenerate with: python ci/lock.py -# specs: ["python 3.14.* *_cp314", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] +# specs: ["python 3.14.* *_cp314", "python >=3.11", "pyyaml >=6.0.1,<7", "jsonschema >=4.20,<5", "litellm >=1.108.4", "httpx >=0.27.0", "numpy >=1.24.0", "scipy >=1.11.0", "pygithub >=2.1.0", "datasets >=2.20,<6", "openai >=1.51,<3", "regex >=2024.11.6", "markdown-it-py >=4.2,<5", "pygments >=2.17,<3", "pip", "pytest >=9.0.3", "hypothesis >=6.100", "pytest-mock >=3.12.0", "pytest-socket >=0.7", "pytest-timeout >=2.2", "pytest-randomly >=3.15", "pytest-xdist >=3.6", "packaging", "mypy ==2.4.1"] # min-age-days: 7 # platform: linux-64 @EXPLICIT diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index 1768257d8b..df5eb45cef 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -37,6 +37,7 @@ requirements: - openai >=1.51,<3 - regex >=2024.11.6 - markdown-it-py >=4.2,<5 + - pygments >=2.17,<3 test: imports: diff --git a/dokimi/changelog.d/20261202_143600_skill-content-checks.md b/dokimi/changelog.d/20261202_143600_skill-content-checks.md new file mode 100644 index 0000000000..b7437ce3fa --- /dev/null +++ b/dokimi/changelog.d/20261202_143600_skill-content-checks.md @@ -0,0 +1,12 @@ + + +### Fixed + +- Catalog checks accept standard text and emoji presentation for the information symbol and four punctuation marks. Stray variation selectors still produce a warning. + +- Catalog checks distinguish JavaScript variable names from retired model IDs, Markdown block definitions from ordinary text, and install operands from directory placeholders and keyword arguments. +- Static catalog evaluation counts every skill path when several plugins have a skill with the same name. JSON output includes the individual paths and their evaluation states. +- Recognize explicit slash-command activation and a fixed inline Python program that reads piped data with isolated imports. diff --git a/dokimi/changelog.d/20261202_144900_inspect-typescript-config.md b/dokimi/changelog.d/20261202_144900_inspect-typescript-config.md new file mode 100644 index 0000000000..013029843d --- /dev/null +++ b/dokimi/changelog.d/20261202_144900_inspect-typescript-config.md @@ -0,0 +1,10 @@ + + +### Fixed + +- `repo inspect` now lists root and nested TypeScript projects with a + `tsconfig.json` as type-checking surfaces, including projects without a + package script. diff --git a/dokimi/changelog.d/20261202_150000_catalog-publication-reports.md b/dokimi/changelog.d/20261202_150000_catalog-publication-reports.md new file mode 100644 index 0000000000..ffba7db955 --- /dev/null +++ b/dokimi/changelog.d/20261202_150000_catalog-publication-reports.md @@ -0,0 +1,8 @@ + + +### Fixed + +- Catalog checks exclude a skill's root governance card and benchmark report from unreferenced-file warnings. Benchmark instructions and documents under `references/` still receive the check. diff --git a/dokimi/changelog.d/20261202_150000_catalog_output_paths.md b/dokimi/changelog.d/20261202_150000_catalog_output_paths.md new file mode 100644 index 0000000000..74c796861e --- /dev/null +++ b/dokimi/changelog.d/20261202_150000_catalog_output_paths.md @@ -0,0 +1,9 @@ + + +### Fixed + +- `catalog check` skips a bare path explicitly described as a generated output or an absent bundled file. It still checks a separate instruction to read the same file. +- Catalog checks skip bare parent-directory notation and recognize an explicitly prohibited bare interactive install command. diff --git a/dokimi/changelog.d/20261202_155800_path-notation-pip-sources.md b/dokimi/changelog.d/20261202_155800_path-notation-pip-sources.md new file mode 100644 index 0000000000..4987a777bd --- /dev/null +++ b/dokimi/changelog.d/20261202_155800_path-notation-pip-sources.md @@ -0,0 +1,8 @@ + + +### Fixed + +- Repository scans recognize hypothetical examples of adding a directory prefix. Catalog checks no longer count quoted wheel filenames or abbreviated version-control URLs as packages that need version pins. diff --git a/dokimi/changelog.d/20261202_160000_catalog_parent_relative_labels.md b/dokimi/changelog.d/20261202_160000_catalog_parent_relative_labels.md new file mode 100644 index 0000000000..a425089bce --- /dev/null +++ b/dokimi/changelog.d/20261202_160000_catalog_parent_relative_labels.md @@ -0,0 +1,8 @@ + + +### Fixed + +- `catalog check` checks the destination of a parent-relative link once when its label displays the same path without the leading parent directories. diff --git a/dokimi/changelog.d/20261202_160000_inspect-workflow-test-runners.md b/dokimi/changelog.d/20261202_160000_inspect-workflow-test-runners.md new file mode 100644 index 0000000000..b5381149e3 --- /dev/null +++ b/dokimi/changelog.d/20261202_160000_inspect-workflow-test-runners.md @@ -0,0 +1,10 @@ + + +### Fixed + +- `repo inspect` recognizes Node and Python standard-library test runners + declared by simple GitHub Actions commands when project manifests omit a + test command. diff --git a/dokimi/changelog.d/20261202_160800_sibling-files-standalone-runners.md b/dokimi/changelog.d/20261202_160800_sibling-files-standalone-runners.md new file mode 100644 index 0000000000..35937a7209 --- /dev/null +++ b/dokimi/changelog.d/20261202_160800_sibling-files-standalone-runners.md @@ -0,0 +1,10 @@ + + +### Fixed + +- `catalog check` resolves an explicitly sibling-owned reference in that + skill’s folder. `repo inspect` identifies standalone unittest and node:test + tests from their source when manifests and CI omit a test command. diff --git a/dokimi/changelog.d/20261202_173000_catalog_negative_assertion_patterns.md b/dokimi/changelog.d/20261202_173000_catalog_negative_assertion_patterns.md new file mode 100644 index 0000000000..212db7630a --- /dev/null +++ b/dokimi/changelog.d/20261202_173000_catalog_negative_assertion_patterns.md @@ -0,0 +1,8 @@ + + +### Fixed + +- The catalog install check skips commands that a JSON evaluation assertion explicitly requires the answer to omit. diff --git a/dokimi/docs/external-content.md b/dokimi/docs/external-content.md index 8741062a5e..34898ee57d 100644 --- a/dokimi/docs/external-content.md +++ b/dokimi/docs/external-content.md @@ -29,6 +29,8 @@ checked (vendored and VCS directories such as `.git`, `node_modules` and `.venv` or task are not part of its digest). A catalog root that is itself a symlink is refused; a symlink in a parent directory is resolved once, and no link below the root is followed (with no `skills.yaml`, a linked directory beside a discovered skill or under `skills/` is an `unsafe-path` finding, not skipped; links elsewhere, such as `.claude/skills`, are ignored). No model, Docker, skill script, oracle or task verifier runs here. +In JSON output, `data.evaluation_rows` preserves the name, path and evaluation state of each skill. The summary counts every path, including skills with the same name. + Tasks are discovered on disk and assigned using their `metadata.skill` field. `evaluation/harbor/suites.json` is cross-checked: a task present on disk but absent from a suite remains visible with a warning; a missing declared implemented task, @@ -119,7 +121,7 @@ Two checks, both `warn`: `replacement` are the vendor's, verbatim, or empty when it gives none. An entry also lists the vendor's alias of a listed ID (`claude-opus-4-0` for `claude-opus-4-20250514`), with the same status and date. - The check reads every mention of a listed ID as a use of it. A line that documents a + The check reads mentions of a listed ID, including strings and comments. In JavaScript and TypeScript it skips uses of a declared variable with the same name. A line that documents a retirement (a row of a retired-models table) or shows the old side of a migration (`# Before`, `# Old`) is reported too, since a heading or comment label is a guess and would hide a real call placed under it. The advice is conditional (`if this text calls the @@ -133,7 +135,7 @@ Two checks, both `warn`: filler (U+034F, U+180E, U+115F, U+1160, U+3164, U+FFA0, U+2800). A variation selector (U+FE00 to U+FE0F, U+E0100 to U+E01EF) is reported at the start of the text, after another selector, or after an ASCII character other than a keycap base (`#`, `*`, `0` to `9`), or after a non-ASCII character that is not a symbol - or an ideograph (a letter, a no-break space); after an emoji, a symbol or an ideograph it is not. U+034F is not reported beside a non-ASCII letter or mark, U+115F and U+1160 beside Hangul (jamo, compatibility and Extended-A/B jamo, syllables, + or an ideograph. The five non-ASCII emoji bases outside the symbol categories (‼, ⁉, ℹ, 〰, 〽) also accept the standard text and emoji presentation selectors U+FE0E and U+FE0F. U+034F is not reported beside a non-ASCII letter or mark, U+115F and U+1160 beside Hangul (jamo, compatibility and Extended-A/B jamo, syllables, halfwidth), and U+2800 beside Braille. When a line holds more than three of the exempt U+034F, U+115F and U+1160, all of them on that line are reported (U+2800 is not counted). Each is reported with its line and codepoint; five per file are listed. A zero-width joiner (U+200C, U+200D) is not reported next to an emoji or symbol (U+2600 to U+27BF, U+1F000 to U+1FAFF) or in Arabic and Indic script, where it is correct. @@ -297,12 +299,16 @@ under a bundle folder (`scripts/`, `references/`, `assets/`, `templates/`, `examples/`, `resources/`), alone or inside a command such as `python scripts/run.py`, is a `warn` (`path-missing`) when the skill does not have that file. A code span that is the label of an inline link to a URL (`[`examples/a.py`](https://...)`) or of a full reference to one (`[`examples/a.py`][ref]`) is the link's text and is not checked; one in a shortcut or collapsed reference (`[`examples/a.py`]`, `[`examples/a.py`][]`) is still checked. +An inline or full reference link whose whole code-span label matches its target after leading `../` segments contributes only the destination check. Folders, flat names, placeholders (`scripts/.py`), user-local `*.local.md` files (`references/secrets.local.md`, which the user keeps out of git) and repo-root paths such as `src/app.py` are not checked, and neither are code fences. A file name with a space is read only when it is quoted or its space is escaped -(`'scripts/my run.py'`, `scripts/my\ run.py`). Only `/` separators are read: a backslash path such as `scripts\run.py` is not checked. Paths joined by `,` or `;` with no space are read one by one when the next one is under a bundle folder (`scripts/a.py,scripts/b.py`); other commas, and an escaped `\,`, stay in the name. Some hits are files the skill tells the agent to -create; `--ignore path-missing` leaves the code out. A link, or a `../` code span, +(`'scripts/my run.py'`, `scripts/my\ run.py`). Only `/` separators are read: a backslash path such as `scripts\run.py` is not checked. Paths joined by `,` or `;` with no space are read one by one when the next one is under a bundle folder (`scripts/a.py,scripts/b.py`); other commas, and an escaped `\,`, stay in the name. A bare path directly described as an output or explicitly absent from the bundle is skipped. +An explicit sibling reference such as “the `engine` skill, its `references/types.md`” +is checked in the adjacent `engine` skill directory when it contains `SKILL.md` inside the catalog. +A missing sibling file still warns. A later local mention is checked independently. +Other descriptions of files the agent creates may still be flagged; `--ignore path-missing` leaves the code out. A link, or a `../` code span, that reaches a file outside the skill directory is a `warn` (`link-escapes-skill`, `path-escapes-skill`), since it breaks when the skill is installed alone. An `allowed-tools` that grants `Bash` for every command (`Bash` @@ -321,6 +327,7 @@ directory name and description but different `SKILL.md` text are a `warn` on bot `.ts`, `.md`, `.txt` and similar) that neither `SKILL.md` nor a document it names ever names, by path, file name or folder, is counted in one `warn` per skill (`bundle-file-unreferenced`): no document names it. Only a link to the skill root in `SKILL.md` (`./`, or `${CLAUDE_SKILL_DIR}/`) names every file; a link to the root from any other document names only its target. Data, images, licence, readme, changelog and `AGENTS.md`-style files, a root translation of `SKILL.md` (`SKILL.ru.md`, `SKILL.zh-CN.md`), +root publication paperwork (`skill-card.md` and a `BENCHMARK.md` with a report, results, metadata or summary heading for evaluation or benchmarking), `_`-prefixed helpers, tests and `evals/` folders, hidden and vendored folders, and nested skills are not counted, nor is a skill at the root of the scanned checkout. The check then gives no count and no `warn`; it gives a `note` (`bundle-file-unchecked`) that says why, when the search cannot see every name: a bundle over 2000 files, more than 50 named @@ -354,7 +361,8 @@ package with no version is a `warn` with the count of distinct packages for the same install shown twice is one, and a command inside the quoted text of an `echo` or `printf` is not an install (unless a `$(...)` or backtick substitution in it runs it, or the output is piped to a shell); a requirements file, a local path, a URL or a `git+` source is not counted. `npx tsc` and `npx tsserver` are not counted when the file installs `typescript` where the `npx` runs (that directory or one above it), a `--prefix`, `--dir` or `-C` target counting only once the script has `cd`ed into it; an `npm uninstall` or `pnpm remove` of `typescript` in the same directory after the install takes it away again, so `npx tsc` after it is counted (an uninstall aimed at another directory with `--prefix`, with `--dry-run`, or a global one with `-g`, does not); an install with `--package-lock-only`, `--dry-run`, `--no-bin-links`, or `--save-dev` with `--omit=dev`, provides nothing. These checks read a Cyrillic or Greek look-alike letter, a fullwidth letter, or a typographic dash as its Latin letter or `-`, so `сurl | bash` with a Cyrillic `с` is still a `pipe-to-shell`; the letter list is short, and a look-alike outside it escapes. Installs are read from code only: the fenced blocks and code spans of a prose file (Markdown, `.mdx`, `.txt`, `.rst`, `.adoc`), and the whole of any other -text file, such as a script. A `.json` file is read as its strings, keys included, each cut where a sentence ends (`, `, `. `, `! ` or `? ` outside quotes); a file that does not parse as JSON is read as text. The scan reads at most 200 +text file, such as a script. A `.json` file is read as its strings, keys included, each cut where a sentence ends (`, `, `. `, `! ` or `? ` outside quotes); a file that does not parse as JSON is read as text. For a JSON `assertions` array, the install check skips the string +`pattern` of a `not_contains_pattern` assertion because it names text the answer must omit. The scan reads at most 200 bundled files of 256 KiB or less; a binary or non-UTF-8 file counts toward the 200 too and is not checked. A skill at the root of a checkout reads its own `SKILL.md` only. diff --git a/dokimi/docs/finding-codes.md b/dokimi/docs/finding-codes.md index aed08591ce..9a30543e16 100644 --- a/dokimi/docs/finding-codes.md +++ b/dokimi/docs/finding-codes.md @@ -45,7 +45,7 @@ The CLI never emits `not-loaded` (only `review_skill_dir` does), so `--ignore no | `bundle-file-unchecked` | note | the search for unreferenced bundled files could not see every name (over 2000 files, over 50 named documents, or a named document that is over 1 MiB, not UTF-8, a symlink or a FIFO), so no count is given; or the command, content or script check could not list a folder, so its files are not checked | yes | | `bundle-file-unreferenced` | warn | bundled scripts and documents that neither `SKILL.md` nor a document it names mentions; the message gives the count and three example paths | yes | | `description-near-duplicate` | warn | the description overlaps another skill's (Jaccard similarity at least 0.5 and at least 3 shared words) | yes | -| `description-no-when` | warn | the description has no "when" clause (the cues are in `when_cues.py`) | yes | +| `description-no-when` | warn | the description has no recognized trigger phrase (cues in `when_cues.py`); review whether its intended use is clear | yes | | `description-too-long` | error | the description is over 1024 characters | yes | | `description-when-not-checked` | note | the description is in a script no when-cue covers, so it is not checked | yes | | `duplicate` | warn | the SKILL.md is identical to another copy; the copy is counted twice | yes | diff --git a/dokimi/docs/repo-evaluation-contract.md b/dokimi/docs/repo-evaluation-contract.md index e632f3adcb..e8c5fd9a19 100644 --- a/dokimi/docs/repo-evaluation-contract.md +++ b/dokimi/docs/repo-evaluation-contract.md @@ -2083,6 +2083,8 @@ fence or span, and a subshell ends at its closing parenthesis. After a `cd` to a directory the tree lacks or to a non-literal one, after `pushd`/`popd`, and after a `cd` that follows `||` or `|`, relative paths are `unresolved`. +An example of adding a prefix, such as “For example, `src/a.py` would be referenced as `kit/src/a.py`”, +contributes no path claims for that pair. Other path references on the same line are checked. A path in a code span is tried at the file's directory and each of its ancestors. If none has it, the path is `fail` when its parent directory exists at one of those bases (a rename or a deleted file), `ok_suffix` when it ends a @@ -2359,13 +2361,22 @@ The report keeps observations apart from findings: harness documents; which files a given harness version loads is measured by the reach probe (§7). - `checks`: ways to build, test, lint and type-check, per project root (the - root and every directory below it with a `package.json`, makefile, + root and every directory below it with a `package.json`, `tsconfig.json`, makefile, `pyproject.toml`, `setup.py`, `setup.cfg`, `Pipfile`, `go.mod` or `Cargo.toml`; Bazel, CMake, Gradle, Maven, .NET and Autotools are read tree-wide). `basis: declared` means the repository names it: a script, a make target, a config section, a pre-commit hook. `basis: toolchain` means the tool offers the command whether or not there is anything for it to run (`go test` beside a - `go.mod`): a place to start, not evidence of tests. + `go.mod`): a place to start, not evidence of tests. A `tsconfig.json` + identifies a TypeScript compiler project. Its toolchain record does not + verify the configuration, compiler installation or outcome. + With no runner found in the project configuration, inspection also checks + literal GitHub Actions `run` steps for `node --test`, `python -m unittest`, + or a Python script that calls `unittest.main()` in its main guard. A + workflow can declare these directly or through `uv run`. If neither a manifest nor + a workflow declares a test, a standalone test file can identify its own runner + through a `unittest.main()` entry point or a literal JavaScript import or + require of `node:test`. The evidence path identifies the source of each declaration. - `capabilities`: what the harness gets from the repository: MCP configs, Claude Code hooks of any type (`command`, `http`, `prompt`, `agent`) and plugins, settings commands (`statusLine`, `apiKeyHelper`), diff --git a/dokimi/dokimi/commands/catalog_eval.py b/dokimi/dokimi/commands/catalog_eval.py index 05af0832c4..5c09c853f5 100644 --- a/dokimi/dokimi/commands/catalog_eval.py +++ b/dokimi/dokimi/commands/catalog_eval.py @@ -252,14 +252,16 @@ def finding(item: dict[str, Any]) -> dict[str, Any]: shared = shared_problems(report["problems"], report["skills"]) evaluation = {row["name"]: row["evaluation"] for row in report["skills"]} states: dict[str, int] = {} - for state in evaluation.values(): + rows = [{"name": row["name"], "path": row.get("path"), "evaluation": row["evaluation"]} for row in report["skills"]] + for row in rows: + state = row["evaluation"] states[state] = states.get(state, 0) + 1 failed = report["status"] != "pass" reason = None if failed: reason = f"{sum(s['verdict'] == 'fail' for s in subjects)} skill(s) fail, {len(shared)} shared finding(s)" cli_output.emit_leaf( - "catalog eval", {"evaluation": evaluation, "shared_findings": shared, "plan_digest": report.get("plan_digest")}, + "catalog eval", {"evaluation": evaluation, "evaluation_rows": rows, "shared_findings": shared, "plan_digest": report.get("plan_digest")}, verdict=report["status"], reason=reason, subjects=subjects, summary={"tier": report["tier"], "skills": len(subjects), "evaluation": states}, artifacts={"out_dir": str(out), "files": [str(out / name) for name in _OUTPUTS]}) diff --git a/dokimi/dokimi/external/bundle_findings.py b/dokimi/dokimi/external/bundle_findings.py index 26a6ae4493..ffc8f94ed5 100644 --- a/dokimi/dokimi/external/bundle_findings.py +++ b/dokimi/dokimi/external/bundle_findings.py @@ -11,8 +11,8 @@ from dokimi.skills import Skill -from .bundle_paths import path_missing -from .finding_lines import link_line, path_needles, text_line +from .bundle_paths import mask_non_input_paths, path_missing, sibling_input_paths +from .finding_lines import body_view, link_line, path_needles, text_line, view_line from .findings import Finding from .link_files import _file_ref from .paths import _exists, _in_checkout, _inside, _resolved @@ -44,7 +44,7 @@ def _link_finding(raw: str, skill_dir: Path, source_root: Path, real_dir: Path) def _span_finding(raw: str, skill_dir: Path, source_root: Path, real_dir: Path) -> Optional[Finding]: """The finding for a code span that names an existing file outside the skill (``../``), or None.""" text = _file_ref(raw) - if text is None or not raw.startswith("../"): + if text is None or not raw.startswith("../") or all(part == ".." for part in Path(raw).parts): return None target = _in_checkout(skill_dir / text, source_root) if target is None or not _exists(target) or target.is_relative_to(real_dir): @@ -74,8 +74,12 @@ def bundle_findings(skill: Skill, source_root: Path) -> list[Finding]: # The line is the first line of SKILL.md that holds the written link or span (its quoted form for a path). lines = [link_line(text, raw) for raw in targets] + [text_line(text, f"`{raw}`", raw) for raw in spans] located = [replace(f, line=line) for f, line in zip(found, lines, strict=True) if f is not None] + view = body_view(mask_non_input_paths(text)) + sibling_missing = sibling_input_paths(view, skill_dir, source_root) + located.extend(Finding("warn", "path-missing", message, line=number) for number, message in sibling_missing) + spans = link_pieces([line for _, line in view])[1] return located + [ - Finding("warn", "path-missing", message, line=text_line(text, *path_needles(message))) + Finding("warn", "path-missing", message, line=view_line(view, *path_needles(message))) for message in path_missing(spans, skill_dir, source_root, real_dir, linked) ] diff --git a/dokimi/dokimi/external/bundle_paths.py b/dokimi/dokimi/external/bundle_paths.py index 861f884f1f..3cccf94524 100644 --- a/dokimi/dokimi/external/bundle_paths.py +++ b/dokimi/dokimi/external/bundle_paths.py @@ -16,10 +16,14 @@ import re import shlex +from itertools import pairwise from pathlib import Path from typing import Optional +from dokimi.code_spans import CodeSpan, iter_code_spans, replace_code_spans + from .paths import _exists, _in_checkout, _resolved +from .skill_markdown import labelled_paragraphs SKILL_DIR_VAR = "${CLAUDE_SKILL_DIR}/" # After a file, a line or a symbol (``run.py:42``, ``run.py:main``): read as the file's name. @@ -38,6 +42,31 @@ # A file the user makes for their own machine (``secrets.local.md``): the skill names it, the bundle never has it. USER_LOCAL_SUFFIX = ".local.md" +# Only the immediately following path is an output or expressly absent. A later read of the same path is still checked. +_NON_INPUT = re.compile( + r"\b(?:(?:does not|doesn't) (?:ship|include|bundle)|(?:writes?|emits?|generates?)(?: advisory)?|" + r"(?:write|save) (?:it |the result )?to)[ \t]+(?=`)", re.IGNORECASE, +) +_BARE_FILE = re.compile(r"(?:\./)?(?:" + "|".join(BUNDLE_DIRS) + r")/[\w./-]+\.\w+") + + +def mask_non_input_paths(text: str) -> str: + """Blank a bare bundle path directly described as absent or as an output, keeping line numbers and Markdown delimiters.""" + def mask_line(line: str) -> str: + starts = {m.end() for m in _NON_INPUT.finditer(line)} + if not starts: + return line + + def mask(span: CodeSpan) -> str: + if span.start() in starts and _BARE_FILE.fullmatch(span.group(2)): + return span.group(1) + " " * len(span.group(2)) + span.group(1) + return span.group() + + return replace_code_spans(line, mask, not_after="\\") + + # mutation-ok[take-branch]: a line without a backtick has no code span to mask; the test only skips the work + return "".join(mask_line(line) if "`" in line else line for line in text.splitlines(keepends=True)) + def _bundle_path(word: str, anchor: bool = True) -> Optional[str]: """The skill-relative file a code span word names under a bundle folder, or None. @@ -162,3 +191,55 @@ def path_missing( f"{text!r} (in {raw!r}) names no file in the skill directory{from_root}; add the file or fix the path" ) return findings + + +_SIBLING_OWNER = re.compile(r"\s+skill(?:[’']s|\s*,\s+its)\s+", re.I) +_SKILL_NAME = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*") + + +def _sibling_file(skill_dir: Path, root: Path, owner: str, ref: str) -> Optional[Path]: + """A target explicitly attributed to a sibling skill, within a verified in-checkout bundle.""" + if len(owner) > 64 or not _SKILL_NAME.fullmatch(owner) or not _BARE_FILE.fullmatch(ref) or not _bundle_path(ref): + return None + sibling = _in_checkout(skill_dir.parent / owner, root) + if sibling is None: + return None + marker = _in_checkout(sibling / "SKILL.md", sibling) + if marker is None or not marker.is_file(): + return None + return _in_checkout(sibling / ref, sibling) + + +def sibling_input_paths(view: list[tuple[int, str]], skill_dir: Path, root: Path) -> list[tuple[int, str]]: + """Remove explicitly sibling-owned file spans from the local check and return missing sibling files by line. + + The owner and the path may be on two lines of one paragraph. A span in the label of a link to a URL describes + that link and names no file, so it is neither removed nor checked.""" + missing: dict[tuple[str, str], tuple[int, str]] = {} + for first, paragraph, labels in labelled_paragraphs([line for _, line in view]): + if "skill" not in paragraph.lower(): + # mutation-ok[delete-statement]: a fast path; an owner needs the word "skill" after it + continue + pieces: list[str] = [] + end = 0 + for owner, path in pairwise(iter_code_spans(paragraph, not_after="\\")): + if not _SIBLING_OWNER.fullmatch(paragraph[owner.end():path.start()]): + continue + if any(a <= owner.start() < b or a <= path.start() < b for a, b in labels): + continue + name, ref = owner.group(2), path.group(2) + target = _sibling_file(skill_dir, root, name, ref) + if target is None: + continue + pieces.append(paragraph[end:path.start()]) + # mutation-ok[delete-statement,swap-addsub]: the blank only keeps the text's length; spans are read from text, not columns + pieces.append(" " * (path.end() - path.start())) + end = path.end() + if not _exists(target): + number = view[first + paragraph.count("\n", 0, path.start())][0] + missing.setdefault((name, ref), (number, f"{ref!r} names no file in the referenced sibling skill {name!r}; fix the path")) + if pieces: + blanked = ("".join(pieces) + paragraph[end:]).split("\n") + for offset, line in enumerate(blanked): + view[first + offset] = (view[first + offset][0], line) + return list(missing.values()) diff --git a/dokimi/dokimi/external/bundle_refs.py b/dokimi/dokimi/external/bundle_refs.py index fad189f7fb..5702d1df63 100644 --- a/dokimi/dokimi/external/bundle_refs.py +++ b/dokimi/dokimi/external/bundle_refs.py @@ -29,6 +29,7 @@ from dokimi.skills.loader import VENDORED_DIR_NAMES from .command_checks import _is_skill_dir +from .skill_markdown import outside_fences COUNTED_SUFFIXES = frozenset( {".py", ".sh", ".bash", ".zsh", ".ps1", ".js", ".mjs", ".cjs", ".ts", ".rb", ".md", ".mdx", ".txt"} @@ -36,6 +37,7 @@ # Files no agent is meant to open for the task: licence and project paperwork, package markers. SKIPPED_STEMS = frozenset({"license", "licence", "readme", "changelog", "notice", "copying", "authors", "contributing"}) SKIPPED_NAMES = frozenset({"__init__.py", "conftest.py", "requirements.txt", "agents.md", "claude.md"}) +REPORT_HEADING = re.compile(r"^#{1,6}[ \t]+(?:evaluation|benchmark) (?:report|results|metadata|summary)\b", re.I | re.M) SKIPPED_DIRS = frozenset({"tests", "test", "__tests__", "evals"}) TEST_STEM = re.compile(r"test_.*|.*_test|.*\.(?:test|spec)") # test_build.py, build_test.py, build.test.js # A root translation of SKILL.md (SKILL.ru.md, SKILL.zh-CN.md) holds the same instructions: no file to browse to. @@ -59,6 +61,13 @@ def _is_localized_skill(name: str) -> bool: return match is not None and match.group(1).lower() in LANGUAGE_CODES +def _root_paperwork(path: Path) -> bool: + name = path.name.lower() + if name == "benchmark.md": + return REPORT_HEADING.search("\n".join(outside_fences(_read_doc(path) or ""))) is not None + return name == "skill-card.md" or _is_localized_skill(path.name) + + WALK_MAX_FILES = 2000 # a skill with more files is a checkout, not a bundle: it is not checked EXAMPLES_SHOWN = 3 DOC_SUFFIXES = frozenset({".md", ".mdx", ".txt"}) @@ -111,7 +120,7 @@ def _walk(skill_dir: Path, *, counted: bool, failed: list[OSError]) -> list[str] or suffix.lower() not in COUNTED_SUFFIXES or (here == skill_dir and name == "SKILL.md") or (counted and ( - (here == skill_dir and _is_localized_skill(name)) # SKILL.ru.md: a translation + (here == skill_dir and _root_paperwork(here / name)) or name.startswith("_") # a private helper (``_common.py``) scripts import or stem.lower() in SKIPPED_STEMS or name.lower() in SKIPPED_NAMES diff --git a/dokimi/dokimi/external/command_checks.py b/dokimi/dokimi/external/command_checks.py index a32741f6b5..69115febdb 100644 --- a/dokimi/dokimi/external/command_checks.py +++ b/dokimi/dokimi/external/command_checks.py @@ -48,6 +48,7 @@ from .command_dirs import cwd_at, cwds, install_dir, installs_here, join_dir, npx_provided from .command_words import _tokens, _words from .command_shell import BLOCK_END, PIPE_TO, SHELL_SCRIPT, SPAN_END, ShellScan, directory_changes, without_printed +from .command_json import json_command_text from .lookalikes import readings from .skill_markdown import code_spans from .unlisted import recorder @@ -80,7 +81,7 @@ def _only_flags(takes_file: str) -> str: # An inline program (`python -c`, `node -e`, `ruby -e`) or `python -m json.tool` takes the download as data, # unless the program execs or evals it; a shell's `-e` and Ruby's `-E` (an encoding) are not inline programs. r"(?:(?:ba|z|da|k)?sh|fish)\b" - rf"|python(?:3(?:\.\d+)?)?(?![\w.])(?![ \t]+-c(?![\w-])[ \t]+{_CLEAN_PROGRAM})(?![ \t]+-m[ \t]+json\.tool(?![\w.-]))" + rf"|python(?:3(?:\.\d+)?)?(?![\w.])(?!(?:[ \t]+-I)?[ \t]+-c(?![\w-])[ \t]+{_CLEAN_PROGRAM})(?![ \t]+-m[ \t]+json\.tool(?![\w.-]))" rf"|node\b(?![ \t]+-[ep](?![\w-])[ \t]+{_CLEAN_PROGRAM})" rf"|perl\b(?![ \t]+-[eE](?![\w-])[ \t]+{_CLEAN_PROGRAM})" rf"|ruby\b(?![ \t]+-e(?![\w-])[ \t]+{_CLEAN_PROGRAM})" @@ -154,7 +155,7 @@ def _pnpm_options(value_options: frozenset[str]) -> str: # ``to avoid X, run `y` `` is a purpose; ``do not avoid `x` `` asks for it # ``do not forget to run `...` `` asks for the command: a negated verb of omission is no prohibition r"(?! (?:forget|fail|hesitate|neglect|omit|skip|miss)\b)" - r"(?: (?:run|use|install|execute|type|call))?" + r"(?: (?:run|use|install|execute|type|call)(?: (?:bare|interactive)){0,2})?" r"(?: ?(?P`+)(?:(?!(?P=tick)).)+?(?P=tick)(?!`)(?: ?,)?" r"(?: (?:or|and|nor)(?: (?:run|use|install|execute|type|call))?)?)* ?$", re.I, @@ -249,12 +250,13 @@ def _label(name: str, was: str, lower: bool = False) -> str: def _unpinned_pip(rest: str, raw: str | None = None) -> list[str]: names = [] for word, was in _words(rest, PIP_VALUE_OPTIONS, raw): + word = word.rstrip('\'")') if not word or word[0] in "-./~$<{[" or any(c in word for c in "/:"): continue # a flag, a path, a URL or a git+ source - if word.lower().endswith(NON_PACKAGE_SUFFIXES): - continue # a requirements file or an archive + if word.lower().endswith(NON_PACKAGE_SUFFIXES) or word.lower().startswith(("git+", "hg+", "svn+", "bzr+")): + continue # a local archive in a quoted example, a requirements file or a VCS source match = PIP_NAME.fullmatch(word) - if match and not PIP_VERSION.match(match.group(3)): + if match and not match.group(3).startswith("=") and not PIP_VERSION.match(match.group(3)): names.append(_label(match.group(1), was, lower=True)) return names @@ -533,45 +535,6 @@ def _ends_inside_url(reading: str, end: int) -> bool: return "://" in reading[start:stop] -def _cut_sentences(item: str) -> str: - """``item`` with a newline for each ``,``, ``.``, ``!`` or ``?`` that ends a word and is outside quotes: a comma - in a quoted requirement (``'a>=2, <3'``) does not end the command. A quote opens after whitespace or ``=`` - only, so the apostrophe of ``isn't`` opens none.""" - out: list[str] = [] - quote = "" - for i, c in enumerate(item): - if quote: - quote = "" if c == quote else quote - elif c in "'\"" and (i == 0 or item[i - 1] in " \t\n="): - quote = c - elif (c in ",.!?" and i > 0 and not item[i - 1].isspace() and item[i + 1:i + 2] in ("", " ", "\t", "\n", "\r") - and not (c == "." and item[i - 1] in "./")): # the dot of a path (``..``, ``../..``) ends nothing - c = "\n" - out.append(c) - return "".join(out) - - -def _json_text(text: str) -> str: - """The strings of a JSON file, one per line, each cut where a sentence ends (``, `` or ``. ``): the commands - in them end there, so a sentence after ``pip install pkg,`` is not read as packages (#969). Text that is not - JSON is returned as it is.""" - try: - data = json.loads(text) - except (ValueError, RecursionError): # a file nested deeper than the parser's limit is read as text - return text - lines: list[str] = [] - stack = [data] - while stack: - item = stack.pop() - if isinstance(item, str): - lines += [_cut_sentences(item), BLOCK_END] # a quote one string opens never closes in the next - elif isinstance(item, dict): - stack += [*item.values(), *item.keys()] - elif isinstance(item, list): - stack += item - return "\n".join(reversed(lines)) - - def _unpinned_in_readings(text: str, markdown: bool, *, is_json: bool = False, own: frozenset[str] = frozenset()) -> list[str]: """The unpinned installs of a text, read as written and folded. The code is taken from the text as written, once, so folding cannot turn a character into a Markdown delimiter. A command found in several readings at the @@ -579,7 +542,7 @@ def _unpinned_in_readings(text: str, markdown: bool, *, is_json: bool = False, o reads fewer arguments: it has ended the command at a fullwidth separator (a fullwidth ``==`` that pins a package may be followed by one). The exception is a separator inside a URL word, which the earlier reading keeps. A command at another place is another install.""" best: dict[tuple[int, str], tuple[int, list[str], str]] = {} - all_readings = readings(_code_text(_json_text(text) if is_json else text, markdown)) + all_readings = readings(_code_text(json_command_text(text, BLOCK_END) if is_json else text, markdown)) for reading in all_readings: for offset, command, end, labels in _unpinned_at(reading, own, all_readings[0]): key = (offset, command) diff --git a/dokimi/dokimi/external/command_json.py b/dokimi/dokimi/external/command_json.py new file mode 100644 index 0000000000..7188032a90 --- /dev/null +++ b/dokimi/dokimi/external/command_json.py @@ -0,0 +1,58 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Extract command text from JSON without interpreting negative assertion patterns as installs.""" + +from __future__ import annotations + +import json + + +def _cut_sentences(item: str) -> str: + """``item`` with a newline for each ``,``, ``.``, ``!`` or ``?`` that ends a word and is outside quotes: a comma + in a quoted requirement (``'a>=2, <3'``) does not end the command. A quote opens after whitespace or ``=`` + only, so the apostrophe of ``isn't`` opens none.""" + out: list[str] = [] + quote = "" + for i, c in enumerate(item): + if quote: + quote = "" if c == quote else quote + elif c in "'\"" and (i == 0 or item[i - 1] in " \t\n="): + quote = c + elif (c in ",.!?" and i > 0 and not item[i - 1].isspace() and item[i + 1:i + 2] in ("", " ", "\t", "\n", "\r") + and not (c == "." and item[i - 1] in "./")): # the dot of a path (``..``, ``../..``) ends nothing + c = "\n" + out.append(c) + return "".join(out) + + +def _skip_negative_patterns(obj: dict[str, object]) -> dict[str, object]: + """A pattern an assertion forbids is comparison data. Keep its other fields available to the scan.""" + assertions = obj.get("assertions") + if isinstance(assertions, list): + for assertion in assertions: + if (isinstance(assertion, dict) and assertion.get("type") == "not_contains_pattern" + and isinstance(assertion.get("pattern"), str)): + assertion["pattern"] = "" + return obj + + +def json_command_text(text: str, block_end: str) -> str: + """The strings of a JSON file, one per line, each cut where a sentence ends (``, `` or ``. ``): the commands + in them end there, so a sentence after ``pip install pkg,`` is not read as packages (#969). Text that is not + JSON is returned as it is.""" + try: + data = json.loads(text, object_hook=_skip_negative_patterns) + except (ValueError, RecursionError): # a file nested deeper than the parser's limit is read as text + return text + lines: list[str] = [] + stack = [data] + while stack: + item = stack.pop() + if isinstance(item, str): + lines += [_cut_sentences(item), block_end] # a quote one string opens never closes in the next + elif isinstance(item, dict): + stack += [*item.values(), *item.keys()] + elif isinstance(item, list): + stack += item + return "\n".join(reversed(lines)) diff --git a/dokimi/dokimi/external/command_words.py b/dokimi/dokimi/external/command_words.py index 8c7d635544..51b4b2437b 100644 --- a/dokimi/dokimi/external/command_words.py +++ b/dokimi/dokimi/external/command_words.py @@ -43,6 +43,8 @@ def _tokens( its comma is the value's). ``raw`` is ``rest`` before folding, of the same length: each character the lexer keeps in a word is tracked to its place in ``raw``, so a quote, an escape or a separator that folding made does not shift the words (#1303). Without ``raw`` the word is its own spelling.""" + # a ``/`` path is one word: its ``<`` and ``>`` are not redirects (same length, so ``raw`` still lines up) + rest = re.sub(r"(?(?=/)", lambda m: "_" * len(m.group()), rest) tracked = raw is not None and len(raw) == len(rest) <= HALF * HALF # a private-use character of the text is encoded like any other, so it never reads as a placeholder text = "".join( diff --git a/dokimi/dokimi/external/content_checks.py b/dokimi/dokimi/external/content_checks.py index 12a14ca8f8..c556e756db 100644 --- a/dokimi/dokimi/external/content_checks.py +++ b/dokimi/dokimi/external/content_checks.py @@ -38,6 +38,7 @@ from dokimi.skills import Skill from dokimi.skills.loader import VENDORED_DIR_NAMES +from .js_bindings import js_bindings as _js_bindings from .lookalikes import fold, readings from .unlisted import recorder @@ -61,6 +62,8 @@ VARIATION_SELECTORS = frozenset(range(0xFE00, 0xFE10)) | frozenset(range(0xE0100, 0xE01F0)) KEYCAP_BASES = frozenset("#*0123456789") # an ASCII character a selector may follow (keycap sequences) BLANK_FILLERS = frozenset({0x034F, 0x180E, 0x115F, 0x1160, 0x3164, 0xFFA0, 0x2800}) # draw nothing +# Non-symbol, non-ASCII bases in Unicode emoji/emoji-variation-sequences.txt. +EMOJI_PRESENTATION_BASES = frozenset("‼⁉ℹ〰〽") JOINERS = frozenset({0x200C, 0x200D}) # ZWNJ, ZWJ: exempt in emoji and Arabic or Indic text Hit = tuple[str, str] # (finding code, message) @@ -121,7 +124,9 @@ def _legacy_hits(where: str, text: str) -> list[Hit]: hits: list[Hit] = [] seen: set[str] = set() # Every reading but the joined one has the length of the text, so the line is the line of the original. - found = [(m.start(), m.end(), m.group()) for reading in readings(text) for m in pattern.finditer(reading)] + plain = [m for reading in readings(text) for m in pattern.finditer(reading)] + found = [(m.start(), m.end(), m.group()) for m in plain] + bindings = _js_bindings(where, text, plain) # Each reading again with the joins removed, its matches mapped back to the text; one counts only where the # letters-folded text (superscripts kept) ends the ID too: ``gpt-\n4.1`` is gpt-4.1, not gpt-4 (#1298). folded = fold(text, nfkc="letters") @@ -155,7 +160,7 @@ def _cut(span: tuple[int, int, str]) -> bool: end = 0 # First occurrence first, whichever reading found it; of matches at one place the longest, and none inside it. for start, stop, model_id in sorted(found, key=lambda m: (m[0], -m[1])): - if start < end: + if start < end or start in bindings: continue end = stop if model_id in seen: @@ -204,10 +209,12 @@ def _bidi_mark_exempt(text: str) -> set[int]: def _selector_stray(text: str, index: int) -> bool: """A variation selector at the start, after another selector, or after a base that takes none: ASCII that is not - a keycap base, or a non-ASCII character that is not a symbol (``S*``) or an ideograph.""" + a keycap base, or a non-ASCII base outside the supported symbol, ideograph and emoji sequences.""" if index == 0 or ord(text[index - 1]) in VARIATION_SELECTORS: return True before = text[index - 1] + if before in EMOJI_PRESENTATION_BASES: + return text[index] not in "\ufe0e\ufe0f" if before.isascii(): return before not in KEYCAP_BASES return not (unicodedata.category(before).startswith("S") or unicodedata.name(before, "").startswith("CJK")) diff --git a/dokimi/dokimi/external/finding_lines.py b/dokimi/dokimi/external/finding_lines.py index 2b9898f505..80e468775f 100644 --- a/dokimi/dokimi/external/finding_lines.py +++ b/dokimi/dokimi/external/finding_lines.py @@ -53,7 +53,11 @@ def text_line(text: str, *needles: "str | tuple[str, ...]") -> Optional[int]: The arguments are tried in order and the first that is found wins; an argument that is a tuple is one group, whose earliest line counts (so ``]: x`` above ``(x)`` is the first occurrence of the same target). """ - view = _body_view(text) + return view_line(body_view(text), *needles) + + +def view_line(view: list[tuple[int, str]], *needles: "str | tuple[str, ...]") -> Optional[int]: + """Find the first matching source line in an already filtered Markdown body.""" for group in needles: group = (group,) if isinstance(group, str) else group for number, line in view: @@ -62,7 +66,7 @@ def text_line(text: str, *needles: "str | tuple[str, ...]") -> Optional[int]: return None -def _body_view(text: str) -> list[tuple[int, str]]: +def body_view(text: str) -> list[tuple[int, str]]: """The body lines the check reads (:func:`fenced_view`: no fenced code, no quote markers), each with its 1-based line in ``text``, or 0 for the blank line the view puts where a block or a quote ends.""" lines = _lines(text) @@ -84,7 +88,7 @@ def link_line(text: str, raw: str) -> Optional[int]: returned), and an inline link counts only when its ``)`` comes before the paragraph ends, as the check reads it; a line that merely contains ``raw`` is the fallback when no link form matches. """ - view = _body_view(text) + view = body_view(text) body = "\n".join(line for _, line in view) word = re.escape(raw) gap = r"[ \t]*(?:\n[ \t]*)?" # spaces, and at most one line break: a blank line ends the paragraph diff --git a/dokimi/dokimi/external/js_bindings.py b/dokimi/dokimi/external/js_bindings.py new file mode 100644 index 0000000000..4f8a7b7d58 --- /dev/null +++ b/dokimi/dokimi/external/js_bindings.py @@ -0,0 +1,129 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The offsets of a JavaScript or TypeScript variable that a model-like word names (``const o1 = first.opacity``).""" + +from __future__ import annotations + +import re + +_JS_FILES = (".js", ".mjs", ".cjs", ".ts", ".tsx") +_DECLARATIONS = frozenset({"var", "const", "let"}) +_OPEN, _CLOSE = "{[(", "}])" + + +def _pattern_names(sig: list, j: int) -> tuple[list[str], int]: + """The names a destructuring pattern binds, from its opener at ``sig[j]``, and the index after its closer. + A key before ``:`` binds nothing; a default value after ``=`` is an expression.""" + from pygments.token import Name, Operator + + names: list[str] = [] + depth = 0 + default_at: int | None = None + while j < len(sig): + _, token, value = sig[j] + if value in _OPEN: + depth += 1 + elif value in _CLOSE: + depth -= 1 + if depth == 0: + return names, j + 1 + if default_at is not None and depth < default_at: + default_at = None + elif value == "=" and token in Operator and default_at is None: + default_at = depth + elif value == "," and default_at == depth: + default_at = None + elif token in Name and default_at is None and (j + 1 >= len(sig) or sig[j + 1][2] != ":"): + names.append(value) + j += 1 + return names, j + + +def _statement_ends(sig: list, j: int, text: str, want_target: bool) -> bool: + """Whether the token at ``sig[j]``, at the top level of a declaration, ends it: a ``;``, the ``of`` or ``in`` of a + loop, or a new line that goes on with a statement of its own.""" + from pygments.token import Operator + + start, _, value = sig[j][0], sig[j][1], sig[j][2] + if want_target: + return False + if value in (";", "of", "in"): + return True + previous = sig[j - 1] + return "\n" in text[previous[0] : start] and previous[2] not in (",", "=") and previous[1] not in Operator \ + and value not in _OPEN + ".," + + +def _declarators(sig: list, k: int, text: str) -> tuple[set[str], int]: + """The names bound by the declaration whose keyword is before ``sig[k]``, and the index where it ends.""" + from pygments.token import Name + + names: set[str] = set() + want_target, depth, j = True, 0, k + while j < len(sig): + _, token, value = sig[j] + if depth == 0: + if _statement_ends(sig, j, text, want_target): + break + if value == "," and not want_target: + want_target = True + j += 1 + continue + if want_target and value in ("{", "["): + bound, j = _pattern_names(sig, j) + names.update(bound) + want_target = False + continue + if want_target and token in Name: + names.add(value) + want_target = False + if value in _OPEN: + depth += 1 + elif value in _CLOSE: + depth -= 1 + j += 1 + return names, j + + +def _declared(sig: list, text: str) -> set[str]: + """Every name a ``var``, ``const`` or ``let`` statement binds: each declarator, and destructured names.""" + from pygments.token import Keyword + + declared: set[str] = set() + k = 0 + while k < len(sig): + _, token, value = sig[k] + k += 1 + if value in _DECLARATIONS and token in Keyword and not (k > 1 and sig[k - 2][2] == "."): + declared |= _declarators(sig, k, text)[0] # a declaration inside its initializer is found as k goes on + return declared + + +def js_bindings(where: str, text: str, matches: list[re.Match]) -> set[int]: + """Offsets where a model-like word is a declared JS variable or a use of it. A property (``models.o1``, a key + ``{o1: 1}``), a string literal and a comment are not, so they stay mentions.""" + if not where.endswith(_JS_FILES): + return set() + # mutation-ok[drop-filter]: skips the lexer early; a declared name is an identifier, so the result is the same + names = {m.group() for m in matches if m.group().isidentifier()} + if not names: + return set() + + from pygments.lexers.javascript import JavascriptLexer + from pygments.token import Comment, Name, Text + + sig = [(i, t, v) for i, t, v in JavascriptLexer().get_tokens_unprocessed(text) if t not in Comment and t not in Text] + declared = _declared(sig, text) & names + if not declared: + return set() + found: set[int] = set() + for n, (i, token, value) in enumerate(sig): + if token not in Name or value not in declared: + continue + before = sig[n - 1][2] if n else "" + after = sig[n + 1][2] if n + 1 < len(sig) else "" + if before in (".", "?.") or (after == ":" and before in ("{", ",")): + continue + found.add(i) + return found diff --git a/dokimi/dokimi/external/skill_markdown.py b/dokimi/dokimi/external/skill_markdown.py index 5d726597b3..61833061c7 100644 --- a/dokimi/dokimi/external/skill_markdown.py +++ b/dokimi/dokimi/external/skill_markdown.py @@ -18,7 +18,6 @@ from urllib.parse import unquote from dokimi.code_spans import CodeSpan, iter_code_spans, replace_code_spans -from dokimi.repos.l0.markdown import split as split_markdown def code_spans(text: str) -> Iterator[CodeSpan]: @@ -53,15 +52,13 @@ def code_spans(text: str) -> Iterator[CodeSpan]: ) # A thematic break line (``---``, ``* * *``, ``___``), with its line end. _THEMATIC_BREAK_RE = re.compile(r" {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})(?:\n|$)") -# A shortcut or collapsed reference: a link only for the nesting check (_external_labels). +# A shortcut or collapsed reference: a link only for the nesting check (_descriptive_labels). _SHORT_REFERENCE_RE = re.compile(r"(? int: return _width(line[:len(line) - len(line.lstrip(" \t"))]) -def _paragraphs(lines: list[str]) -> list[str]: - """The paragraphs of ``lines`` (blank lines end one), each joined by newlines. +def _paragraph_blocks(lines: list[str]) -> list[tuple[int, str]]: + """The paragraphs of ``lines`` (blank lines end one), each joined by newlines, with the index in ``lines`` of its first line. A thematic break ends one and is no part of any. A list item and an ATX heading are blocks of their own: a code span cannot run across them (CommonMark). """ - out: list[str] = [] + out: list[tuple[int, str]] = [] block: list[str] = [] - for line in lines + [""]: + first = 0 + for index, line in enumerate(lines + [""]): if _THEMATIC_BREAK_RE.match(line): # a break ends the paragraph: no link or code span runs across it if block: - out.append("\n".join(block)) + out.append((first, "\n".join(block))) block = [] continue if not line.strip() or _LIST_ITEM_RE.match(line) or _HEADING_RE.match(line): if block: - out.append("\n".join(block)) + out.append((first, "\n".join(block))) block = [] if line.strip(): + if not block: + first = index block.append(line) if _HEADING_RE.match(line): - out.append("\n".join(block)) + out.append((first, "\n".join(block))) block = [] return out +def _paragraphs(lines: list[str]) -> list[str]: + """The paragraphs of ``lines`` (see :func:`_paragraph_blocks`).""" + return [paragraph for _, paragraph in _paragraph_blocks(lines)] + + # What an escaped bracket is masked to: two characters that are no bracket and no space, so that a label # ``g\\]`` stays unlike ``g`` (:func:`_unmask_brackets` gives the backslash form back). _ESCAPED_BRACKET = {"[": "\ue000\ue001", "]": "\ue000\ue002"} @@ -274,21 +279,6 @@ def _inline_destinations(text: str) -> list[str]: return found -def _join_label_lines(lines: list[str]) -> list[str]: - """``lines`` with each reference label alone on its line joined to the line after it, so that a - definition whose destination is on the next line reads as one line for the splitter.""" - out: list[str] = [] - i = 0 - while i < len(lines): - if _LABEL_ONLY_RE.match(lines[i]) and i + 1 < len(lines): - out.append(f"{lines[i]} {lines[i + 1]}") - i += 2 - else: - out.append(lines[i]) - i += 1 - return out - - def is_uri(text: str) -> bool: """Whether a link destination, already decoded (``<>`` off, escapes, ``#``, ``?`` and ``%`` read), is a URL or another URI (``https:``, ``mailto:``, ``tel:``, ``x:``), not a file. A dotted scheme with a line or symbol after @@ -299,14 +289,14 @@ def is_uri(text: str) -> bool: return bool(scheme and not ("." in scheme.group() and _FILE_SUFFIX_RE.fullmatch(text[scheme.end() :]))) -def _is_uri_destination(raw: str) -> bool: - """:func:`is_uri` of a destination as written, decoded as :func:`dokimi.external.link_files._file_ref` decodes it.""" +def _decoded_destination(raw: str) -> str: + """The destination as a path or URI, decoded as the bundled link check decodes it.""" text = raw.strip() if text.startswith("<") and text.endswith(">"): text = text[1:-1].strip() text = ESCAPE_RE.sub(r"\1", text) - text = unquote(text.split("#", 1)[0].split("?", 1)[0].strip()) - return not text.startswith("/") and is_uri(text) + # mutation-ok[bump-int]: only the piece before the first ``#`` or ``?`` is read + return unquote(text.split("#", 1)[0].split("?", 1)[0].strip()) _SQUARE_RE = re.compile(r"[\[\]]") @@ -350,27 +340,35 @@ def _label_key(paragraph: str, m: re.Match[str]) -> str: return " ".join(paragraph[m.start(1) : m.end(1)].casefold().split()) -def _reference_definitions(paragraph: str, masked: str, found: dict[str, bool]) -> None: +def _reference_definitions(paragraph: str, masked: str, found: dict[str, str]) -> list[str]: """Add to ``found`` the reference definitions of ``paragraph``, masked as ``masked``: label (:func:`_label_key`) - -> whether the destination is a URL. A definition cannot interrupt a paragraph, so only those at its start - count, one after the other. A thematic break starts a new block, so a definition may follow one after prose. - The first definition of a label decides, as in CommonMark.""" + -> decoded destination. A definition cannot interrupt a paragraph, so only those at its start + count, one after the other. A thematic break or a setext underline starts a new block, so a definition may follow + one after prose. + The first definition decides the label. Return all valid destinations for the file checks.""" + targets = [] pos, block_start = 0, True while pos < len(masked): if rule := _THEMATIC_BREAK_RE.match(masked, pos): # a break (or a setext underline) ends the block before it pos, block_start = rule.end(), True + elif not block_start and (underline := _SETEXT_UNDERLINE_RE.match(masked, pos)): + pos, block_start = underline.end(), True # the heading above ends here, so a definition may follow elif ( block_start and (m := _DEFINITION_RE.match(masked, pos)) and _balanced(m.group(2)) and (key := _label_key(paragraph, m)) # a blank label is no definition: the line is prose ): - found.setdefault(key, _is_uri_destination(m.group(2))) + target = _unmask_brackets(m.group(2)) + targets.append(target) + found.setdefault(key, _decoded_destination(target)) pos = m.end() else: eol = masked.find("\n", pos) pos, block_start = (len(masked) if eol == -1 else eol + 1), False + return targets + def _is_image(masked: str, open_at: int) -> bool: """Whether the ``[`` at ``open_at`` follows an unescaped ``!``.""" @@ -382,11 +380,11 @@ def _is_image(masked: str, open_at: int) -> bool: return slashes % 2 == 0 -def _link_closes(paragraph: str, masked: str, definitions: dict[str, bool]) -> tuple[list[tuple[int, bool]], str]: - """The ``(index of "]", destination is a URL)`` of each inline, reference, collapsed and shortcut link in ``masked``, +def _link_closes(paragraph: str, masked: str, definitions: dict[str, str]) -> tuple[list[tuple[int, Optional[str]]], str]: + """The ``(index of "]", decoded destination)`` of each inline, reference, collapsed and shortcut link in ``masked``, and ``masked`` with the destinations and titles of the inline links blanked (their text is literal). ``paragraph`` is ``masked`` as written, for the reference keys.""" - closes: list[tuple[int, bool]] = [] + closes: list[tuple[int, Optional[str]]] = [] chars = list(masked) consumed = 0 inline_closes: set[int] = set() # the "]" of each inline link: a shortcut there is that link's label @@ -397,7 +395,7 @@ def _link_closes(paragraph: str, masked: str, definitions: dict[str, bool]) -> t end = _LINK_END_RE.match(masked, stop) if stop is not None else None if end is not None: inline_closes.add(opened.start()) - closes.append((opened.start(), _is_uri_destination(masked[opened.end() : stop]))) + closes.append((opened.start(), _decoded_destination(_unmask_brackets(masked[opened.end() : stop])))) consumed = end.end() chars[opened.end() : end.end() - 1] = " " * (end.end() - 1 - opened.end()) literal = "".join(chars) @@ -412,12 +410,24 @@ def _link_closes(paragraph: str, masked: str, definitions: dict[str, bool]) -> t full = _FULL_REFERENCE_RE.match(literal, short.end()) if full and _label_key(paragraph, full) in definitions: continue # ``[a][b]`` with ``b`` defined is the full reference, counted above; else ``[a]`` stands alone - closes.append((short.start(1) + len(short.group(1)), False)) # a link, never a label read here + closes.append((short.start(1) + len(short.group(1)), None)) # a link, never a label read here return closes, literal -def _external_labels(paragraph: str, masked: str, definitions: dict[str, bool]) -> list[tuple[int, int]]: - """The ``(start, end)`` of each link label in ``masked`` whose destination has a URL scheme (``https:``, ``mailto:``). +_LEADING_PARENTS = re.compile(r"^(?:\.\./)+") +_CODE_LABEL = re.compile(r"(`+)([^`]+)\1") + + +def _descriptive_label(paragraph: str, start: int, close: int, destination: str) -> bool: + """A URL label, or one bare code span spelling a parent-relative destination without its leading parents.""" + if destination.startswith("../"): + span = _CODE_LABEL.fullmatch(paragraph, start + 1, close) + return bool(span and span[2].strip() == _LEADING_PARENTS.sub("", destination)) + return not destination.startswith("/") and is_uri(destination) + + +def _descriptive_labels(paragraph: str, masked: str, definitions: dict[str, str]) -> list[tuple[int, int]]: + """The ``(start, end)`` of each link label in ``masked`` that describes its destination instead of naming a separate bundled file. The destination is inline, or a reference whose first definition in ``definitions`` has one. A code span in such a label is the link's text, not a file of the skill. A label that holds another link (an image is fine) is @@ -427,9 +437,10 @@ def _external_labels(paragraph: str, masked: str, definitions: dict[str, bool]) pairs = _bracket_pairs(literal) link_starts = sorted(pairs[c] for c, _ in closes if c in pairs and not _is_image(literal, pairs[c])) found: list[tuple[int, int]] = [] - for close, is_url in closes: + for close, destination in closes: start = pairs.get(close) - if start is None or not is_url: + # mutation-ok[drop-clause]: every close _link_closes returns has its opener in ``pairs``; this guards the lookup + if start is None or destination is None or not _descriptive_label(paragraph, start, close, destination): continue inner = bisect_right(link_starts, start) # brackets pair up, so a link that starts inside the label ends inside it if not (inner < len(link_starts) and link_starts[inner] < close): @@ -454,15 +465,30 @@ def _inside(spans: list[tuple[int, int]], starts: list[int], pos: int) -> bool: return i >= 0 and pos < spans[i][1] +def labelled_paragraphs(lines: list[str]) -> list[tuple[int, str, list[tuple[int, int]]]]: + """The paragraphs of ``lines`` as ``(index of its first line, text, label spans)``: the spans are the + ``(start, end)`` of each link label that describes its destination (:func:`_descriptive_labels`), merged.""" + blocks = _paragraph_blocks(lines) + paragraphs = [paragraph for _, paragraph in blocks] + maskeds = [ + _unlinked_brackets(replace_code_spans(p, lambda m: " " * len(m.group()), not_after="\\")) for p in paragraphs + ] + definitions: dict[str, str] = {} + for paragraph, masked in zip(paragraphs, maskeds, strict=True): + _reference_definitions(paragraph, masked, definitions) + return [ + (first, paragraph, _merged(_descriptive_labels(paragraph, masked, definitions))) + for (first, paragraph), masked in zip(blocks, maskeds, strict=True) + ] + + def link_pieces(lines: list[str]) -> tuple[list[str], list[str]]: """The link destinations and the code-span texts of ``lines`` (outside fences), as written. A code span is matched by its run of backticks, across the lines of its paragraph, and its text is taken whole, except one in the label of a link with a URL destination (``[`examples/a.py`](https://...)``, or a reference to a definition with one), - which is the link's text. Its text and the escaped brackets are then blanked. Inline links are read from the - paragraph (parentheses up to 32 deep, a destination over lines), and reference definitions by the - markdown splitter of L0 (``dokimi.repos.l0.markdown.split``), line by line. The splitter's inline - reader is not used: it reads one level of parentheses and no escapes, so it would disagree with this one. + or a code span that is the full label and spells a parent-relative destination after its leading ../ segments. + Those labels describe the destination. Inline links and block-start reference definitions share the masked paragraphs. """ targets: dict[str, None] = {} spans: dict[str, None] = {} @@ -470,11 +496,12 @@ def link_pieces(lines: list[str]) -> tuple[list[str], list[str]]: maskeds = [ _unlinked_brackets(replace_code_spans(p, lambda m: " " * len(m.group()), not_after="\\")) for p in paragraphs ] - definitions: dict[str, bool] = {} - for paragraph, masked in zip(paragraphs, maskeds, strict=True): - _reference_definitions(paragraph, masked, definitions) - for paragraph, masked in zip(paragraphs, maskeds, strict=True): - labels = _merged(_external_labels(paragraph, masked, definitions)) + definitions: dict[str, str] = {} + # mutation-ok[flip-bool]: both lists are built from ``paragraphs``, so the zips never see unequal lengths + block_targets = [_reference_definitions(p, m, definitions) for p, m in zip(paragraphs, maskeds, strict=True)] + # mutation-ok[flip-bool]: as above + for paragraph, masked, refs in zip(paragraphs, maskeds, block_targets, strict=True): + labels = _merged(_descriptive_labels(paragraph, masked, definitions)) label_starts = [a for a, _ in labels] for m in code_spans(paragraph): text = m.group(2).replace("\n", " ").strip() @@ -482,9 +509,5 @@ def link_pieces(lines: list[str]) -> tuple[list[str], list[str]]: spans[text] = None for target in _inline_destinations(masked): targets[target] = None - for line in _join_label_lines(masked.split("\n")): - if not _DEFINITION_START_RE.match(line): - continue - for _, target, _ in split_markdown(line).links: # the label stays masked: the splitter reads no escape in it - targets[_unmask_brackets(target)] = None + targets.update(dict.fromkeys(refs)) return list(targets), list(spans) diff --git a/dokimi/dokimi/external/validate.py b/dokimi/dokimi/external/validate.py index cd7c3ce981..ed3f12a4b3 100644 --- a/dokimi/dokimi/external/validate.py +++ b/dokimi/dokimi/external/validate.py @@ -520,8 +520,8 @@ def _description_findings(skill: Skill) -> list[Finding]: Finding( "warn", "description-no-when", - "description has no 'when' clause (e.g. 'use when ...'); the model chooses " - "the skill from the description alone", + "no recognized trigger phrase (e.g. 'use when ...'); check whether the description makes clear when to choose " + "this skill", ) ] return [] diff --git a/dokimi/dokimi/external/when_cues.py b/dokimi/dokimi/external/when_cues.py index 5042018c48..da9f06dd1a 100644 --- a/dokimi/dokimi/external/when_cues.py +++ b/dokimi/dokimi/external/when_cues.py @@ -34,12 +34,12 @@ # A "when" clause or use phrase per language: the model chooses a skill from its description alone. # Latin cues take word boundaries, CJK cues are substrings; bare 使用 (use) or 用于 (for) are too broad. WHEN_CUES = { - "en": r"\b(?:when\s+\w|use for\b|use (?:this skill )?to\s+[*_`~]*(?![.;!?)*_`~\s])\S|use this skill\b|trigger(?:s|ed)?\s*(?:on\b|:)|invoke only\b|" + "en": r"\b(?:when\s+[`\x22\x27“‘]?\w|use for\b|use (?:this skill )?to\s+[*_`~]*(?![.;!?)*_`~\s])\S|use this skill\b|trigger(?:s|ed)?\s*(?:on\b|:)|invoke only\b|runs? only on\s+`?/\w|" r"activate\b|invoke this\b|use (?:it |this |these )?(?:when|if|whenever|proactively|anytime)\b|" # "Use after sglang-xpu-run." names a skill, not a situation: 2+ hyphens, no of/the/and/or/to/in/on/for part. # A dot ends the name only before a space or the end, so "pre-commit-hooks.sh" stays a cue (#969). r"use (?:it |this |these )?(?:before|after)\b(?!\s*(?:[.;!?)]|$)|\s+`?\w+(?:-(?!(?:of|the|and|or|to|in|on|for)\b)\w+){2,}`?\s*(?:[;!?)]|\.(?!\w)|$))|" - r"whenever\b|" + _SENTENCE_START + r"applies to\b)", + r"whenever\b|" + _SENTENCE_START + r"(?:applies to|ideal for|use as (?:a|an|the))\b)", "es": r"(? list[str]: """The root and every directory below it with a project manifest, outside generated and test trees.""" roots = {"."} for f in scan.files: - if posixpath.basename(f) in PROJECT_MARKERS and "/" in f and not is_generated(f) and not _TEST_DIR.search(f): + if posixpath.basename(f) in _INSPECT_PROJECT_MARKERS and "/" in f and not is_generated(f) and not _TEST_DIR.search(f): roots.add(posixpath.dirname(f)) return sorted(roots, key=lambda r: (r != ".", r)) @@ -271,11 +273,15 @@ def detect_checks(scan: Scan) -> list[Check]: scan.preload([_at(r, m) for r in roots for m in sorted(PROJECT_MARKERS)]) for root in roots: found += (_node(scan, root) + _make(scan, root) + + _toolchain(scan, root, "node", "tsconfig.json", ("typecheck",)) + _toolchain(scan, root, "go", "go.mod", ("build", "test", "lint")) + _toolchain(scan, root, "rust", "Cargo.toml", ("build", "test", "lint", "typecheck")) + _python(scan, root)) # these read the whole tree: one build graph, wherever its files are found += _cmake(scan) + _bazel(scan) + _gradle(scan) + _maven(scan) + _dotnet(scan) + _autotools(scan) found += _pre_commit(scan) + if not any(check.kind == "test" for check in found): + found.extend(Check(ecosystem, "test", "declared", evidence, name, directory) + for ecosystem, evidence, name, directory in test_runners(scan, roots)) return sorted(dict.fromkeys(found), key=lambda c: (c.directory != ".", c.directory, ECOSYSTEMS.index(c.ecosystem), KINDS.index(c.kind), c.evidence, c.name or "")) diff --git a/dokimi/dokimi/repos/environment/workflow_tests.py b/dokimi/dokimi/repos/environment/workflow_tests.py new file mode 100644 index 0000000000..a2a1d23fb5 --- /dev/null +++ b/dokimi/dokimi/repos/environment/workflow_tests.py @@ -0,0 +1,159 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Built-in test runners explicitly named by GitHub Actions or by standalone test modules.""" + +from __future__ import annotations + +import ast +import posixpath +import re +from collections.abc import Callable, Iterator +from typing import Any + +import yaml + +from dokimi.repos.l0.core import Scan +from dokimi.repos.l0.workflows import runnable + +from .files import is_generated, is_test_file + +_WORDS = re.compile(r"[\w./:@=,+-]+(?:[ \t]+[\w./:@=,+-]+)*") + + +def _unittest_script(text: str) -> bool: + if "unittest" not in text: + return False + try: + body = ast.parse(text).body + except (SyntaxError, ValueError, RecursionError): + return False + modules = {a.asname or a.name for stmt in body if isinstance(stmt, ast.Import) + for a in stmt.names if a.name == "unittest"} + for stmt in body: + match stmt: + case ast.If(test=ast.Compare(left=ast.Name(id="__name__"), ops=[ast.Eq()], + comparators=[ast.Constant(value="__main__")]), body=guarded): + for expr in guarded: + match expr: + case ast.Expr(value=ast.Call(func=ast.Attribute(value=ast.Name(id=module), attr="main"))): + if module in modules: + return True + return False + + +def _python_test(scan: Scan, words: list[str], uv_run: bool, directory: str) -> bool: + if words and re.fullmatch(r"python(?:3(?:\.\d+)?)?", words[0]): + if words[1:3] == ["-m", "unittest"]: + return True + words = words[1:] + elif not uv_run: + return False + if not words or not words[0].endswith(".py"): + return False + script = posixpath.normpath(posixpath.join(directory, words[0])) + # mutation-ok[drop-clause]: ``scan.text`` of a path outside the scan is empty, which is no unittest script + return script in scan.file_set and not is_generated(script) and _unittest_script(scan.text(script)) + + +def _runner(scan: Scan, command: str, directory: str) -> tuple[str, str] | None: + command = command.strip() + if not _WORDS.fullmatch(command): + return None + words = command.split() + if any(arg in {"-h", "--help", "--version"} for arg in words): + return None + uv_run = words[:2] == ["uv", "run"] + if uv_run: + words = words[2:] + if words[:2] == ["node", "--test"]: + return "node", "node --test" + return ("python", "unittest") if _python_test(scan, words, uv_run, directory) else None + + +def _mapping(value: Any) -> dict: + return value if isinstance(value, dict) else {} + + +def _defaults(owner: dict) -> dict: + return _mapping(_mapping(owner.get("defaults")).get("run")) + + +def _steps(workflow: dict) -> Iterator[tuple[str, str]]: + for raw_job in _mapping(workflow.get("jobs")).values(): + job = _mapping(raw_job) + steps = job.get("steps") + if not isinstance(steps, list): + continue + defaults = _defaults(workflow) | _defaults(job) + for raw_step in steps: + step = defaults | _mapping(raw_step) + directory = step.get("working-directory", ".") + if isinstance(step.get("run"), str) and isinstance(directory, str) and step.get("shell", "bash") in ( + "bash", "sh", "pwsh", "powershell", "cmd" + ): + yield step["run"], posixpath.normpath(directory) + + +def _workflow_runners(scan: Scan) -> Iterator[tuple[str, str, str, str]]: + """Yield ecosystem, workflow, runner and working directory. The commands are never executed.""" + paths = runnable(scan) + scan.preload(paths) # mutation-ok[delete-statement]: one fetch for all; ``scan.text`` reads the same without it + for path in paths: + try: + workflow = yaml.safe_load(scan.text(path)) + except (yaml.YAMLError, ValueError, RecursionError): + continue + for command, directory in _steps(_mapping(workflow)): + if directory not in scan.dir_set or not re.fullmatch(r"[\w./-]+", directory): + continue + if runner := _runner(scan, command, directory): + yield runner[0], path, runner[1], directory + + +_NODE_IMPORT_BINDING = r"(?:[\w$]+|(?:[\w$]+\s*,\s*)?(?:\{[\w\s,$]{1,4096}\}|\*\s+as\s+[\w$]+))" +_NODE_TEST_IMPORT = re.compile( + rf"""(? bool: + if "node:test" not in text: + return False + from pygments.lexers.javascript import JavascriptLexer + from pygments.token import Keyword, Name + + # Only a real import/require token qualifies. A quoted example, template string or comment cannot declare a runner. + # mutation-ok[drop-clause]: a string or comment token holding just the bare word is never followed by the import + return any(value in ("import", "require") and (token in Keyword or token in Name) + and _NODE_TEST_IMPORT.match(text, offset) is not None + for offset, token, value in JavascriptLexer().get_tokens_unprocessed(text)) + + +def _first_test(scan: Scan, paths: list[str], uses_runner: Callable[[str], bool]) -> str | None: + """Fetch candidates in small batches on a blob-less clone and stop once the runner is verified.""" + for start in range(0, len(paths), 32): # mutation-ok[bump-int]: the batch size only sets how many are fetched at once + batch = paths[start:start + 32] # mutation-ok[bump-int]: as above + scan.preload(batch) # mutation-ok[delete-statement]: ``scan.text`` reads the same without it + for path in batch: + if uses_runner(scan.text(path)): + return path + return None + + +def test_runners(scan: Scan, roots: list[str]) -> Iterator[tuple[str, str, str, str]]: + workflows = list(_workflow_runners(scan)) + if workflows: + yield from workflows + return + candidates = [f for f in scan.files if is_test_file(f) and not is_generated(f)] + groups: dict[str, list[str]] = {} # the candidates under each deepest project root, so each root has its own check + for f in candidates: + groups.setdefault(max((r for r in roots if f.startswith(r + "/")), key=len, default="."), []).append(f) + for ecosystem, runner, suffixes, predicate in ( + ("python", "unittest", (".py",), _unittest_script), ("node", "node:test", (".js", ".mjs", ".cjs"), _node_test_script) + ): + for directory in sorted(groups): + evidence = _first_test(scan, [f for f in groups[directory] if f.endswith(suffixes)], predicate) + if evidence: + yield ecosystem, evidence, runner, directory diff --git a/dokimi/dokimi/repos/l0/markdown.py b/dokimi/dokimi/repos/l0/markdown.py index afed1acab5..4ada1560e4 100644 --- a/dokimi/dokimi/repos/l0/markdown.py +++ b/dokimi/dokimi/repos/l0/markdown.py @@ -25,6 +25,11 @@ # A reference definition, `[label]: target "title"`, on a line of its own. Not a footnote (`[^1]: text`). _REFDEF_RE = re.compile(rf"^ {{0,3}}\[(?!\^)[^\]]+\]:\s*(<[^<>\n]*>|\S+){_TITLE}\s*$") _SPAN_RE = re.compile(r"(?[^`\s]+/[^`\s]+)`[ \t]+(?:would|could) be (?:referenced|written|expressed) as " + r"`[^`\s]+/(?-i:(?P=path))`", re.I, +) _FENCE_RE = re.compile(r"^\s*(```+|~~~+)\s*([\w+-]*)") @@ -69,7 +74,8 @@ def split(text: str) -> Pieces: prose = _SPAN_RE.sub("", line) # not in code ref = _REFDEF_RE.match(prose) out.links.extend((n, t, line) for t in ([ref.group(1)] if ref else _LINK_RE.findall(prose))) - out.spans.extend((n, s.strip(), line) for s in _SPAN_RE.findall(line) if s.strip()) + spans = _SPAN_RE.findall(_PATH_NOTATION.sub("", line)) + out.spans.extend((n, s.strip(), line) for s in spans if s.strip()) if fence is not None: # unterminated: still checked out.fences.append(fence) return out diff --git a/dokimi/pyproject.toml b/dokimi/pyproject.toml index 10a5abec54..ab1a492ae4 100644 --- a/dokimi/pyproject.toml +++ b/dokimi/pyproject.toml @@ -38,6 +38,7 @@ dependencies = [ # The reference `regex` check runs with a timeout, which `re` lacks. "regex>=2024.11.6", "markdown-it-py>=4.2,<5", + "Pygments>=2.17,<3", ] [project.optional-dependencies] diff --git a/dokimi/requirements.txt b/dokimi/requirements.txt index 633dfb5245..8258f3f835 100644 --- a/dokimi/requirements.txt +++ b/dokimi/requirements.txt @@ -14,3 +14,4 @@ scipy>=1.11.0 # The reference `regex` check runs with a timeout, which `re` lacks. regex>=2024.11.6 markdown-it-py>=4.2,<5 +Pygments>=2.17,<3 diff --git a/dokimi/tests/test_catalog_bundle_unreferenced.py b/dokimi/tests/test_catalog_bundle_unreferenced.py index 3a11da9aff..3689b2977b 100644 --- a/dokimi/tests/test_catalog_bundle_unreferenced.py +++ b/dokimi/tests/test_catalog_bundle_unreferenced.py @@ -73,6 +73,7 @@ def test_unnamed_files_are_one_warning_with_the_count(tmp_path): [ "LICENSE.txt", "README.md", + "skill-card.md", "scripts/__init__.py", "tests/test_build.py", ".hidden/x.py", @@ -93,7 +94,7 @@ def test_test_files_outside_a_tests_folder_are_not_counted(tmp_path, rel): assert "bundle-file-unreferenced" not in _codes(review) -@pytest.mark.parametrize("doc", ["README.md", "AGENTS.md"]) +@pytest.mark.parametrize("doc", ["README.md", "AGENTS.md", "skill-card.md"]) def test_a_skipped_document_that_skill_md_names_is_still_read(tmp_path, doc): # Not counted itself, but an agent that opens it is pointed at the script it names. skill_dir = _skill(tmp_path / "skills", "kit", name="kit", description="Use when testing.", body=f"See {doc}.\n") @@ -104,6 +105,33 @@ def test_a_skipped_document_that_skill_md_names_is_still_read(tmp_path, doc): assert "bundle-file-unreferenced" not in _codes(review) +def test_only_root_benchmark_reports_are_excluded(tmp_path): + # external-content.md: root publication reports are paperwork; procedure guides remain task resources. + skill = _skill(tmp_path / "skills", "kit", name="kit", description="Use when testing.", body="# Body\n") + (skill / "references").mkdir() + report = "# Benchmark results\n\nThree of four tasks passed.\n" + (skill / "BENCHMARK.md").write_text(report, encoding="utf-8") + (skill / "references" / "BENCHMARK.md").write_text(report, encoding="utf-8") + (skill / "references" / "skill-card.md").write_text("Task reference.\n", encoding="utf-8") + + [review] = review_skills(read_skill_manifest(tmp_path)) + [finding] = [f for f in review.findings if f.code == "bundle-file-unreferenced"] + assert "2 of 2" in finding.message + assert "(references/BENCHMARK.md, references/skill-card.md)" in finding.message + + (skill / "BENCHMARK.md").write_text("# Running the benchmarks\nRun the timing script.\n", encoding="utf-8") + [review] = review_skills(read_skill_manifest(tmp_path)) + [finding] = [f for f in review.findings if f.code == "bundle-file-unreferenced"] + assert "(BENCHMARK.md, references/BENCHMARK.md, references/skill-card.md)" in finding.message + + # a report heading inside a fenced example does not make a procedure guide a report + guide = "# Running the benchmarks\n\n```markdown\n# Benchmark results\n```\n" + (skill / "BENCHMARK.md").write_text(guide, encoding="utf-8") + [review] = review_skills(read_skill_manifest(tmp_path)) + [finding] = [f for f in review.findings if f.code == "bundle-file-unreferenced"] + assert "(BENCHMARK.md, references/BENCHMARK.md, references/skill-card.md)" in finding.message + + @pytest.mark.parametrize( ("doc", "content", "script"), [ diff --git a/dokimi/tests/test_catalog_command_checks_operands.py b/dokimi/tests/test_catalog_command_checks_operands.py index f08557a137..17f31bd261 100644 --- a/dokimi/tests/test_catalog_command_checks_operands.py +++ b/dokimi/tests/test_catalog_command_checks_operands.py @@ -5,6 +5,8 @@ from __future__ import annotations +import json + import pytest from dokimi.external.command_checks import _findings_in @@ -35,3 +37,86 @@ def test_a_command_written_as_a_json_key_is_still_read(): """A JSON key is text of the file too, as it was before JSON strings were decoded.""" found = _findings_in([("evals.json", '{"pip install requests": 1}')]) assert any(code == "install-unpinned" and "pip requests" in msg for code, msg in found) + + +def test_negative_assertion_pattern_is_not_an_install_requirement(): + """external-content.md excludes only the prohibited pattern from JSON assertions.""" + fixture = {"cases": [{"assertions": [ + {"type": "not_contains_pattern", "pattern": "pip install rejected", "hint": "pip install suggested"}, + {"type": "contains_pattern", "pattern": "pip install expected"}, + ]}]} + files = [("evals/evals.json", json.dumps(fixture)), ("evals/Dockerfile", "RUN pip install required\n")] + [(_, message)] = [f for f in _findings_in(files) if f[0] == "install-unpinned"] + assert message.startswith("3 installs ") + assert all("pip " + name in message for name in ("suggested", "expected", "required")) + + +@pytest.mark.parametrize("fixture", [ + {"type": "not_contains_pattern", "pattern": "pip install requests"}, + {"assertions": {"type": "not_contains_pattern", "pattern": "pip install requests"}}, + {"assertions": ["pip install requests"]}, + {"assertions": [{"type": "not_contains_pattern", "pattern": {"script": "pip install requests"}}]}, +]) +def test_only_a_typed_string_pattern_inside_an_assertions_array_is_exempt(fixture): + found = _findings_in([("config.json", json.dumps(fixture))]) + assert any(code == "install-unpinned" and "pip requests" in msg for code, msg in found) + + + +def test_placeholder_prefix_does_not_install_a_package_named_after_the_directory(): + text = "npm install --prefix /scripts lodash" + found = [msg for code, msg in _findings_in([("SKILL.md", f"`{text}`")]) if code == "install-unpinned"] + assert len(found) == 1 and "1 install" in found[0] and "npm lodash" in found[0] + + +def test_python_print_keyword_is_not_a_pip_requirement(): + text = 'print("Install with: pip install httpx -r requirements.txt", file=sys.stderr)' + found = [msg for code, msg in _findings_in([("helper.py", text)]) if code == "install-unpinned"] + assert len(found) == 1 and "1 install" in found[0] and "pip httpx" in found[0] + + +@pytest.mark.parametrize("vcs", ["git", "hg", "svn", "bzr"]) +def test_an_abbreviated_vcs_source_is_not_a_package_name(vcs): + """external-content.md excludes VCS references from unpinned package counts.""" + found = [msg for code, msg in _findings_in([("SKILL.md", f"Compare `pip install {vcs}+…` with `pip install requests`.\n")]) + if code == "install-unpinned"] + assert len(found) == 1 and found[0].startswith("1 install name no version (pip requests)") + + +def test_local_wheel_and_abbreviated_vcs_source_are_not_package_names(): + """external-content.md excludes local artifacts and VCS references from unpinned package counts.""" + text = ('```python\nsubprocess.run(shlex.split("pip install example-1.2-py3-none-any.whl"), check=True)\n```\n' + 'Compare `pip install git+…` with `pip install requests`.\n') + found = [msg for code, msg in _findings_in([("SKILL.md", text)]) if code == "install-unpinned"] + assert len(found) == 1 and found[0].startswith("1 install name no version (pip requests)") + + +def test_isolated_python_reading_json_from_a_pipe_receives_data(): + """The fixed inline program reads JSON, including when the interpreter isolates its imports.""" + line = """curl $URL | python3 -I -c 'import json,sys; print(json.load(sys.stdin))'""" + assert not any(code == "pipe-to-shell" for code, _ in _findings_in([("run.sh", line)])) + assert any(code == "pipe-to-shell" for code, _ in _findings_in([("run.sh", "curl $URL | python3 -I")])) + + +def test_only_a_json_file_has_its_negative_assertion_patterns_skipped(): + """external-content.md: the exemption reads JSON files; the same text in YAML is still a command.""" + text = json.dumps({"assertions": [{"type": "not_contains_pattern", "pattern": "pip install requests"}]}) + assert not _findings_in([("evals.json", text)]) + assert [code for code, _ in _findings_in([("evals.yaml", text)])] == ["install-unpinned"] + + +@pytest.mark.parametrize(("item", "cut"), [ + ("It's simple: pip install foo. Then go", "It's simple: pip install foo\n Then go"), # an apostrophe opens no quote + ("pip install 'a>=2, <3', then go", "pip install 'a>=2, <3'\n then go"), # a quote after a space does + (", pip install foo", ", pip install foo"), # a mark at the start ends no word + ("'a, b' c", "'a, b' c"), # a quote at the start opens + ("cd ../.. then", "cd ../.. then"), + ("pip install numpy.linalg x", "pip install numpy.linalg x"), # a dot inside a word ends nothing + ("a, b", "a\n b"), ("pip install foo.", "pip install foo\n"), # after the first word; at the end + ("foo,\tbar", "foo\n\tbar"), ("foo,\rbar", "foo\n\rbar"), # before a tab or a carriage return # the dot of a path ends nothing + ("files in ./, then stop", "files in ./\n then stop"), # a comma after a path still does +]) +def test_json_strings_are_cut_where_a_sentence_ends_outside_quotes(item, cut): + """external-content.md (#969): a command in a JSON string ends where its sentence ends.""" + from dokimi.external.command_json import json_command_text + assert json_command_text(json.dumps([item]), "END") == f"END\n{cut}" diff --git a/dokimi/tests/test_catalog_command_prohibited.py b/dokimi/tests/test_catalog_command_prohibited.py index aec7ec4836..54e2f6f9eb 100644 --- a/dokimi/tests/test_catalog_command_prohibited.py +++ b/dokimi/tests/test_catalog_command_prohibited.py @@ -15,6 +15,7 @@ "Do not `pip install lemonade-sdk` to get it.", "Please don't `pip install lemonade-sdk` here.", "Never run `pip install lemonade-sdk`.", + "Never use bare interactive `npx tsc` to detect the compiler.", "We avoid `pip install lemonade-sdk` for it.", "**Do not** use `pip install lemonade-sdk`.", ]) diff --git a/dokimi/tests/test_catalog_eval_cli.py b/dokimi/tests/test_catalog_eval_cli.py index 9851f0e82b..51946b9cb4 100644 --- a/dokimi/tests/test_catalog_eval_cli.py +++ b/dokimi/tests/test_catalog_eval_cli.py @@ -980,3 +980,16 @@ def test_an_untracked_root_without_a_base_has_no_selection_note(tmp_path): done = _run(root, out) assert done.returncode == 0, done.stderr assert "selection_note" not in json.loads((out / "catalog.json").read_text()) + + +def test_json_evaluation_counts_separately_packaged_skills_with_the_same_name(tmp_path): + root = tmp_path / "catalog" + for plugin in ("first", "second"): + skill = root / plugin / "skills" / "setup" + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text(f"---\nname: setup\ndescription: Use when configuring {plugin}.\n---\nDo it.\n") + result = json.loads(_run(root, tmp_path / "out", "--json").stdout) + assert result["summary"]["evaluation"] == {"no_tasks": 2} + assert {row["path"] for row in result["data"]["evaluation_rows"]} == { + "first/skills/setup", "second/skills/setup"} + assert result["data"]["evaluation"] == {"setup": "no_tasks"} diff --git a/dokimi/tests/test_catalog_links.py b/dokimi/tests/test_catalog_links.py index f9c405d73c..c9f2b6af5c 100644 --- a/dokimi/tests/test_catalog_links.py +++ b/dokimi/tests/test_catalog_links.py @@ -585,3 +585,45 @@ def test_a_placeholder_link_in_a_code_span_or_fence_is_not_checked(tmp_path, bod [review] = review_skills(read_skill_manifest(tmp_path)) assert review.findings == [] + + +def test_type_signatures_inside_a_paragraph_are_not_reference_definitions(tmp_path): + """CommonMark §4.7 allows reference definitions only at a block boundary.""" + body = "interface Fields {\n[key: string]: string\n}\n\n[guide]: references/missing.md\n" + _skill(tmp_path / "skills", "types", name="types", description="Use for types.", body=body) + [review] = review_skills(read_skill_manifest(tmp_path)) + [finding] = review.findings + assert finding.code == "link-missing" and "references/missing.md" in finding.message + + +def test_parent_notation_without_a_named_target_is_not_a_bundle_reference(tmp_path): + """A parent-directory escape warning needs a named file or directory outside the skill.""" + _skill(tmp_path, "sample", name="sample", body="Avoid `../` or `../../` paths. Read `../notes.md`.") + (tmp_path / "notes.md").touch() + [review] = review_skills(read_skill_manifest(tmp_path)) + [warning] = review.findings + assert warning.code == "path-escapes-skill" + assert "'../notes.md'" in warning.message + + +@pytest.mark.parametrize(("raw", "escapes"), [ + ("../notes.md", True), + ("../${OTHER}/notes.md", False), # a template variable names no file to check + ("sub/../../notes.md", False), # only a span that starts with ``../`` is read as leaving the skill +]) +def test_a_span_escapes_the_skill_only_from_a_leading_parent_to_a_named_file(tmp_path, raw, escapes): + from dokimi.external.bundle_findings import _span_finding + skill_dir = _skill(tmp_path, "sample", name="sample") + (tmp_path / "notes.md").touch() + finding = _span_finding(raw, skill_dir, tmp_path, skill_dir.resolve()) + assert (finding is not None and finding.code == "path-escapes-skill") is escapes + + +@pytest.mark.parametrize("underline", ["=====", "--", "== "], ids=["equals", "two-dashes", "trailing-space"]) +def test_a_definition_after_a_setext_heading_is_checked(tmp_path, underline): + """A setext underline ends the heading, so the definition under it is a block of its own (CommonMark §4.7).""" + body = f"Guide\n{underline}\n[guide]: references/missing.md\n\nRead [guide].\n" + _skill(tmp_path / "skills", "setext", name="setext", description="Use for guides.", body=body) + [review] = review_skills(read_skill_manifest(tmp_path)) + [finding] = review.findings + assert finding.code == "link-missing" and "references/missing.md" in finding.message diff --git a/dokimi/tests/test_catalog_path_missing.py b/dokimi/tests/test_catalog_path_missing.py index 39dfb8761e..b61b9cb427 100644 --- a/dokimi/tests/test_catalog_path_missing.py +++ b/dokimi/tests/test_catalog_path_missing.py @@ -811,3 +811,152 @@ def test_missing_span_is_reported_when_the_destination_is_not_a_url(tmp_path, bo """#1089: a label is skipped only for a real URL link; these four forms are not one.""" review, _ = _review(tmp_path, body, files=("notes.md",)) assert "scripts/deploy.sh" in " ".join(f.message for f in _path_findings(review)) + +@pytest.mark.parametrize("phrase", ["does not ship", "emits", "writes advisory", "write it to"]) +def test_non_input_path_is_skipped_but_missing_input_on_same_line_remains(tmp_path, phrase): + """external-content.md: a directly described output or absent file is not a bundled input.""" + review, _ = _review(tmp_path, f"The runner {phrase} `resources/plan.json`; read `references/guide.md`.\n") + [finding] = _path_findings(review) + assert "'references/guide.md'" in finding.message + + +def test_missing_input_points_to_the_use_after_a_negated_mention(tmp_path): + review, _ = _review(tmp_path, "This skill does not ship `scripts/run.py`.\nRun `scripts/run.py`.\n") + [finding] = _path_findings(review) + assert "'scripts/run.py'" in finding.message + assert finding.line == 6 + + +def test_output_cue_does_not_hide_a_command_reference(tmp_path): + review, _ = _review(tmp_path, "The tool emits `resources/plan.json; python scripts/format.py` as its suggestion.\n") + assert len(_path_findings(review)) == 2 + + + +@pytest.mark.parametrize("link", [ + "[`templates/ledger.md`](../../templates/ledger.md)", + "[``templates/ledger.md``](<../templates/ledger.md#record>)", + "[`templates/ledger.md`][ledger]\n\n[ledger]: ../../templates/ledger.md", +]) +def test_parent_relative_target_and_its_exact_path_label_are_one_claim(tmp_path, link): + """external-content.md: shortened path labels do not add a second skill-root path.""" + review, _ = _review(tmp_path, link) + assert not _path_findings(review) + assert any(f.code == "link-escapes-skill" and "templates/ledger.md" in f.message for f in review.findings) + + +@pytest.mark.parametrize("body", [ + "[`templates/ledger.md`](../../references/ledger.md)", + "[read `templates/ledger.md`](../../templates/ledger.md)", + "[`templates/ledger.md`](../../templates/ledger.md). Also read `templates/ledger.md`.", +]) +def test_different_parent_relative_label_or_separate_mention_keeps_its_check(tmp_path, body): + review, _ = _review(tmp_path, body) + [finding] = _path_findings(review) + assert "'templates/ledger.md'" in finding.message + + +def test_explicit_sibling_owner_does_not_hide_a_local_missing_path(tmp_path): + """external-content.md: an explicitly named sibling owns only the following reference.""" + root = tmp_path / "skills" + doc = "Use the `engine` skill, its `references/types.md`.\nRead `references/types.md` here.\n" + _skill(root, "router", name="router", body=doc) + other = _skill(root, "engine", name="engine") + (other / "references").mkdir() + (other / "references/types.md").write_text("## Types\n") + entries = read_skill_manifest(tmp_path) + review = next(r for e, r in zip(entries, review_skills(entries), strict=True) if e.name == "router") + assert [(f.line, f.message) for f in _path_findings(review)] == [ + (6, "'references/types.md' (in 'references/types.md') names no file in the skill directory; add the file or fix the path") + ] + + +def test_missing_sibling_target_is_reported_even_if_local_copy_exists(tmp_path): + """external-content.md: verify the referenced skill rather than satisfying its path from the current skill.""" + root = tmp_path / "skills" + here = _skill(root, "router", name="router", body="Use the `engine` skill's `references/types.md`.\n" + "See the `engine` skill, its `references/types.md`, and the `engine` skill's `references/x.py`.\n") + _skill(root, "engine", name="engine") + (here / "references").mkdir() + (here / "references/types.md").write_text("## Local types\n") + entries = read_skill_manifest(tmp_path) + review = next(r for e, r in zip(entries, review_skills(entries), strict=True) if e.name == "router") + assert [(f.line, f.message) for f in _path_findings(review)] == [ + (5, "'references/types.md' names no file in the referenced sibling skill 'engine'; fix the path") + ] + + +def _router_review(tmp_path, doc, sibling="engine", marker=True): + root = tmp_path / "skills" + _skill(root, "router", name="router", body=doc) + other = root / sibling + if marker == "outside": # its SKILL.md is a link out of the folder: no verified skill + other.mkdir(parents=True) + (tmp_path / "SKILL.md").write_text(f"---\nname: {sibling}\ndescription: Use it.\n---\n", encoding="utf-8") + (other / "SKILL.md").symlink_to(tmp_path / "SKILL.md") + elif marker: + other = _skill(root, sibling, name=sibling) + (other / "references").mkdir(parents=True, exist_ok=True) + entries = read_skill_manifest(tmp_path) + return next(r for e, r in zip(entries, review_skills(entries), strict=True) if e.name == "router") + + +@pytest.mark.parametrize(("sibling", "marker", "ref", "between"), [ + ("Engine", True, "references/types.md", " skill's "), + ("engine", False, "references/types.md", " skill's "), + ("engine", "outside", "references/types.md", " skill's "), + ("engine", True, "references/types.md", " skill reads "), # not " skill's" or " skill, its" + ("engine", True, "references/types.md#intro", " skill's "), # not a bare file + ("e" * 65, True, "references/types.md", " skill's "), # longer than a skill name may be +]) +def test_an_owner_that_is_not_a_sibling_skill_leaves_the_path_local(tmp_path, sibling, marker, ref, between): + """external-content.md: only a lowercase skill name whose folder holds its own SKILL.md owns the path.""" + review = _router_review(tmp_path, f"Use the `{sibling}`{between}`{ref}`.\n", sibling, marker) + [finding] = _path_findings(review) + assert "names no file in the skill directory" in finding.message and "sibling" not in finding.message + + +def test_a_sibling_name_of_the_longest_allowed_length_owns_its_path(tmp_path): + """external-content.md: a skill name is at most 64 characters.""" + review = _router_review(tmp_path, f"Use the `{'e' * 64}` skill's `references/types.md`.\n", "e" * 64) + [finding] = _path_findings(review) + assert "referenced sibling skill" in finding.message + + +def test_a_local_path_before_a_sibling_reference_on_one_line_is_still_checked(tmp_path): + """external-content.md: a sibling owns only the reference after its name.""" + review = _router_review(tmp_path, "`scripts/run.py` then the `engine` skill's `references/types.md`.\n") + assert sorted(f.message.split(" ")[0] for f in _path_findings(review)) == ["'references/types.md'", "'scripts/run.py'"] + assert any("sibling skill 'engine'" in f.message for f in _path_findings(review)) + + +@pytest.mark.parametrize("doc", [ + "Use the `engine` skill's\n`references/types.md`.\n", + "Use the `engine`\nskill's `references/types.md`.\n", + "> Use the `engine` skill,\n> its `references/types.md`.\n", +], ids=["path-on-next-line", "skill-on-next-line", "quoted"]) +def test_a_sibling_reference_wrapped_over_lines_is_read_as_one(tmp_path, doc): + """A soft line break in a paragraph does not separate the owner from its path.""" + review = _router_review(tmp_path, doc) + [finding] = _path_findings(review) + assert "referenced sibling skill 'engine'" in finding.message and finding.line == 6 + + +def test_a_wrapped_sibling_reference_to_an_existing_file_is_not_missing(tmp_path): + root = tmp_path / "skills" + _skill(root, "router", name="router", body="Use the `engine` skill's\n`references/types.md`.\n") + other = _skill(root, "engine", name="engine") + (other / "references").mkdir() + (other / "references/types.md").write_text("## Types\n") + entries = read_skill_manifest(tmp_path) + review = next(r for e, r in zip(entries, review_skills(entries), strict=True) if e.name == "router") + assert _path_findings(review) == [] + + +@pytest.mark.parametrize("doc", [ + "See [the `engine` skill's `references/types.md`](https://example.com/types.md).\n", + "See [the `engine` skill's `references/types.md`][types].\n\n[types]: https://example.com/types.md\n", +], ids=["inline", "reference"]) +def test_a_sibling_path_in_the_label_of_a_url_link_is_not_checked(tmp_path, doc): + """external-content.md: the label of a link to a URL describes the link and names no file.""" + assert _path_findings(_router_review(tmp_path, doc)) == [] diff --git a/dokimi/tests/test_code_spans.py b/dokimi/tests/test_code_spans.py index 182f5116c9..55788fe293 100644 --- a/dokimi/tests/test_code_spans.py +++ b/dokimi/tests/test_code_spans.py @@ -363,3 +363,11 @@ def watch(frame: Any, event: str, arg: Any) -> None: text_growth = len(shape(25 * FACTOR)) / len(shape(25)) assert 0 < small_chars and large_chars <= 4 * text_growth * small_chars, (small_chars, large_chars) assert large_calls <= 2 * small_calls, (small_calls, large_calls) + + +@pytest.mark.parametrize(("destination", "kept"), [ + ("https://example.com/a", False), ("/go/https://example.com/a", True), ("templates/a.md", True), +]) +def test_a_code_label_describes_only_a_url_destination(destination, kept): + """external-content.md: a label of an absolute path that holds ``://`` still names a bundled file.""" + assert ("templates/a.md" in link_pieces([f"[`templates/a.md`]({destination})"])[1]) is kept diff --git a/dokimi/tests/test_content_checks.py b/dokimi/tests/test_content_checks.py index 90dc178336..00f70180d5 100644 --- a/dokimi/tests/test_content_checks.py +++ b/dokimi/tests/test_content_checks.py @@ -44,6 +44,18 @@ def _messages(root: Path, code: str) -> list[str]: # ---- legacy-model-id ---------------------------------------------------------------------------- +def test_model_like_javascript_binding_keeps_real_mentions(tmp_path): + script = "const o1 = first.opacity;\nif (o1 < 0.5) fade();\n" + _skill(tmp_path / "skills", "animation", body="Use this tool.", files={ + "scripts/animation.mjs": script, + "scripts/call.js": script + 'send({model: "o1"});\n', + "scripts/help.ts": script + "// The o1 model is retired.\n", + }) + messages = _messages(tmp_path, "legacy-model-id") + assert len(messages) == 2 + assert all(any(m.startswith(f"scripts/{name} line 3:") for m in messages) for name in ("call.js", "help.ts")) + + def test_retired_model_id_in_skill_body_is_a_warning_with_its_replacement(tmp_path): _skill(tmp_path / "skills", "triage", body="# Triage\n\nRoute tickets with claude-3-haiku-20240307.\n") @@ -636,6 +648,13 @@ def test_variation_selector_at_the_start_and_in_a_run_are_reported(tmp_path): assert len(_messages(tmp_path / "skills2", "hidden-unicode")) == 1 +@pytest.mark.parametrize("base", "‼⁉ℹ〰〽") +def test_emoji_punctuation_and_letters_accept_only_presentation_selectors(tmp_path, base): + """Unicode emoji-variation-sequences.txt lists text and emoji presentation for these bases.""" + [message] = _hidden(tmp_path, f"{base}\ufe0e {base}\ufe0f {base}\U000e0100") + assert "U+E0100" in message + + @pytest.mark.parametrize("text", ["❤️", "1️⃣", "#️⃣", "葛\U000e0100", "❤︎"], ids=["emoji", "keycap-digit", "keycap-hash", "ideograph", "symbol-text"]) def test_variation_selector_in_emoji_keycap_and_ideograph_sequences_is_not_reported(tmp_path, text): @@ -938,3 +957,37 @@ def test_a_long_run_of_blank_braille_patterns_is_scanned_in_linear_time(): ratio, found = growth(lambda k: partial(_hidden_indices, "x" + "\u2800" * k), 500) assert found == list(range(1, 8001)) assert ratio < GROWTH_LIMIT + + +@pytest.mark.parametrize(("name", "bound"), [ + ("a.js", {6}), ("a.mjs", {6}), ("a.cjs", {6}), ("a.ts", {6}), ("a.tsx", {6}), ("a.py", set()), +]) +def test_only_a_declared_javascript_name_is_a_binding(name, bound): + """A model-like name used but not declared, or written in a template string, is still a mention; only a JS or + TS file is lexed (external-content.md, legacy model IDs).""" + import re + + from dokimi.external.content_checks import _js_bindings + text = "const o1 = 1;\nuse(o3);\nsend(`o1`);\n" + assert _js_bindings(name, text, list(re.finditer(r"o1|o3", text))) == bound + + +@pytest.mark.parametrize(("text", "count"), [ + ("const first = 1, o1 = first;\nconsume(o1);\n", 2), + ("const {o1} = settings;\nconsume(o1);\n", 2), + ("const {a: o1, b = o3} = settings;\nconsume(o1, o3);\n", 2), + ("const [x, o1] = pair;\nconsume(o1);\n", 2), + ("const o1 = first.opacity;\nclient.create({model: models.o1});\n", 1), + ("const o1 = first.opacity;\nclient.create({o1: 1});\n", 1), + ("const first = 1;\nconst second = o1;\n", 0), + ("const f = () => { const o1 = 1; return o1; };\n", 2), +], ids=["declarators", "destructured", "renamed-and-default", "array", "property", "key", "initializer-only", "nested"]) +def test_javascript_binding_covers_declarators_and_not_properties(text, count): + """Every declarator and destructured name is a variable and so are its uses; a property or key is a mention.""" + import re + + from dokimi.external.content_checks import _js_bindings + found = list(re.finditer(r"\bo[13]\b", text)) + bound = _js_bindings("a.js", text, found) + assert len(bound) == count + assert all(text[i : i + 2] in ("o1", "o3") for i in bound) diff --git a/dokimi/tests/test_description_when_cues.py b/dokimi/tests/test_description_when_cues.py index ed730b849d..3139deb86d 100644 --- a/dokimi/tests/test_description_when_cues.py +++ b/dokimi/tests/test_description_when_cues.py @@ -672,3 +672,17 @@ def test_applies_to_in_the_middle_of_a_sentence_is_not_a_cue(description): def test_applies_to_in_emphasis_at_a_sentence_start_is_a_cue(description): """#1330: ``**Applies to**`` starts the sentence as ``Applies to`` does.""" assert when_clause_found(description) is True + + + +@pytest.mark.parametrize("description", [ + "Ideal for React apps and custom layouts.", "Use as the top-level router for rendering tasks.", + "Select a backend when 'Hydrogen' is mentioned.", + "It runs only on `/review` or an explicit ask.", +]) +def test_explicit_audience_or_quoted_condition_is_a_when_cue(description): + assert when_clause_found(description) is True + + +def test_an_unrelated_ideal_for_in_prose_is_not_a_cue(): + assert when_clause_found("Reads build logs. The output is ideal for printing.") is False diff --git a/dokimi/tests/test_project_markers.py b/dokimi/tests/test_project_markers.py index fc672cdad0..7f6db93c3f 100644 --- a/dokimi/tests/test_project_markers.py +++ b/dokimi/tests/test_project_markers.py @@ -6,6 +6,10 @@ The expected sets are the literal lists the readers carried before ``dokimi/repos/project_markers.py``. """ +import json + +import pytest + from dokimi.repos import project_markers from dokimi.repos.environment import checks from dokimi.repos.l0 import adapters, core @@ -87,3 +91,31 @@ def test_make_target_scan_reads_a_lowercase_makefile(tmp_path): (tmp_path / "makefile").write_text("onlylower:\n", encoding="utf-8") assert "onlylower" in adapters._make_facts(Scan(WorkTree(tmp_path), frozenset()))["targets"] + + +def _scan(tmp_path, files): + from dokimi.repos.l0.core import Scan + from dokimi.repos.source import WorkTree + + for name, text in files.items(): + (tmp_path / name).parent.mkdir(parents=True, exist_ok=True) + (tmp_path / name).write_text(text, encoding="utf-8") + return Scan(WorkTree(tmp_path), frozenset()) + + +def test_project_roots_are_folders_with_a_manifest(tmp_path): + """repo-evaluation-contract.md §8.1: generated and test trees are not project roots.""" + scan = _scan(tmp_path, {"package.json": "{}", "docs/readme.md": "x\n", "pkg/pyproject.toml": "[project]\n", + "node_modules/dep/package.json": "{}", "tests/app/package.json": "{}", "vendor/lib/package.json": "{}"}) + assert checks.project_roots(scan) == [".", "pkg"] + + +@pytest.mark.parametrize(("package", "names"), [ + ({}, ["node --test"]), # no declared test: the runner the workflow calls is the check + ({"scripts": {"test": "jest"}}, ["test"]), # a declared test script wins +]) +def test_a_workflow_runner_is_read_only_without_a_declared_test(tmp_path, package, names): + """repo-evaluation-contract.md §8.1.""" + workflow = {"jobs": {"check": {"steps": [{"run": "node --test"}]}}} + scan = _scan(tmp_path, {"package.json": json.dumps(package), ".github/workflows/check.yml": json.dumps(workflow)}) + assert [c.name for c in checks.detect_checks(scan) if c.kind == "test"] == names diff --git a/dokimi/tests/test_repo_inspect_cli.py b/dokimi/tests/test_repo_inspect_cli.py index 7102ad5314..f0af00553d 100644 --- a/dokimi/tests/test_repo_inspect_cli.py +++ b/dokimi/tests/test_repo_inspect_cli.py @@ -40,6 +40,27 @@ def test_cli_json_prints_the_stamped_payload(tmp_path, capsys): validate_artifact("repo_environment", data) +def test_inspect_reports_typescript_projects_outside_fixtures(tmp_path, capsys): + """Contract §8.1: tsconfig.json is compiler project evidence, including below the checkout root.""" + _repo(tmp_path, { + "package.json": '{"scripts":{"test":"node --test"}}', + "packages/build/tsconfig.json": '{"compilerOptions":{"strict":true}}', + "tsconfig.json": '{"references":[{"path":"packages/build"}]}', + "tests/fixtures/demo/tsconfig.json": "{}", + "node_modules/demo/tsconfig.json": "{}", + "templates/tsconfig.example.json": "{}", + }) + args = build_parser().parse_args(["repo", "inspect", str(tmp_path), "--json"]) + args.func(args) + payload = json.loads(capsys.readouterr().out)["data"] + assert [c for c in payload["checks"] if c["kind"] == "typecheck"] == [ + {"ecosystem": "node", "kind": "typecheck", "basis": "toolchain", "directory": directory, + "evidence": path, "name": None} + for directory, path in ((".", "tsconfig.json"), ("packages/build", "packages/build/tsconfig.json")) + ] + assert "checks.typecheck.missing" not in {f["rule"] for f in payload["findings"]} + + @pytest.mark.outcome("cjm-repo-inspect") @pytest.mark.parametrize("case", ["missing source", "unwritable out"]) def test_cli_exits_2_when_it_cannot_read_or_write(tmp_path, capsys, case): diff --git a/dokimi/tests/test_repo_inspect_workflow_tests.py b/dokimi/tests/test_repo_inspect_workflow_tests.py new file mode 100644 index 0000000000..8d06c853c2 --- /dev/null +++ b/dokimi/tests/test_repo_inspect_workflow_tests.py @@ -0,0 +1,169 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""Repo evaluation contract §8.1, test runners declared in CI steps and standalone modules +(``dokimi.repos.environment.workflow_tests``).""" + +from __future__ import annotations + +import json + +import pytest + +from dokimi.repos.environment import inspect_repo +from dokimi.repos.source import WorkTree +from tests.test_repo_environment import _repo + + +def _inspect(tmp_path, *steps, extra=None): + workflow = {"defaults": {"run": {"working-directory": "pkg"}}, + "jobs": {"check": {"steps": list(steps)}}} + _repo(tmp_path, {".github/workflows/check.yml": json.dumps(workflow), + "pkg/test_helper.py": "# runner unknown\n", + "pkg/local_check.py": "import unittest as u\nif __name__ == '__main__':\n u.main()\n", + **(extra or {})}) + return inspect_repo(WorkTree(tmp_path)) + + +def test_workflow_declares_standalone_runners_and_respects_working_directories(tmp_path): + payload = _inspect(tmp_path, {"run": "uv run local_check.py"}, {"run": "node --test", "working-directory": "."}) + tests = [c for c in payload["checks"] if c["kind"] == "test"] + assert [(c["ecosystem"], c["name"], c["directory"]) for c in tests] == [ + ("node", "node --test", "."), ("python", "unittest", "pkg")] + assert all(c["basis"] == "declared" and c["evidence"] == ".github/workflows/check.yml" for c in tests) + assert "checks.test.runner-unknown" not in {f["rule"] for f in payload["findings"]} + + +@pytest.mark.parametrize("command", ["python3 -m unittest discover", "uv run python -m unittest", "python3 local_check.py"]) +def test_direct_unittest_invocations(tmp_path, command): + payload = _inspect(tmp_path, {"run": command}) + assert any(c["name"] == "unittest" for c in payload["checks"]) + + +@pytest.mark.parametrize("step", [ + {"name": "node --test", "run": "echo node --test"}, {"uses": "node/test@v1"}, + {"run": "node --test --help"}, {"run": "node --test", "shell": "python"}, + {"run": "echo <