Upload folder using huggingface_hub (part 180)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- 20260907-014537-computing-math-08ed12/environment/public_data/input/README.mdAdded+6
- 20260907-014537-computing-math-08ed12/environment/public_data/input/analysis_spec.jsonAdded+98
- 20260907-014537-computing-math-08ed12/environment/public_data/input/dockerfile_packaging_corpus.mdAdded+447
- 20260907-014537-computing-math-08ed12/environment/public_data/input/dockerfile_text_windows.csvAdded+226
- 20260907-014537-computing-math-08ed12/environment/public_data/input/source_context_windows.jsonlAdded
- 20260907-014537-computing-math-08ed12/environment/public_data/input/tutorial_metadata.jsonAdded+37
- 20260907-014537-computing-math-08ed12/environment/public_data/main.pyAdded+180
- 20260907-014537-computing-math-08ed12/environment/public_data/software/command_examples.csvAdded+11
- 20260907-014537-computing-math-08ed12/environment/public_data/software/software_manifest.jsonAdded+16
- 20260907-014537-computing-math-08ed12/environment/public_data/software/validate_outputs.pyAdded+41
- 20260907-014537-computing-math-08ed12/environment/public_data/task_card.jsonAdded+111
- 20260907-014537-computing-math-08ed12/instruction.mdAdded+33
- 20260907-014537-computing-math-08ed12/solution/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-014537-computing-math-08ed12/solution/internal/workflow_runtime.pyAdded+5
- 20260907-014537-computing-math-08ed12/solution/reference_solution.pyAdded+20
- 20260907-014537-computing-math-08ed12/solution/solve.shAdded+7
- 20260907-014537-computing-math-08ed12/task.tomlAdded+45
- 20260907-014537-computing-math-08ed12/tests/DockerfileAdded+6
- 20260907-014537-computing-math-08ed12/tests/evaluator_runner.pyAdded+92
- 20260907-014537-computing-math-08ed12/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
- 20260907-014537-computing-math-08ed12/tests/reference/evaluator.pyAdded+114
- 20260907-014537-computing-math-08ed12/tests/reference/ground_truth/code_block_inventory.csvAdded+12
- 20260907-014537-computing-math-08ed12/tests/reference/ground_truth/keyword_inventory.csvAdded+14
- 20260907-014537-computing-math-08ed12/tests/reference/ground_truth/section_outline.csvAdded+33
- 20260907-014537-computing-math-08ed12/tests/reference/ground_truth/summary.jsonAdded+11
- 20260907-014537-computing-math-08ed12/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-014537-computing-math-08ed12/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260907-014537-computing-math-08ed12/tests/reference/reference_manifest.jsonAdded+34
- 20260907-014537-computing-math-08ed12/tests/reference/reference_solution.pyAdded+20
- 20260907-014537-computing-math-08ed12/tests/test.shAdded+29
- 20260907-014555-computing-math-bb0058/.DS_StoreAdded+3
- 20260907-014555-computing-math-bb0058/environment/DockerfileAdded+12
- 20260907-014555-computing-math-bb0058/environment/public_data/README.mdAdded+11
- 20260907-014555-computing-math-bb0058/environment/public_data/input/README.mdAdded+6
- 20260907-014555-computing-math-bb0058/environment/public_data/input/analysis_spec.jsonAdded+96
- 20260907-014555-computing-math-bb0058/environment/public_data/input/dockerfile_packaging_corpus.mdAdded+447
- 20260907-014555-computing-math-bb0058/environment/public_data/input/dockerfile_text_windows.csvAdded+226
- 20260907-014555-computing-math-bb0058/environment/public_data/input/source_context_windows.jsonlAdded
- 20260907-014555-computing-math-bb0058/environment/public_data/input/tutorial_metadata.jsonAdded+35
- 20260907-014555-computing-math-bb0058/environment/public_data/main.pyAdded+180
- 20260907-014555-computing-math-bb0058/environment/public_data/software/command_examples.csvAdded+10
- 20260907-014555-computing-math-bb0058/environment/public_data/software/software_manifest.jsonAdded+16
- 20260907-014555-computing-math-bb0058/environment/public_data/software/validate_outputs.pyAdded+41
- 20260907-014555-computing-math-bb0058/environment/public_data/task_card.jsonAdded+111
- 20260907-014555-computing-math-bb0058/instruction.mdAdded+33
- 20260907-014555-computing-math-bb0058/solution/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-014555-computing-math-bb0058/solution/internal/workflow_runtime.pyAdded+5
- 20260907-014555-computing-math-bb0058/solution/reference_solution.pyAdded+20
- 20260907-014555-computing-math-bb0058/solution/solve.shAdded+7
- 20260907-014555-computing-math-bb0058/task.tomlAdded+45
123456This directory contains the public staged input for this task.input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.Primary data file: input/dockerfile_text_windows.csv.Workflow kind: software_tutorial_doc_audit.Required output files: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv.Solve the task from the staged local files only; do not fetch fresh remote data during solve time.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798{ "input_file": "dockerfile_text_windows.csv", "source_file": "dockerfile_packaging_corpus.md", "workflow_kind": "software_tutorial_doc_audit", "software_name": "Docker / Python Official Image", "tutorial_url": "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md", "source_urls": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "heading_rule": "Extract h1-h6 headings from HTML; if no HTML headings are present, use Markdown # headings.", "keyword_rule": "Count case-insensitive occurrences of required_terms and code_terms in the cleaned tutorial text.", "required_terms": [ "Dockerfile", "FROM", "RUN", "ENV", "COPY", "CMD", "GPG_KEY", "Tags", "GitRepo" ], "code_terms": [ "CMD", "apt-get", "curl", "gpg", "make", "FROM", "RUN", "ENV" ], "executables": [ "docker", "docker build" ], "required_system_packages": [ "docker.io" ], "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "section_outline.csv", "type": "csv" }, { "path": "keyword_inventory.csv", "type": "csv" }, { "path": "code_block_inventory.csv", "type": "csv" } ], "output_schemas": { "summary.json": { "software_name": "string", "source_file": "string", "window_count": "integer", "heading_count": "integer", "code_block_count": "integer", "keyword_total": "integer", "unique_required_terms_found": "integer", "top_keyword": "string|null", "source_character_count": "integer" }, "section_outline.csv": [ "rank", "heading_level", "heading_text", "slug" ], "keyword_inventory.csv": [ "term", "category", "count", "first_window", "appears_in_code" ], "code_block_inventory.csv": [ "block_index", "line_count", "char_count", "contains_code_term", "first_line" ] }, "notes": "Audit the staged offline official tutorial corpus. Do not fetch fresh documentation. All counts must be derived from the staged source file and tutorial_text_windows.csv."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447# Source 1: README.md
- URL: https://github.com/docker-library/official-images/raw/refs/heads/master/README.md- SHA256: 7b092c41c25d31902face488f7a5ed9928abb002548b1e3d64ee318afbbd2acf- Bytes: 34724
```markdown# Docker Official Images
## Table of Contents
<!-- AUTOGENERATED TOC -->
1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are "Official Images"?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64) 4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity) 5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment) 6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew)
<!-- AUTOGENERATED TOC -->
## What are "Official Images"?
The Docker Official Images are curated images [hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are:
- Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software
- Support [multiple architectures](#architectures-other-than-amd64)
- Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [Actively rebuild](#library-definition-files) for updates and security fixes
- Adhere to upstream recommendations
- Add minimal quality-of-life behavior for the container environment where fit
See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program.
In essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the best practices for Dockerfiles to serve as a reference when making or deriving your own images from them.
(If you are a representative of an upstream for which there exists an image and you would like to get involved, please see the [Maintainership](#maintainership) section below!)
## Architectures other than amd64?
Some images have been ported for other architectures, and many of these are officially supported (to various degrees).
- Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/)) - ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/ - Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/- Other architectures built by official images: (but *not* officially supported by Docker, Inc.) - ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/ - x86/i686 (`i386`): https://hub.docker.com/u/i386/
These other architectures are included under the non-prefixed images via [OCI "image indexes"](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for example, `docker run hello-world` should run as-is on all supported platforms.
If you're curious about how these are built, head over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process source files.
See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image.
## More FAQs?
Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and about our practices).
## Contributing to the standard library
Thank you for your interest in the Docker official images project! We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here.
Be sure to familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These will be the foundation of the review process performed by the official images maintainers. If you'd like the review process to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines), before submitting a pull request.
Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs), whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit a PR there as well, pending acceptance of your image here.
### Review Guidelines
Because the official images are intended to be learning tools for those new to Docker as well as the base images for advanced users to build their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability. While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while also adhering to the "Best Practices" where appropriate.
A checklist which may be used by the maintainers during review can be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md).
#### Maintainership
Version bumps and security fixes should be attended to in a timely manner.
If you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a smooth transition of image maintainership over to upstream.
For upstreams interested in taking over maintainership of an existing repository, the first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known within the "image community" (even if that "community" is just the current maintainer) are all important places to start to ensure that the transition is unsurprising to existing contributors and users.
When taking over an existing repository, please ensure that the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie, `git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the git repository. This can be accomplished without giving either group admin access to the other owner's repository:
- create temporary intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help- give old and new owners admin access to intermediary organization- old owner transfers repo ownership to intermediary organization- new owner transfers repo ownership to its new home - recommend that old owner does not fork new repo back into the old organization to ensure that GitHub redirects will just work
#### Repeatability
Rebuilding the same `Dockerfile` should result in the same version of the image being packaged, even if the second build happens several versions later, or the build should fail outright, such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using `apt` to install the main program for the image, be sure to pin it to a specific version (ex: `... apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them to a version.
No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)).
#### Consistency
All official images should provide a consistent interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`. It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1 --arg2` without having to specify the binary to execute.
1. If the startup process does not need arguments, just use `CMD`:
```Dockerfile CMD ["irb"] ```
2. If there is initialization that needs to be done on start, like creating the initial database, use an `ENTRYPOINT` along with `CMD`:
```Dockerfile ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["postgres"] ```
1. Ensure that `docker run official-image bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something else, just `exec "$@"` (run whatever was passed, properly keeping the arguments escaped).
```sh #!/bin/sh set -e
# this if will check if the first argument is a flag # but only works if all arguments require a hyphenated flag # -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then set -- mongod "$@" fi
# check for the expected command if [ "$1" = 'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu mongod "$@" fi
# else default to run whatever the user wanted like "bash" or "sh" exec "$@" ```
3. If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to use the executable as the `ENTRYPOINT`, since that is the only thing that can run:
```Dockerfile ENTRYPOINT ["fully-static-binary"] CMD ["--help"] ```
The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`).
#### Clarity
Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples, look at the current official images.
Some examples at the time of writing:
- [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile)- [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile)- [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile)
#### init
Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly this means just one process per container, so there is no need for a full init system. There are two situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see "NOTE" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If the process spawns child processes and does not properly reap them it will lead to a full process table, which can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and signal forwarding.
Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate.
It is best to install tini from a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here is a snippet of a `Dockerfile` to add in tini:
```Dockerfile# Install tini for signal processing and zombie killingENV TINI_VERSION v0.18.0ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7RUN set -eux; \ wget -O /usr/local/bin/tini "https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini"; \ wget -O /usr/local/bin/tini.asc "https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc"; \ export GNUPGHOME="$(mktemp -d)"; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$TINI_SIGN_KEY"; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf && gpgconf --kill all || :; \ rm -r "$GNUPGHOME" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version```
#### Cacheability
This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips might help:
- Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead of `COPY . /somewhere`).
The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of what needs to be `COPY`ed (for example).
- Ensure that lines which are less likely to change come before lines that are more likely to change (with the caveat that each line should generate an image that still runs successfully without assumptions of later lines).
For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`).
#### Security
##### Image Build
The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and no signature.
The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the download is from a trusted source which also happens to make interception much more difficult.
The purpose in recommending PGP signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification).
The purpose in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes, the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally downloading newer-than-expected artifacts on poorly versioned files.
Below are some examples:
- **Preferred**: *download over https, PGP key full fingerprint import and `asc` verification, embedded checksum verified.*
```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz" -o python.tar.xz; \ curl -fL "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc" -o python.tar.xz.asc; \ export GNUPGHOME="$(mktemp -d)"; \ # gpg: key F73C700D: public key "Larry Hastings <larry@hastings.org>" imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r "$GNUPGHOME" python.tar.xz.asc; \ echo "$PYTHON_DOWNLOAD_SHA512 *python.tar.xz" | sha512sum --strict --check; \ # install ```
- **Alternate**: *full key fingerprint imported to apt which will check signatures and checksums when packages are downloaded and installed.*
```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME="$(mktemp -d)"; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key"; \ gpg --batch --armor --export "$key" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \ rm -rf "$GNUPGHOME"; \ apt-key list > /dev/null
RUN set -eux; \ echo "deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client="${MYSQL_VERSION}" mysql-community-server-core="${MYSQL_VERSION}"; \ rm -rf /var/lib/apt/lists/*; \ # ... ```
(As a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).)
- **Less Secure Alternate**: *embed the checksum into the `Dockerfile`.*
```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz "https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz"; \ echo "$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz" | sha256sum --strict --check; \ # install ```
- **Note:** the use of either SHA1 or MD5 should be considered a "checksum of last resort" as both are considered generally unsafe:
- ["Single-block collision for MD5" from 2012](https://marc-stevens.nl/research/md5-1block-collision/) - ["Announcing the first SHA1 collision" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html)
- **Unacceptable**: *download the file over http(s) with no verification.*
```Dockerfile RUN curl -fL "https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz" | tar ... \ # install ```
##### Runtime Configuration
By default, Docker containers are executed with reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a container may require additional privileges in order to function correctly, and there are a number of command line options to customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference.
Official Repositories that require additional privileges should specify the minimal set of command line options for the software to function, and may still be rejected if this introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g. X11 socket).
##### Security Releases
For image updates which constitute a security fix, there are a few things we recommend to help ensure your update is merged, built, and released as quickly as possible:
1. [Send an email to `doi@docker.com`](mailto:doi@docker.com) a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule time for the incoming update appropriately).2. Include `[security]` in the title of your pull request (for example, `[security] Update FooBar to 1.2.5, 1.3.7, 2.0.1`).3. Keep the pull request free of changes that are unrelated to the security fix -- we'll still be doing review of the update, but it will be expedited so this will help us help you.4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more so if the timing of the release is of importance).
#### Multiple Architectures
Each repo can specify multiple architectures for any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go` file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27):
- `amd64`- `arm32v6`- `arm32v7`- `arm64v8`- `i386`- `ppc64le`- `riscv64`- `s390x`- `windows-amd64`
The `Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`.
Images must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s.
If different parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or `apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed. See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download the binary release.
For base images like `debian` it will be necessary to have a different `Dockerfile` and build context in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`, and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world):
```Maintainers: Tianon Gravi <admwiggin@gmail.com> (@tianon), Joseph Ferguson <yosifkit@gmail.com> (@yosifkit)GitRepo: https://github.com/docker-library/hello-world.gitGitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87
Tags: latestArchitectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x# all the same commit; easy for us to generate this way since they could be differentamd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87amd64-Directory: amd64/hello-worldarm32v5-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm32v5-Directory: arm32v5/hello-worldarm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm32v7-Directory: arm32v7/hello-worldarm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm64v8-Directory: arm64v8/hello-worldppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87ppc64le-Directory: ppc64le/hello-worlds390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87s390x-Directory: s390x/hello-world
Tags: nanoserverArchitectures: windows-amd64# if there is only one architecture, you can use the unprefixed fieldsDirectory: amd64/hello-world/nanoserver# or use the prefixed versionswindows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87Constraints: nanoserver```
See the [instruction format section](#instruction-format) for more information on the format of the library file.
### Commitment
Proposing a new official image should not be undertaken lightly. We expect and require a commitment to maintain your image (including and especially timely updates as appropriate, as noted above).
## Library definition files
The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file controls the current "supported" set of image tags that appear on the Docker Hub description. Tags that are removed from a library file do not get removed from the Docker Hub, so that old versions can continue to be available for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file are only built through an update to that library file or as a result of its base image being updated (ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will be rebuilt when a base has updates.
Given this policy, it is worth clarifying a few cases: backfilled versions, release candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive historical archive which is not the intention. Another common case where the term "supported" is stretched a bit is with release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle based on code commits or a regular schedule are not appropriate.
It is highly recommended that you browse some of the existing `library/` file contents (and history to get a feel for how they change over time) before creating a new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can focus on content instead of esoteric formatting or tag usage/naming).
### Filenames
The filename of a definition file will determine the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags in the `ubuntu` repository.
### Tags and aliases
The tags of a repository should reflect upstream's versions or variations. For example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so `ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag is a special case, but it's a bit of a misnomer; `latest` really is the "default" tag. When one does `docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be used as simply `xyz`). Put another way, having an alias for the "highest 2.2-series release of XYZ" should be `xyz:2.2`, not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or `xyz:latest-alpine`.
It is strongly encouraged that version number tags be given aliases which make it easy for the user to stay on the "most recent" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7 and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very different, and can be thought of as the `latest` tag for each of the major release tracks of Python).
As described above, `latest` is really "default", so the image that it is an alias for should reflect which version or variation of the software users should use if they do not know or do not care which version they use. Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority of users should be using if they know they want Ubuntu but do not know or care which version (especially considering it will be the most "stable" and well-supported release at any given time).
### Instruction format
The manifest file format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with the "headers" of many popular internet protocols/formats such as HTTP or email.
The primary additions are inspired by the way Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and "entries" are separated by a blank line.
The first entry is the "global" metadata for the image. The only required field in the global entry is `Maintainers`, whose value is comma-separated in the format of `Name <email> (@github)` or `Name (@github)`. Any field specified in the global entry will be the default for the rest of the entries and can be overridden in an individual entry.
# this is a comment and will be ignored Maintainers: John Smith <jsmith@example.com> (@example-jsmith), Anne Smith <asmith@example.com> (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc, rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use
Bashbrew will fetch code out of the Git repository (`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`, it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order to get the commit necessary.
The built image will be tagged as `<manifest-filename>:<tag>` (ie, `library/golang` with a `Tags` value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`).
Optionally, if `Directory` is present, Bashbrew will look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the ["context" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of `Dockerfile` will be used.
See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or `Directory` for a specific architecture.
### Creating a new repository
- Create a new file in the `library/` folder. Its name will be the name of your repository on the Hub.- Add your tag definitions using the appropriate syntax (see above).- Create a pull request adding the file from your forked repository to this one. Please be sure to add details as to what your repository does.
### Adding a new tag in an existing repository (that you're the maintainer of)
- Add your tag definition using the instruction format documented above.- Create a pull request from your Git repository to this one. Please be sure to add details about what's new, if possible.
### Change to a tag in an existing repository (that you're the maintainer of)
- Update the relevant tag definition using the instruction format documented above.- Create a pull request from your Git repository to this one. Please be sure to add details about what's changed, if possible.
## Bashbrew
Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the Docker official images. See [the Bashbrew `README`](https://github.com/docker-library/bashbrew#readme) for more information.```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226window_id,start_word,end_word,text,contains_code_term,matched_required_terms
1,0,40,"# Source 1: README.md - URL: https://github.com/docker-library/official-images/raw/refs/heads/master/README.md - SHA256: 7b092c41c25d31902face488f7a5ed9928abb002548b1e3d64ee318afbbd2acf - Bytes: 34724 ```markdown # Docker Official Images ## Table of Contents 1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are ""Official Images""?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64)",false,
2,20,60,"of Contents 1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are ""Official Images""?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64) 4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity)",false,
3,40,80,4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity) 5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment),true,RUN
4,60,100,5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment) 6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding,true,RUN|Tags
5,80,120,6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing,false,Tags
6,100,140,"a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew) ## What are ""Official Images""? The Docker Official Images are curated images",false,
7,120,160,"repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew) ## What are ""Official Images""? The Docker Official Images are curated images [hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are: - Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software - Support [multiple architectures](#architectures-other-than-amd64) -",false,
8,140,180,[hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are: - Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software - Support [multiple architectures](#architectures-other-than-amd64) - Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Actively rebuild](#library-definition-files) for updates and security fixes - Adhere to upstream recommendations - Add minimal,false,Dockerfile
9,160,200,Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Actively rebuild](#library-definition-files) for updates and security fixes - Adhere to upstream recommendations - Add minimal quality-of-life behavior for the container environment where fit See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program. In,true,Dockerfile|ENV
10,180,220,quality-of-life behavior for the container environment where fit See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program. In essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are,true,ENV
11,200,240,essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the,false,
12,220,260,maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the best practices for Dockerfiles to serve as a reference when making or deriving your own images from them. (If you,true,Dockerfile|FROM
13,240,280,"best practices for Dockerfiles to serve as a reference when making or deriving your own images from them. (If you are a representative of an upstream for which there exists an image and you would like to get involved, please",true,Dockerfile|FROM
14,260,300,"are a representative of an upstream for which there exists an image and you would like to get involved, please see the [Maintainership](#maintainership) section below!) ## Architectures other than amd64? Some images have been ported for other architectures, and many",false,
15,280,320,"see the [Maintainership](#maintainership) section below!) ## Architectures other than amd64? Some images have been ported for other architectures, and many of these are officially supported (to various degrees). - Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/))",true,RUN
16,300,340,"of these are officially supported (to various degrees). - Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/)) - ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/",true,RUN
17,320,360,"- ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/ - Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/ - Other architectures built by official images: (but *not* officially supported by Docker, Inc.) -",false,
18,340,380,"- Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/ - Other architectures built by official images: (but *not* officially supported by Docker, Inc.) - ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/",false,
19,360,400,"ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/ - x86/i686 (`i386`): https://hub.docker.com/u/i386/ These other architectures are included under the non-prefixed images via [OCI ""image indexes""](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for",false,
20,380,420,"- x86/i686 (`i386`): https://hub.docker.com/u/i386/ These other architectures are included under the non-prefixed images via [OCI ""image indexes""](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for example, `docker run hello-world` should run as-is on all supported platforms. If you're curious about how these are built, head",true,RUN
21,400,440,"example, `docker run hello-world` should run as-is on all supported platforms. If you're curious about how these are built, head over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process",true,RUN
22,420,460,over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process source files. See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image. ## More FAQs?,false,
23,440,480,source files. See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image. ## More FAQs? Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and,false,
24,460,500,Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and about our practices). ## Contributing to the standard library Thank you for your interest in the Docker official images project!,false,
25,480,520,"about our practices). ## Contributing to the standard library Thank you for your interest in the Docker official images project! We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate",true,
26,500,540,"We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here. Be sure to",true,
27,520,560,to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here. Be sure to familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These,false,Dockerfile
28,540,580,familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These will be the foundation of the review process performed by the official images maintainers. If you'd like the review process,false,Dockerfile
29,560,600,"will be the foundation of the review process performed by the official images maintainers. If you'd like the review process to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines),",false,Dockerfile
30,580,620,"to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines), before submitting a pull request. Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs),",false,Dockerfile
31,600,640,"before submitting a pull request. Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs), whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit",false,
32,620,660,"whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit a PR there as well, pending acceptance of your image here. ### Review Guidelines Because the official images are intended",false,
33,640,680,"a PR there as well, pending acceptance of your image here. ### Review Guidelines Because the official images are intended to be learning tools for those new to Docker as well as the base images for advanced users to build",false,
34,660,700,"to be learning tools for those new to Docker as well as the base images for advanced users to build their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability.",false,Dockerfile
35,680,720,"their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability. While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while",false,Dockerfile
36,700,740,"While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while also adhering to the ""Best Practices"" where appropriate. A checklist which may be used by the maintainers during review can",false,
37,720,760,"also adhering to the ""Best Practices"" where appropriate. A checklist which may be used by the maintainers during review can be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md). #### Maintainership Version bumps and security fixes should be attended to in a timely manner. If",false,
38,740,780,"be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md). #### Maintainership Version bumps and security fixes should be attended to in a timely manner. If you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a",false,
39,760,800,"you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a smooth transition of image maintainership over to upstream. For upstreams interested in taking over maintainership of an existing repository, the",false,
40,780,820,"smooth transition of image maintainership over to upstream. For upstreams interested in taking over maintainership of an existing repository, the first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known",false,
41,800,840,"first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known within the ""image community"" (even if that ""community"" is just the current maintainer) are all important places to start to",false,
42,820,860,"within the ""image community"" (even if that ""community"" is just the current maintainer) are all important places to start to ensure that the transition is unsurprising to existing contributors and users. When taking over an existing repository, please ensure that",false,
43,840,880,"ensure that the transition is unsurprising to existing contributors and users. When taking over an existing repository, please ensure that the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review",true,
44,860,900,"the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but",true,FROM
45,880,920,"process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie,",true,FROM
46,900,940,"can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie, `git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the",true,FROM
47,920,960,"`git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the git repository. This can be accomplished without giving either group admin access to the other owner's repository: - create temporary",false,
48,940,980,git repository. This can be accomplished without giving either group admin access to the other owner's repository: - create temporary intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help - give old and new,false,
49,960,1000,intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help - give old and new owners admin access to intermediary organization - old owner transfers repo ownership to intermediary organization - new owner transfers repo,false,
50,980,1020,owners admin access to intermediary organization - old owner transfers repo ownership to intermediary organization - new owner transfers repo ownership to its new home - recommend that old owner does not fork new repo back into the old organization,false,
51,1000,1040,ownership to its new home - recommend that old owner does not fork new repo back into the old organization to ensure that GitHub redirects will just work #### Repeatability Rebuilding the same `Dockerfile` should result in the same version,false,Dockerfile
52,1020,1060,"to ensure that GitHub redirects will just work #### Repeatability Rebuilding the same `Dockerfile` should result in the same version of the image being packaged, even if the second build happens several versions later, or the build should fail outright,",false,Dockerfile
53,1040,1080,"of the image being packaged, even if the second build happens several versions later, or the build should fail outright, such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using",false,Dockerfile
54,1060,1100,"such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using `apt` to install the main program for the image, be sure to pin it to a specific version (ex: `...",false,Dockerfile
55,1080,1120,"`apt` to install the main program for the image, be sure to pin it to a specific version (ex: `... apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them",true,
56,1100,1140,"apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them to a version. No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and",true,FROM
57,1120,1160,"to a version. No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)). #### Consistency All official images should provide a consistent",true,FROM
58,1140,1180,the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)). #### Consistency All official images should provide a consistent interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`.,true,RUN
59,1160,1200,"interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`. It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1",true,RUN
60,1180,1220,"It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1 --arg2` without having to specify the binary to execute. 1. If the startup process does not need arguments, just use",true,RUN
61,1200,1240,"--arg2` without having to specify the binary to execute. 1. If the startup process does not need arguments, just use `CMD`: ```Dockerfile CMD [""irb""] ``` 2. If there is initialization that needs to be done on start, like creating the",true,Dockerfile|CMD
62,1220,1260,"`CMD`: ```Dockerfile CMD [""irb""] ``` 2. If there is initialization that needs to be done on start, like creating the initial database, use an `ENTRYPOINT` along with `CMD`: ```Dockerfile ENTRYPOINT [""/docker-entrypoint.sh""] CMD [""postgres""] ``` 1. Ensure that `docker run official-image",true,Dockerfile|RUN|CMD
63,1240,1280,"initial database, use an `ENTRYPOINT` along with `CMD`: ```Dockerfile ENTRYPOINT [""/docker-entrypoint.sh""] CMD [""postgres""] ``` 1. Ensure that `docker run official-image bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something",true,Dockerfile|RUN|CMD
64,1260,1300,"bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something else, just `exec ""$@""` (run whatever was passed, properly keeping the arguments escaped). ```sh #!/bin/sh set -e # this if",true,RUN
65,1280,1320,"else, just `exec ""$@""` (run whatever was passed, properly keeping the arguments escaped). ```sh #!/bin/sh set -e # this if will check if the first argument is a flag # but only works if all arguments require a hyphenated flag",true,RUN
66,1300,1340,"will check if the first argument is a flag # but only works if all arguments require a hyphenated flag # -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ ""$#"" -eq 0 ] || [",false,
67,1320,1360,"# -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ ""$#"" -eq 0 ] || [ ""${1#-}"" != ""$1"" ]; then set -- mongod ""$@"" fi # check for the expected command if [ ""$1"" =",false,
68,1340,1380,"""${1#-}"" != ""$1"" ]; then set -- mongod ""$@"" fi # check for the expected command if [ ""$1"" = 'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu",false,
69,1360,1400,"'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu mongod ""$@"" fi # else default to run whatever the user wanted like ""bash"" or ""sh"" exec ""$@"" ``` 3.",true,RUN
70,1380,1420,"mongod ""$@"" fi # else default to run whatever the user wanted like ""bash"" or ""sh"" exec ""$@"" ``` 3. If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to",true,RUN
71,1400,1440,"If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to use the executable as the `ENTRYPOINT`, since that is the only thing that can run: ```Dockerfile ENTRYPOINT [""fully-static-binary""] CMD [""--help""]",true,Dockerfile|RUN|CMD
72,1420,1460,"use the executable as the `ENTRYPOINT`, since that is the only thing that can run: ```Dockerfile ENTRYPOINT [""fully-static-binary""] CMD [""--help""] ``` The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`).",true,Dockerfile|FROM|RUN|CMD
73,1440,1480,"``` The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`). #### Clarity Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to",true,Dockerfile|FROM
74,1460,1500,"#### Clarity Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes",true,Dockerfile|RUN
75,1480,1520,"put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to",true,Dockerfile|RUN
76,1500,1540,"the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples,",true,Dockerfile|RUN|ENV
77,1520,1560,"put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples, look at the current official images. Some examples at the time of writing: - [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile) - [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile) - [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile) ####",true,Dockerfile|RUN|ENV
78,1540,1580,look at the current official images. Some examples at the time of writing: - [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile) - [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile) - [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile) #### init Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly,false,Dockerfile
79,1560,1600,"init Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly this means just one process per container, so there is no need for a full init system. There are two",false,
80,1580,1620,"this means just one process per container, so there is no need for a full init system. There are two situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched",false,
81,1600,1640,"situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see",false,
82,1620,1660,"does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see ""NOTE"" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If",true,RUN
83,1640,1680,"""NOTE"" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If the process spawns child processes and does not properly reap them it will lead to a full process table, which",true,RUN
84,1660,1700,"the process spawns child processes and does not properly reap them it will lead to a full process table, which can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is",true,FROM
85,1680,1720,"can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and",true,FROM
86,1700,1740,"incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and signal forwarding. Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate. It is best to install tini from",true,FROM|CMD
87,1720,1760,"signal forwarding. Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate. It is best to install tini from a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here",true,FROM|CMD
88,1740,1780,"a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here is a snippet of a `Dockerfile` to add in tini: ```Dockerfile # Install tini for signal processing and zombie killing",true,Dockerfile
89,1760,1800,"is a snippet of a `Dockerfile` to add in tini: ```Dockerfile # Install tini for signal processing and zombie killing ENV TINI_VERSION v0.18.0 ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7 RUN set -eux; \ wget -O /usr/local/bin/tini ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini""; \ wget -O /usr/local/bin/tini.asc ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc""; \",true,Dockerfile|RUN|ENV
90,1780,1820,"ENV TINI_VERSION v0.18.0 ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7 RUN set -eux; \ wget -O /usr/local/bin/tini ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini""; \ wget -O /usr/local/bin/tini.asc ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc""; \ export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$TINI_SIGN_KEY""; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf",true,RUN|ENV
91,1800,1840,"export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$TINI_SIGN_KEY""; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf && gpgconf --kill all || :; \ rm -r ""$GNUPGHOME"" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version ``` ####",true,
92,1820,1860,"&& gpgconf --kill all || :; \ rm -r ""$GNUPGHOME"" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version ``` #### Cacheability This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips",true,
93,1840,1880,"Cacheability This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips might help: - Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead",false,COPY
94,1860,1900,"might help: - Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead of `COPY . /somewhere`). The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to",false,COPY
95,1880,1920,"of `COPY . /somewhere`). The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of",true,COPY
96,1900,1940,"be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of what needs to be `COPY`ed (for example). - Ensure that lines which are less likely to change come before lines",true,COPY
97,1920,1960,what needs to be `COPY`ed (for example). - Ensure that lines which are less likely to change come before lines that are more likely to change (with the caveat that each line should generate an image that still runs successfully,true,RUN|COPY
98,1940,1980,"that are more likely to change (with the caveat that each line should generate an image that still runs successfully without assumptions of later lines). For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come",true,RUN|ENV
99,1960,2000,"without assumptions of later lines). For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`). ####",true,RUN|ENV
100,1980,2020,after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`). #### Security ##### Image Build The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on,true,Dockerfile|RUN
101,2000,2040,"Security ##### Image Build The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using",false,Dockerfile
102,2020,2060,"three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in",false,Dockerfile
103,2040,2080,https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature,false,Dockerfile
104,2060,2100,"the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and",false,Dockerfile
105,2080,2120,"is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and no signature. The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the",false,
106,2100,2140,no signature. The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the download is from a trusted source which also happens to make interception much more difficult. The purpose in recommending PGP,true,FROM
107,2120,2160,"download is from a trusted source which also happens to make interception much more difficult. The purpose in recommending PGP signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use",true,FROM
108,2140,2180,"signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification). The purpose",false,
109,2160,2200,"the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification). The purpose in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes,",false,
110,2180,2220,"in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes, the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally",false,Dockerfile
111,2200,2240,"the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally downloading newer-than-expected artifacts on poorly versioned files. Below are some examples: - **Preferred**: *download over https, PGP key full fingerprint",false,Dockerfile
112,2220,2260,"downloading newer-than-expected artifacts on poorly versioned files. Below are some examples: - **Preferred**: *download over https, PGP key full fingerprint import and `asc` verification, embedded checksum verified.* ```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz"" -o python.tar.xz;",true,Dockerfile|RUN|ENV
113,2240,2280,"import and `asc` verification, embedded checksum verified.* ```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz"" -o python.tar.xz; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc"" -o python.tar.xz.asc; \ export GNUPGHOME=""$(mktemp -d)""; \ # gpg: key F73C700D: public key ""Larry Hastings """,true,Dockerfile|RUN|ENV
114,2260,2300,"\ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc"" -o python.tar.xz.asc; \ export GNUPGHOME=""$(mktemp -d)""; \ # gpg: key F73C700D: public key ""Larry Hastings "" imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r ""$GNUPGHOME"" python.tar.xz.asc; \ echo",true,
115,2280,2320,"imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r ""$GNUPGHOME"" python.tar.xz.asc; \ echo ""$PYTHON_DOWNLOAD_SHA512 *python.tar.xz"" | sha512sum --strict --check; \ # install ``` - **Alternate**: *full key fingerprint imported to apt which will",true,
116,2300,2340,"""$PYTHON_DOWNLOAD_SHA512 *python.tar.xz"" | sha512sum --strict --check; \ # install ``` - **Alternate**: *full key fingerprint imported to apt which will check signatures and checksums when packages are downloaded and installed.* ```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME=""$(mktemp -d)"";",true,Dockerfile|RUN
117,2320,2360,"check signatures and checksums when packages are downloaded and installed.* ```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$key""; \ gpg --batch --armor --export ""$key"" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \",true,Dockerfile|RUN
118,2340,2380,"\ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$key""; \ gpg --batch --armor --export ""$key"" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \ rm -rf ""$GNUPGHOME""; \ apt-key list > /dev/null RUN set -eux; \ echo ""deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}""",true,RUN
119,2360,2400,"rm -rf ""$GNUPGHOME""; \ apt-key list > /dev/null RUN set -eux; \ echo ""deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}"" > /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client=""${MYSQL_VERSION}"" mysql-community-server-core=""${MYSQL_VERSION}""; \ rm -rf /var/lib/apt/lists/*; \ # ... ``` (As",true,RUN
120,2380,2420,"> /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client=""${MYSQL_VERSION}"" mysql-community-server-core=""${MYSQL_VERSION}""; \ rm -rf /var/lib/apt/lists/*; \ # ... ``` (As a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't",true,
121,2400,2440,"a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).) - **Less Secure Alternate**: *embed",true,Dockerfile
122,2420,2460,"include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).) - **Less Secure Alternate**: *embed the checksum into the `Dockerfile`.* ```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz ""https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz""; \ echo",true,Dockerfile|RUN|ENV
123,2440,2480,"the checksum into the `Dockerfile`.* ```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz ""https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz""; \ echo ""$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz"" | sha256sum --strict --check; \ # install ``` - **Note:** the use of either SHA1 or MD5 should",true,Dockerfile|RUN|ENV
124,2460,2500,"""$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz"" | sha256sum --strict --check; \ # install ``` - **Note:** the use of either SHA1 or MD5 should be considered a ""checksum of last resort"" as both are considered generally unsafe: - [""Single-block collision for MD5"" from 2012](https://marc-stevens.nl/research/md5-1block-collision/)",true,FROM
125,2480,2520,"be considered a ""checksum of last resort"" as both are considered generally unsafe: - [""Single-block collision for MD5"" from 2012](https://marc-stevens.nl/research/md5-1block-collision/) - [""Announcing the first SHA1 collision"" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html) - **Unacceptable**: *download the file over http(s) with no verification.* ```Dockerfile RUN",true,Dockerfile|FROM|RUN
126,2500,2540,"- [""Announcing the first SHA1 collision"" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html) - **Unacceptable**: *download the file over http(s) with no verification.* ```Dockerfile RUN curl -fL ""https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz"" | tar ... \ # install ``` ##### Runtime Configuration By default, Docker containers are executed with",true,Dockerfile|FROM|RUN
127,2520,2560,"curl -fL ""https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz"" | tar ... \ # install ``` ##### Runtime Configuration By default, Docker containers are executed with reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a",true,RUN
128,2540,2580,"reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a container may require additional privileges in order to function correctly, and there are a number of command line options to",true,RUN
129,2560,2600,"container may require additional privileges in order to function correctly, and there are a number of command line options to customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference. Official Repositories that require additional privileges should",true,RUN
130,2580,2620,"customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference. Official Repositories that require additional privileges should specify the minimal set of command line options for the software to function, and may still be rejected if this",true,RUN
131,2600,2640,"specify the minimal set of command line options for the software to function, and may still be rejected if this introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options",false,
132,2620,2660,"introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g.",false,
133,2640,2680,"may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g. X11 socket). ##### Security Releases For image updates which constitute a security fix, there are a few things we recommend",false,
134,2660,2700,"X11 socket). ##### Security Releases For image updates which constitute a security fix, there are a few things we recommend to help ensure your update is merged, built, and released as quickly as possible: 1. [Send an email to `doi@docker.com`](mailto:doi@docker.com)",false,
135,2680,2720,"to help ensure your update is merged, built, and released as quickly as possible: 1. [Send an email to `doi@docker.com`](mailto:doi@docker.com) a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule",false,
136,2700,2740,"a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule time for the incoming update appropriately). 2. Include `[security]` in the title of your pull request (for example, `[security] Update",false,
137,2720,2760,"time for the incoming update appropriately). 2. Include `[security]` in the title of your pull request (for example, `[security] Update FooBar to 1.2.5, 1.3.7, 2.0.1`). 3. Keep the pull request free of changes that are unrelated to the security fix",false,
138,2740,2780,"FooBar to 1.2.5, 1.3.7, 2.0.1`). 3. Keep the pull request free of changes that are unrelated to the security fix -- we'll still be doing review of the update, but it will be expedited so this will help us help",false,
139,2760,2800,"-- we'll still be doing review of the update, but it will be expedited so this will help us help you. 4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more",false,
140,2780,2820,"you. 4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more so if the timing of the release is of importance). #### Multiple Architectures Each repo can specify multiple architectures for",false,
141,2800,2840,"so if the timing of the release is of importance). #### Multiple Architectures Each repo can specify multiple architectures for any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify",false,Tags
142,2820,2860,"any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go`",false,Tags
143,2840,2880,"more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go` file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27): - `amd64` - `arm32v6` - `arm32v7` - `arm64v8` - `i386` - `ppc64le` - `riscv64` - `s390x` - `windows-amd64` The",false,
144,2860,2900,file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27): - `amd64` - `arm32v6` - `arm32v7` - `arm64v8` - `i386` - `ppc64le` - `riscv64` - `s390x` - `windows-amd64` The `Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`. Images,true,FROM
145,2880,2920,`Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`. Images must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means,true,Dockerfile|FROM
146,2900,2940,"must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for",true,Dockerfile|FROM
147,2920,2960,"that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s. If different",true,Dockerfile|FROM
148,2940,2980,"examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s. If different parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or",false,Dockerfile
149,2960,3000,"parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or `apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed.",false,Dockerfile
150,2980,3020,`apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed. See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download,true,Dockerfile|FROM
151,3000,3040,See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download the binary release. For base images like `debian` it will be necessary to have a different `Dockerfile` and build context,true,Dockerfile|FROM
152,3020,3060,the binary release. For base images like `debian` it will be necessary to have a different `Dockerfile` and build context in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use,false,Dockerfile
153,3040,3080,"in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`,",false,Tags|GitRepo
154,3060,3100,"the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`, and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not",false,Tags|GitRepo
155,3080,3120,"and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See",false,
156,3100,3140,have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world): ``` Maintainers: Tianon,false,
157,3120,3160,"the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world): ``` Maintainers: Tianon Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/hello-world.git GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Tags: latest Architectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x # all",false,Tags|GitRepo
158,3140,3180,"Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/hello-world.git GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Tags: latest Architectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x # all the same commit; easy for us to generate this way since they could be different amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 amd64-Directory: amd64/hello-world arm32v5-GitCommit:",false,Tags|GitRepo
159,3160,3200,the same commit; easy for us to generate this way since they could be different amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 amd64-Directory: amd64/hello-world arm32v5-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v5-Directory: arm32v5/hello-world arm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v7-Directory: arm32v7/hello-world arm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm64v8-Directory: arm64v8/hello-world ppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 ppc64le-Directory: ppc64le/hello-world s390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 s390x-Directory: s390x/hello-world Tags:,false,Tags
160,3180,3220,"7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v5-Directory: arm32v5/hello-world arm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v7-Directory: arm32v7/hello-world arm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm64v8-Directory: arm64v8/hello-world ppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 ppc64le-Directory: ppc64le/hello-world s390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 s390x-Directory: s390x/hello-world Tags: nanoserver Architectures: windows-amd64 # if there is only one architecture, you can use the unprefixed fields Directory: amd64/hello-world/nanoserver # or",false,Tags
161,3200,3240,"nanoserver Architectures: windows-amd64 # if there is only one architecture, you can use the unprefixed fields Directory: amd64/hello-world/nanoserver # or use the prefixed versions windows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Constraints: nanoserver ``` See the [instruction format section](#instruction-format) for more information on the format",false,
162,3220,3260,use the prefixed versions windows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Constraints: nanoserver ``` See the [instruction format section](#instruction-format) for more information on the format of the library file. ### Commitment Proposing a new official image should not be undertaken lightly. We expect and require,false,
163,3240,3280,"of the library file. ### Commitment Proposing a new official image should not be undertaken lightly. We expect and require a commitment to maintain your image (including and especially timely updates as appropriate, as noted above). ## Library definition files",false,
164,3260,3300,"a commitment to maintain your image (including and especially timely updates as appropriate, as noted above). ## Library definition files The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file",false,
165,3280,3320,"The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file controls the current ""supported"" set of image tags that appear on the Docker Hub description. Tags that are removed from",true,FROM|Tags
166,3300,3340,"controls the current ""supported"" set of image tags that appear on the Docker Hub description. Tags that are removed from a library file do not get removed from the Docker Hub, so that old versions can continue to be available",true,FROM|Tags
167,3320,3360,"a library file do not get removed from the Docker Hub, so that old versions can continue to be available for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file",true,FROM|Tags
168,3340,3380,"for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file are only built through an update to that library file or as a result of its base image being updated",false,Tags
169,3360,3400,"are only built through an update to that library file or as a result of its base image being updated (ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will",true,FROM
170,3380,3420,"(ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will be rebuilt when a base has updates. Given this policy, it is worth clarifying a few cases: backfilled versions, release",true,FROM
171,3400,3440,"be rebuilt when a base has updates. Given this policy, it is worth clarifying a few cases: backfilled versions, release candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions",false,
172,3420,3460,"candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive",false,
173,3440,3480,"in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive historical archive which is not the intention. Another common case where the term ""supported"" is stretched a bit is with",false,
174,3460,3500,"historical archive which is not the intention. Another common case where the term ""supported"" is stretched a bit is with release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so",false,
175,3480,3520,"release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle",false,
176,3500,3540,"they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle based on code commits or a regular schedule are not appropriate. It is highly recommended that you browse some of",false,
177,3520,3560,based on code commits or a regular schedule are not appropriate. It is highly recommended that you browse some of the existing `library/` file contents (and history to get a feel for how they change over time) before creating a,false,
178,3540,3580,the existing `library/` file contents (and history to get a feel for how they change over time) before creating a new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can,false,
179,3560,3600,new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can focus on content instead of esoteric formatting or tag usage/naming). ### Filenames The filename of a definition file will determine,false,
180,3580,3620,"focus on content instead of esoteric formatting or tag usage/naming). ### Filenames The filename of a definition file will determine the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags",false,Tags
181,3600,3640,"the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags in the `ubuntu` repository. ### Tags and aliases The tags of a repository should reflect upstream's versions or variations. For",false,Tags
182,3620,3660,"in the `ubuntu` repository. ### Tags and aliases The tags of a repository should reflect upstream's versions or variations. For example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so",false,Tags
183,3640,3680,"example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so `ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag",false,
184,3660,3700,"`ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag is a special case, but it's a bit of a misnomer; `latest` really is the ""default"" tag. When one does",false,
185,3680,3720,"is a special case, but it's a bit of a misnomer; `latest` really is the ""default"" tag. When one does `docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the",true,RUN
186,3700,3740,"`docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be",true,RUN
187,3720,3760,"string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be used as simply `xyz`). Put another way, having an alias for the ""highest 2.2-series release of XYZ"" should be `xyz:2.2`,",false,
188,3740,3780,"used as simply `xyz`). Put another way, having an alias for the ""highest 2.2-series release of XYZ"" should be `xyz:2.2`, not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or",false,
189,3760,3800,"not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or `xyz:latest-alpine`. It is strongly encouraged that version number tags be given aliases which make it easy for the user to",true,Tags
190,3780,3820,"`xyz:latest-alpine`. It is strongly encouraged that version number tags be given aliases which make it easy for the user to stay on the ""most recent"" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7",true,Tags
191,3800,3840,"stay on the ""most recent"" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7 and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the",false,Tags
192,3820,3860,"and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less",false,Tags
193,3840,3880,"user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very",false,
194,3860,3900,"granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very different, and can be thought of as the `latest` tag for each of the major release tracks of Python). As",false,
195,3880,3920,"different, and can be thought of as the `latest` tag for each of the major release tracks of Python). As described above, `latest` is really ""default"", so the image that it is an alias for should reflect which version or",false,
196,3900,3940,"described above, `latest` is really ""default"", so the image that it is an alias for should reflect which version or variation of the software users should use if they do not know or do not care which version they use.",false,
197,3920,3960,"variation of the software users should use if they do not know or do not care which version they use. Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority",false,
198,3940,3980,"Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority of users should be using if they know they want Ubuntu but do not know or care which version (especially",false,
199,3960,4000,"of users should be using if they know they want Ubuntu but do not know or care which version (especially considering it will be the most ""stable"" and well-supported release at any given time). ### Instruction format The manifest file",false,
200,3980,4020,"considering it will be the most ""stable"" and well-supported release at any given time). ### Instruction format The manifest file format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with",false,
201,4000,4040,"format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with the ""headers"" of many popular internet protocols/formats such as HTTP or email. The primary additions are inspired by the way",false,
202,4020,4060,"the ""headers"" of many popular internet protocols/formats such as HTTP or email. The primary additions are inspired by the way Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and ""entries"" are separated by a blank line.",false,
203,4040,4080,"Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and ""entries"" are separated by a blank line. The first entry is the ""global"" metadata for the image. The only required field in the global entry is `Maintainers`,",false,
204,4060,4100,"The first entry is the ""global"" metadata for the image. The only required field in the global entry is `Maintainers`, whose value is comma-separated in the format of `Name (@github)` or `Name (@github)`. Any field specified in the global entry",false,
205,4080,4120,whose value is comma-separated in the format of `Name (@github)` or `Name (@github)`. Any field specified in the global entry will be the default for the rest of the entries and can be overridden in an individual entry. # this,false,
206,4100,4140,"will be the default for the rest of the entries and can be overridden in an individual entry. # this is a comment and will be ignored Maintainers: John Smith (@example-jsmith), Anne Smith (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this",false,GitRepo
207,4120,4160,"is a comment and will be ignored Maintainers: John Smith (@example-jsmith), Anne Smith (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc,",false,Tags|GitRepo
208,4140,4180,"is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc, rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use Bashbrew will fetch code out of the Git repository",false,Dockerfile|Tags|GitRepo
209,4160,4200,"rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use Bashbrew will fetch code out of the Git repository (`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`,",false,Dockerfile|GitRepo
210,4180,4220,"(`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`, it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order",false,GitRepo
211,4200,4240,"it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order to get the commit necessary. The built image will be tagged as ` : ` (ie, `library/golang` with a `Tags`",false,Tags
212,4220,4260,"to get the commit necessary. The built image will be tagged as ` : ` (ie, `library/golang` with a `Tags` value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`). Optionally, if `Directory` is present, Bashbrew will",false,Tags
213,4240,4280,"value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`). Optionally, if `Directory` is present, Bashbrew will look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the",false,Dockerfile|Tags
214,4260,4300,"look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the [""context"" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of",false,Dockerfile
215,4280,4320,"[""context"" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of `Dockerfile` will be used. See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or",false,Dockerfile|GitRepo
216,4300,4340,"`Dockerfile` will be used. See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or `Directory` for a specific architecture. ### Creating a new repository - Create a new file in the `library/` folder. Its",false,Dockerfile|GitRepo
217,4320,4360,`Directory` for a specific architecture. ### Creating a new repository - Create a new file in the `library/` folder. Its name will be the name of your repository on the Hub. - Add your tag definitions using the appropriate syntax,false,
218,4340,4380,name will be the name of your repository on the Hub. - Add your tag definitions using the appropriate syntax (see above). - Create a pull request adding the file from your forked repository to this one. Please be sure,true,FROM
219,4360,4400,(see above). - Create a pull request adding the file from your forked repository to this one. Please be sure to add details as to what your repository does. ### Adding a new tag in an existing repository (that you're,true,FROM
220,4380,4420,to add details as to what your repository does. ### Adding a new tag in an existing repository (that you're the maintainer of) - Add your tag definition using the instruction format documented above. - Create a pull request from,true,FROM
221,4400,4440,"the maintainer of) - Add your tag definition using the instruction format documented above. - Create a pull request from your Git repository to this one. Please be sure to add details about what's new, if possible. ### Change to",true,FROM
222,4420,4460,"your Git repository to this one. Please be sure to add details about what's new, if possible. ### Change to a tag in an existing repository (that you're the maintainer of) - Update the relevant tag definition using the instruction",false,
223,4440,4480,a tag in an existing repository (that you're the maintainer of) - Update the relevant tag definition using the instruction format documented above. - Create a pull request from your Git repository to this one. Please be sure to add,true,FROM
224,4460,4500,"format documented above. - Create a pull request from your Git repository to this one. Please be sure to add details about what's changed, if possible. ## Bashbrew Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the",true,FROM
225,4480,4511,"details about what's changed, if possible. ## Bashbrew Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the Docker official images. See [the Bashbrew `README`](https://github.com/docker-library/bashbrew#readme) for more information. ```",false,12345678910111213141516171819202122232425262728293031323334353637{ "software_name": "Docker / Python Official Image", "tutorial_url": "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md", "source_urls": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "source_file": "dockerfile_packaging_corpus.md", "window_file": "dockerfile_text_windows.csv", "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "required_terms": [ "Dockerfile", "FROM", "RUN", "ENV", "COPY", "CMD", "GPG_KEY", "Tags", "GitRepo" ], "code_terms": [ "CMD", "apt-get", "curl", "gpg", "make", "FROM", "RUN", "ENV" ], "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180from __future__ import annotations
import importlib.utilimport jsonimport osimport shleximport shutilfrom pathlib import Pathfrom typing import Any
class Task: def __init__(self, task_id: str, description: str, metadata: dict[str, Any]): self.task_id = task_id self.description = description self.prompt = description self.metadata = metadata self.computer = {"setup_config": {"os_type": "linux"}}
def _task_dir() -> Path: return Path(__file__).resolve().parent
def _load_card() -> dict[str, Any]: path = _task_dir() / "task_card.json" if not path.is_file(): return { "taskId": os.environ.get("ALE_TASK_ID", "computing_math/audit_docker_official_image_packaging_corpus"), "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.", "metadata": { "domain": "computing_math", "task": "audit_docker_official_image_packaging_corpus", "variant": "base", "domain_name": "computing_math", "task_name": "audit_docker_official_image_packaging_corpus", "variant_name": "base", "requires_task_data": True, "task_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging_corpus/base", "input_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging_corpus/base/input", "software_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging_corpus/base/software", "remote_output_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging_corpus/base/output", "reference_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging_corpus/base/reference", }, } with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def load() -> list[Task]: card = _load_card() metadata = dict(card.get("metadata") or {}) if not metadata: domain, _, task = str(card["taskId"]).partition("/") variant = "base" task_dir = f"/media/user/data/agenthle/{domain}/{task}/{variant}" metadata.update({ "domain": domain, "task": task, "variant": variant, "domain_name": domain, "task_name": task, "variant_name": variant, "requires_task_data": True, "task_dir": task_dir, "input_dir": f"{task_dir}/input", "software_dir": f"{task_dir}/software", "remote_output_dir": f"{task_dir}/output", "reference_dir": f"{task_dir}/reference", }) return [Task(task_id=card["taskId"], description=card["taskPrompt"], metadata=metadata)]
def _metadata(cfg: Any = None) -> dict[str, Any]: if cfg is None: return {} value = getattr(cfg, "metadata", None) return value if isinstance(value, dict) else {}
def _remote_path(metadata: dict[str, Any], key: str, fallback: str) -> str: value = str(metadata.get(key) or "").strip() return value or fallback
async def _remote_run(session: Any, command: str, *, check: bool = False) -> Any: try: return await session.run_command(command, check=check) except TypeError: return await session.run_command(command)
async def _remote_start(cfg: Any, session: Any) -> dict[str, Any]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") input_dir = _remote_path(metadata, "input_dir", "input") software_dir = _remote_path(metadata, "software_dir", "software") command = ( "set -eu\n" f"mkdir -p {shlex.quote(output_dir)}\n" f"find {shlex.quote(output_dir)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {{}} +\n" ) await _remote_run(session, command, check=True) return {"ok": True, "input_dir": input_dir, "software_dir": software_dir, "output_dir": output_dir}
def start(cfg: Any = None, session: Any = None) -> dict[str, Any]: if session is not None: return _remote_start(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) output_dir.mkdir(parents=True, exist_ok=True) for child in output_dir.iterdir(): if child.is_dir(): shutil.rmtree(child) else: child.unlink() input_dir = Path(os.environ.get("ALE_INPUT_DIR", "input")) software_dir = Path(os.environ.get("ALE_SOFTWARE_DIR", "software")) return { "ok": True, "input_dir": str(input_dir), "software_dir": str(software_dir), "output_dir": str(output_dir), }
async def _remote_evaluate(cfg: Any, session: Any) -> list[float]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") reference_dir = _remote_path(metadata, "reference_dir", "reference") script = f"""import importlib.utilimport jsonimport pathlib
output_dir = pathlib.Path({output_dir!r})reference_dir = pathlib.Path({reference_dir!r})evaluator_path = reference_dir / "evaluator.py"if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {{evaluator_path}}")spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path)if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {{evaluator_path}}")module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)result = module.evaluate(output_dir, reference_dir)print(json.dumps(result))""" command = "python3 - <<'PY'\n" + script + "\nPY" result = await _remote_run(session, command, check=True) stdout = getattr(result, "stdout", "") or "" for line in reversed([item.strip() for item in stdout.splitlines() if item.strip()]): try: payload = json.loads(line) if isinstance(payload, list): return [float(max(0.0, min(1.0, value))) for value in payload] except Exception: continue raise RuntimeError("hidden evaluator did not emit a JSON score list")
def evaluate(cfg: Any = None, session: Any = None) -> list[float]: if session is not None: return _remote_evaluate(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) reference_dir = Path(os.environ.get("ALE_REFERENCE_DIR", "reference")) evaluator_path = reference_dir / "evaluator.py" if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {evaluator_path}") spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) result = module.evaluate(output_dir, reference_dir) if not isinstance(result, list): raise TypeError("hidden evaluator must return list[float]") return [float(max(0.0, min(1.0, value))) for value in result]1234567891011term,kind,software_name
CMD,code_term,Docker / Python Official Image
apt-get,code_term,Docker / Python Official Image
curl,code_term,Docker / Python Official Image
gpg,code_term,Docker / Python Official Image
make,code_term,Docker / Python Official Image
FROM,code_term,Docker / Python Official Image
RUN,code_term,Docker / Python Official Image
ENV,code_term,Docker / Python Official Image
docker,executable,Docker / Python Official Image
docker build,executable,Docker / Python Official Image12345678910111213141516{ "software_name": "Docker / Python Official Image", "executables": [ "docker", "docker build" ], "required_system_packages": [ "docker.io" ], "official_sources": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "solve_time_network": "disabled", "python_wrapper_only": false, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs."}1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env python3from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
def required_outputs(input_dir: Path) -> list[str]: spec_path = input_dir / "analysis_spec.json" if spec_path.is_file(): payload = json.loads(spec_path.read_text(encoding="utf-8")) required = payload.get("required_outputs") if isinstance(payload, dict) else None if isinstance(required, list): rows = [str(item.get("path") or "") for item in required if isinstance(item, dict)] rows = [item for item in rows if item] if rows: return rows return [ "summary.json", "magnitude_depth_bins.csv", "region_daily_counts.csv", "filtered_events.geojson", ]
def main() -> int: output_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("output") input_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(os.environ.get("ALE_INPUT_DIR", "input")) required = required_outputs(input_dir) missing = [name for name in required if not (output_dir / name).is_file()] if missing: print(json.dumps({"ok": False, "missing": missing}, indent=2)) return 1 print(json.dumps({"ok": True, "required": required}, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111{ "taskId": "computing_math/audit_docker_official_image_packaging_corpus__20260907-014537_computing_math_08ed12", "title": "Repair4 20260907 017 Repair3 20260907 018 Repair2 20260906 020 Repair 20260906 Software 0026", "summary": "Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 4: 9 terms) (ALE-100 software diversity variant 6) (independent source snapshot 6). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3). (targeted repair round 4).", "category": "computing_math", "taxonomy": { "domain_id": "9", "domain_code": "computing_math", "subdomain_id": "9.6", "subdomain_code": "infra_cloud", "subdomain_name": "Infrastructure Engineering & Cloud Operations", "classifier": { "source": "public software metadata mapping", "rationale": "Subdomain selected from public task metadata." } }, "taskPrompt": "Use a Linux command-line workflow to audit the staged offline official tutorial corpus for Docker / Python Official Image. The source document is input/dockerfile_packaging_corpus.md, and input/dockerfile_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is software_tutorial_doc_audit. The primary staged data file is input/dockerfile_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:\n- output/summary.json: JSON keys and nested shape {\"code_block_count\": \"integer\", \"heading_count\": \"integer\", \"keyword_total\": \"integer\", \"software_name\": \"string\", \"source_character_count\": \"integer\", \"source_file\": \"string\", \"top_keyword\": \"string|null\", \"unique_required_terms_found\": \"integer\", \"window_count\": \"integer\"}\n- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug\n- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code\n- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_line\nCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.", "agentMustDo": [ "Read input/analysis_spec.json first and treat it as the authoritative public specification.", "Read input/dockerfile_text_windows.csv and compute results from the staged local data.", "Create output/summary.json as json exactly as specified by analysis_spec.json.", "Create output/section_outline.csv as csv exactly as specified by analysis_spec.json.", "Create output/keyword_inventory.csv as csv exactly as specified by analysis_spec.json.", "Create output/code_block_inventory.csv as csv exactly as specified by analysis_spec.json.", "Place every final deliverable directly under output/ with the exact required filename.", "Use only local staged files and installed Linux CLI tooling; do not download fresh data." ], "inputFiles": [ { "name": "README.md", "format": "Markdown", "path": "input/README.md", "description": "Agent-visible staged input file for this task." }, { "name": "analysis_spec.json", "format": "JSON", "path": "input/analysis_spec.json", "description": "Agent-visible staged input file for this task." }, { "name": "dockerfile_packaging_corpus.md", "format": "Markdown", "path": "input/dockerfile_packaging_corpus.md", "description": "Agent-visible staged input file for this task." }, { "name": "dockerfile_text_windows.csv", "format": "CSV", "path": "input/dockerfile_text_windows.csv", "description": "Agent-visible staged input file for this task." }, { "name": "source_context_windows.jsonl", "format": "JSONL", "path": "input/source_context_windows.jsonl", "description": "Agent-visible staged input file for this task." }, { "name": "tutorial_metadata.json", "format": "JSON", "path": "input/tutorial_metadata.json", "description": "Agent-visible staged input file for this task." } ], "referenceFiles": [ { "name": "summary.json", "format": "JSON", "path": "output/summary.json", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "section_outline.csv", "format": "CSV", "path": "output/section_outline.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "keyword_inventory.csv", "format": "CSV", "path": "output/keyword_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "code_block_inventory.csv", "format": "CSV", "path": "output/code_block_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." } ], "software": [ "Docker / Python Official Image", "docker", "docker build", "Python 3.11", "standard Unix shell", "software/command_examples.csv", "software/software_manifest.json", "software/validate_outputs.py" ], "requiredSystemPackages": [ "docker.io" ], "evaluation": "Final required files under output/ are compared against standard-reference outputs generated by the deterministic workflow for this task.", "vm": { "machineType": "c4-standard-4", "snapshot": "cpu-free-ubuntu", "timeout": 7200 }}123456789101112131415161718192021222324252627282930313233# Repair4 20260907 017 Repair3 20260907 018 Repair2 20260906 020 Repair 20260906 Software 0026
Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 4: 9 terms) (ALE-100 software diversity variant 6) (independent source snapshot 6). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3). (targeted repair round 4).
## Task
Use a Linux command-line workflow to audit the staged offline official tutorial corpus for Docker / Python Official Image. The source document is input/dockerfile_packaging_corpus.md, and input/dockerfile_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is software_tutorial_doc_audit. The primary staged data file is input/dockerfile_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:- output/summary.json: JSON keys and nested shape {"code_block_count": "integer", "heading_count": "integer", "keyword_total": "integer", "software_name": "string", "source_character_count": "integer", "source_file": "string", "top_keyword": "string|null", "unique_required_terms_found": "integer", "window_count": "integer"}- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_lineCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.
## Workspace
You are working in `/workspace`.
- Public input files are under `/workspace/input/`.- Public helper software and validation scripts are under `/workspace/software/`.- The public task card is available at `/workspace/task_card.json`.- The public task driver is available at `/workspace/main.py` for reference only.- Do not use hidden reference data, network downloads, credentials, GUI tools, or browser automation.
## Required Outputs
Create every final deliverable exactly at these paths:
- `/workspace/output/summary.json` (json)- `/workspace/output/section_outline.csv` (csv)- `/workspace/output/keyword_inventory.csv` (csv)- `/workspace/output/code_block_inventory.csv` (csv)
Follow `/workspace/input/analysis_spec.json` whenever it is more specific than prose. You may run public validation helpers, but the files under `/workspace/output/` are what will be evaluated.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_outputs(input_dir, output_dir)1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567#!/bin/bashset -euo pipefailINPUT_DIR="${1:-/workspace/input}"OUTPUT_DIR="${2:-/workspace/output}"SOLUTION_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"mkdir -p "${OUTPUT_DIR}"python "${SOLUTION_DIR}/reference_solution.py" --input "${INPUT_DIR}" --output "${OUTPUT_DIR}"123456789101112131415161718192021222324252627282930313233343536373839404142434445schema_version = "1.3"artifacts = ["/workspace/output/summary.json", "/workspace/output/section_outline.csv", "/workspace/output/keyword_inventory.csv", "/workspace/output/code_block_inventory.csv"]
[task]name = "ale-cli/20260907-014537-computing-math-08ed12"description = "Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 4: 9 terms) (ALE-100 software diversity variant 6) (independent source snapshot 6). (repair batch 20260906; independent offici"keywords = ["agents-last-exam", "ale-cli", "computing-math", "deterministic-evaluator", "linux-cli", "software-tutorial-doc-audit"]
[metadata]benchmark = "ale_cli"source_format = "ale_cli_official_style"converter = "ale_cli_to_harbor"source_task_key = "20260907-014537_computing_math_08ed12"task_id = "computing_math/audit_docker_official_image_packaging_corpus__20260907-014537_computing_math_08ed12"domain = "computing_math"task = "audit_docker_official_image_packaging_corpus"variant = "base"oracle_available = truescoring_method = "deterministic_hidden_evaluator"required_outputs = ["summary.json", "section_outline.csv", "keyword_inventory.csv", "code_block_inventory.csv"]
[agent]timeout_sec = 1800
[verifier]timeout_sec = 600environment_mode = "separate"
[verifier.environment]build_timeout_sec = 900.0network_mode = "public"os = "linux"cpus = 1memory_mb = 2048storage_mb = 4096gpus = 0
[environment]build_timeout_sec = 1200.0network_mode = "public"os = "linux"cpus = 2memory_mb = 4096storage_mb = 10240gpus = 0123456FROM python:3.12-slim
WORKDIR /workspace
COPY . /testsRUN chmod +x /tests/test.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3from __future__ import annotations
import argparseimport importlib.utilimport jsonfrom pathlib import Pathfrom typing import Any
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def reward( *, score: float, output_present: float, evaluator_available: float, item_count: int, format_score: float = 1.0,) -> dict[str, float]: clipped = max(0.0, min(1.0, float(score))) return { "score": clipped, "weighted_score": clipped, "format": max(0.0, min(1.0, float(format_score))), "output_present": max(0.0, min(1.0, float(output_present))), "evaluator_available": max(0.0, min(1.0, float(evaluator_available))), "item_count": float(item_count), }
def load_evaluator(reference_dir: Path): evaluator_path = reference_dir / "evaluator.py" spec = importlib.util.spec_from_file_location("ale_hidden_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
def required_outputs(reference_dir: Path) -> list[dict[str, str]]: manifest_path = reference_dir / "reference_manifest.json" if not manifest_path.is_file(): return [] manifest = read_json(manifest_path) rows = manifest.get("required_outputs") if isinstance(manifest, dict) else [] return [row for row in rows if isinstance(row, dict) and row.get("path")]
def main() -> int: parser = argparse.ArgumentParser(description="Run a hidden ALE CLI evaluator in Harbor.") parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--reference-dir", type=Path, required=True) parser.add_argument("--reward-json", type=Path, required=True) parser.add_argument("--details-json", type=Path, required=True) args = parser.parse_args()
required = required_outputs(args.reference_dir) present = [row for row in required if (args.output_dir / str(row["path"])).is_file()] item_count = len(required) if not required: write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=0.0, item_count=0, format_score=0.0)) write_json(args.details_json, {"ok": False, "error": "reference_manifest.required_outputs missing"}) return 0 if len(present) != len(required): write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "reason": "missing required outputs", "present": [row["path"] for row in present]}) return 0 try: module = load_evaluator(args.reference_dir) result = module.evaluate(args.output_dir, args.reference_dir) if not isinstance(result, list) or not result: raise TypeError("hidden evaluator must return non-empty list[float]") score = float(result[0]) write_json(args.reward_json, reward(score=score, output_present=1.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "raw_score": result, "required_outputs": required}) except Exception as exc: write_json(args.reward_json, reward(score=0.0, output_present=1.0, evaluator_available=0.0, item_count=item_count)) write_json(args.details_json, {"ok": False, "error": f"{type(exc).__name__}: {exc}", "required_outputs": required}) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114from __future__ import annotations
import csvimport jsonimport mathfrom pathlib import Pathfrom typing import Any
def _load_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _num_close(a: Any, b: Any, tol: float) -> bool: try: af = float(a) bf = float(b) except (TypeError, ValueError): return False if math.isnan(af) and math.isnan(bf): return True return abs(af - bf) <= tol
def _compare_json(actual: Any, expected: Any, tol: float) -> float: if isinstance(expected, dict): if not isinstance(actual, dict): return 0.0 if not expected: return 1.0 scores = [] for key, exp_value in expected.items(): if key not in actual: scores.append(0.0) else: scores.append(_compare_json(actual[key], exp_value, tol)) return sum(scores) / len(scores) if isinstance(expected, list): if not isinstance(actual, list) or len(actual) != len(expected): return 0.0 if not expected: return 1.0 return sum(_compare_json(a, e, tol) for a, e in zip(actual, expected)) / len(expected) if isinstance(expected, (int, float)): return 1.0 if _num_close(actual, expected, tol) else 0.0 return 1.0 if actual == expected else 0.0
def _read_csv(path: Path) -> list[dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as handle: return list(csv.DictReader(handle))
def _compare_csv(actual_path: Path, expected_path: Path, tol: float) -> float: try: actual = _read_csv(actual_path) expected = _read_csv(expected_path) except Exception: return 0.0 if len(actual) != len(expected): return 0.0 if not expected: return 1.0 row_scores = [] for actual_row, expected_row in zip(actual, expected): keys = list(expected_row) if set(actual_row) != set(keys): row_scores.append(0.0) continue cell_scores = [] for key in keys: exp_value = expected_row[key] act_value = actual_row[key] if exp_value == act_value: cell_scores.append(1.0) elif _num_close(act_value, exp_value, tol): cell_scores.append(1.0) else: cell_scores.append(0.0) row_scores.append(sum(cell_scores) / len(cell_scores) if cell_scores else 1.0) return sum(row_scores) / len(row_scores)
def evaluate(output_dir: str | Path, reference_dir: str | Path | None = None) -> list[float]: output_dir = Path(output_dir) reference_dir = Path(reference_dir) if reference_dir is not None else Path(__file__).resolve().parent manifest = _load_json(reference_dir / "reference_manifest.json") tolerance = float(manifest.get("numeric_tolerance", 1e-9)) required = manifest.get("required_outputs") or [] if not required: return [0.0] scores = [] for item in required: rel = item["path"] kind = item["type"] actual_path = output_dir / rel expected_path = reference_dir / "ground_truth" / rel if not actual_path.is_file() or not expected_path.is_file(): scores.append(0.0) continue try: if kind == "json": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) elif kind == "csv": scores.append(_compare_csv(actual_path, expected_path, tolerance)) elif kind == "geojson": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) else: scores.append(1.0 if actual_path.read_bytes() == expected_path.read_bytes() else 0.0) except Exception: scores.append(0.0) score = max(0.0, min(1.0, sum(scores) / len(scores))) return [score]123456789101112block_index,line_count,char_count,contains_code_term,first_line
1,85,9922,true,# Docker Official Images
2,1,135,true,"2. If there is initialization that needs to be done on start, like creating the initial database, use an `ENTRYPOINT` along with `CMD`:"
3,1,234,true,"1. Ensure that `docker run official-image bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something else, just `exec ""$@""` (run whatever was passed, proper"
4,1,190,true,"3. If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to use the executable as the `ENTRYPOINT`, since that is the only thing that can run:"
5,11,2434,true,The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`).
6,14,2878,true,#### Cacheability
7,1,141,false,- **Alternate**: *full key fingerprint imported to apt which will check signatures and checksums when packages are downloaded and installed.*
8,2,387,true,"(As a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't include the extra ~8MB of APT package list data, and enforces [appropr"
9,4,445,true,"- **Note:** the use of either SHA1 or MD5 should be considered a ""checksum of last resort"" as both are considered generally unsafe:"
10,24,4866,true,##### Runtime Configuration
11,47,8381,true,See the [instruction format section](#instruction-format) for more information on the format of the library file.1234567891011121314term,category,count,first_window,appears_in_code
apt-get,code,7,55,true
curl,code,4,112,false
gpg,code,10,90,false
make,code,6,25,true
CMD,required,6,61,true
COPY,required,6,93,true
Dockerfile,required,42,8,true
ENV,required,7,9,true
FROM,required,20,12,true
GitRepo,required,7,153,true
GPG_KEY,required,0,,false
RUN,required,28,3,true
Tags,required,19,4,true123456789101112131415161718192021222324252627282930313233rank,heading_level,heading_text,slug
1,h1,Source 1: README.md,source_1_readme_md
2,h1,Docker Official Images,docker_official_images
3,h2,Table of Contents,table_of_contents
4,h2,"What are ""Official Images""?",what_are_official_images
5,h2,Architectures other than amd64?,architectures_other_than_amd64
6,h2,More FAQs?,more_faqs
7,h2,Contributing to the standard library,contributing_to_the_standard_library
8,h3,Review Guidelines,review_guidelines
9,h4,Maintainership,maintainership
10,h4,Repeatability,repeatability
11,h4,Consistency,consistency
12,h4,Clarity,clarity
13,h4,init,init
14,h1,Install tini for signal processing and zombie killing,install_tini_for_signal_processing_and_zombie_killing
15,h4,Cacheability,cacheability
16,h4,Security,security
17,h5,Image Build,image_build
18,h5,Runtime Configuration,runtime_configuration
19,h5,Security Releases,security_releases
20,h4,Multiple Architectures,multiple_architectures
21,h1,all the same commit; easy for us to generate this way since they could be different,all_the_same_commit_easy_for_us_to_generate_this_way_since_they_could_be_differe
22,h1,"if there is only one architecture, you can use the unprefixed fields",if_there_is_only_one_architecture_you_can_use_the_unprefixed_fields
23,h1,or use the prefixed versions,or_use_the_prefixed_versions
24,h3,Commitment,commitment
25,h2,Library definition files,library_definition_files
26,h3,Filenames,filenames
27,h3,Tags and aliases,tags_and_aliases
28,h3,Instruction format,instruction_format
29,h3,Creating a new repository,creating_a_new_repository
30,h3,Adding a new tag in an existing repository (that you're the maintainer of),adding_a_new_tag_in_an_existing_repository_that_you_re_the_maintainer_of
31,h3,Change to a tag in an existing repository (that you're the maintainer of),change_to_a_tag_in_an_existing_repository_that_you_re_the_maintainer_of
32,h2,Bashbrew,bashbrew1234567891011{ "software_name": "Docker / Python Official Image", "source_file": "dockerfile_packaging_corpus.md", "window_count": 225, "heading_count": 32, "code_block_count": 11, "keyword_total": 162, "unique_required_terms_found": 8, "top_keyword": "Dockerfile", "source_character_count": 34274}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_outputs(input_dir, output_dir)12345678910111213141516171819202122232425262728293031323334{ "workflow_kind": "software_tutorial_doc_audit", "task_id": "repair4_20260907_017_repair3_20260907_018_repair2_20260906_020_repair_20260906_software_0026", "domain": "computing_math", "task": "audit_docker_official_image_packaging_corpus", "variant": "base", "created_from": "standard reference workflow", "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "section_outline.csv", "type": "csv" }, { "path": "keyword_inventory.csv", "type": "csv" }, { "path": "code_block_inventory.csv", "type": "csv" } ], "numeric_tolerance": 1e-09, "source_prior_sha256": "99c608c4d37fd90c8e21ae0e7f94f39f704e1d81cd60d416c10d9644db3cdd73", "gold_output_hashes": { "summary.json": "5795da5120039e87a81d9873724f639f67dc86f0c14efbcecf5f9f8c353eba17", "section_outline.csv": "0e41828df0f65a7d5af562b235f5f1c850492c2ad59fca2a8f31d827482fabd4", "keyword_inventory.csv": "0d1aa810b2ad77b8e37c6d75186c22bb844896b2696a9a9b3309d88e8f3c2bae", "code_block_inventory.csv": "cd7dad69071d4232783ae757ffc9ad44d7c5c124df07e1ebcc67d7bc8e956389" }}1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829#!/bin/bashset -u
TESTS_DIR="${HARBOR_TESTS_DIR:-/tests}"WORKSPACE_DIR="${HARBOR_WORKSPACE_DIR:-/workspace}"LOGS_DIR="${HARBOR_LOGS_DIR:-/logs/verifier}"
mkdir -p "${LOGS_DIR}" "${WORKSPACE_DIR}/output"
python "${TESTS_DIR}/evaluator_runner.py" \ --output-dir "${WORKSPACE_DIR}/output" \ --reference-dir "${TESTS_DIR}/reference" \ --reward-json "${LOGS_DIR}/reward.json" \ --details-json "${LOGS_DIR}/ale_evaluator_details.json"
if [ ! -f "${LOGS_DIR}/reward.json" ]; then echo '{"score":0.0,"format":0.0,"output_present":0.0,"evaluator_available":0.0,"item_count":0.0}' > "${LOGS_DIR}/reward.json"fi
python - <<'PY' "${LOGS_DIR}/reward.json" "${LOGS_DIR}/reward.txt"import jsonimport sysfrom pathlib import Pathreward = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))score = float(reward.get("score", 0.0))Path(sys.argv[2]).write_text(f"{score}\n", encoding="utf-8")PY
exit 0123version https://git-lfs.github.com/spec/v1oid sha256:ee45bfa665faf1a194302abdf3b57505503f48f4914cd46ec558f1aa9d1bb593size 6148123456789101112FROM python:3.12-slim
WORKDIR /workspace
COPY public_data/input /workspace/inputCOPY public_data/software /workspace/softwareCOPY public_data/task_card.json /workspace/task_card.jsonCOPY public_data/main.py /workspace/main.pyCOPY public_data/README.md /workspace/README.md
RUN mkdir -p /workspace/output /workspace/report /logs/agent /logs/artifacts \ && chmod -R 777 /workspace/output /workspace/report /logs1234567891011# Public Task Inputs
Files in this directory are copied into the workspace:
- `input/` -> `/workspace/input/`- `software/` -> `/workspace/software/`- `task_card.json` -> `/workspace/task_card.json`- `main.py` -> `/workspace/main.py`
Hidden reference data and evaluator files are not present in the agent workspace.Final deliverables must be written under `/workspace/output/`.123456This directory contains the public staged input for this task.input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.Primary data file: input/dockerfile_text_windows.csv.Workflow kind: software_tutorial_doc_audit.Required output files: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv.Solve the task from the staged local files only; do not fetch fresh remote data during solve time.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596{ "input_file": "dockerfile_text_windows.csv", "source_file": "dockerfile_packaging_corpus.md", "workflow_kind": "software_tutorial_doc_audit", "software_name": "Docker / Python Official Image", "tutorial_url": "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md", "source_urls": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "heading_rule": "Extract h1-h6 headings from HTML; if no HTML headings are present, use Markdown # headings.", "keyword_rule": "Count case-insensitive occurrences of required_terms and code_terms in the cleaned tutorial text.", "required_terms": [ "Dockerfile", "FROM", "RUN", "ENV", "CMD", "PYTHON_VERSION", "Tags", "GitRepo" ], "code_terms": [ "apt-get", "curl", "gpg", "make", "FROM", "RUN", "ENV" ], "executables": [ "docker", "docker build" ], "required_system_packages": [ "docker.io" ], "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "section_outline.csv", "type": "csv" }, { "path": "keyword_inventory.csv", "type": "csv" }, { "path": "code_block_inventory.csv", "type": "csv" } ], "output_schemas": { "summary.json": { "software_name": "string", "source_file": "string", "window_count": "integer", "heading_count": "integer", "code_block_count": "integer", "keyword_total": "integer", "unique_required_terms_found": "integer", "top_keyword": "string|null", "source_character_count": "integer" }, "section_outline.csv": [ "rank", "heading_level", "heading_text", "slug" ], "keyword_inventory.csv": [ "term", "category", "count", "first_window", "appears_in_code" ], "code_block_inventory.csv": [ "block_index", "line_count", "char_count", "contains_code_term", "first_line" ] }, "notes": "Audit the staged offline official tutorial corpus. Do not fetch fresh documentation. All counts must be derived from the staged source file and tutorial_text_windows.csv."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447# Source 1: README.md
- URL: https://github.com/docker-library/official-images/raw/refs/heads/master/README.md- SHA256: 7b092c41c25d31902face488f7a5ed9928abb002548b1e3d64ee318afbbd2acf- Bytes: 34724
```markdown# Docker Official Images
## Table of Contents
<!-- AUTOGENERATED TOC -->
1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are "Official Images"?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64) 4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity) 5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment) 6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew)
<!-- AUTOGENERATED TOC -->
## What are "Official Images"?
The Docker Official Images are curated images [hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are:
- Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software
- Support [multiple architectures](#architectures-other-than-amd64)
- Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)
- [Actively rebuild](#library-definition-files) for updates and security fixes
- Adhere to upstream recommendations
- Add minimal quality-of-life behavior for the container environment where fit
See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program.
In essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the best practices for Dockerfiles to serve as a reference when making or deriving your own images from them.
(If you are a representative of an upstream for which there exists an image and you would like to get involved, please see the [Maintainership](#maintainership) section below!)
## Architectures other than amd64?
Some images have been ported for other architectures, and many of these are officially supported (to various degrees).
- Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/)) - ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/ - Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/- Other architectures built by official images: (but *not* officially supported by Docker, Inc.) - ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/ - x86/i686 (`i386`): https://hub.docker.com/u/i386/
These other architectures are included under the non-prefixed images via [OCI "image indexes"](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for example, `docker run hello-world` should run as-is on all supported platforms.
If you're curious about how these are built, head over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process source files.
See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image.
## More FAQs?
Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and about our practices).
## Contributing to the standard library
Thank you for your interest in the Docker official images project! We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here.
Be sure to familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These will be the foundation of the review process performed by the official images maintainers. If you'd like the review process to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines), before submitting a pull request.
Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs), whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit a PR there as well, pending acceptance of your image here.
### Review Guidelines
Because the official images are intended to be learning tools for those new to Docker as well as the base images for advanced users to build their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability. While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while also adhering to the "Best Practices" where appropriate.
A checklist which may be used by the maintainers during review can be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md).
#### Maintainership
Version bumps and security fixes should be attended to in a timely manner.
If you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a smooth transition of image maintainership over to upstream.
For upstreams interested in taking over maintainership of an existing repository, the first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known within the "image community" (even if that "community" is just the current maintainer) are all important places to start to ensure that the transition is unsurprising to existing contributors and users.
When taking over an existing repository, please ensure that the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie, `git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the git repository. This can be accomplished without giving either group admin access to the other owner's repository:
- create temporary intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help- give old and new owners admin access to intermediary organization- old owner transfers repo ownership to intermediary organization- new owner transfers repo ownership to its new home - recommend that old owner does not fork new repo back into the old organization to ensure that GitHub redirects will just work
#### Repeatability
Rebuilding the same `Dockerfile` should result in the same version of the image being packaged, even if the second build happens several versions later, or the build should fail outright, such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using `apt` to install the main program for the image, be sure to pin it to a specific version (ex: `... apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them to a version.
No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)).
#### Consistency
All official images should provide a consistent interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`. It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1 --arg2` without having to specify the binary to execute.
1. If the startup process does not need arguments, just use `CMD`:
```Dockerfile CMD ["irb"] ```
2. If there is initialization that needs to be done on start, like creating the initial database, use an `ENTRYPOINT` along with `CMD`:
```Dockerfile ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["postgres"] ```
1. Ensure that `docker run official-image bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something else, just `exec "$@"` (run whatever was passed, properly keeping the arguments escaped).
```sh #!/bin/sh set -e
# this if will check if the first argument is a flag # but only works if all arguments require a hyphenated flag # -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then set -- mongod "$@" fi
# check for the expected command if [ "$1" = 'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu mongod "$@" fi
# else default to run whatever the user wanted like "bash" or "sh" exec "$@" ```
3. If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to use the executable as the `ENTRYPOINT`, since that is the only thing that can run:
```Dockerfile ENTRYPOINT ["fully-static-binary"] CMD ["--help"] ```
The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`).
#### Clarity
Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples, look at the current official images.
Some examples at the time of writing:
- [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile)- [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile)- [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile)
#### init
Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly this means just one process per container, so there is no need for a full init system. There are two situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see "NOTE" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If the process spawns child processes and does not properly reap them it will lead to a full process table, which can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and signal forwarding.
Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate.
It is best to install tini from a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here is a snippet of a `Dockerfile` to add in tini:
```Dockerfile# Install tini for signal processing and zombie killingENV TINI_VERSION v0.18.0ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7RUN set -eux; \ wget -O /usr/local/bin/tini "https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini"; \ wget -O /usr/local/bin/tini.asc "https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc"; \ export GNUPGHOME="$(mktemp -d)"; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$TINI_SIGN_KEY"; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf && gpgconf --kill all || :; \ rm -r "$GNUPGHOME" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version```
#### Cacheability
This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips might help:
- Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead of `COPY . /somewhere`).
The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of what needs to be `COPY`ed (for example).
- Ensure that lines which are less likely to change come before lines that are more likely to change (with the caveat that each line should generate an image that still runs successfully without assumptions of later lines).
For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`).
#### Security
##### Image Build
The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and no signature.
The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the download is from a trusted source which also happens to make interception much more difficult.
The purpose in recommending PGP signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification).
The purpose in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes, the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally downloading newer-than-expected artifacts on poorly versioned files.
Below are some examples:
- **Preferred**: *download over https, PGP key full fingerprint import and `asc` verification, embedded checksum verified.*
```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz" -o python.tar.xz; \ curl -fL "https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc" -o python.tar.xz.asc; \ export GNUPGHOME="$(mktemp -d)"; \ # gpg: key F73C700D: public key "Larry Hastings <larry@hastings.org>" imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r "$GNUPGHOME" python.tar.xz.asc; \ echo "$PYTHON_DOWNLOAD_SHA512 *python.tar.xz" | sha512sum --strict --check; \ # install ```
- **Alternate**: *full key fingerprint imported to apt which will check signatures and checksums when packages are downloaded and installed.*
```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME="$(mktemp -d)"; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys "$key"; \ gpg --batch --armor --export "$key" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \ rm -rf "$GNUPGHOME"; \ apt-key list > /dev/null
RUN set -eux; \ echo "deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}" > /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client="${MYSQL_VERSION}" mysql-community-server-core="${MYSQL_VERSION}"; \ rm -rf /var/lib/apt/lists/*; \ # ... ```
(As a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).)
- **Less Secure Alternate**: *embed the checksum into the `Dockerfile`.*
```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz "https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz"; \ echo "$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz" | sha256sum --strict --check; \ # install ```
- **Note:** the use of either SHA1 or MD5 should be considered a "checksum of last resort" as both are considered generally unsafe:
- ["Single-block collision for MD5" from 2012](https://marc-stevens.nl/research/md5-1block-collision/) - ["Announcing the first SHA1 collision" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html)
- **Unacceptable**: *download the file over http(s) with no verification.*
```Dockerfile RUN curl -fL "https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz" | tar ... \ # install ```
##### Runtime Configuration
By default, Docker containers are executed with reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a container may require additional privileges in order to function correctly, and there are a number of command line options to customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference.
Official Repositories that require additional privileges should specify the minimal set of command line options for the software to function, and may still be rejected if this introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g. X11 socket).
##### Security Releases
For image updates which constitute a security fix, there are a few things we recommend to help ensure your update is merged, built, and released as quickly as possible:
1. [Send an email to `doi@docker.com`](mailto:doi@docker.com) a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule time for the incoming update appropriately).2. Include `[security]` in the title of your pull request (for example, `[security] Update FooBar to 1.2.5, 1.3.7, 2.0.1`).3. Keep the pull request free of changes that are unrelated to the security fix -- we'll still be doing review of the update, but it will be expedited so this will help us help you.4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more so if the timing of the release is of importance).
#### Multiple Architectures
Each repo can specify multiple architectures for any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go` file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27):
- `amd64`- `arm32v6`- `arm32v7`- `arm64v8`- `i386`- `ppc64le`- `riscv64`- `s390x`- `windows-amd64`
The `Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`.
Images must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s.
If different parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or `apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed. See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download the binary release.
For base images like `debian` it will be necessary to have a different `Dockerfile` and build context in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`, and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world):
```Maintainers: Tianon Gravi <admwiggin@gmail.com> (@tianon), Joseph Ferguson <yosifkit@gmail.com> (@yosifkit)GitRepo: https://github.com/docker-library/hello-world.gitGitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87
Tags: latestArchitectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x# all the same commit; easy for us to generate this way since they could be differentamd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87amd64-Directory: amd64/hello-worldarm32v5-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm32v5-Directory: arm32v5/hello-worldarm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm32v7-Directory: arm32v7/hello-worldarm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87arm64v8-Directory: arm64v8/hello-worldppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87ppc64le-Directory: ppc64le/hello-worlds390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87s390x-Directory: s390x/hello-world
Tags: nanoserverArchitectures: windows-amd64# if there is only one architecture, you can use the unprefixed fieldsDirectory: amd64/hello-world/nanoserver# or use the prefixed versionswindows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87Constraints: nanoserver```
See the [instruction format section](#instruction-format) for more information on the format of the library file.
### Commitment
Proposing a new official image should not be undertaken lightly. We expect and require a commitment to maintain your image (including and especially timely updates as appropriate, as noted above).
## Library definition files
The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file controls the current "supported" set of image tags that appear on the Docker Hub description. Tags that are removed from a library file do not get removed from the Docker Hub, so that old versions can continue to be available for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file are only built through an update to that library file or as a result of its base image being updated (ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will be rebuilt when a base has updates.
Given this policy, it is worth clarifying a few cases: backfilled versions, release candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive historical archive which is not the intention. Another common case where the term "supported" is stretched a bit is with release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle based on code commits or a regular schedule are not appropriate.
It is highly recommended that you browse some of the existing `library/` file contents (and history to get a feel for how they change over time) before creating a new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can focus on content instead of esoteric formatting or tag usage/naming).
### Filenames
The filename of a definition file will determine the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags in the `ubuntu` repository.
### Tags and aliases
The tags of a repository should reflect upstream's versions or variations. For example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so `ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag is a special case, but it's a bit of a misnomer; `latest` really is the "default" tag. When one does `docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be used as simply `xyz`). Put another way, having an alias for the "highest 2.2-series release of XYZ" should be `xyz:2.2`, not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or `xyz:latest-alpine`.
It is strongly encouraged that version number tags be given aliases which make it easy for the user to stay on the "most recent" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7 and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very different, and can be thought of as the `latest` tag for each of the major release tracks of Python).
As described above, `latest` is really "default", so the image that it is an alias for should reflect which version or variation of the software users should use if they do not know or do not care which version they use. Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority of users should be using if they know they want Ubuntu but do not know or care which version (especially considering it will be the most "stable" and well-supported release at any given time).
### Instruction format
The manifest file format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with the "headers" of many popular internet protocols/formats such as HTTP or email.
The primary additions are inspired by the way Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and "entries" are separated by a blank line.
The first entry is the "global" metadata for the image. The only required field in the global entry is `Maintainers`, whose value is comma-separated in the format of `Name <email> (@github)` or `Name (@github)`. Any field specified in the global entry will be the default for the rest of the entries and can be overridden in an individual entry.
# this is a comment and will be ignored Maintainers: John Smith <jsmith@example.com> (@example-jsmith), Anne Smith <asmith@example.com> (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc, rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use
Bashbrew will fetch code out of the Git repository (`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`, it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order to get the commit necessary.
The built image will be tagged as `<manifest-filename>:<tag>` (ie, `library/golang` with a `Tags` value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`).
Optionally, if `Directory` is present, Bashbrew will look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the ["context" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of `Dockerfile` will be used.
See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or `Directory` for a specific architecture.
### Creating a new repository
- Create a new file in the `library/` folder. Its name will be the name of your repository on the Hub.- Add your tag definitions using the appropriate syntax (see above).- Create a pull request adding the file from your forked repository to this one. Please be sure to add details as to what your repository does.
### Adding a new tag in an existing repository (that you're the maintainer of)
- Add your tag definition using the instruction format documented above.- Create a pull request from your Git repository to this one. Please be sure to add details about what's new, if possible.
### Change to a tag in an existing repository (that you're the maintainer of)
- Update the relevant tag definition using the instruction format documented above.- Create a pull request from your Git repository to this one. Please be sure to add details about what's changed, if possible.
## Bashbrew
Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the Docker official images. See [the Bashbrew `README`](https://github.com/docker-library/bashbrew#readme) for more information.```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226window_id,start_word,end_word,text,contains_code_term,matched_required_terms
1,0,40,"# Source 1: README.md - URL: https://github.com/docker-library/official-images/raw/refs/heads/master/README.md - SHA256: 7b092c41c25d31902face488f7a5ed9928abb002548b1e3d64ee318afbbd2acf - Bytes: 34724 ```markdown # Docker Official Images ## Table of Contents 1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are ""Official Images""?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64)",false,
2,20,60,"of Contents 1. [Docker Official Images](#docker-official-images) 1. [Table of Contents](#table-of-contents) 2. [What are ""Official Images""?](#what-are-official-images) 3. [Architectures other than amd64?](#architectures-other-than-amd64) 4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity)",false,
3,40,80,4. [More FAQs?](#more-faqs) 5. [Contributing to the standard library](#contributing-to-the-standard-library) 1. [Review Guidelines](#review-guidelines) 1. [Maintainership](#maintainership) 2. [Repeatability](#repeatability) 3. [Consistency](#consistency) 4. [Clarity](#clarity) 5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment),true,RUN
4,60,100,5. [init](#init) 6. [Cacheability](#cacheability) 7. [Security](#security) 1. [Image Build](#image-build) 2. [Runtime Configuration](#runtime-configuration) 3. [Security Releases](#security-releases) 8. [Multiple Architectures](#multiple-architectures) 2. [Commitment](#commitment) 6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding,true,RUN|Tags
5,80,120,6. [Library definition files](#library-definition-files) 1. [Filenames](#filenames) 2. [Tags and aliases](#tags-and-aliases) 3. [Instruction format](#instruction-format) 4. [Creating a new repository](#creating-a-new-repository) 5. [Adding a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing,false,Tags
6,100,140,"a new tag in an existing repository (that you're the maintainer of)](#adding-a-new-tag-in-an-existing-repository-that-youre-the-maintainer-of) 6. [Change to a tag in an existing repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew) ## What are ""Official Images""? The Docker Official Images are curated images",false,
7,120,160,"repository (that you're the maintainer of)](#change-to-a-tag-in-an-existing-repository-that-youre-the-maintainer-of) 7. [Bashbrew](#bashbrew) ## What are ""Official Images""? The Docker Official Images are curated images [hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are: - Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software - Support [multiple architectures](#architectures-other-than-amd64) -",false,
8,140,180,[hosted on Docker Hub](https://hub.docker.com/u/library). The main tenets are: - Focus on [Free](https://www.debian.org/social_contract#guidelines) and [Open-Source](https://opensource.org/) Software - Support [multiple architectures](#architectures-other-than-amd64) - Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Actively rebuild](#library-definition-files) for updates and security fixes - Adhere to upstream recommendations - Add minimal,false,Dockerfile
9,160,200,Exemplify [`Dockerfile` best practices](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/) - [Actively rebuild](#library-definition-files) for updates and security fixes - Adhere to upstream recommendations - Add minimal quality-of-life behavior for the container environment where fit See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program. In,true,Dockerfile|ENV
10,180,220,quality-of-life behavior for the container environment where fit See [Docker's documentation](https://docs.docker.com/docker-hub/official_repos/) for a good high-level overview of the program. In essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are,true,ENV
11,200,240,essence we strive to heed upstream's recommendations on how they intend for their software to be consumed. Many images are maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the,false,
12,220,260,maintained in collaboration with the relevant upstream project if not maintained directly by them. Additionally we aim to exemplify the best practices for Dockerfiles to serve as a reference when making or deriving your own images from them. (If you,true,Dockerfile|FROM
13,240,280,"best practices for Dockerfiles to serve as a reference when making or deriving your own images from them. (If you are a representative of an upstream for which there exists an image and you would like to get involved, please",true,Dockerfile|FROM
14,260,300,"are a representative of an upstream for which there exists an image and you would like to get involved, please see the [Maintainership](#maintainership) section below!) ## Architectures other than amd64? Some images have been ported for other architectures, and many",false,
15,280,320,"see the [Maintainership](#maintainership) section below!) ## Architectures other than amd64? Some images have been ported for other architectures, and many of these are officially supported (to various degrees). - Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/))",true,RUN
16,300,340,"of these are officially supported (to various degrees). - Architectures officially supported by Docker, Inc. for running Docker: (see [download.docker.com](https://download.docker.com/linux/)) - ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/",true,RUN
17,320,360,"- ARMv6 32-bit (`arm32v6`): https://hub.docker.com/u/arm32v6/ - ARMv7 32-bit (`arm32v7`): https://hub.docker.com/u/arm32v7/ - ARMv8 64-bit (`arm64v8`): https://hub.docker.com/u/arm64v8/ - Linux x86-64 (`amd64`): https://hub.docker.com/u/amd64/ - Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/ - Other architectures built by official images: (but *not* officially supported by Docker, Inc.) -",false,
18,340,380,"- Windows x86-64 (`windows-amd64`): https://hub.docker.com/u/winamd64/ - Other architectures built by official images: (but *not* officially supported by Docker, Inc.) - ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/",false,
19,360,400,"ARMv5 32-bit (`arm32v5`): https://hub.docker.com/u/arm32v5/ - IBM POWER8 (`ppc64le`): https://hub.docker.com/u/ppc64le/ - IBM z Systems (`s390x`): https://hub.docker.com/u/s390x/ - RISC-V 64-bit (`riscv64`): https://hub.docker.com/u/riscv64/ - x86/i686 (`i386`): https://hub.docker.com/u/i386/ These other architectures are included under the non-prefixed images via [OCI ""image indexes""](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for",false,
20,380,420,"- x86/i686 (`i386`): https://hub.docker.com/u/i386/ These other architectures are included under the non-prefixed images via [OCI ""image indexes""](https://github.com/opencontainers/image-spec/blob/v1.1.1/image-index.md), such that, for example, `docker run hello-world` should run as-is on all supported platforms. If you're curious about how these are built, head",true,RUN
21,400,440,"example, `docker run hello-world` should run as-is on all supported platforms. If you're curious about how these are built, head over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process",true,RUN
22,420,460,over to [our FAQ entry](https://github.com/docker-library/faq#an-images-source-changed-in-git-now-what) to see an explanation of the process or visit [meta-scripts](https://github.com/docker-library/meta-scripts) to see the build process source files. See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image. ## More FAQs?,false,
23,440,480,source files. See the [multi-arch section](#multiple-architectures) below for recommendations in adding more architectures to an official image. ## More FAQs? Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and,false,
24,460,500,Yes! We have [a dedicated FAQ repository](https://github.com/docker-library/faq) where we try to collect other common questions (both about the program and about our practices). ## Contributing to the standard library Thank you for your interest in the Docker official images project!,false,
25,480,520,"about our practices). ## Contributing to the standard library Thank you for your interest in the Docker official images project! We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate",true,
26,500,540,"We strive to make these instructions as simple and straightforward as possible, but if you find yourself lost, don't hesitate to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here. Be sure to",true,
27,520,560,to seek us out on [Libera.Chat IRC](https://libera.chat) in channel `#docker-library` or by creating a GitHub issue here. Be sure to familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These,false,Dockerfile
28,540,580,familiarize yourself with [Official Repositories on Docker Hub](https://docs.docker.com/docker-hub/official_repos/) and the [Best practices for writing Dockerfiles](https://docs.docker.com/articles/dockerfile_best-practices/) in the Docker documentation. These will be the foundation of the review process performed by the official images maintainers. If you'd like the review process,false,Dockerfile
29,560,600,"will be the foundation of the review process performed by the official images maintainers. If you'd like the review process to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines),",false,Dockerfile
30,580,620,"to go more smoothly, please ensure that your `Dockerfile`s adhere to all the points mentioned there, as well as [below](README.md#review-guidelines), before submitting a pull request. Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs),",false,Dockerfile
31,600,640,"before submitting a pull request. Also, the Hub descriptions for these images are currently stored separately in the [`docker-library/docs` repository](https://github.com/docker-library/docs), whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit",false,
32,620,660,"whose [`README.md` file](https://github.com/docker-library/docs/blob/master/README.md) explains more about how it's structured and how to contribute to it. Please be prepared to submit a PR there as well, pending acceptance of your image here. ### Review Guidelines Because the official images are intended",false,
33,640,680,"a PR there as well, pending acceptance of your image here. ### Review Guidelines Because the official images are intended to be learning tools for those new to Docker as well as the base images for advanced users to build",false,
34,660,700,"to be learning tools for those new to Docker as well as the base images for advanced users to build their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability.",false,Dockerfile
35,680,720,"their production releases, we review each proposed `Dockerfile` to ensure that it meets a minimum standard for quality and maintainability. While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while",false,Dockerfile
36,700,740,"While some of that standard is hard to define (due to subjectivity), as much as possible is defined here, while also adhering to the ""Best Practices"" where appropriate. A checklist which may be used by the maintainers during review can",false,
37,720,760,"also adhering to the ""Best Practices"" where appropriate. A checklist which may be used by the maintainers during review can be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md). #### Maintainership Version bumps and security fixes should be attended to in a timely manner. If",false,
38,740,780,"be found in [`NEW-IMAGE-CHECKLIST.md`](NEW-IMAGE-CHECKLIST.md). #### Maintainership Version bumps and security fixes should be attended to in a timely manner. If you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a",false,
39,760,800,"you do not represent upstream and upstream becomes interested in maintaining the image, steps should be taken to ensure a smooth transition of image maintainership over to upstream. For upstreams interested in taking over maintainership of an existing repository, the",false,
40,780,820,"smooth transition of image maintainership over to upstream. For upstreams interested in taking over maintainership of an existing repository, the first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known",false,
41,800,840,"first step is to get involved in the existing repository. Making comments on issues, proposing changes, and making yourself known within the ""image community"" (even if that ""community"" is just the current maintainer) are all important places to start to",false,
42,820,860,"within the ""image community"" (even if that ""community"" is just the current maintainer) are all important places to start to ensure that the transition is unsurprising to existing contributors and users. When taking over an existing repository, please ensure that",false,
43,840,880,"ensure that the transition is unsurprising to existing contributors and users. When taking over an existing repository, please ensure that the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review",true,
44,860,900,"the entire Git history of the original repository is kept in the new upstream-maintained repository to make sure the review process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but",true,FROM
45,880,920,"process isn't stalled during the transition. This is most easily accomplished by forking the new from the existing repository, but can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie,",true,FROM
46,900,940,"can also be accomplished by fetching the commits directly from the original and pushing them into the new repo (ie, `git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the",true,FROM
47,920,960,"`git fetch https://github.com/jsmith/example.git master`, `git rebase FETCH_HEAD`, `git push -f`). On GitHub, an alternative is to move ownership of the git repository. This can be accomplished without giving either group admin access to the other owner's repository: - create temporary",false,
48,940,980,git repository. This can be accomplished without giving either group admin access to the other owner's repository: - create temporary intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help - give old and new,false,
49,960,1000,intermediary organization - [docker-library-transitioner](https://github.com/docker-library-transitioner) is available for this purpose if you would like our help - give old and new owners admin access to intermediary organization - old owner transfers repo ownership to intermediary organization - new owner transfers repo,false,
50,980,1020,owners admin access to intermediary organization - old owner transfers repo ownership to intermediary organization - new owner transfers repo ownership to its new home - recommend that old owner does not fork new repo back into the old organization,false,
51,1000,1040,ownership to its new home - recommend that old owner does not fork new repo back into the old organization to ensure that GitHub redirects will just work #### Repeatability Rebuilding the same `Dockerfile` should result in the same version,false,Dockerfile
52,1020,1060,"to ensure that GitHub redirects will just work #### Repeatability Rebuilding the same `Dockerfile` should result in the same version of the image being packaged, even if the second build happens several versions later, or the build should fail outright,",false,Dockerfile
53,1040,1080,"of the image being packaged, even if the second build happens several versions later, or the build should fail outright, such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using",false,Dockerfile
54,1060,1100,"such that an inadvertent rebuild of a `Dockerfile` tagged as `0.1.0` doesn't end up containing `0.2.3`. For example, if using `apt` to install the main program for the image, be sure to pin it to a specific version (ex: `...",false,Dockerfile
55,1080,1120,"`apt` to install the main program for the image, be sure to pin it to a specific version (ex: `... apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them",true,
56,1100,1140,"apt-get install -y my-package=0.1.0 ...`). For dependent packages installed by `apt` there is not usually a need to pin them to a version. No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and",true,FROM
57,1120,1160,"to a version. No official images can be derived from, or depend on, non-official images (allowing the non-image [`scratch`](https://hub.docker.com/_/scratch/) and the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)). #### Consistency All official images should provide a consistent",true,FROM
58,1140,1180,the intentionally limited exceptions pinned in [`.external-pins`](.external-pins) -- see also [`.external-pins/list.sh`](.external-pins/list.sh)). #### Consistency All official images should provide a consistent interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`.,true,RUN
59,1160,1200,"interface. A beginning user should be able to `docker run official-image bash` (or `sh`) without needing to learn about `--entrypoint`. It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1",true,RUN
60,1180,1220,"It is also nice for advanced users to take advantage of entrypoint, so that they can `docker run official-image --arg1 --arg2` without having to specify the binary to execute. 1. If the startup process does not need arguments, just use",true,RUN
61,1200,1240,"--arg2` without having to specify the binary to execute. 1. If the startup process does not need arguments, just use `CMD`: ```Dockerfile CMD [""irb""] ``` 2. If there is initialization that needs to be done on start, like creating the",false,Dockerfile|CMD
62,1220,1260,"`CMD`: ```Dockerfile CMD [""irb""] ``` 2. If there is initialization that needs to be done on start, like creating the initial database, use an `ENTRYPOINT` along with `CMD`: ```Dockerfile ENTRYPOINT [""/docker-entrypoint.sh""] CMD [""postgres""] ``` 1. Ensure that `docker run official-image",true,Dockerfile|RUN|CMD
63,1240,1280,"initial database, use an `ENTRYPOINT` along with `CMD`: ```Dockerfile ENTRYPOINT [""/docker-entrypoint.sh""] CMD [""postgres""] ``` 1. Ensure that `docker run official-image bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something",true,Dockerfile|RUN|CMD
64,1260,1300,"bash` (or `sh`) works too. The easiest way is to check for the expected command and if it is something else, just `exec ""$@""` (run whatever was passed, properly keeping the arguments escaped). ```sh #!/bin/sh set -e # this if",true,RUN
65,1280,1320,"else, just `exec ""$@""` (run whatever was passed, properly keeping the arguments escaped). ```sh #!/bin/sh set -e # this if will check if the first argument is a flag # but only works if all arguments require a hyphenated flag",true,RUN
66,1300,1340,"will check if the first argument is a flag # but only works if all arguments require a hyphenated flag # -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ ""$#"" -eq 0 ] || [",false,
67,1320,1360,"# -v; -SL; -f arg; etc will work, but not arg1 arg2 if [ ""$#"" -eq 0 ] || [ ""${1#-}"" != ""$1"" ]; then set -- mongod ""$@"" fi # check for the expected command if [ ""$1"" =",false,
68,1340,1380,"""${1#-}"" != ""$1"" ]; then set -- mongod ""$@"" fi # check for the expected command if [ ""$1"" = 'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu",false,
69,1360,1400,"'mongod' ]; then # init db stuff.... # use gosu (or su-exec) to drop to a non-root user exec gosu mongod ""$@"" fi # else default to run whatever the user wanted like ""bash"" or ""sh"" exec ""$@"" ``` 3.",true,RUN
70,1380,1420,"mongod ""$@"" fi # else default to run whatever the user wanted like ""bash"" or ""sh"" exec ""$@"" ``` 3. If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to",true,RUN
71,1400,1440,"If the image only contains the main executable and its linked libraries (ie no shell) then it is fine to use the executable as the `ENTRYPOINT`, since that is the only thing that can run: ```Dockerfile ENTRYPOINT [""fully-static-binary""] CMD [""--help""]",true,Dockerfile|RUN|CMD
72,1420,1460,"use the executable as the `ENTRYPOINT`, since that is the only thing that can run: ```Dockerfile ENTRYPOINT [""fully-static-binary""] CMD [""--help""] ``` The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`).",true,Dockerfile|FROM|RUN|CMD
73,1440,1480,"``` The most common indicator of whether this is appropriate is that the image `Dockerfile` starts with [`scratch`](https://registry.hub.docker.com/_/scratch/) (`FROM scratch`). #### Clarity Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to",true,Dockerfile|FROM
74,1460,1500,"#### Clarity Try to make the `Dockerfile` easy to understand/read. It may be tempting, for the sake of brevity, to put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes",true,Dockerfile|RUN
75,1480,1520,"put complicated initialization details into a standalone script and merely add a `RUN` command in the `Dockerfile`. However, this causes the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to",true,Dockerfile|RUN
76,1500,1540,"the resulting `Dockerfile` to be overly opaque, and such `Dockerfile`s are unlikely to pass review. Instead, it is recommended to put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples,",true,Dockerfile|RUN|ENV
77,1520,1560,"put all the commands for initialization into the `Dockerfile` as appropriate `RUN` or `ENV` command combinations. To find good examples, look at the current official images. Some examples at the time of writing: - [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile) - [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile) - [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile) ####",true,Dockerfile|RUN|ENV
78,1540,1580,look at the current official images. Some examples at the time of writing: - [php](https://github.com/docker-library/php/blob/b4aeb948e2e240c732d78890ff03285b16e8edda/5.6/Dockerfile) - [python](https://github.com/docker-library/python/blob/3e5826ad0c6e29f07f6dc7ff8f30b4c54385d1bb/3.4/Dockerfile) - [ruby:2.2](https://github.com/docker-library/ruby/blob/e34b201a0f0b49818fc8373f6a9148e13d546bdf/2.2/Dockerfile) #### init Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly,false,Dockerfile
79,1560,1600,"init Following the Docker guidelines it is highly recommended that the resulting image be just one concern per container; predominantly this means just one process per container, so there is no need for a full init system. There are two",false,
80,1580,1620,"this means just one process per container, so there is no need for a full init system. There are two situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched",false,
81,1600,1640,"situations where an init-like process would be helpful for the container. The first being signal handling. If the process launched does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see",false,
82,1620,1660,"does not handle `SIGTERM` by exiting, it will not be killed since it is PID 1 in the container (see ""NOTE"" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If",true,RUN
83,1640,1680,"""NOTE"" at the end of the [Foreground section](https://docs.docker.com/engine/reference/run/#foreground) in the docker docs). The second situation would be zombie reaping. If the process spawns child processes and does not properly reap them it will lead to a full process table, which",true,RUN
84,1660,1700,"the process spawns child processes and does not properly reap them it will lead to a full process table, which can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is",true,FROM
85,1680,1720,"can prevent the whole system from spawning any new processes. For both of these concerns we recommend [tini](https://github.com/krallin/tini). It is incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and",true,FROM
86,1700,1740,"incredibly small, has minimal external dependencies, fills each of these roles, and does only the necessary parts of reaping and signal forwarding. Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate. It is best to install tini from",true,FROM|CMD
87,1720,1760,"signal forwarding. Be sure to use tini in `CMD` or `ENTRYPOINT` as appropriate. It is best to install tini from a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here",true,FROM|CMD
88,1740,1780,"a distribution-provided package (ex. `apt-get install tini`). If tini is not available in your distribution or is too old, here is a snippet of a `Dockerfile` to add in tini: ```Dockerfile # Install tini for signal processing and zombie killing",true,Dockerfile
89,1760,1800,"is a snippet of a `Dockerfile` to add in tini: ```Dockerfile # Install tini for signal processing and zombie killing ENV TINI_VERSION v0.18.0 ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7 RUN set -eux; \ wget -O /usr/local/bin/tini ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini""; \ wget -O /usr/local/bin/tini.asc ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc""; \",true,Dockerfile|RUN|ENV
90,1780,1820,"ENV TINI_VERSION v0.18.0 ENV TINI_SIGN_KEY 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7 RUN set -eux; \ wget -O /usr/local/bin/tini ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini""; \ wget -O /usr/local/bin/tini.asc ""https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc""; \ export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$TINI_SIGN_KEY""; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf",true,RUN|ENV
91,1800,1840,"export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$TINI_SIGN_KEY""; \ gpg --batch --verify /usr/local/bin/tini.asc /usr/local/bin/tini; \ command -v gpgconf && gpgconf --kill all || :; \ rm -r ""$GNUPGHOME"" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version ``` ####",true,
92,1820,1860,"&& gpgconf --kill all || :; \ rm -r ""$GNUPGHOME"" /usr/local/bin/tini.asc; \ chmod +x /usr/local/bin/tini; \ tini --version ``` #### Cacheability This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips",true,
93,1840,1880,"Cacheability This is one place that experience ends up trumping documentation for the path to enlightenment, but the following tips might help: - Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead",false,
94,1860,1900,"might help: - Avoid `COPY`/`ADD` whenever possible, but when necessary, be as specific as possible (ie, `COPY one-file.sh /somewhere/` instead of `COPY . /somewhere`). The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to",false,
95,1880,1920,"of `COPY . /somewhere`). The reason for this is that the cache for `COPY` instructions considers file `mtime` changes to be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of",true,
96,1900,1940,"be a cache bust, which can make the cache behavior of `COPY` unpredictable sometimes, especially when `.git` is part of what needs to be `COPY`ed (for example). - Ensure that lines which are less likely to change come before lines",true,
97,1920,1960,what needs to be `COPY`ed (for example). - Ensure that lines which are less likely to change come before lines that are more likely to change (with the caveat that each line should generate an image that still runs successfully,true,RUN
98,1940,1980,"that are more likely to change (with the caveat that each line should generate an image that still runs successfully without assumptions of later lines). For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come",true,RUN|ENV
99,1960,2000,"without assumptions of later lines). For example, the line that contains the software version number (`ENV MYSOFTWARE_VERSION 4.2`) should come after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`). ####",true,RUN|ENV
100,1980,2020,after a line that sets up the APT repository `.list` file (`RUN echo 'deb http://example.com/mysoftware/debian some-suite main' > /etc/apt/sources.list.d/mysoftware.list`). #### Security ##### Image Build The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on,true,Dockerfile|RUN
101,2000,2040,"Security ##### Image Build The `Dockerfile` should be written to help mitigate interception attacks during build. Our requirements focus on three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using",false,Dockerfile
102,2020,2060,"three main objectives: verifying the source, verifying author, and verifying the content; these are respectively accomplished by the following: using https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in",false,Dockerfile
103,2040,2080,https where possible; importing PGP keys with the full fingerprint in the `Dockerfile` to check signatures; embedding checksums directly in the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature,false,Dockerfile
104,2060,2100,"the `Dockerfile`. All three should be used when possible. Just https and embedded checksum can be used when no signature is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and",false,Dockerfile
105,2080,2120,"is published. As a last resort, just an embedded checksum is acceptable if the site doesn't have https available and no signature. The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the",false,
106,2100,2140,no signature. The purpose in recommending the use of https for downloading needed artifacts is that it ensures that the download is from a trusted source which also happens to make interception much more difficult. The purpose in recommending PGP,true,FROM
107,2120,2160,"download is from a trusted source which also happens to make interception much more difficult. The purpose in recommending PGP signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use",true,FROM
108,2140,2180,"signature verification is to ensure that only an authorized user published the given artifact. When importing PGP keys, please use the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification). The purpose",false,
109,2160,2200,"the [the `keys.openpgp.org` service](https://keys.openpgp.org/about) when possible (preferring `keyserver.ubuntu.com` otherwise). See also the FAQ section on [keys and verification](https://github.com/docker-library/faq/#openpgp--gnupg-keys-and-verification). The purpose in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes,",false,
110,2180,2220,"in recommending checksum verification is to verify that the artifact is as expected. This ensures that when remote content changes, the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally",false,Dockerfile
111,2200,2240,"the Dockerfile also will change and provide a natural `docker build` cache bust. As a bonus, this also prevents accidentally downloading newer-than-expected artifacts on poorly versioned files. Below are some examples: - **Preferred**: *download over https, PGP key full fingerprint",false,Dockerfile
112,2220,2260,"downloading newer-than-expected artifacts on poorly versioned files. Below are some examples: - **Preferred**: *download over https, PGP key full fingerprint import and `asc` verification, embedded checksum verified.* ```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz"" -o python.tar.xz;",true,Dockerfile|RUN|ENV|PYTHON_VERSION
113,2240,2280,"import and `asc` verification, embedded checksum verified.* ```Dockerfile ENV PYTHON_DOWNLOAD_SHA512 (sha512-value-here) RUN set -eux; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz"" -o python.tar.xz; \ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc"" -o python.tar.xz.asc; \ export GNUPGHOME=""$(mktemp -d)""; \ # gpg: key F73C700D: public key ""Larry Hastings """,true,Dockerfile|RUN|ENV|PYTHON_VERSION
114,2260,2300,"\ curl -fL ""https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tar.xz.asc"" -o python.tar.xz.asc; \ export GNUPGHOME=""$(mktemp -d)""; \ # gpg: key F73C700D: public key ""Larry Hastings "" imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r ""$GNUPGHOME"" python.tar.xz.asc; \ echo",true,PYTHON_VERSION
115,2280,2320,"imported gpg --batch --keyserver keyserver.ubuntu.com --recv-keys 97FC712E4C024BBEA48A61ED3A5CA953F73C700D; \ gpg --batch --verify python.tar.xz.asc python.tar.xz; \ rm -r ""$GNUPGHOME"" python.tar.xz.asc; \ echo ""$PYTHON_DOWNLOAD_SHA512 *python.tar.xz"" | sha512sum --strict --check; \ # install ``` - **Alternate**: *full key fingerprint imported to apt which will",true,
116,2300,2340,"""$PYTHON_DOWNLOAD_SHA512 *python.tar.xz"" | sha512sum --strict --check; \ # install ``` - **Alternate**: *full key fingerprint imported to apt which will check signatures and checksums when packages are downloaded and installed.* ```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME=""$(mktemp -d)"";",true,Dockerfile|RUN
117,2320,2360,"check signatures and checksums when packages are downloaded and installed.* ```Dockerfile RUN set -eux; \ key='A4A9406876FCBD3C456770C88C718D3B5072E1F5'; \ export GNUPGHOME=""$(mktemp -d)""; \ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$key""; \ gpg --batch --armor --export ""$key"" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \",true,Dockerfile|RUN
118,2340,2380,"\ gpg --batch --keyserver keyserver.ubuntu.com --recv-keys ""$key""; \ gpg --batch --armor --export ""$key"" > /etc/apt/keyrings/mysql.asc; \ gpgconf --kill all; \ rm -rf ""$GNUPGHOME""; \ apt-key list > /dev/null RUN set -eux; \ echo ""deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}""",true,RUN
119,2360,2400,"rm -rf ""$GNUPGHOME""; \ apt-key list > /dev/null RUN set -eux; \ echo ""deb [ signed-by=/etc/apt/keyrings/mysql.asc ] http://repo.mysql.com/apt/debian/ bookworm mysql-${MYSQL_MAJOR}"" > /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client=""${MYSQL_VERSION}"" mysql-community-server-core=""${MYSQL_VERSION}""; \ rm -rf /var/lib/apt/lists/*; \ # ... ``` (As",true,RUN
120,2380,2420,"> /etc/apt/sources.list.d/mysql.list; \ apt-get update; \ apt-get install -y mysql-community-client=""${MYSQL_VERSION}"" mysql-community-server-core=""${MYSQL_VERSION}""; \ rm -rf /var/lib/apt/lists/*; \ # ... ``` (As a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't",true,
121,2400,2440,"a side note, `rm -rf /var/lib/apt/lists/*` is *roughly* the opposite of `apt-get update` -- it ensures that the layer doesn't include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).) - **Less Secure Alternate**: *embed",true,Dockerfile
122,2420,2460,"include the extra ~8MB of APT package list data, and enforces [appropriate `apt-get update` usage](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#apt-get).) - **Less Secure Alternate**: *embed the checksum into the `Dockerfile`.* ```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz ""https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz""; \ echo",true,Dockerfile|RUN|ENV
123,2440,2480,"the checksum into the `Dockerfile`.* ```Dockerfile ENV RUBY_DOWNLOAD_SHA256 (sha256-value-here) RUN set -eux; \ curl -fL -o ruby.tar.gz ""https://cache.ruby-lang.org/pub/ruby/$RUBY_MAJOR/ruby-$RUBY_VERSION.tar.gz""; \ echo ""$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz"" | sha256sum --strict --check; \ # install ``` - **Note:** the use of either SHA1 or MD5 should",true,Dockerfile|RUN|ENV
124,2460,2500,"""$RUBY_DOWNLOAD_SHA256 *ruby.tar.gz"" | sha256sum --strict --check; \ # install ``` - **Note:** the use of either SHA1 or MD5 should be considered a ""checksum of last resort"" as both are considered generally unsafe: - [""Single-block collision for MD5"" from 2012](https://marc-stevens.nl/research/md5-1block-collision/)",true,FROM
125,2480,2520,"be considered a ""checksum of last resort"" as both are considered generally unsafe: - [""Single-block collision for MD5"" from 2012](https://marc-stevens.nl/research/md5-1block-collision/) - [""Announcing the first SHA1 collision"" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html) - **Unacceptable**: *download the file over http(s) with no verification.* ```Dockerfile RUN",true,Dockerfile|FROM|RUN
126,2500,2540,"- [""Announcing the first SHA1 collision"" from 2017](https://security.googleblog.com/2017/02/announcing-first-sha1-collision.html) - **Unacceptable**: *download the file over http(s) with no verification.* ```Dockerfile RUN curl -fL ""https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz"" | tar ... \ # install ``` ##### Runtime Configuration By default, Docker containers are executed with",true,Dockerfile|FROM|RUN
127,2520,2560,"curl -fL ""https://julialang.s3.amazonaws.com/bin/linux/x64/${JULIA_VERSION%[.-]*}/julia-${JULIA_VERSION}-linux-x86_64.tar.gz"" | tar ... \ # install ``` ##### Runtime Configuration By default, Docker containers are executed with reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a",true,RUN
128,2540,2580,"reduced privileges: whitelisted Linux capabilities, Control Groups, and a default Seccomp profile (1.10+ w/ host support). Software running in a container may require additional privileges in order to function correctly, and there are a number of command line options to",true,RUN
129,2560,2600,"container may require additional privileges in order to function correctly, and there are a number of command line options to customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference. Official Repositories that require additional privileges should",true,RUN
130,2580,2620,"customize container execution. See [`docker run` Reference](https://docs.docker.com/engine/reference/run/) and [Seccomp for Docker](https://docs.docker.com/engine/security/seccomp/) for reference. Official Repositories that require additional privileges should specify the minimal set of command line options for the software to function, and may still be rejected if this",true,RUN
131,2600,2640,"specify the minimal set of command line options for the software to function, and may still be rejected if this introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options",false,
132,2620,2660,"introduces significant portability or security issues. In general, `--privileged` is not allowed, but a combination of `--cap-add` and `--device` options may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g.",false,
133,2640,2680,"may be acceptable. Additionally, `--volume` can be tricky as there are many host filesystem locations that introduce portability/security issues (e.g. X11 socket). ##### Security Releases For image updates which constitute a security fix, there are a few things we recommend",false,
134,2660,2700,"X11 socket). ##### Security Releases For image updates which constitute a security fix, there are a few things we recommend to help ensure your update is merged, built, and released as quickly as possible: 1. [Send an email to `doi@docker.com`](mailto:doi@docker.com)",false,
135,2680,2720,"to help ensure your update is merged, built, and released as quickly as possible: 1. [Send an email to `doi@docker.com`](mailto:doi@docker.com) a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule",false,
136,2700,2740,"a few (business) days in advance to give us a heads up and a timing estimate (so we can schedule time for the incoming update appropriately). 2. Include `[security]` in the title of your pull request (for example, `[security] Update",false,
137,2720,2760,"time for the incoming update appropriately). 2. Include `[security]` in the title of your pull request (for example, `[security] Update FooBar to 1.2.5, 1.3.7, 2.0.1`). 3. Keep the pull request free of changes that are unrelated to the security fix",false,
138,2740,2780,"FooBar to 1.2.5, 1.3.7, 2.0.1`). 3. Keep the pull request free of changes that are unrelated to the security fix -- we'll still be doing review of the update, but it will be expedited so this will help us help",false,
139,2760,2800,"-- we'll still be doing review of the update, but it will be expedited so this will help us help you. 4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more",false,
140,2780,2820,"you. 4. Be active and responsive to comments on the pull request after it's opened (as usual, but even more so if the timing of the release is of importance). #### Multiple Architectures Each repo can specify multiple architectures for",false,
141,2800,2840,"so if the timing of the release is of importance). #### Multiple Architectures Each repo can specify multiple architectures for any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify",false,Tags
142,2820,2860,"any and all tags. If no architecture is specified, images are built in Linux on `amd64` (aka x86-64). To specify more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go`",false,Tags
143,2840,2880,"more or different architectures, use the `Architectures` field (comma-delimited list, whitespace is trimmed). Valid architectures are found in [Bashbrew's `oci-platform.go` file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27): - `amd64` - `arm32v6` - `arm32v7` - `arm64v8` - `i386` - `ppc64le` - `riscv64` - `s390x` - `windows-amd64` The",false,
144,2860,2900,file](https://github.com/docker-library/bashbrew/blob/v0.1.2/architecture/oci-platform.go#L14-L27): - `amd64` - `arm32v6` - `arm32v7` - `arm64v8` - `i386` - `ppc64le` - `riscv64` - `s390x` - `windows-amd64` The `Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`. Images,true,FROM
145,2880,2920,`Architectures` of any given tag must be a strict subset of the `Architectures` of the tag it is `FROM`. Images must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means,true,Dockerfile|FROM
146,2900,2940,"must have a single `Dockerfile` per entry in the library file that can be used for multiple architectures. This means that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for",true,Dockerfile|FROM
147,2920,2960,"that each supported architecture will have the same `FROM` line (e.g. `FROM debian:bookworm`). See [`golang`](https://github.com/docker-library/official-images/blob/master/library/golang), [`docker`](https://github.com/docker-library/official-images/blob/master/library/docker), [`haproxy`](https://github.com/docker-library/official-images/blob/master/library/haproxy), and [`php`](https://github.com/docker-library/official-images/blob/master/library/php) for examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s. If different",true,Dockerfile|FROM
148,2940,2980,"examples of library files using one `Dockerfile` per entry and see their respective git repos for example `Dockerfile`s. If different parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or",false,Dockerfile
149,2960,3000,"parts of the Dockerfile only happen in one architecture or another, use control flow (e.g.`if`/`case`) along with `dpkg --print-architecture` or `apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed.",false,Dockerfile
150,2980,3020,`apk -print-arch` to detect the userspace architecture. Only use `uname` for architecture detection when more accurate tools cannot be installed. See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download,true,Dockerfile|FROM
151,3000,3040,See [golang](https://github.com/docker-library/golang/blob/72bc141d781ae54ef20f71aa1105449cb6c2edc4/1.20/bookworm/Dockerfile#L26-L63) for an example where some architectures require building binaries from the upstream source packages and some merely download the binary release. For base images like `debian` it will be necessary to have a different `Dockerfile` and build context,true,Dockerfile|FROM
152,3020,3060,the binary release. For base images like `debian` it will be necessary to have a different `Dockerfile` and build context in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use,false,Dockerfile
153,3040,3080,"in order to `ADD` architecture specific binaries and this is a valid exception to the above. Since these images use the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`,",false,Tags|GitRepo
154,3060,3100,"the same `Tags`, they need to be in the same entry. Use the architecture specific fields for `GitRepo`, `GitFetch`, `GitCommit`, and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not",false,Tags|GitRepo
155,3080,3120,"and `Directory`, which are the architecture concatenated with hyphen (`-`) and the field (e.g. `arm32v7-GitCommit`). Any architecture that does not have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See",false,
156,3100,3140,have an architecture-specific field will use the default field (e.g. no `arm32v7-Directory` means `Directory` will be used for `arm32v7`). See the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world): ``` Maintainers: Tianon,false,
157,3120,3160,"the [`debian`](https://github.com/docker-library/official-images/blob/master/library/debian) or [`ubuntu`](https://github.com/docker-library/official-images/blob/master/library/ubuntu) files in the library for examples. The following is an example for [`hello-world`](https://github.com/docker-library/official-images/blob/master/library/hello-world): ``` Maintainers: Tianon Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/hello-world.git GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Tags: latest Architectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x # all",false,Tags|GitRepo
158,3140,3180,"Gravi (@tianon), Joseph Ferguson (@yosifkit) GitRepo: https://github.com/docker-library/hello-world.git GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Tags: latest Architectures: amd64, arm32v5, arm32v7, arm64v8, ppc64le, s390x # all the same commit; easy for us to generate this way since they could be different amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 amd64-Directory: amd64/hello-world arm32v5-GitCommit:",false,Tags|GitRepo
159,3160,3200,the same commit; easy for us to generate this way since they could be different amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 amd64-Directory: amd64/hello-world arm32v5-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v5-Directory: arm32v5/hello-world arm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v7-Directory: arm32v7/hello-world arm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm64v8-Directory: arm64v8/hello-world ppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 ppc64le-Directory: ppc64le/hello-world s390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 s390x-Directory: s390x/hello-world Tags:,false,Tags
160,3180,3220,"7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v5-Directory: arm32v5/hello-world arm32v7-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm32v7-Directory: arm32v7/hello-world arm64v8-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 arm64v8-Directory: arm64v8/hello-world ppc64le-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 ppc64le-Directory: ppc64le/hello-world s390x-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 s390x-Directory: s390x/hello-world Tags: nanoserver Architectures: windows-amd64 # if there is only one architecture, you can use the unprefixed fields Directory: amd64/hello-world/nanoserver # or",false,Tags
161,3200,3240,"nanoserver Architectures: windows-amd64 # if there is only one architecture, you can use the unprefixed fields Directory: amd64/hello-world/nanoserver # or use the prefixed versions windows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Constraints: nanoserver ``` See the [instruction format section](#instruction-format) for more information on the format",false,
162,3220,3260,use the prefixed versions windows-amd64-GitCommit: 7d0ee592e4ed60e2da9d59331e16ecdcadc1ed87 Constraints: nanoserver ``` See the [instruction format section](#instruction-format) for more information on the format of the library file. ### Commitment Proposing a new official image should not be undertaken lightly. We expect and require,false,
163,3240,3280,"of the library file. ### Commitment Proposing a new official image should not be undertaken lightly. We expect and require a commitment to maintain your image (including and especially timely updates as appropriate, as noted above). ## Library definition files",false,
164,3260,3300,"a commitment to maintain your image (including and especially timely updates as appropriate, as noted above). ## Library definition files The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file",false,
165,3280,3320,"The library definition files are plain text files found in the [`library/` directory of the `official-images` repository](https://github.com/docker-library/official-images/tree/master/library). Each library file controls the current ""supported"" set of image tags that appear on the Docker Hub description. Tags that are removed from",true,FROM|Tags
166,3300,3340,"controls the current ""supported"" set of image tags that appear on the Docker Hub description. Tags that are removed from a library file do not get removed from the Docker Hub, so that old versions can continue to be available",true,FROM|Tags
167,3320,3360,"a library file do not get removed from the Docker Hub, so that old versions can continue to be available for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file",true,FROM|Tags
168,3340,3380,"for use, but are not maintained by upstream or the maintainer of the official image. Tags in the library file are only built through an update to that library file or as a result of its base image being updated",false,Tags
169,3360,3400,"are only built through an update to that library file or as a result of its base image being updated (ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will",true,FROM
170,3380,3420,"(ie, an image `FROM debian:bookworm` would be rebuilt when `debian:bookworm` is built). Only what is in the library file will be rebuilt when a base has updates. Given this policy, it is worth clarifying a few cases: backfilled versions, release",true,FROM
171,3400,3440,"be rebuilt when a base has updates. Given this policy, it is worth clarifying a few cases: backfilled versions, release candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions",false,
172,3420,3460,"candidates, and continuous integration builds. When a new repository is proposed, it is common to include some older unsupported versions in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive",false,
173,3440,3480,"in the initial pull request with the agreement to remove them right after acceptance. Don't confuse this with a comprehensive historical archive which is not the intention. Another common case where the term ""supported"" is stretched a bit is with",false,
174,3460,3500,"historical archive which is not the intention. Another common case where the term ""supported"" is stretched a bit is with release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so",false,
175,3480,3520,"release candidates. A release candidate is really just a naming convention for what are expected to be shorter-lived releases, so they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle",false,
176,3500,3540,"they are totally acceptable and encouraged. Unlike a release candidate, continuous integration builds which have a fully automated release cycle based on code commits or a regular schedule are not appropriate. It is highly recommended that you browse some of",false,
177,3520,3560,based on code commits or a regular schedule are not appropriate. It is highly recommended that you browse some of the existing `library/` file contents (and history to get a feel for how they change over time) before creating a,false,
178,3540,3580,the existing `library/` file contents (and history to get a feel for how they change over time) before creating a new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can,false,
179,3560,3600,new one to become familiar with the prevailing conventions and further help streamline the review process (so that we can focus on content instead of esoteric formatting or tag usage/naming). ### Filenames The filename of a definition file will determine,false,
180,3580,3620,"focus on content instead of esoteric formatting or tag usage/naming). ### Filenames The filename of a definition file will determine the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags",false,Tags
181,3600,3640,"the name of the image repository it creates on the Docker Hub. For example, the `library/ubuntu` file will create tags in the `ubuntu` repository. ### Tags and aliases The tags of a repository should reflect upstream's versions or variations. For",false,Tags
182,3620,3660,"in the `ubuntu` repository. ### Tags and aliases The tags of a repository should reflect upstream's versions or variations. For example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so",false,Tags
183,3640,3680,"example, Ubuntu 14.04 is also known as Ubuntu Trusty Tahr, but often as simply Ubuntu Trusty (especially in usage), so `ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag",false,
184,3660,3700,"`ubuntu:14.04` (version number) and `ubuntu:trusty` (version name) are appropriate aliases for the same image contents. In Docker, the `latest` tag is a special case, but it's a bit of a misnomer; `latest` really is the ""default"" tag. When one does",false,
185,3680,3720,"is a special case, but it's a bit of a misnomer; `latest` really is the ""default"" tag. When one does `docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the",true,RUN
186,3700,3740,"`docker run xyz`, Docker interprets that to mean `docker run xyz:latest`. Given that background, no other tag ever contains the string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be",true,RUN
187,3720,3760,"string `latest`, since it's not something users are expected or encouraged to actually type out (ie, `xyz:latest` should really be used as simply `xyz`). Put another way, having an alias for the ""highest 2.2-series release of XYZ"" should be `xyz:2.2`,",false,
188,3740,3780,"used as simply `xyz`). Put another way, having an alias for the ""highest 2.2-series release of XYZ"" should be `xyz:2.2`, not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or",false,
189,3760,3800,"not `xyz:2.2-latest`. Similarly, if there is an Alpine variant of `xyz:latest`, it should be aliased as `xyz:alpine`, not `xyz:alpine-latest` or `xyz:latest-alpine`. It is strongly encouraged that version number tags be given aliases which make it easy for the user to",true,Tags
190,3780,3820,"`xyz:latest-alpine`. It is strongly encouraged that version number tags be given aliases which make it easy for the user to stay on the ""most recent"" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7",true,Tags
191,3800,3840,"stay on the ""most recent"" release of a particular series. For example, given currently supported XYZ Software versions of 2.3.7 and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the",false,Tags
192,3820,3860,"and 2.2.4, suggested aliases would be `Tags: 2.3.7, 2.3, 2, latest` and `Tags: 2.2.4, 2.2`, respectively. In this example, the user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less",false,Tags
193,3840,3880,"user can use `xyz:2.2` to easily use the most recent patch release of the 2.2 series, or `xyz:2` if less granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very",false,
194,3860,3900,"granularity is needed (Python is a good example of where that's most obviously useful -- `python:2` and `python:3` are very different, and can be thought of as the `latest` tag for each of the major release tracks of Python). As",false,
195,3880,3920,"different, and can be thought of as the `latest` tag for each of the major release tracks of Python). As described above, `latest` is really ""default"", so the image that it is an alias for should reflect which version or",false,
196,3900,3940,"described above, `latest` is really ""default"", so the image that it is an alias for should reflect which version or variation of the software users should use if they do not know or do not care which version they use.",false,
197,3920,3960,"variation of the software users should use if they do not know or do not care which version they use. Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority",false,
198,3940,3980,"Using Ubuntu as an example, `ubuntu:latest` points to the most recent LTS release, given that it is what the majority of users should be using if they know they want Ubuntu but do not know or care which version (especially",false,
199,3960,4000,"of users should be using if they know they want Ubuntu but do not know or care which version (especially considering it will be the most ""stable"" and well-supported release at any given time). ### Instruction format The manifest file",false,
200,3980,4020,"considering it will be the most ""stable"" and well-supported release at any given time). ### Instruction format The manifest file format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with",false,
201,4000,4040,"format is officially based on [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt), and as such should be familiar to folks who are already familiar with the ""headers"" of many popular internet protocols/formats such as HTTP or email. The primary additions are inspired by the way",false,
202,4020,4060,"the ""headers"" of many popular internet protocols/formats such as HTTP or email. The primary additions are inspired by the way Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and ""entries"" are separated by a blank line.",false,
203,4040,4080,"Debian commonly uses 2822 -- namely, lines starting with `#` are ignored and ""entries"" are separated by a blank line. The first entry is the ""global"" metadata for the image. The only required field in the global entry is `Maintainers`,",false,
204,4060,4100,"The first entry is the ""global"" metadata for the image. The only required field in the global entry is `Maintainers`, whose value is comma-separated in the format of `Name (@github)` or `Name (@github)`. Any field specified in the global entry",false,
205,4080,4120,whose value is comma-separated in the format of `Name (@github)` or `Name (@github)`. Any field specified in the global entry will be the default for the rest of the entries and can be overridden in an individual entry. # this,false,
206,4100,4140,"will be the default for the rest of the entries and can be overridden in an individual entry. # this is a comment and will be ignored Maintainers: John Smith (@example-jsmith), Anne Smith (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this",false,GitRepo
207,4120,4160,"is a comment and will be ignored Maintainers: John Smith (@example-jsmith), Anne Smith (@example-asmith) GitRepo: https://github.com/example/docker-example.git GitCommit: deadbeefdeadbeefdeadbeefdeadbeefdeadbeef # this is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc,",false,Tags|GitRepo
208,4140,4180,"is also a comment, and will also be ignored Tags: 1.2.3, 1.2, 1, latest Directory: 1 Tags: 2.0-rc1, 2.0-rc, 2-rc, rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use Bashbrew will fetch code out of the Git repository",false,Dockerfile|Tags|GitRepo
209,4160,4200,"rc GitRepo: https://github.com/example/docker-example-rc.git GitFetch: refs/heads/2.0-pre-release GitCommit: beefdeadbeefdeadbeefdeadbeefdeadbeefdead Directory: 2 File: Dockerfile-to-use Bashbrew will fetch code out of the Git repository (`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`,",false,Dockerfile|GitRepo
210,4180,4220,"(`GitRepo`) at the commit specified (`GitCommit`). If the commit referenced is not available by fetching `master` of the associated `GitRepo`, it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order",false,GitRepo
211,4200,4240,"it becomes necessary to supply a value for `GitFetch` in order to tell Bashbrew what ref to fetch in order to get the commit necessary. The built image will be tagged as ` : ` (ie, `library/golang` with a `Tags`",false,Tags
212,4220,4260,"to get the commit necessary. The built image will be tagged as ` : ` (ie, `library/golang` with a `Tags` value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`). Optionally, if `Directory` is present, Bashbrew will",false,Tags
213,4240,4280,"value of `1.6, 1, latest` will create tags of `golang:1.6`, `golang:1`, and `golang:latest`). Optionally, if `Directory` is present, Bashbrew will look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the",false,Dockerfile|Tags
214,4260,4300,"look for the `Dockerfile` inside the specified subdirectory instead of at the root (and `Directory` will be used as the [""context"" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of",false,Dockerfile
215,4280,4320,"[""context"" for the build](https://docs.docker.com/reference/builder/) instead of the top-level of the repository). If `File` is present, the specified filename instead of `Dockerfile` will be used. See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or",false,Dockerfile|GitRepo
216,4300,4340,"`Dockerfile` will be used. See the [multi-arch section](#multiple-architectures) for details on how to specify a different `GitRepo`, `GitFetch`, `GitCommit`, or `Directory` for a specific architecture. ### Creating a new repository - Create a new file in the `library/` folder. Its",false,Dockerfile|GitRepo
217,4320,4360,`Directory` for a specific architecture. ### Creating a new repository - Create a new file in the `library/` folder. Its name will be the name of your repository on the Hub. - Add your tag definitions using the appropriate syntax,false,
218,4340,4380,name will be the name of your repository on the Hub. - Add your tag definitions using the appropriate syntax (see above). - Create a pull request adding the file from your forked repository to this one. Please be sure,true,FROM
219,4360,4400,(see above). - Create a pull request adding the file from your forked repository to this one. Please be sure to add details as to what your repository does. ### Adding a new tag in an existing repository (that you're,true,FROM
220,4380,4420,to add details as to what your repository does. ### Adding a new tag in an existing repository (that you're the maintainer of) - Add your tag definition using the instruction format documented above. - Create a pull request from,true,FROM
221,4400,4440,"the maintainer of) - Add your tag definition using the instruction format documented above. - Create a pull request from your Git repository to this one. Please be sure to add details about what's new, if possible. ### Change to",true,FROM
222,4420,4460,"your Git repository to this one. Please be sure to add details about what's new, if possible. ### Change to a tag in an existing repository (that you're the maintainer of) - Update the relevant tag definition using the instruction",false,
223,4440,4480,a tag in an existing repository (that you're the maintainer of) - Update the relevant tag definition using the instruction format documented above. - Create a pull request from your Git repository to this one. Please be sure to add,true,FROM
224,4460,4500,"format documented above. - Create a pull request from your Git repository to this one. Please be sure to add details about what's changed, if possible. ## Bashbrew Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the",true,FROM
225,4480,4511,"details about what's changed, if possible. ## Bashbrew Bashbrew (`bashbrew`) is a tool for cloning, building, tagging, and pushing the Docker official images. See [the Bashbrew `README`](https://github.com/docker-library/bashbrew#readme) for more information. ```",false,1234567891011121314151617181920212223242526272829303132333435{ "software_name": "Docker / Python Official Image", "tutorial_url": "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md", "source_urls": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "source_file": "dockerfile_packaging_corpus.md", "window_file": "dockerfile_text_windows.csv", "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "required_terms": [ "Dockerfile", "FROM", "RUN", "ENV", "CMD", "PYTHON_VERSION", "Tags", "GitRepo" ], "code_terms": [ "apt-get", "curl", "gpg", "make", "FROM", "RUN", "ENV" ], "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180from __future__ import annotations
import importlib.utilimport jsonimport osimport shleximport shutilfrom pathlib import Pathfrom typing import Any
class Task: def __init__(self, task_id: str, description: str, metadata: dict[str, Any]): self.task_id = task_id self.description = description self.prompt = description self.metadata = metadata self.computer = {"setup_config": {"os_type": "linux"}}
def _task_dir() -> Path: return Path(__file__).resolve().parent
def _load_card() -> dict[str, Any]: path = _task_dir() / "task_card.json" if not path.is_file(): return { "taskId": os.environ.get("ALE_TASK_ID", "computing_math/audit_docker_official_image_packaging"), "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.", "metadata": { "domain": "computing_math", "task": "audit_docker_official_image_packaging", "variant": "base", "domain_name": "computing_math", "task_name": "audit_docker_official_image_packaging", "variant_name": "base", "requires_task_data": True, "task_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging/base", "input_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging/base/input", "software_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging/base/software", "remote_output_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging/base/output", "reference_dir": "/media/user/data/agenthle/computing_math/audit_docker_official_image_packaging/base/reference", }, } with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def load() -> list[Task]: card = _load_card() metadata = dict(card.get("metadata") or {}) if not metadata: domain, _, task = str(card["taskId"]).partition("/") variant = "base" task_dir = f"/media/user/data/agenthle/{domain}/{task}/{variant}" metadata.update({ "domain": domain, "task": task, "variant": variant, "domain_name": domain, "task_name": task, "variant_name": variant, "requires_task_data": True, "task_dir": task_dir, "input_dir": f"{task_dir}/input", "software_dir": f"{task_dir}/software", "remote_output_dir": f"{task_dir}/output", "reference_dir": f"{task_dir}/reference", }) return [Task(task_id=card["taskId"], description=card["taskPrompt"], metadata=metadata)]
def _metadata(cfg: Any = None) -> dict[str, Any]: if cfg is None: return {} value = getattr(cfg, "metadata", None) return value if isinstance(value, dict) else {}
def _remote_path(metadata: dict[str, Any], key: str, fallback: str) -> str: value = str(metadata.get(key) or "").strip() return value or fallback
async def _remote_run(session: Any, command: str, *, check: bool = False) -> Any: try: return await session.run_command(command, check=check) except TypeError: return await session.run_command(command)
async def _remote_start(cfg: Any, session: Any) -> dict[str, Any]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") input_dir = _remote_path(metadata, "input_dir", "input") software_dir = _remote_path(metadata, "software_dir", "software") command = ( "set -eu\n" f"mkdir -p {shlex.quote(output_dir)}\n" f"find {shlex.quote(output_dir)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {{}} +\n" ) await _remote_run(session, command, check=True) return {"ok": True, "input_dir": input_dir, "software_dir": software_dir, "output_dir": output_dir}
def start(cfg: Any = None, session: Any = None) -> dict[str, Any]: if session is not None: return _remote_start(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) output_dir.mkdir(parents=True, exist_ok=True) for child in output_dir.iterdir(): if child.is_dir(): shutil.rmtree(child) else: child.unlink() input_dir = Path(os.environ.get("ALE_INPUT_DIR", "input")) software_dir = Path(os.environ.get("ALE_SOFTWARE_DIR", "software")) return { "ok": True, "input_dir": str(input_dir), "software_dir": str(software_dir), "output_dir": str(output_dir), }
async def _remote_evaluate(cfg: Any, session: Any) -> list[float]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") reference_dir = _remote_path(metadata, "reference_dir", "reference") script = f"""import importlib.utilimport jsonimport pathlib
output_dir = pathlib.Path({output_dir!r})reference_dir = pathlib.Path({reference_dir!r})evaluator_path = reference_dir / "evaluator.py"if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {{evaluator_path}}")spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path)if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {{evaluator_path}}")module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)result = module.evaluate(output_dir, reference_dir)print(json.dumps(result))""" command = "python3 - <<'PY'\n" + script + "\nPY" result = await _remote_run(session, command, check=True) stdout = getattr(result, "stdout", "") or "" for line in reversed([item.strip() for item in stdout.splitlines() if item.strip()]): try: payload = json.loads(line) if isinstance(payload, list): return [float(max(0.0, min(1.0, value))) for value in payload] except Exception: continue raise RuntimeError("hidden evaluator did not emit a JSON score list")
def evaluate(cfg: Any = None, session: Any = None) -> list[float]: if session is not None: return _remote_evaluate(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) reference_dir = Path(os.environ.get("ALE_REFERENCE_DIR", "reference")) evaluator_path = reference_dir / "evaluator.py" if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {evaluator_path}") spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) result = module.evaluate(output_dir, reference_dir) if not isinstance(result, list): raise TypeError("hidden evaluator must return list[float]") return [float(max(0.0, min(1.0, value))) for value in result]12345678910term,kind,software_name
apt-get,code_term,Docker / Python Official Image
curl,code_term,Docker / Python Official Image
gpg,code_term,Docker / Python Official Image
make,code_term,Docker / Python Official Image
FROM,code_term,Docker / Python Official Image
RUN,code_term,Docker / Python Official Image
ENV,code_term,Docker / Python Official Image
docker,executable,Docker / Python Official Image
docker build,executable,Docker / Python Official Image12345678910111213141516{ "software_name": "Docker / Python Official Image", "executables": [ "docker", "docker build" ], "required_system_packages": [ "docker.io" ], "official_sources": [ "https://github.com/docker-library/official-images/raw/refs/heads/master/README.md" ], "solve_time_network": "disabled", "python_wrapper_only": false, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs."}1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env python3from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
def required_outputs(input_dir: Path) -> list[str]: spec_path = input_dir / "analysis_spec.json" if spec_path.is_file(): payload = json.loads(spec_path.read_text(encoding="utf-8")) required = payload.get("required_outputs") if isinstance(payload, dict) else None if isinstance(required, list): rows = [str(item.get("path") or "") for item in required if isinstance(item, dict)] rows = [item for item in rows if item] if rows: return rows return [ "summary.json", "magnitude_depth_bins.csv", "region_daily_counts.csv", "filtered_events.geojson", ]
def main() -> int: output_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("output") input_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(os.environ.get("ALE_INPUT_DIR", "input")) required = required_outputs(input_dir) missing = [name for name in required if not (output_dir / name).is_file()] if missing: print(json.dumps({"ok": False, "missing": missing}, indent=2)) return 1 print(json.dumps({"ok": True, "required": required}, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111{ "taskId": "computing_math/audit_docker_official_image_packaging__20260907-014555_computing_math_bb0058", "title": "Repair4 20260907 018 Repair3 20260907 019 Repair2 20260906 021 Repair 20260906 Software 0027", "summary": "Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 23: 8 terms) (ALE-100 software diversity variant 25) (independent source snapshot 25). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3). (targeted repair round 4).", "category": "computing_math", "taxonomy": { "domain_id": "9", "domain_code": "computing_math", "subdomain_id": "9.6", "subdomain_code": "infra_cloud", "subdomain_name": "Infrastructure Engineering & Cloud Operations", "classifier": { "source": "public software metadata mapping", "rationale": "Subdomain selected from public task metadata." } }, "taskPrompt": "Use a Linux command-line workflow to audit the staged offline official tutorial corpus for Docker / Python Official Image. The source document is input/dockerfile_packaging_corpus.md, and input/dockerfile_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is software_tutorial_doc_audit. The primary staged data file is input/dockerfile_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:\n- output/summary.json: JSON keys and nested shape {\"code_block_count\": \"integer\", \"heading_count\": \"integer\", \"keyword_total\": \"integer\", \"software_name\": \"string\", \"source_character_count\": \"integer\", \"source_file\": \"string\", \"top_keyword\": \"string|null\", \"unique_required_terms_found\": \"integer\", \"window_count\": \"integer\"}\n- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug\n- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code\n- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_line\nCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.", "agentMustDo": [ "Read input/analysis_spec.json first and treat it as the authoritative public specification.", "Read input/dockerfile_text_windows.csv and compute results from the staged local data.", "Create output/summary.json as json exactly as specified by analysis_spec.json.", "Create output/section_outline.csv as csv exactly as specified by analysis_spec.json.", "Create output/keyword_inventory.csv as csv exactly as specified by analysis_spec.json.", "Create output/code_block_inventory.csv as csv exactly as specified by analysis_spec.json.", "Place every final deliverable directly under output/ with the exact required filename.", "Use only local staged files and installed Linux CLI tooling; do not download fresh data." ], "inputFiles": [ { "name": "README.md", "format": "Markdown", "path": "input/README.md", "description": "Agent-visible staged input file for this task." }, { "name": "analysis_spec.json", "format": "JSON", "path": "input/analysis_spec.json", "description": "Agent-visible staged input file for this task." }, { "name": "dockerfile_packaging_corpus.md", "format": "Markdown", "path": "input/dockerfile_packaging_corpus.md", "description": "Agent-visible staged input file for this task." }, { "name": "dockerfile_text_windows.csv", "format": "CSV", "path": "input/dockerfile_text_windows.csv", "description": "Agent-visible staged input file for this task." }, { "name": "source_context_windows.jsonl", "format": "JSONL", "path": "input/source_context_windows.jsonl", "description": "Agent-visible staged input file for this task." }, { "name": "tutorial_metadata.json", "format": "JSON", "path": "input/tutorial_metadata.json", "description": "Agent-visible staged input file for this task." } ], "referenceFiles": [ { "name": "summary.json", "format": "JSON", "path": "output/summary.json", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "section_outline.csv", "format": "CSV", "path": "output/section_outline.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "keyword_inventory.csv", "format": "CSV", "path": "output/keyword_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "code_block_inventory.csv", "format": "CSV", "path": "output/code_block_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." } ], "software": [ "Docker / Python Official Image", "docker", "docker build", "Python 3.11", "standard Unix shell", "software/command_examples.csv", "software/software_manifest.json", "software/validate_outputs.py" ], "requiredSystemPackages": [ "docker.io" ], "evaluation": "Final required files under output/ are compared against standard-reference outputs generated by the deterministic workflow for this task.", "vm": { "machineType": "c4-standard-4", "snapshot": "cpu-free-ubuntu", "timeout": 7200 }}123456789101112131415161718192021222324252627282930313233# Repair4 20260907 018 Repair3 20260907 019 Repair2 20260906 021 Repair 20260906 Software 0027
Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 23: 8 terms) (ALE-100 software diversity variant 25) (independent source snapshot 25). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3). (targeted repair round 4).
## Task
Use a Linux command-line workflow to audit the staged offline official tutorial corpus for Docker / Python Official Image. The source document is input/dockerfile_packaging_corpus.md, and input/dockerfile_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is software_tutorial_doc_audit. The primary staged data file is input/dockerfile_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:- output/summary.json: JSON keys and nested shape {"code_block_count": "integer", "heading_count": "integer", "keyword_total": "integer", "software_name": "string", "source_character_count": "integer", "source_file": "string", "top_keyword": "string|null", "unique_required_terms_found": "integer", "window_count": "integer"}- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_lineCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.
## Workspace
You are working in `/workspace`.
- Public input files are under `/workspace/input/`.- Public helper software and validation scripts are under `/workspace/software/`.- The public task card is available at `/workspace/task_card.json`.- The public task driver is available at `/workspace/main.py` for reference only.- Do not use hidden reference data, network downloads, credentials, GUI tools, or browser automation.
## Required Outputs
Create every final deliverable exactly at these paths:
- `/workspace/output/summary.json` (json)- `/workspace/output/section_outline.csv` (csv)- `/workspace/output/keyword_inventory.csv` (csv)- `/workspace/output/code_block_inventory.csv` (csv)
Follow `/workspace/input/analysis_spec.json` whenever it is more specific than prose. You may run public validation helpers, but the files under `/workspace/output/` are what will be evaluated.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_outputs(input_dir, output_dir)1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567#!/bin/bashset -euo pipefailINPUT_DIR="${1:-/workspace/input}"OUTPUT_DIR="${2:-/workspace/output}"SOLUTION_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"mkdir -p "${OUTPUT_DIR}"python "${SOLUTION_DIR}/reference_solution.py" --input "${INPUT_DIR}" --output "${OUTPUT_DIR}"123456789101112131415161718192021222324252627282930313233343536373839404142434445schema_version = "1.3"artifacts = ["/workspace/output/summary.json", "/workspace/output/section_outline.csv", "/workspace/output/keyword_inventory.csv", "/workspace/output/code_block_inventory.csv"]
[task]name = "ale-cli/20260907-014555-computing-math-bb0058"description = "Audit staged Docker Official Image packaging sources for Python and produce reproducible Dockerfile, tag, and command inventories from local files (keyword-subset experiment 23: 8 terms) (ALE-100 software diversity variant 25) (independent source snapshot 25). (repair batch 20260906; independent off"keywords = ["agents-last-exam", "ale-cli", "computing-math", "deterministic-evaluator", "linux-cli", "software-tutorial-doc-audit"]
[metadata]benchmark = "ale_cli"source_format = "ale_cli_official_style"converter = "ale_cli_to_harbor"source_task_key = "20260907-014555_computing_math_bb0058"task_id = "computing_math/audit_docker_official_image_packaging__20260907-014555_computing_math_bb0058"domain = "computing_math"task = "audit_docker_official_image_packaging"variant = "base"oracle_available = truescoring_method = "deterministic_hidden_evaluator"required_outputs = ["summary.json", "section_outline.csv", "keyword_inventory.csv", "code_block_inventory.csv"]
[agent]timeout_sec = 1800
[verifier]timeout_sec = 600environment_mode = "separate"
[verifier.environment]build_timeout_sec = 900.0network_mode = "public"os = "linux"cpus = 1memory_mb = 2048storage_mb = 4096gpus = 0
[environment]build_timeout_sec = 1200.0network_mode = "public"os = "linux"cpus = 2memory_mb = 4096storage_mb = 10240gpus = 020260907-014537-computing-math-08ed12/environment/public_data/input/README.mdAdded+6
20260907-014537-computing-math-08ed12/environment/public_data/input/analysis_spec.jsonAdded+98
20260907-014537-computing-math-08ed12/environment/public_data/input/dockerfile_packaging_corpus.mdAdded+447
20260907-014537-computing-math-08ed12/environment/public_data/input/dockerfile_text_windows.csvAdded+226
20260907-014537-computing-math-08ed12/environment/public_data/input/source_context_windows.jsonlAdded
20260907-014537-computing-math-08ed12/environment/public_data/input/tutorial_metadata.jsonAdded+37
20260907-014537-computing-math-08ed12/environment/public_data/main.pyAdded+180
20260907-014537-computing-math-08ed12/environment/public_data/software/command_examples.csvAdded+11
20260907-014537-computing-math-08ed12/environment/public_data/software/software_manifest.jsonAdded+16
20260907-014537-computing-math-08ed12/environment/public_data/software/validate_outputs.pyAdded+41
20260907-014537-computing-math-08ed12/environment/public_data/task_card.jsonAdded+111
20260907-014537-computing-math-08ed12/instruction.mdAdded+33
20260907-014537-computing-math-08ed12/solution/internal/workflow_adapters_runtime.pyAdded+679
20260907-014537-computing-math-08ed12/solution/internal/workflow_runtime.pyAdded+5
20260907-014537-computing-math-08ed12/solution/reference_solution.pyAdded+20
20260907-014537-computing-math-08ed12/solution/solve.shAdded+7
20260907-014537-computing-math-08ed12/task.tomlAdded+45
20260907-014537-computing-math-08ed12/tests/DockerfileAdded+6
20260907-014537-computing-math-08ed12/tests/evaluator_runner.pyAdded+92
20260907-014537-computing-math-08ed12/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
20260907-014537-computing-math-08ed12/tests/reference/evaluator.pyAdded+114
20260907-014537-computing-math-08ed12/tests/reference/ground_truth/code_block_inventory.csvAdded+12
20260907-014537-computing-math-08ed12/tests/reference/ground_truth/keyword_inventory.csvAdded+14
20260907-014537-computing-math-08ed12/tests/reference/ground_truth/section_outline.csvAdded+33
20260907-014537-computing-math-08ed12/tests/reference/ground_truth/summary.jsonAdded+11
20260907-014537-computing-math-08ed12/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260907-014537-computing-math-08ed12/tests/reference/internal/workflow_runtime.pyAdded+5
20260907-014537-computing-math-08ed12/tests/reference/reference_manifest.jsonAdded+34
20260907-014537-computing-math-08ed12/tests/reference/reference_solution.pyAdded+20
20260907-014537-computing-math-08ed12/tests/test.shAdded+29
20260907-014555-computing-math-bb0058/.DS_StoreAdded+3
20260907-014555-computing-math-bb0058/environment/DockerfileAdded+12
20260907-014555-computing-math-bb0058/environment/public_data/README.mdAdded+11
20260907-014555-computing-math-bb0058/environment/public_data/input/README.mdAdded+6
20260907-014555-computing-math-bb0058/environment/public_data/input/analysis_spec.jsonAdded+96
20260907-014555-computing-math-bb0058/environment/public_data/input/dockerfile_packaging_corpus.mdAdded+447
20260907-014555-computing-math-bb0058/environment/public_data/input/dockerfile_text_windows.csvAdded+226
20260907-014555-computing-math-bb0058/environment/public_data/input/source_context_windows.jsonlAdded
20260907-014555-computing-math-bb0058/environment/public_data/input/tutorial_metadata.jsonAdded+35
20260907-014555-computing-math-bb0058/environment/public_data/main.pyAdded+180
20260907-014555-computing-math-bb0058/environment/public_data/software/command_examples.csvAdded+10
20260907-014555-computing-math-bb0058/environment/public_data/software/software_manifest.jsonAdded+16
20260907-014555-computing-math-bb0058/environment/public_data/software/validate_outputs.pyAdded+41
20260907-014555-computing-math-bb0058/environment/public_data/task_card.jsonAdded+111
20260907-014555-computing-math-bb0058/instruction.mdAdded+33
20260907-014555-computing-math-bb0058/solution/internal/workflow_adapters_runtime.pyAdded+679
20260907-014555-computing-math-bb0058/solution/internal/workflow_runtime.pyAdded+5
20260907-014555-computing-math-bb0058/solution/reference_solution.pyAdded+20
20260907-014555-computing-math-bb0058/solution/solve.shAdded+7
20260907-014555-computing-math-bb0058/task.tomlAdded+45