diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..00f4863
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,47 @@
+name: CI
+
+on:
+ push:
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ name: Linux / Go 1.26.x
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - name: Set up Go
+ uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
+ with:
+ go-version: '1.26.x'
+ check-latest: true
+ cache: false
+
+ - name: Validate
+ shell: bash
+ run: |
+ test -z "$(gofmt -l .)"
+ go mod tidy
+ go vet ./...
+ CGO_ENABLED=0 go test -count=1 ./...
+ go test -race -count=1 ./...
+ go test -count=3 ./...
+ go list -m all
+ git diff --check
+
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
+ go build -trimpath -buildvcs=false -ldflags="-buildid=" \
+ -o /tmp/tell-a ./cmd/tell
+
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
+ go build -trimpath -buildvcs=false -ldflags="-buildid=" \
+ -o /tmp/tell-b ./cmd/tell
+
+ cmp /tmp/tell-a /tmp/tell-b
+ /tmp/tell-a version
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4250b64
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+/tell
+/tell-report-v1.json
+*.test
+*.out
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..ce038fc
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,9 @@
+## 1.0.0 — 2026-07-26
+
+- Initial release of the Linux-first TELL failure-oracle auditor.
+- Added the fixed `tell-default-v1` mutation profile and deterministic `tell-report-v1` JSON reports.
+- Added direct process execution, bounded binary output capture, process-group cleanup, and sequential integration coverage.
+
+TELL deterministically mutates a known-valid binary input and detects discrete differences in a target command’s rejection behavior.
+
+TELL does not claim that generated candidates are malformed or provide general security, fuzz-coverage, side-channel, exploitability, memory-safety, or cryptographic guarantees.
diff --git a/LICENSE b/LICENSE
index 0ad25db..0474813 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,661 +1,21 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU Affero General Public License is a free, copyleft license for
-software and other kinds of works, specifically designed to ensure
-cooperation with the community in the case of network server software.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-our General Public Licenses are intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- Developers that use our General Public Licenses protect your rights
-with two steps: (1) assert copyright on the software, and (2) offer
-you this License which gives you legal permission to copy, distribute
-and/or modify the software.
-
- A secondary benefit of defending all users' freedom is that
-improvements made in alternate versions of the program, if they
-receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
-software used on network servers, this result may fail to come about.
-The GNU General Public License permits making a modified version and
-letting the public access it on a server without ever releasing its
-source code to the public.
-
- The GNU Affero General Public License is designed specifically to
-ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
-provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
-a publicly accessible server, gives the public access to the source
-code of the modified version.
-
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
-a different license, not a version of the Affero GPL, but Affero has
-released a new version of the Affero GPL which permits relicensing under
-this license.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU Affero General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Remote Network Interaction; Use with the GNU General Public License.
-
- Notwithstanding any other provision of this License, if you modify the
-Program, your modified version must prominently offer all users
-interacting with it remotely through a computer network (if your version
-supports such interaction) an opportunity to receive the Corresponding
-Source of your version by providing access to the Corresponding Source
-from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
-shall include the Corresponding Source for any work covered by version 3
-of the GNU General Public License that is incorporated pursuant to the
-following paragraph.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the work with which it is combined will remain governed by version
-3 of the GNU General Public License.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU Affero General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU Affero General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU Affero General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published
- by the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If your software can interact with users remotely through a computer
-network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
-interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
-solutions will be better for different programs; see section 13 for the
-specific requirements.
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU AGPL, see
-.
+MIT License
+
+Copyright (c) 2026 TELL contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..fb720dd
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,50 @@
+GO ?= go
+GOFMT ?= gofmt
+BINARY ?= tell
+
+.PHONY: all build install format fmt-check tidy vet test race repeat modules diff-check check reproducible
+
+all: build
+
+build:
+ CGO_ENABLED=0 $(GO) build -trimpath -buildvcs=false -ldflags="-buildid=" -o $(BINARY) ./cmd/tell
+
+install:
+ CGO_ENABLED=0 $(GO) install -trimpath -buildvcs=false -ldflags="-buildid=" ./cmd/tell
+
+format:
+ command -v $(GOFMT) >/dev/null
+ find . -type f -name '*.go' -exec $(GOFMT) -w {} +
+
+fmt-check:
+ command -v $(GOFMT) >/dev/null
+ test -z "$$(find . -type f -name '*.go' -exec $(GOFMT) -l {} +)"
+
+tidy:
+ $(GO) mod tidy
+
+vet:
+ $(GO) vet ./...
+
+test:
+ CGO_ENABLED=0 $(GO) test -count=1 ./...
+
+race:
+ $(GO) test -race -count=1 ./...
+
+repeat:
+ $(GO) test -count=3 ./...
+
+modules:
+ $(GO) list -m all
+
+diff-check:
+ git diff --check
+
+check: fmt-check tidy vet test race repeat modules diff-check
+
+reproducible:
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build -trimpath -buildvcs=false -ldflags="-buildid=" -o /tmp/tell-a ./cmd/tell
+ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 $(GO) build -trimpath -buildvcs=false -ldflags="-buildid=" -o /tmp/tell-b ./cmd/tell
+ cmp /tmp/tell-a /tmp/tell-b
+ /tmp/tell-a version
diff --git a/README.md b/README.md
index 9e49c33..e369216 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,106 @@
# TELL
Malformed inputs should not tell.
+
+TELL is a Linux-first black-box failure-oracle auditor that checks whether a target command rejects a deterministic set of presumed-invalid binary mutants uniformly.
+
+TELL deterministically mutates a known-valid binary input and detects discrete differences in a target command’s rejection behavior.
+
+## Build and install
+
+TELL requires Linux and Go 1.26.x. Production builds use only the Go standard library and disable cgo.
+
+```sh
+git clone https://github.com/chasebryan/TELL.git
+cd TELL
+CGO_ENABLED=0 go build -trimpath -buildvcs=false -o tell ./cmd/tell
+```
+
+To install from a checkout into the active Go binary directory:
+
+```sh
+CGO_ENABLED=0 go install -trimpath ./cmd/tell
+```
+
+## Run an audit
+
+```sh
+tell run \
+ --seed valid-message.bin \
+ --stdin \
+ --timeout 2s \
+ --max-output-bytes 65536 \
+ --report tell-report-v1.json \
+ -- ./decoder --strict "literal argument"
+```
+
+`--seed`, `--stdin`, the `--` separator, and a command are required. Everything after `--` is passed as the command's literal argument vector. TELL executes the target directly; it does not invoke a shell or perform expansion, interpolation, globbing, redirection, or transcoding. The caller's working directory and environment are inherited.
+
+## PASS rule
+
+An audit passes only when all of the following are true:
+
+1. The baseline seed exits normally with code `0`.
+2. At least one unique mutation different from the seed is executed.
+3. Every mutation exits normally with a nonzero code.
+4. Every mutation has exactly the same observation tuple: `(exit code, exact stdout bytes, exact stderr bytes)`.
+
+An accepted mutation, a differing rejection, a signal, a timeout, or output overflow makes a completed audit fail. A launch, capture, cleanup, report-writing, or internal error makes the audit incomplete. Ordinary audit failures do not stop the remaining mutation cases; infrastructure failures do.
+
+## Exit codes
+
+| Code | Meaning |
+| ---: | --- |
+| `0` | Completed audit: PASS |
+| `1` | Completed audit: FAIL |
+| `2` | Usage, setup, invalid baseline, interruption, launch, runner, cleanup, report-write, unsupported-platform, or internal error |
+
+## Safety
+
+> **TELL is not a sandbox.** The target runs with the caller's privileges and may perform filesystem, network, or other side effects. TELL uses Linux process groups for cleanup, but process groups do not prevent a deliberately hostile descendant from escaping with `setsid` or `setpgid`. Audit only commands and inputs you are prepared to execute in the current environment.
+
+## Reports and sensitive data
+
+> Reports contain the complete command argument vector and the target's raw stdout and stderr, which may be sensitive. Review a report before publishing or sharing it.
+
+The deterministic JSON schema is named `tell-report-v1`. Reports contain seed and mutant length/hash metadata, never the input bytes themselves. File reports are atomically published with mode `0600`; incomplete audits do not replace an existing report. Report determinism excludes target nondeterminism: v1 executes each input once, so nondeterministic or environment-dependent target output can create apparent differences.
+
+## Fixed v1 limits
+
+| Limit | Value |
+| --- | ---: |
+| Seed size | 16 MiB |
+| Default timeout | 2 seconds |
+| Allowed timeout | 10 milliseconds through 60 seconds, in whole milliseconds |
+| Default output cap | 65,536 bytes per stream |
+| Maximum output cap | 1,048,576 bytes per stream |
+| Pipe cleanup grace | 250 milliseconds |
+| Maximum planned cases | 29 |
+
+v1 supports stdin input only, runs the baseline and cases sequentially, and uses the fixed `tell-default-v1` mutation profile. The empty seed is valid. Non-Linux builds return an unsupported-platform error.
+
+## Limitations and nonclaims
+
+TELL does not prove:
+
+- That generated candidates are actually malformed.
+- That all malformed inputs are rejected.
+- Constant-time behavior or absence of side channels.
+- Exploitability or vulnerability severity.
+- Memory safety.
+- Cryptographic correctness.
+- Complete input-space or fuzz coverage.
+- General security.
+
+The fixed mutations are deterministic, presumed-invalid probes—not random, exhaustive, grammar-aware, coverage-guided, or cumulative fuzzing. TELL does not isolate the target, and its observation equivalence excludes time, resource use, process identity, scheduling, and side channels.
+
+## Development
+
+```sh
+make format
+make test
+make race
+make check
+make reproducible
+```
+
+The normative v1 behavior, schema, limits, and compatibility policy are specified in [SPEC.md](SPEC.md).
diff --git a/SPEC.md b/SPEC.md
new file mode 100644
index 0000000..8878ace
--- /dev/null
+++ b/SPEC.md
@@ -0,0 +1,439 @@
+# TELL v1 Specification
+
+This document is normative for TELL 1.x. “Must,” “must not,” “should,” and “may” describe requirements, recommendations, and permissions respectively.
+
+## 1. Purpose and scope
+
+TELL is a Linux-first black-box failure-oracle auditor. Given a known-valid binary seed `S` and a target command `C`, it sends `S` and a fixed, deterministic sequence of independently generated byte mutations to `C` through standard input.
+
+For an input that exits normally with a nonzero code, its rejection observation is:
+
+```text
+O(x) = (exit code, exact stdout bytes, exact stderr bytes)
+```
+
+TELL observes discrete process results. Time, PID, resource usage, scheduling data, and all other side-channel information are outside `O(x)`.
+
+Generated inputs are deterministic, presumed-invalid mutants. TELL does not know the target's grammar and must not describe them as proven malformed.
+
+## 2. Platform and implementation
+
+The v1 implementation uses Go 1.26.x and the Go standard library only. Its module identity is:
+
+```go
+module github.com/chasebryan/TELL
+
+go 1.26.0
+```
+
+Production builds must set `CGO_ENABLED=0`. The implementation must not use cgo, `unsafe`, or third-party modules. v1 has no public Go API; executable code lives in `cmd/tell`, with substantive implementation in packages below `internal/`.
+
+Linux is the supported execution platform. A non-Linux build must compile and return a clear unsupported-platform error rather than failing compilation.
+
+## 3. Command-line interface
+
+The complete v1 command grammar is:
+
+```text
+tell run \
+ --seed PATH \
+ --stdin \
+ [--timeout 2s] \
+ [--max-output-bytes 65536] \
+ [--report tell-report-v1.json] \
+ -- COMMAND [ARG...]
+
+tell version
+tell help
+tell run --help
+```
+
+`--seed`, `--stdin`, the literal `--` separator, and a nonempty command vector are required. v1 supports standard input transport only. Unknown commands, flags, positional arguments before `--`, missing flag values, duplicate singleton flags, and malformed values are usage errors.
+
+`tell version` writes `tell 1.0.0` followed by one newline to stdout and exits `0`. Help commands write plain, non-colored usage text to stdout and exit `0`. Help must include the safety and report-sensitivity warnings. Usage diagnostics go to stderr. TELL never emits ANSI color or control sequences.
+
+Everything after `--` is the target's literal argument vector. TELL must:
+
+- Reject any target argument that is not valid UTF-8, because the vector cannot otherwise be represented faithfully in JSON.
+- Preserve every supplied argument, including `argv[0]`, in the report and child process.
+- Resolve and execute `argv[0]` directly with `os/exec`.
+- Never invoke a shell or perform quoting, expansion, interpolation, globbing, redirection, or command-string evaluation.
+- Inherit the caller's working directory and environment.
+
+The baseline and every retained mutation execute sequentially. TELL sends the exact input bytes to the child's stdin, adds no newline, performs no transcoding, closes stdin to deliver EOF, and captures stdout and stderr separately as raw bytes.
+
+### 3.1 Options and hard limits
+
+| Setting | Default | Allowed value |
+| --- | ---: | ---: |
+| Seed byte length | — | `0` through `16,777,216` |
+| Timeout | `2s` | `10ms` through `60s` |
+| Output bytes per stream | `65,536` | `0` through `1,048,576` |
+| Pipe cleanup grace | `250ms` | Fixed |
+| Planned mutation cases | — | At most `29` |
+
+Timeout syntax uses Go duration syntax, must resolve to a whole number of milliseconds, and is represented in the report as an integer millisecond count. A fractional-millisecond value is invalid even when it is within the numeric bounds.
+
+`--max-output-bytes` is a base-10 integer cap applied independently to stdout and stderr. A negative value or a value above the maximum is invalid. A cap of zero permits only empty output.
+
+The seed is read as opaque bytes. An empty seed is valid. An unreadable seed or a seed exceeding the limit is a setup error.
+
+### 3.2 Process exit codes
+
+```text
+0 completed audit: PASS
+1 completed audit: FAIL
+2 usage, setup, baseline, interruption, launch, runner,
+ cleanup, report-write, unsupported-platform, or internal error
+```
+
+An exit code `2` means the audit did not complete. No new report may be published on exit `2`, and an existing destination report must remain untouched.
+
+## 4. Deterministic mutation profile
+
+The sole v1 profile is named:
+
+```text
+tell-default-v1
+```
+
+Every candidate starts independently from the original seed. Candidates are never cumulative.
+
+For a seed of length `n`, form the unique values from:
+
+```text
+0
+floor(n / 4)
+floor(n / 2)
+floor(3n / 4)
+n - 1
+```
+
+Sort them numerically. For byte positions, discard values outside `[0,n)`. For truncation lengths, discard values outside `[0,n]` and exclude `n`.
+
+Generate candidate descriptors in this exact order:
+
+1. Truncate to each selected unique length.
+2. Delete one byte at each selected byte position.
+3. XOR the byte at each position with `0x01`.
+4. XOR the byte at each position with `0x80`.
+5. Replace the byte at each position with `0x00`.
+6. Append one `0x00` byte.
+7. Append one `0xff` byte.
+8. Append eight `0x00` bytes.
+9. Append eight `0xff` bytes.
+
+The empty seed has no positional or truncation candidate and still produces the four append candidates. At most 29 descriptors are planned.
+
+Each descriptor has all of these fields in this order; irrelevant fields are JSON `null`:
+
+```json
+{
+ "kind": "truncate|delete|bit_flip|zero|append",
+ "offset": null,
+ "new_length": null,
+ "mask": null,
+ "data_base64": null
+}
+```
+
+Relevant values are:
+
+- `truncate`: `new_length` is the selected length.
+- `delete`: `offset` is the selected position.
+- `bit_flip`: `offset` is the selected position and `mask` is `1` or `128`.
+- `zero`: `offset` is the selected position.
+- `append`: `data_base64` is padded standard Base64 for exactly the appended byte sequence.
+
+For each generated candidate, TELL must:
+
+1. Increment `planned`.
+2. Skip it and increment `skipped_unchanged` if it is byte-for-byte identical to the seed.
+3. Skip it and increment `skipped_duplicate` if it is byte-for-byte identical to an earlier retained candidate.
+4. Otherwise retain its first-producing descriptor, assign the next ID (`case-0001`, `case-0002`, ...), increment `unique`, execute it, and then discard its full input bytes.
+
+Deduplication may use SHA-256 as an index, but exact byte equality must decide identity. A matching digest therefore requires an exact comparison, such as regenerating the earlier candidate; digest equality alone is insufficient. The implementation must not retain all full candidates simultaneously, including for a 16 MiB seed.
+
+Every retained case records its byte length and complete lowercase SHA-256 hex digest. `unique` equals the number of executed case objects.
+
+## 5. Process supervision and capture
+
+For every baseline or mutation execution, TELL must use direct `os/exec` invocation. It must not use `sh`, `bash`, a command string, `CombinedOutput`, or any equivalent merged capture.
+
+### 5.1 Linux child lifecycle
+
+The child starts in a new Linux process group:
+
+```go
+SysProcAttr: &syscall.SysProcAttr{Setpgid: true}
+```
+
+`Cmd.WaitDelay` is fixed at 250 milliseconds. After each successful `Start`, TELL must call `Wait` exactly once. It must never attempt a process-group kill before `Start` succeeds or with a nonpositive PID.
+
+On timeout, output overflow, caller interruption, or cancellation, TELL sends `SIGKILL` to the negative direct-child PID, targeting the process group. `ESRCH` means the group is already absent and counts as successful cleanup. Once the direct child terminates, TELL performs another best-effort group kill to remove descendants.
+
+A first-cause-wins cancellation mechanism must record why termination was induced. An induced `SIGKILL` is classified as its originating timeout or output overflow, not as a natural target signal. If timeout and overflow race, the first successfully recorded cause determines the execution outcome.
+
+TELL must inspect Linux `WaitStatus` to distinguish normal `exit(137)` from signal termination by `SIGKILL` or another signal.
+
+### 5.2 Pipes and I/O
+
+TELL uses explicit pipes where necessary to bound stdin delivery and stdout/stderr drainage. It must close every unused pipe end promptly, drain stdout and stderr concurrently, and join all I/O goroutines before returning.
+
+The stdin writer sends the exact input then closes its pipe. An early stdin `EPIPE` is nonfatal when a valid child termination result is available. Other unexplained delivery or capture errors are infrastructure errors.
+
+Capture is bounded independently per stream. TELL retains at most the configured cap and probes for byte `cap+1`:
+
+- Exactly `cap` bytes followed by EOF is allowed and has `truncated: false`.
+- Observing byte `cap+1` causes `output_limited`; only the first `cap` bytes are retained and the overflowing stream has `truncated: true`.
+
+Captured bytes must never be normalized, trimmed, decoded as UTF-8, or merged. NUL bytes, invalid UTF-8, trailing newlines, and stream separation are significant and preserved through report Base64.
+
+Descendants that retain inherited stdout or stderr pipe descriptors must not hang TELL indefinitely. Group cleanup, `WaitDelay`, prompt local pipe closure, and goroutine joins must bound cleanup. A cleanup failure is infrastructure failure, not an audit FAIL.
+
+### 5.3 Interruption
+
+TELL handles `SIGINT` and `SIGTERM`. It kills the current process group, completes bounded cleanup, exits `2`, removes temporary report artifacts, and leaves any existing destination report untouched.
+
+## 6. Execution outcomes
+
+Mutation execution outcomes are exactly:
+
+```text
+accepted normal exit code 0
+rejected normal nonzero exit code
+signaled natural signal termination
+timed_out execution deadline exceeded
+output_limited stdout or stderr exceeded its cap
+```
+
+Only a normally rejected execution has a rejection observation and may belong to a rejection class.
+
+A baseline is a valid precondition only if it exits normally with code `0` without timing out or exceeding either output cap. Baseline rejection, natural signal, timeout, or output overflow is an invalid precondition: exit `2` and publish no new report. Baseline launch, capture, cleanup, or runner failure is likewise incomplete.
+
+After a valid baseline, TELL continues through all retained mutations after ordinary audit outcomes, including acceptance, differing rejection, natural signal, timeout, or output overflow. It aborts on launch, pipe, capture, cleanup, report-generation, or internal infrastructure errors.
+
+## 7. Rejection equivalence classes
+
+Only `rejected` cases participate. Two rejected cases are members of the same class only when their exit codes, stdout byte slices, and stderr byte slices are exactly equal. Strings and hashes alone must not establish equality.
+
+The class digest preimage is the concatenation:
+
+```text
+ASCII "TELL\0OBSERVATION\0V1\0"
+|| uint32_be(exit_code)
+|| uint64_be(stdout_length)
+|| stdout_bytes
+|| uint64_be(stderr_length)
+|| stderr_bytes
+```
+
+The class ID is:
+
+```text
+obs-
+```
+
+Integer encodings are unsigned, fixed-width, big-endian. Lengths are the exact byte lengths of the complete captured observations. Class membership is established with exact equality before or alongside digest indexing. If two unequal observations produce the same digest, TELL must return internal error `2` and must never merge them.
+
+Classes are sorted lexicographically by complete class ID. Within a class, `case_ids` remain in mutation/case order.
+
+## 8. Verdict
+
+A completed audit is PASS if and only if:
+
+1. The baseline seed exited normally with code `0`.
+2. At least one unique mutation different from the seed was executed.
+3. Every mutation exited normally with a nonzero code.
+4. Every mutation had exactly the same rejection observation tuple.
+
+Any other completed audit is FAIL. Applicable reason codes appear once each in this fixed order:
+
+```text
+accepted_mutation
+nonuniform_rejection
+target_signaled
+target_timeout
+output_limit_exceeded
+```
+
+`accepted_mutation` applies when any mutation outcome is `accepted`. `nonuniform_rejection` applies when rejected mutations occupy more than one exact rejection class. The three target execution reasons apply when any case has the corresponding outcome. Reason order does not depend on case order.
+
+## 9. Deterministic JSON report
+
+The schema identifier is `tell-report-v1`. This is deterministic JSON, not “RFC-canonical JSON.” Reports use Go structs, never maps, so declared field order is stable.
+
+The top-level fields occur in this exact order:
+
+```text
+schema
+tool
+verdict
+reasons
+configuration
+command
+seed
+baseline
+mutation_counts
+cases
+rejection_classes
+```
+
+Their required content is:
+
+```text
+schema: "tell-report-v1"
+
+tool:
+ name: "tell"
+ version: "1.0.0"
+
+verdict: "pass" or "fail"
+
+reasons: ordered array of reason-code strings
+
+configuration:
+ transport: "stdin"
+ mutation_profile: "tell-default-v1"
+ timeout_ms: integer
+ max_output_bytes_per_stream: integer
+
+command: exact supplied target argv array
+
+seed:
+ byte_length: integer
+ sha256_hex: string
+
+baseline: execution object
+
+mutation_counts:
+ planned: integer
+ unique: integer
+ skipped_unchanged: integer
+ skipped_duplicate: integer
+
+cases: ordered case objects
+
+rejection_classes: class objects sorted lexicographically by id
+```
+
+An execution object has this exact field order and shape:
+
+```text
+outcome: "accepted|rejected|signaled|timed_out|output_limited"
+
+termination:
+ kind: "exit|signal|timeout|output_limit"
+ exit_code: integer or null
+ signal_number: Linux integer or null
+
+stdout:
+ captured_byte_length: integer
+ sha256_hex: string
+ data_base64: string
+ truncated: boolean
+
+stderr:
+ captured_byte_length: integer
+ sha256_hex: string
+ data_base64: string
+ truncated: boolean
+```
+
+Normal exits use `kind: "exit"`, an integer `exit_code`, and null `signal_number`. Natural signals use `kind: "signal"`, null `exit_code`, and the Linux signal number. Timeout and output-limit terminations use their matching kind and null code/signal fields, even when cleanup induced `SIGKILL`.
+
+Each stream digest and Base64 value covers the retained captured bytes. `captured_byte_length` is their byte length. An overflowing stream retains exactly the cap and has `truncated: true`; the other stream is independently described.
+
+Each case object has this exact field order:
+
+```text
+id: "case-NNNN"
+mutation: mutation descriptor
+input:
+ byte_length: integer
+ sha256_hex: string
+execution: execution object
+observation_class_id: class ID or null
+```
+
+`observation_class_id` is non-null only for a normally rejected case.
+
+Each rejection class object has this exact field order:
+
+```text
+id
+exit_code
+stdout_byte_length
+stdout_sha256_hex
+stderr_byte_length
+stderr_sha256_hex
+case_ids
+```
+
+Class objects contain metadata and membership, not output content. Output content remains available in each case execution object.
+
+### 9.1 Serialization
+
+Serialization must:
+
+- Preserve struct declaration and array order.
+- Use padded standard Base64.
+- Use complete lowercase SHA-256 hex.
+- Use JSON integers, never floats.
+- Emit every required field without `omitempty`, including required nulls.
+- Use two-space indentation.
+- Disable HTML escaping.
+- End with exactly one newline.
+
+The report must exclude timestamps, durations, hostnames, usernames, PIDs, cwd, seed path, report path, resolved executable path, temporary paths, Go runtime version, random identifiers, and environment maps. It stores only seed and mutant length/hash metadata, never seed or mutant input contents.
+
+Reports can contain sensitive command arguments and target stdout/stderr. Documentation and CLI help must warn users before they publish or share a report.
+
+### 9.2 Publication and summary
+
+TELL serializes the complete report before publication. It creates a same-directory temporary file with mode `0600`, writes and closes it successfully, and atomically renames it over the destination. On any exit `2`, it removes temporary artifacts and leaves an existing destination unchanged.
+
+After successful publication, TELL writes exactly one plain, non-colored summary line to stdout. PASS uses:
+
+```text
+PASS cases=N rejected=N classes=N report=PATH
+```
+
+FAIL uses:
+
+```text
+FAIL cases=N accepted=A rejected=R signaled=S timed_out=T output_limited=O classes=K report=PATH
+```
+
+The counts are base-10 integers, `cases` is the number of executed mutation cases, and `classes` is the number of rejection classes. Diagnostics go to stderr.
+
+## 10. Determinism
+
+Given the same seed bytes, option values, literal command vector, and exact sequence of target execution results, TELL must generate byte-identical reports. Candidate order, case IDs, reason order, class order, JSON field order, encoding, and the final newline are fixed by this specification.
+
+Target behavior is not made deterministic by TELL. A target may vary with environment, filesystem state, network state, randomness, concurrency, or other external conditions. Such variation can create apparent differences. v1 executes the baseline and each mutation exactly once and performs no repeated sampling or timing analysis.
+
+## 11. Security model and nonclaims
+
+TELL is not a sandbox. Targets run with the caller's privileges and may perform filesystem, network, or other side effects. Linux process groups improve ordinary descendant cleanup but do not stop a deliberately hostile descendant from escaping through `setsid`, `setpgid`, or comparable behavior.
+
+TELL does not prove:
+
+- That generated candidates are actually malformed.
+- That all malformed inputs are rejected.
+- Constant-time behavior or absence of side channels.
+- Exploitability or vulnerability severity.
+- Memory safety.
+- Cryptographic correctness.
+- Complete input-space or fuzz coverage.
+- General security.
+
+TELL is not a random, exhaustive, grammar-aware, or coverage-guided fuzzer. It does not minimize cases or manage a corpus.
+
+## 12. Compatibility policy
+
+The identifiers `tell-default-v1` and `tell-report-v1` permanently name the mutation and report contracts in this document. A change that alters mutation bytes/order/descriptors, observation equivalence, verdict semantics, field meaning/order, or serialization must use a new profile or schema identifier as appropriate.
+
+TELL 1.x may receive bug fixes and implementation hardening that preserve these observable contracts. It must not silently repurpose v1 fields or identifiers. A breaking CLI change requires a new major tool version. Report consumers should dispatch on the exact `schema` value and must not treat an unknown schema as v1.
+
+The v1 scope is complete: stdin transport, one fixed deterministic profile, sequential local process execution, and JSON file reports. Other transports, mutation systems, parallelism, timing analysis, public SDKs, servers, telemetry, sandboxing, and additional report formats are outside v1.
diff --git a/cmd/tell/main.go b/cmd/tell/main.go
new file mode 100644
index 0000000..e195116
--- /dev/null
+++ b/cmd/tell/main.go
@@ -0,0 +1,17 @@
+package main
+
+import (
+ "context"
+ "os"
+ "os/signal"
+ "syscall"
+
+ "github.com/chasebryan/TELL/internal/app"
+)
+
+func main() {
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ code := app.Main(ctx, os.Args[1:], os.Stdout, os.Stderr)
+ stop()
+ os.Exit(code)
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..bb94196
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module github.com/chasebryan/TELL
+
+go 1.26.0
diff --git a/internal/app/app.go b/internal/app/app.go
new file mode 100644
index 0000000..158b02d
--- /dev/null
+++ b/internal/app/app.go
@@ -0,0 +1,263 @@
+// Package app implements TELL's command-line application.
+package app
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/chasebryan/TELL/internal/report"
+)
+
+const (
+ ExitPass = 0
+ ExitFail = 1
+ ExitError = 2
+
+ defaultTimeout = 2 * time.Second
+ minimumTimeout = 10 * time.Millisecond
+ maximumTimeout = 60 * time.Second
+ defaultMaxOutputBytes = 65_536
+ maximumOutputBytes = 1_048_576
+ maximumSeedBytes = 16 * 1024 * 1024
+ cleanupGrace = 250 * time.Millisecond
+ defaultReportPath = "tell-report-v1.json"
+)
+
+const helpText = `Usage:
+ tell run --seed PATH --stdin [--timeout 2s] [--max-output-bytes 65536] [--report tell-report-v1.json] -- COMMAND [ARG...]
+ tell version
+ tell help
+
+TELL deterministically audits a command's black-box rejection behavior.
+
+Safety: TELL is not a sandbox. Targets run with your privileges and may have
+filesystem or network side effects.
+
+Report warning: reports contain command arguments and raw target output; review
+them before publishing or sharing.
+`
+
+const runHelpText = `Usage:
+ tell run --seed PATH --stdin [--timeout 2s] [--max-output-bytes 65536] [--report tell-report-v1.json] -- COMMAND [ARG...]
+
+Required:
+ --seed PATH known-valid binary seed (maximum 16 MiB)
+ --stdin send each exact input through standard input
+ -- end TELL options; the remaining argv is literal
+ COMMAND target executable
+
+Options:
+ --timeout DURATION per-execution timeout (default 2s; 10ms through 60s)
+ --max-output-bytes N cap for each output stream (default 65536; max 1048576)
+ --report PATH report destination (default tell-report-v1.json)
+
+TELL is not a sandbox. The target runs with your privileges and can have
+filesystem or network side effects.
+
+Reports contain command arguments and raw target output; review them before
+publishing or sharing.
+`
+
+type options struct {
+ seedPath string
+ timeout time.Duration
+ maxOutput int
+ reportPath string
+ command []string
+ stdinSelected bool
+}
+
+// Main runs one CLI invocation and returns its process exit code.
+func Main(ctx context.Context, args []string, stdout, stderr io.Writer) int {
+ if err := validateUTF8(args); err != nil {
+ return usageError(stderr, err)
+ }
+ if len(args) == 0 {
+ return usageError(stderr, errors.New("a subcommand is required"))
+ }
+
+ switch args[0] {
+ case "help":
+ if len(args) != 1 {
+ return usageError(stderr, errors.New("tell help takes no arguments"))
+ }
+ _, _ = io.WriteString(stdout, helpText)
+ return ExitPass
+ case "version":
+ if len(args) != 1 {
+ return usageError(stderr, errors.New("tell version takes no arguments"))
+ }
+ _, _ = fmt.Fprintf(stdout, "tell %s\n", report.ToolVersion)
+ return ExitPass
+ case "run":
+ if len(args) == 2 && args[1] == "--help" {
+ _, _ = io.WriteString(stdout, runHelpText)
+ return ExitPass
+ }
+ parsed, err := parseRun(args[1:])
+ if err != nil {
+ return usageError(stderr, err)
+ }
+ return audit(ctx, parsed, stdout, stderr)
+ default:
+ return usageError(stderr, fmt.Errorf("unknown subcommand %q", args[0]))
+ }
+}
+
+func validateUTF8(args []string) error {
+ for _, argument := range args {
+ if !utf8.ValidString(argument) {
+ return errors.New("arguments must be valid UTF-8")
+ }
+ }
+ return nil
+}
+
+func usageError(stderr io.Writer, err error) int {
+ _, _ = fmt.Fprintf(stderr, "tell: %v\n\n%s", err, helpText)
+ return ExitError
+}
+
+func parseRun(args []string) (options, error) {
+ parsed := options{
+ timeout: defaultTimeout,
+ maxOutput: defaultMaxOutputBytes,
+ reportPath: defaultReportPath,
+ }
+ seen := make(map[string]bool)
+ separator := false
+
+ for index := 0; index < len(args); index++ {
+ argument := args[index]
+ if argument == "--" {
+ separator = true
+ parsed.command = append([]string(nil), args[index+1:]...)
+ break
+ }
+
+ name, value, inline := splitOption(argument)
+ switch name {
+ case "--seed", "--timeout", "--max-output-bytes", "--report":
+ if seen[name] {
+ return options{}, fmt.Errorf("%s may be specified only once", name)
+ }
+ seen[name] = true
+ if !inline {
+ index++
+ if index >= len(args) {
+ return options{}, fmt.Errorf("%s requires a value", name)
+ }
+ value = args[index]
+ }
+ if value == "" {
+ return options{}, fmt.Errorf("%s requires a nonempty value", name)
+ }
+ switch name {
+ case "--seed":
+ parsed.seedPath = value
+ case "--timeout":
+ duration, err := parseTimeout(value)
+ if err != nil {
+ return options{}, err
+ }
+ parsed.timeout = duration
+ case "--max-output-bytes":
+ limit, err := parseOutputLimit(value)
+ if err != nil {
+ return options{}, err
+ }
+ parsed.maxOutput = limit
+ case "--report":
+ parsed.reportPath = value
+ }
+ case "--stdin":
+ if inline {
+ return options{}, errors.New("--stdin does not take a value")
+ }
+ if seen[name] {
+ return options{}, errors.New("--stdin may be specified only once")
+ }
+ seen[name] = true
+ parsed.stdinSelected = true
+ case "--help":
+ return options{}, errors.New("--help must be used as tell run --help")
+ default:
+ if strings.HasPrefix(argument, "-") {
+ return options{}, fmt.Errorf("unknown option %q", argument)
+ }
+ return options{}, fmt.Errorf("unexpected argument %q before --", argument)
+ }
+ }
+
+ if !separator {
+ return options{}, errors.New("literal -- separator is required")
+ }
+ if parsed.seedPath == "" {
+ return options{}, errors.New("--seed is required")
+ }
+ if !parsed.stdinSelected {
+ return options{}, errors.New("--stdin is required in v1")
+ }
+ if len(parsed.command) == 0 || parsed.command[0] == "" {
+ return options{}, errors.New("COMMAND is required after --")
+ }
+ return parsed, nil
+}
+
+func splitOption(argument string) (name, value string, inline bool) {
+ if index := strings.IndexByte(argument, '='); index >= 0 {
+ return argument[:index], argument[index+1:], true
+ }
+ return argument, "", false
+}
+
+func parseTimeout(value string) (time.Duration, error) {
+ duration, err := time.ParseDuration(value)
+ if err != nil {
+ return 0, fmt.Errorf("invalid --timeout %q: %w", value, err)
+ }
+ if duration%time.Millisecond != 0 {
+ return 0, errors.New("--timeout must be a whole number of milliseconds")
+ }
+ if duration < minimumTimeout || duration > maximumTimeout {
+ return 0, fmt.Errorf("--timeout must be between %s and %s", minimumTimeout, maximumTimeout)
+ }
+ return duration, nil
+}
+
+func parseOutputLimit(value string) (int, error) {
+ limit, err := strconv.ParseInt(value, 10, 32)
+ if err != nil {
+ return 0, fmt.Errorf("invalid --max-output-bytes %q", value)
+ }
+ if limit < 0 || limit > maximumOutputBytes {
+ return 0, fmt.Errorf("--max-output-bytes must be between 0 and %d", maximumOutputBytes)
+ }
+ return int(limit), nil
+}
+
+func readSeed(path string) ([]byte, error) {
+ file, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf("open seed: %w", err)
+ }
+ data, readErr := io.ReadAll(io.LimitReader(file, maximumSeedBytes+1))
+ closeErr := file.Close()
+ if readErr != nil {
+ return nil, fmt.Errorf("read seed: %w", readErr)
+ }
+ if closeErr != nil {
+ return nil, fmt.Errorf("close seed: %w", closeErr)
+ }
+ if len(data) > maximumSeedBytes {
+ return nil, fmt.Errorf("seed exceeds %d-byte limit", maximumSeedBytes)
+ }
+ return data, nil
+}
diff --git a/internal/app/app_test.go b/internal/app/app_test.go
new file mode 100644
index 0000000..3c09f5b
--- /dev/null
+++ b/internal/app/app_test.go
@@ -0,0 +1,615 @@
+//go:build linux
+
+package app
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "reflect"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+
+ "github.com/chasebryan/TELL/internal/report"
+)
+
+const fixtureEnvironment = "TELL_APP_TEST_FIXTURE"
+
+func TestTargetFixture(t *testing.T) {
+ if os.Getenv(fixtureEnvironment) != "1" {
+ return
+ }
+ separator := -1
+ for index, argument := range os.Args {
+ if argument == "--" {
+ separator = index
+ break
+ }
+ }
+ if separator < 0 || len(os.Args) < separator+3 {
+ os.Exit(120)
+ }
+ arguments := os.Args[separator+1:]
+ mode := arguments[0]
+ seed, err := base64.StdEncoding.DecodeString(arguments[1])
+ if err != nil {
+ os.Exit(121)
+ }
+ extra := arguments[2:]
+ input, err := io.ReadAll(os.Stdin)
+ if err != nil {
+ os.Exit(122)
+ }
+ baseline := bytes.Equal(input, seed)
+
+ uniformReject := func() {
+ _, _ = os.Stdout.Write([]byte{0, 0xff, '\n'})
+ _, _ = os.Stderr.Write([]byte{'e', 'r', 'r', 0xfe, '\n'})
+ os.Exit(23)
+ }
+ switch mode {
+ case "uniform":
+ if baseline {
+ os.Exit(0)
+ }
+ uniformReject()
+ case "vary":
+ if baseline {
+ os.Exit(0)
+ }
+ _, _ = fmt.Fprintf(os.Stdout, "%x", input)
+ os.Exit(23)
+ case "accept-one":
+ if baseline || len(input) == 0 {
+ os.Exit(0)
+ }
+ uniformReject()
+ case "signal":
+ if baseline {
+ os.Exit(0)
+ }
+ _ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
+ time.Sleep(time.Second)
+ os.Exit(123)
+ case "timeout", "timeout-one":
+ if baseline {
+ os.Exit(0)
+ }
+ if mode == "timeout-one" && len(input) != 0 {
+ uniformReject()
+ }
+ time.Sleep(10 * time.Second)
+ os.Exit(124)
+ case "stdout-overflow", "stderr-overflow", "exact-cap":
+ if baseline {
+ os.Exit(0)
+ }
+ if len(extra) != 1 {
+ os.Exit(125)
+ }
+ limit, err := strconv.Atoi(extra[0])
+ if err != nil {
+ os.Exit(126)
+ }
+ count := limit
+ if mode != "exact-cap" {
+ count++
+ }
+ output := bytes.Repeat([]byte{'x'}, count)
+ if mode == "stderr-overflow" {
+ _, _ = os.Stderr.Write(output)
+ } else {
+ _, _ = os.Stdout.Write(output)
+ }
+ os.Exit(23)
+ case "literal":
+ if len(extra) < 1 {
+ os.Exit(127)
+ }
+ encoded, err := base64.StdEncoding.DecodeString(extra[0])
+ if err != nil {
+ os.Exit(128)
+ }
+ var expected []string
+ if err := json.Unmarshal(encoded, &expected); err != nil || !reflect.DeepEqual(extra[1:], expected) {
+ os.Exit(129)
+ }
+ if baseline {
+ os.Exit(0)
+ }
+ uniformReject()
+ case "context":
+ if len(extra) != 3 {
+ os.Exit(130)
+ }
+ cwd, err := os.Getwd()
+ if err != nil || cwd != extra[0] || os.Getenv(extra[1]) != extra[2] {
+ os.Exit(131)
+ }
+ if baseline {
+ os.Exit(0)
+ }
+ uniformReject()
+ case "baseline-reject":
+ os.Exit(9)
+ case "baseline-signal":
+ _ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
+ time.Sleep(time.Second)
+ os.Exit(132)
+ case "baseline-timeout":
+ time.Sleep(10 * time.Second)
+ os.Exit(133)
+ case "baseline-stdout-overflow":
+ _, _ = os.Stdout.Write(bytes.Repeat([]byte{'x'}, 6))
+ os.Exit(0)
+ case "baseline-stderr-overflow":
+ _, _ = os.Stderr.Write(bytes.Repeat([]byte{'x'}, 6))
+ os.Exit(0)
+ default:
+ os.Exit(134)
+ }
+}
+
+func TestHelpVersionUsageAndUTF8(t *testing.T) {
+ tests := []struct {
+ name string
+ args []string
+ wantCode int
+ wantStdout string
+ wantStderr string
+ }{
+ {name: "help", args: []string{"help"}, wantCode: 0, wantStdout: "Usage:\n"},
+ {name: "run help", args: []string{"run", "--help"}, wantCode: 0, wantStdout: "Usage:\n"},
+ {name: "version", args: []string{"version"}, wantCode: 0, wantStdout: "tell 1.0.0\n"},
+ {name: "missing command", args: nil, wantCode: 2, wantStderr: "tell: a subcommand is required"},
+ {name: "unknown", args: []string{"unknown"}, wantCode: 2, wantStderr: "tell: unknown subcommand"},
+ {name: "help extra", args: []string{"help", "extra"}, wantCode: 2, wantStderr: "tell help takes no arguments"},
+ {name: "version extra", args: []string{"version", "extra"}, wantCode: 2, wantStderr: "tell version takes no arguments"},
+ {name: "invalid utf8", args: []string{"run", string([]byte{0xff})}, wantCode: 2, wantStderr: "arguments must be valid UTF-8"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ var stdout, stderr bytes.Buffer
+ code := Main(context.Background(), test.args, &stdout, &stderr)
+ if code != test.wantCode {
+ t.Fatalf("code = %d, want %d", code, test.wantCode)
+ }
+ if !strings.Contains(stdout.String(), test.wantStdout) {
+ t.Fatalf("stdout = %q, want substring %q", stdout.String(), test.wantStdout)
+ }
+ if !strings.Contains(stderr.String(), test.wantStderr) {
+ t.Fatalf("stderr = %q, want substring %q", stderr.String(), test.wantStderr)
+ }
+ if strings.Contains(stdout.String(), "\x1b[") || strings.Contains(stderr.String(), "\x1b[") {
+ t.Fatal("CLI emitted ANSI color")
+ }
+ })
+ }
+}
+
+func TestParseRunContractAndBoundaries(t *testing.T) {
+ valid := []string{"--seed=seed.bin", "--stdin", "--timeout", "10ms", "--max-output-bytes=0", "--report", "out.json", "--", "command", "space arg"}
+ parsed, err := parseRun(valid)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if parsed.seedPath != "seed.bin" || parsed.timeout != 10*time.Millisecond || parsed.maxOutput != 0 || parsed.reportPath != "out.json" || !reflect.DeepEqual(parsed.command, []string{"command", "space arg"}) {
+ t.Fatalf("parsed options = %#v", parsed)
+ }
+
+ validTimeouts := []string{"10ms", "0.01s", "1500ms", "1.5s", "60s"}
+ for _, value := range validTimeouts {
+ if _, err := parseTimeout(value); err != nil {
+ t.Errorf("parseTimeout(%q): %v", value, err)
+ }
+ }
+ invalidTimeouts := []string{"", "9ms", "60.001s", "10001us", "garbage"}
+ for _, value := range invalidTimeouts {
+ if _, err := parseTimeout(value); err == nil {
+ t.Errorf("parseTimeout(%q) succeeded", value)
+ }
+ }
+ for _, value := range []string{"0", "65536", "1048576"} {
+ if _, err := parseOutputLimit(value); err != nil {
+ t.Errorf("parseOutputLimit(%q): %v", value, err)
+ }
+ }
+ for _, value := range []string{"-1", "1048577", "1.5", "x"} {
+ if _, err := parseOutputLimit(value); err == nil {
+ t.Errorf("parseOutputLimit(%q) succeeded", value)
+ }
+ }
+
+ invalid := [][]string{
+ {"--stdin", "--", "cmd"},
+ {"--seed", "seed", "--", "cmd"},
+ {"--seed", "seed", "--stdin", "cmd"},
+ {"--seed", "seed", "--stdin", "--"},
+ {"--seed", "seed", "--stdin", "--unknown", "--", "cmd"},
+ {"--seed", "seed", "--seed", "other", "--stdin", "--", "cmd"},
+ {"--seed", "seed", "--stdin", "--stdin", "--", "cmd"},
+ {"--seed", "seed", "--stdin=true", "--", "cmd"},
+ {"--seed=", "--stdin", "--", "cmd"},
+ {"--seed", "seed", "--stdin", "positional", "--", "cmd"},
+ }
+ for index, args := range invalid {
+ if _, err := parseRun(args); err == nil {
+ t.Errorf("invalid case %d succeeded: %#v", index, args)
+ }
+ }
+}
+
+func TestUniformRejectionPassesAndReportsRawBytesDeterministically(t *testing.T) {
+ seed := []byte("VALID")
+ firstCode, firstStdout, firstStderr, firstBytes, first := runFixtureAudit(t, seed, "uniform", nil, defaultTimeout, defaultMaxOutputBytes)
+ if firstCode != ExitPass {
+ t.Fatalf("code = %d, stdout=%q stderr=%q", firstCode, firstStdout, firstStderr)
+ }
+ if first.Verdict != "pass" || len(first.Reasons) != 0 || first.MutationCounts.Unique == 0 || len(first.Cases) != first.MutationCounts.Unique || len(first.RejectionClasses) != 1 {
+ t.Fatalf("unexpected report: verdict=%q reasons=%#v counts=%+v cases=%d classes=%d", first.Verdict, first.Reasons, first.MutationCounts, len(first.Cases), len(first.RejectionClasses))
+ }
+ if !strings.HasPrefix(firstStdout, fmt.Sprintf("PASS cases=%d rejected=%d classes=1 report=", first.MutationCounts.Unique, first.MutationCounts.Unique)) || firstStderr != "" {
+ t.Fatalf("summary stdout=%q stderr=%q", firstStdout, firstStderr)
+ }
+ for _, item := range first.Cases {
+ if item.ObservationClassID == nil || *item.ObservationClassID != first.RejectionClasses[0].ID {
+ t.Fatalf("case %s class ID = %v", item.ID, item.ObservationClassID)
+ }
+ stdoutData, err := base64.StdEncoding.DecodeString(item.Execution.Stdout.DataBase64)
+ if err != nil || !bytes.Equal(stdoutData, []byte{0, 0xff, '\n'}) {
+ t.Fatalf("case %s stdout round trip = %x, err=%v", item.ID, stdoutData, err)
+ }
+ stderrData, err := base64.StdEncoding.DecodeString(item.Execution.Stderr.DataBase64)
+ if err != nil || !bytes.Equal(stderrData, []byte{'e', 'r', 'r', 0xfe, '\n'}) {
+ t.Fatalf("case %s stderr round trip = %x, err=%v", item.ID, stderrData, err)
+ }
+ }
+
+ secondCode, _, _, secondBytes, _ := runFixtureAudit(t, seed, "uniform", nil, defaultTimeout, defaultMaxOutputBytes)
+ if secondCode != ExitPass || !bytes.Equal(firstBytes, secondBytes) {
+ t.Fatal("identical fixtures did not produce byte-identical reports")
+ }
+}
+
+func TestCompletedAuditFailureOutcomes(t *testing.T) {
+ tests := []struct {
+ name string
+ mode string
+ seed []byte
+ extra []string
+ timeout time.Duration
+ limit int
+ wantReason string
+ }{
+ {name: "different observations", mode: "vary", seed: []byte("VALID"), timeout: defaultTimeout, limit: defaultMaxOutputBytes, wantReason: "nonuniform_rejection"},
+ {name: "accepted mutation", mode: "accept-one", seed: []byte("A"), timeout: defaultTimeout, limit: defaultMaxOutputBytes, wantReason: "accepted_mutation"},
+ {name: "natural signal", mode: "signal", seed: []byte("A"), timeout: defaultTimeout, limit: defaultMaxOutputBytes, wantReason: "target_signaled"},
+ {name: "timeout", mode: "timeout-one", seed: []byte("A"), timeout: defaultTimeout, limit: defaultMaxOutputBytes, wantReason: "target_timeout"},
+ {name: "stdout overflow", mode: "stdout-overflow", seed: []byte("A"), extra: []string{"4"}, timeout: defaultTimeout, limit: 4, wantReason: "output_limit_exceeded"},
+ {name: "stderr overflow", mode: "stderr-overflow", seed: []byte("A"), extra: []string{"4"}, timeout: defaultTimeout, limit: 4, wantReason: "output_limit_exceeded"},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ code, stdout, stderr, _, document := runFixtureAudit(t, test.seed, test.mode, test.extra, test.timeout, test.limit)
+ if code != ExitFail || document.Verdict != "fail" || !contains(document.Reasons, test.wantReason) {
+ t.Fatalf("code=%d verdict=%q reasons=%#v stdout=%q stderr=%q", code, document.Verdict, document.Reasons, stdout, stderr)
+ }
+ if !strings.HasPrefix(stdout, "FAIL cases=") || stderr != "" {
+ t.Fatalf("stdout=%q stderr=%q", stdout, stderr)
+ }
+ })
+ }
+}
+
+func TestExactlyAtOutputCapDoesNotOverflow(t *testing.T) {
+ code, _, stderr, _, document := runFixtureAudit(t, []byte("A"), "exact-cap", []string{"4"}, defaultTimeout, 4)
+ if code != ExitPass || document.Verdict != "pass" {
+ t.Fatalf("code=%d verdict=%q reasons=%#v stderr=%q", code, document.Verdict, document.Reasons, stderr)
+ }
+ for _, item := range document.Cases {
+ if item.Execution.Stdout.CapturedByteLength != 4 || item.Execution.Stdout.Truncated {
+ t.Fatalf("case %s stdout=%+v", item.ID, item.Execution.Stdout)
+ }
+ }
+}
+
+func TestBaselineAndLaunchErrorsDoNotPublish(t *testing.T) {
+ tests := []struct {
+ name string
+ mode string
+ timeout time.Duration
+ limit int
+ }{
+ {name: "rejection", mode: "baseline-reject", timeout: defaultTimeout, limit: defaultMaxOutputBytes},
+ {name: "signal", mode: "baseline-signal", timeout: defaultTimeout, limit: defaultMaxOutputBytes},
+ {name: "timeout", mode: "baseline-timeout", timeout: 10 * time.Millisecond, limit: defaultMaxOutputBytes},
+ {name: "stdout overflow", mode: "baseline-stdout-overflow", timeout: defaultTimeout, limit: 4},
+ {name: "stderr overflow", mode: "baseline-stderr-overflow", timeout: defaultTimeout, limit: 4},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ directory := t.TempDir()
+ seedPath := writeSeed(t, directory, []byte("VALID"))
+ reportPath := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(reportPath, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv(fixtureEnvironment, "1")
+ options := fixtureOptions(seedPath, reportPath, []byte("VALID"), test.mode, nil, test.timeout, test.limit)
+ var stdout, stderr bytes.Buffer
+ if code := audit(context.Background(), options, &stdout, &stderr); code != ExitError {
+ t.Fatalf("code=%d stdout=%q stderr=%q", code, stdout.String(), stderr.String())
+ }
+ assertFileContents(t, reportPath, "existing")
+ })
+ }
+
+ t.Run("missing command", func(t *testing.T) {
+ directory := t.TempDir()
+ seedPath := writeSeed(t, directory, []byte("VALID"))
+ reportPath := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(reportPath, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ options := options{seedPath: seedPath, stdinSelected: true, timeout: defaultTimeout, maxOutput: 10, reportPath: reportPath, command: []string{filepath.Join(directory, "missing")}}
+ if code := audit(context.Background(), options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("code = %d", code)
+ }
+ assertFileContents(t, reportPath, "existing")
+ })
+
+ t.Run("non executable command", func(t *testing.T) {
+ directory := t.TempDir()
+ seedPath := writeSeed(t, directory, []byte("VALID"))
+ reportPath := filepath.Join(directory, "report.json")
+ commandPath := filepath.Join(directory, "not-executable")
+ if err := os.WriteFile(commandPath, []byte("data"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ options := options{seedPath: seedPath, stdinSelected: true, timeout: defaultTimeout, maxOutput: 10, reportPath: reportPath, command: []string{commandPath}}
+ if code := audit(context.Background(), options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("code = %d", code)
+ }
+ if _, err := os.Stat(reportPath); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("report exists or stat failed: %v", err)
+ }
+ })
+}
+
+func TestLiteralArgvExactStdinEOFEnvironmentAndWorkingDirectory(t *testing.T) {
+ directory := t.TempDir()
+ sentinel := filepath.Join(directory, "shell-expanded")
+ literal := []string{
+ "space value",
+ `"double" and 'single'`,
+ "*",
+ "$HOME",
+ "semi;colon",
+ `back\\slash`,
+ "$(touch " + sentinel + ")",
+ }
+ encoded, err := json.Marshal(literal)
+ if err != nil {
+ t.Fatal(err)
+ }
+ extra := append([]string{base64.StdEncoding.EncodeToString(encoded)}, literal...)
+ code, _, stderr, _, _ := runFixtureAudit(t, []byte{0, 1, 0xff, '\n'}, "literal", extra, defaultTimeout, defaultMaxOutputBytes)
+ if code != ExitPass {
+ t.Fatalf("literal audit code=%d stderr=%q", code, stderr)
+ }
+ if _, err := os.Stat(sentinel); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("shell substitution sentinel exists or stat failed: %v", err)
+ }
+
+ cwd, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ const environmentName = "TELL_FIXTURE_INHERITED"
+ const environmentValue = "exact inherited value"
+ t.Setenv(environmentName, environmentValue)
+ code, _, stderr, _, _ = runFixtureAudit(t, []byte("VALID"), "context", []string{cwd, environmentName, environmentValue}, defaultTimeout, defaultMaxOutputBytes)
+ if code != ExitPass {
+ t.Fatalf("context audit code=%d stderr=%q", code, stderr)
+ }
+}
+
+func TestInterruptionAndReportFailureLeaveExistingDestination(t *testing.T) {
+ t.Run("interruption", func(t *testing.T) {
+ directory := t.TempDir()
+ seed := []byte("A")
+ seedPath := writeSeed(t, directory, seed)
+ reportPath := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(reportPath, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv(fixtureEnvironment, "1")
+ options := fixtureOptions(seedPath, reportPath, seed, "timeout", nil, maximumTimeout, defaultMaxOutputBytes)
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
+ defer cancel()
+ if code := audit(ctx, options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("code = %d", code)
+ }
+ assertFileContents(t, reportPath, "existing")
+ })
+
+ t.Run("report publication", func(t *testing.T) {
+ directory := t.TempDir()
+ seed := []byte("A")
+ seedPath := writeSeed(t, directory, seed)
+ reportPath := filepath.Join(directory, "report.json")
+ if err := os.Mkdir(reportPath, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ sentinel := filepath.Join(reportPath, "sentinel")
+ if err := os.WriteFile(sentinel, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv(fixtureEnvironment, "1")
+ options := fixtureOptions(seedPath, reportPath, seed, "uniform", nil, defaultTimeout, defaultMaxOutputBytes)
+ if code := audit(context.Background(), options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("code = %d", code)
+ }
+ assertFileContents(t, sentinel, "existing")
+ entries, err := os.ReadDir(directory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 2 { // seed and destination directory
+ t.Fatalf("temporary report artifact remained: %#v", entries)
+ }
+ })
+}
+
+func TestSeedLimitAndSetupFailure(t *testing.T) {
+ directory := t.TempDir()
+ reportPath := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(reportPath, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ options := options{seedPath: filepath.Join(directory, "missing"), reportPath: reportPath}
+ if code := audit(context.Background(), options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("missing seed code = %d", code)
+ }
+ assertFileContents(t, reportPath, "existing")
+
+ tooLarge := filepath.Join(directory, "too-large")
+ file, err := os.Create(tooLarge)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := file.Truncate(maximumSeedBytes + 1); err != nil {
+ t.Fatal(err)
+ }
+ if err := file.Close(); err != nil {
+ t.Fatal(err)
+ }
+ options.seedPath = tooLarge
+ if code := audit(context.Background(), options, io.Discard, io.Discard); code != ExitError {
+ t.Fatalf("oversize seed code = %d", code)
+ }
+ assertFileContents(t, reportPath, "existing")
+
+ exact := filepath.Join(directory, "exact")
+ file, err = os.Create(exact)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := file.Truncate(maximumSeedBytes); err != nil {
+ t.Fatal(err)
+ }
+ if err := file.Close(); err != nil {
+ t.Fatal(err)
+ }
+ data, err := readSeed(exact)
+ if err != nil || len(data) != maximumSeedBytes {
+ t.Fatalf("exact-limit seed len=%d err=%v", len(data), err)
+ }
+}
+
+func TestFailureReasonOrder(t *testing.T) {
+ got := failureReasons(outcomeCounts{accepted: 1, signaled: 1, timedOut: 1, outputLimited: 1}, 2)
+ want := []string{"accepted_mutation", "nonuniform_rejection", "target_signaled", "target_timeout", "output_limit_exceeded"}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("reasons = %#v, want %#v", got, want)
+ }
+}
+
+func TestSummaryEscapesControlCharactersInReportPath(t *testing.T) {
+ path := "report\n\x1b[31m\u2028.json"
+ got := summary("fail", 1, outcomeCounts{accepted: 1}, 0, path)
+ if strings.ContainsAny(got, "\n\r\x1b") || strings.ContainsRune(got, '\u2028') {
+ t.Fatalf("summary contains a line break or terminal control: %q", got)
+ }
+ if !strings.Contains(got, `report="report\n\x1b[31m\u2028.json"`) {
+ t.Fatalf("summary path was not escaped: %q", got)
+ }
+ ordinary := summary("pass", 1, outcomeCounts{rejected: 1}, 1, "directory/report file.json")
+ if !strings.HasSuffix(ordinary, "report=directory/report file.json") {
+ t.Fatalf("ordinary report path changed: %q", ordinary)
+ }
+}
+
+func runFixtureAudit(t *testing.T, seed []byte, mode string, extra []string, timeout time.Duration, limit int) (int, string, string, []byte, report.Document) {
+ t.Helper()
+ directory := t.TempDir()
+ seedPath := writeSeed(t, directory, seed)
+ reportPath := filepath.Join(directory, "report.json")
+ t.Setenv(fixtureEnvironment, "1")
+ options := fixtureOptions(seedPath, reportPath, seed, mode, extra, timeout, limit)
+ var stdout, stderr bytes.Buffer
+ code := audit(context.Background(), options, &stdout, &stderr)
+ data, err := os.ReadFile(reportPath)
+ if err != nil {
+ t.Fatalf("read report after code %d (stderr %q): %v", code, stderr.String(), err)
+ }
+ info, err := os.Stat(reportPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != 0o600 {
+ t.Fatalf("report mode = %#o, want 0600", info.Mode().Perm())
+ }
+ var document report.Document
+ if err := json.Unmarshal(data, &document); err != nil {
+ t.Fatalf("decode report: %v\n%s", err, data)
+ }
+ return code, stdout.String(), stderr.String(), data, document
+}
+
+func fixtureOptions(seedPath, reportPath string, seed []byte, mode string, extra []string, timeout time.Duration, limit int) options {
+ command := []string{
+ os.Args[0],
+ "-test.run=^TestTargetFixture$",
+ "--",
+ mode,
+ base64.StdEncoding.EncodeToString(seed),
+ }
+ command = append(command, extra...)
+ return options{
+ seedPath: seedPath,
+ stdinSelected: true,
+ timeout: timeout,
+ maxOutput: limit,
+ reportPath: reportPath,
+ command: command,
+ }
+}
+
+func writeSeed(t *testing.T, directory string, seed []byte) string {
+ t.Helper()
+ path := filepath.Join(directory, "seed.bin")
+ if err := os.WriteFile(path, seed, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func assertFileContents(t *testing.T, path, want string) {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != want {
+ t.Fatalf("%s = %q, want %q", path, data, want)
+ }
+}
+
+func contains(values []string, want string) bool {
+ for _, value := range values {
+ if value == want {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/app/audit.go b/internal/app/audit.go
new file mode 100644
index 0000000..08e2ca2
--- /dev/null
+++ b/internal/app/audit.go
@@ -0,0 +1,242 @@
+package app
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+ "unicode"
+
+ "github.com/chasebryan/TELL/internal/mutate"
+ "github.com/chasebryan/TELL/internal/observe"
+ "github.com/chasebryan/TELL/internal/report"
+ "github.com/chasebryan/TELL/internal/runner"
+)
+
+type outcomeCounts struct {
+ accepted int
+ rejected int
+ signaled int
+ timedOut int
+ outputLimited int
+}
+
+func audit(ctx context.Context, options options, stdout, stderr io.Writer) int {
+ seed, err := readSeed(options.seedPath)
+ if err != nil {
+ return operationalError(stderr, err)
+ }
+ configuration := runner.Config{
+ Timeout: options.timeout,
+ MaxOutputBytes: options.maxOutput,
+ CleanupGrace: cleanupGrace,
+ }
+
+ baselineResult, err := runner.Run(ctx, options.command, seed, configuration)
+ if err != nil {
+ return runnerError(stderr, "baseline", err)
+ }
+ if baselineResult.Outcome != runner.OutcomeAccepted || baselineResult.ExitCode == nil || *baselineResult.ExitCode != 0 {
+ return operationalError(stderr, fmt.Errorf("baseline is not a valid accepted precondition: outcome=%s", baselineResult.Outcome))
+ }
+
+ document := report.NewDocument()
+ document.Configuration = report.Configuration{
+ Transport: "stdin",
+ MutationProfile: mutate.Profile,
+ TimeoutMS: options.timeout.Milliseconds(),
+ MaxOutputBytesPerStream: options.maxOutput,
+ }
+ document.Command = append([]string(nil), options.command...)
+ document.Seed = report.NewInput(seed)
+ document.Baseline = execution(baselineResult)
+
+ classes := observe.NewSet()
+ var outcomes outcomeCounts
+ counts, err := mutate.ForEach(seed, func(id string, descriptor mutate.Descriptor, candidate []byte, byteLength int64, sha256Hex string) error {
+ if err := ctx.Err(); err != nil {
+ return &runner.CanceledError{Cause: err}
+ }
+ result, err := runner.Run(ctx, options.command, candidate, configuration)
+ if err != nil {
+ return fmt.Errorf("execute %s: %w", id, err)
+ }
+
+ caseReport := report.Case{
+ ID: id,
+ Mutation: report.Mutation{
+ Kind: descriptor.Kind,
+ Offset: descriptor.Offset,
+ NewLength: descriptor.NewLength,
+ Mask: descriptor.Mask,
+ DataBase64: descriptor.DataBase64,
+ },
+ Input: report.Input{
+ ByteLength: int(byteLength),
+ SHA256Hex: sha256Hex,
+ },
+ Execution: execution(result),
+ }
+
+ switch result.Outcome {
+ case runner.OutcomeAccepted:
+ outcomes.accepted++
+ case runner.OutcomeRejected:
+ if result.ExitCode == nil {
+ return fmt.Errorf("%s: rejected result has no exit code", id)
+ }
+ outcomes.rejected++
+ classID, err := classes.Add(id, observe.Observation{
+ ExitCode: *result.ExitCode,
+ Stdout: result.Stdout.Data,
+ Stderr: result.Stderr.Data,
+ })
+ if err != nil {
+ return fmt.Errorf("classify %s: %w", id, err)
+ }
+ caseReport.ObservationClassID = &classID
+ case runner.OutcomeSignaled:
+ outcomes.signaled++
+ case runner.OutcomeTimedOut:
+ outcomes.timedOut++
+ case runner.OutcomeOutputLimited:
+ outcomes.outputLimited++
+ default:
+ return fmt.Errorf("%s: unknown outcome %q", id, result.Outcome)
+ }
+ document.Cases = append(document.Cases, caseReport)
+ return nil
+ })
+ if err != nil {
+ return runnerError(stderr, "mutation audit", err)
+ }
+ if counts.Planned > mutate.MaxPlannedCases || counts.Unique == 0 || len(document.Cases) != counts.Unique {
+ return operationalError(stderr, errors.New("internal mutation count invariant failed"))
+ }
+ document.MutationCounts = report.MutationCounts{
+ Planned: counts.Planned,
+ Unique: counts.Unique,
+ SkippedUnchanged: counts.SkippedUnchanged,
+ SkippedDuplicate: counts.SkippedDuplicate,
+ }
+
+ observedClasses := classes.Classes()
+ for _, class := range observedClasses {
+ stdoutMetadata := report.NewStream(class.Value.Stdout, false)
+ stderrMetadata := report.NewStream(class.Value.Stderr, false)
+ document.RejectionClasses = append(document.RejectionClasses, report.RejectionClass{
+ ID: class.ID,
+ ExitCode: class.Value.ExitCode,
+ StdoutByteLength: len(class.Value.Stdout),
+ StdoutSHA256Hex: stdoutMetadata.SHA256Hex,
+ StderrByteLength: len(class.Value.Stderr),
+ StderrSHA256Hex: stderrMetadata.SHA256Hex,
+ CaseIDs: append([]string(nil), class.CaseIDs...),
+ })
+ }
+
+ document.Reasons = failureReasons(outcomes, len(observedClasses))
+ if len(document.Reasons) == 0 {
+ document.Verdict = "pass"
+ } else {
+ document.Verdict = "fail"
+ }
+ if err := ctx.Err(); err != nil {
+ return runnerError(stderr, "audit", &runner.CanceledError{Cause: err})
+ }
+ if err := report.WriteAtomicContext(ctx, options.reportPath, document); err != nil {
+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return runnerError(stderr, "report publication", err)
+ }
+ return operationalError(stderr, fmt.Errorf("write report: %w", err))
+ }
+ _, _ = fmt.Fprintln(stdout, summary(document.Verdict, counts.Unique, outcomes, len(observedClasses), options.reportPath))
+ if document.Verdict == "pass" {
+ return ExitPass
+ }
+ return ExitFail
+}
+
+func execution(result runner.Result) report.Execution {
+ termination := report.Termination{
+ ExitCode: result.ExitCode,
+ SignalNumber: result.SignalNumber,
+ }
+ switch result.Outcome {
+ case runner.OutcomeAccepted, runner.OutcomeRejected:
+ termination.Kind = "exit"
+ case runner.OutcomeSignaled:
+ termination.Kind = "signal"
+ case runner.OutcomeTimedOut:
+ termination.Kind = "timeout"
+ case runner.OutcomeOutputLimited:
+ termination.Kind = "output_limit"
+ }
+ return report.Execution{
+ Outcome: string(result.Outcome),
+ Termination: termination,
+ Stdout: report.NewStream(result.Stdout.Data, result.Stdout.Truncated),
+ Stderr: report.NewStream(result.Stderr.Data, result.Stderr.Truncated),
+ }
+}
+
+func failureReasons(outcomes outcomeCounts, classCount int) []string {
+ reasons := make([]string, 0, 5)
+ if outcomes.accepted > 0 {
+ reasons = append(reasons, "accepted_mutation")
+ }
+ if classCount > 1 {
+ reasons = append(reasons, "nonuniform_rejection")
+ }
+ if outcomes.signaled > 0 {
+ reasons = append(reasons, "target_signaled")
+ }
+ if outcomes.timedOut > 0 {
+ reasons = append(reasons, "target_timeout")
+ }
+ if outcomes.outputLimited > 0 {
+ reasons = append(reasons, "output_limit_exceeded")
+ }
+ return reasons
+}
+
+func summary(verdict string, cases int, outcomes outcomeCounts, classes int, reportPath string) string {
+ if verdict == "pass" {
+ return fmt.Sprintf("PASS cases=%d rejected=%d classes=%d report=%s", cases, outcomes.rejected, classes, safeSummaryPath(reportPath))
+ }
+ parts := []string{
+ "FAIL",
+ fmt.Sprintf("cases=%d", cases),
+ fmt.Sprintf("accepted=%d", outcomes.accepted),
+ fmt.Sprintf("rejected=%d", outcomes.rejected),
+ fmt.Sprintf("signaled=%d", outcomes.signaled),
+ fmt.Sprintf("timed_out=%d", outcomes.timedOut),
+ fmt.Sprintf("output_limited=%d", outcomes.outputLimited),
+ fmt.Sprintf("classes=%d", classes),
+ "report=" + safeSummaryPath(reportPath),
+ }
+ return strings.Join(parts, " ")
+}
+
+func safeSummaryPath(path string) string {
+ if strings.IndexFunc(path, func(character rune) bool {
+ return unicode.IsControl(character) || character == '\u2028' || character == '\u2029'
+ }) >= 0 {
+ return strconv.Quote(path)
+ }
+ return path
+}
+
+func runnerError(stderr io.Writer, stage string, err error) int {
+ if errors.Is(err, runner.ErrCanceled) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+ return operationalError(stderr, fmt.Errorf("%s interrupted: %w", stage, err))
+ }
+ return operationalError(stderr, fmt.Errorf("%s incomplete: %w", stage, err))
+}
+
+func operationalError(stderr io.Writer, err error) int {
+ _, _ = fmt.Fprintf(stderr, "tell: %v\n", err)
+ return ExitError
+}
diff --git a/internal/mutate/mutate.go b/internal/mutate/mutate.go
new file mode 100644
index 0000000..b063387
--- /dev/null
+++ b/internal/mutate/mutate.go
@@ -0,0 +1,255 @@
+// Package mutate implements TELL's deterministic mutation profile.
+package mutate
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "fmt"
+)
+
+const (
+ // Profile is the name of the mutation profile implemented by this package.
+ Profile = "tell-default-v1"
+ // MaxPlannedCases is the largest number of candidates in the profile before
+ // unchanged and duplicate candidates are removed.
+ MaxPlannedCases = 29
+)
+
+const (
+ kindTruncate = "truncate"
+ kindDelete = "delete"
+ kindBitFlip = "bit_flip"
+ kindZero = "zero"
+ kindAppend = "append"
+)
+
+// Descriptor is the stable, reportable description of one mutation. Fields
+// that do not apply to a mutation are nil and therefore encode as JSON null.
+type Descriptor struct {
+ Kind string `json:"kind"`
+ Offset *int `json:"offset"`
+ NewLength *int `json:"new_length"`
+ Mask *uint8 `json:"mask"`
+ DataBase64 *string `json:"data_base64"`
+}
+
+// Counts describes candidate planning and filtering for one profile run.
+type Counts struct {
+ Planned int `json:"planned"`
+ Unique int `json:"unique"`
+ SkippedUnchanged int `json:"skipped_unchanged"`
+ SkippedDuplicate int `json:"skipped_duplicate"`
+}
+
+// Callback receives one retained candidate. candidate must be treated as
+// read-only and is valid only until the callback returns. Callers that need to
+// retain it must copy it. Callbacks are invoked sequentially.
+type Callback func(id string, descriptor Descriptor, candidate []byte, byteLength int64, sha256Hex string) error
+
+type candidateSpec struct {
+ descriptor Descriptor
+ offset int
+ newLength int
+ mask byte
+ data []byte
+}
+
+// ForEach generates the profile in its fixed order. It executes callback once
+// for every unique candidate that differs from seed, then discards that
+// candidate before generating the next one. Full candidate inputs are never
+// accumulated by this package.
+func ForEach(seed []byte, callback Callback) (Counts, error) {
+ return forEach(seed, nil, callback)
+}
+
+// indexDigestFunc is a test seam for exercising digest collisions in the
+// deduplication index. A nil function uses each candidate's real SHA-256.
+// Reported candidate hashes are always real SHA-256 values.
+type indexDigestFunc func([]byte) [sha256.Size]byte
+
+func forEach(seed []byte, indexDigest indexDigestFunc, callback Callback) (Counts, error) {
+ if callback == nil {
+ return Counts{}, fmt.Errorf("mutation callback is nil")
+ }
+
+ specs := plan(len(seed))
+ counts := Counts{Planned: len(specs)}
+ if counts.Planned > MaxPlannedCases {
+ return Counts{}, fmt.Errorf("internal mutation plan exceeds maximum: %d", counts.Planned)
+ }
+
+ // Buckets retain descriptors only. If hashes collide, exact equality is
+ // checked by comparing candidate bytes with the bytes described by every
+ // previously retained descriptor in the bucket.
+ seen := make(map[[sha256.Size]byte][]candidateSpec, len(specs))
+ for _, spec := range specs {
+ candidate := materialize(seed, spec)
+ if bytes.Equal(candidate, seed) {
+ counts.SkippedUnchanged++
+ continue
+ }
+
+ realDigest := sha256.Sum256(candidate)
+ indexKey := realDigest
+ if indexDigest != nil {
+ indexKey = indexDigest(candidate)
+ }
+
+ duplicate := false
+ for _, previous := range seen[indexKey] {
+ if describesBytes(seed, previous, candidate) {
+ duplicate = true
+ break
+ }
+ }
+ if duplicate {
+ counts.SkippedDuplicate++
+ continue
+ }
+
+ seen[indexKey] = append(seen[indexKey], spec)
+ counts.Unique++
+ id := fmt.Sprintf("case-%04d", counts.Unique)
+ if err := callback(id, spec.descriptor, candidate, int64(len(candidate)), hex.EncodeToString(realDigest[:])); err != nil {
+ return counts, err
+ }
+ }
+
+ return counts, nil
+}
+
+func plan(seedLength int) []candidateSpec {
+ positions := selectedPositions(seedLength)
+ specs := make([]candidateSpec, 0, MaxPlannedCases)
+
+ for _, length := range positions {
+ if length == seedLength {
+ continue
+ }
+ newLength := length
+ specs = append(specs, candidateSpec{
+ descriptor: Descriptor{Kind: kindTruncate, NewLength: &newLength},
+ newLength: length,
+ })
+ }
+ for _, offset := range positions {
+ reportOffset := offset
+ specs = append(specs, candidateSpec{
+ descriptor: Descriptor{Kind: kindDelete, Offset: &reportOffset},
+ offset: offset,
+ })
+ }
+ for _, mask := range []byte{0x01, 0x80} {
+ for _, offset := range positions {
+ reportOffset := offset
+ reportMask := uint8(mask)
+ specs = append(specs, candidateSpec{
+ descriptor: Descriptor{Kind: kindBitFlip, Offset: &reportOffset, Mask: &reportMask},
+ offset: offset,
+ mask: mask,
+ })
+ }
+ }
+ for _, offset := range positions {
+ reportOffset := offset
+ specs = append(specs, candidateSpec{
+ descriptor: Descriptor{Kind: kindZero, Offset: &reportOffset},
+ offset: offset,
+ })
+ }
+ for _, data := range [][]byte{
+ {0x00},
+ {0xff},
+ make([]byte, 8),
+ bytes.Repeat([]byte{0xff}, 8),
+ } {
+ encoded := base64.StdEncoding.EncodeToString(data)
+ specs = append(specs, candidateSpec{
+ descriptor: Descriptor{Kind: kindAppend, DataBase64: &encoded},
+ data: data,
+ })
+ }
+
+ return specs
+}
+
+func selectedPositions(seedLength int) []int {
+ if seedLength == 0 {
+ return nil
+ }
+
+ quarter, remainder := seedLength/4, seedLength%4
+ threeQuarters := quarter*3 + (remainder*3)/4
+ values := [...]int{0, quarter, seedLength / 2, threeQuarters, seedLength - 1}
+ positions := make([]int, 0, len(values))
+ for _, value := range values {
+ if value < 0 || value >= seedLength {
+ continue
+ }
+ if len(positions) == 0 || positions[len(positions)-1] != value {
+ positions = append(positions, value)
+ }
+ }
+ return positions
+}
+
+func materialize(seed []byte, spec candidateSpec) []byte {
+ switch spec.descriptor.Kind {
+ case kindTruncate:
+ candidate := make([]byte, spec.newLength)
+ copy(candidate, seed[:spec.newLength])
+ return candidate
+ case kindDelete:
+ candidate := make([]byte, len(seed)-1)
+ copy(candidate, seed[:spec.offset])
+ copy(candidate[spec.offset:], seed[spec.offset+1:])
+ return candidate
+ case kindBitFlip:
+ candidate := bytes.Clone(seed)
+ candidate[spec.offset] ^= spec.mask
+ return candidate
+ case kindZero:
+ candidate := bytes.Clone(seed)
+ candidate[spec.offset] = 0
+ return candidate
+ case kindAppend:
+ candidate := make([]byte, len(seed)+len(spec.data))
+ copy(candidate, seed)
+ copy(candidate[len(seed):], spec.data)
+ return candidate
+ default:
+ panic("unknown mutation kind")
+ }
+}
+
+// describesBytes checks exact equality without allocating another full
+// candidate. This keeps live candidate storage bounded even if every index
+// digest collides.
+func describesBytes(seed []byte, spec candidateSpec, candidate []byte) bool {
+ switch spec.descriptor.Kind {
+ case kindTruncate:
+ return len(candidate) == spec.newLength && bytes.Equal(candidate, seed[:spec.newLength])
+ case kindDelete:
+ return len(candidate) == len(seed)-1 &&
+ bytes.Equal(candidate[:spec.offset], seed[:spec.offset]) &&
+ bytes.Equal(candidate[spec.offset:], seed[spec.offset+1:])
+ case kindBitFlip:
+ return len(candidate) == len(seed) &&
+ bytes.Equal(candidate[:spec.offset], seed[:spec.offset]) &&
+ candidate[spec.offset] == seed[spec.offset]^spec.mask &&
+ bytes.Equal(candidate[spec.offset+1:], seed[spec.offset+1:])
+ case kindZero:
+ return len(candidate) == len(seed) &&
+ bytes.Equal(candidate[:spec.offset], seed[:spec.offset]) &&
+ candidate[spec.offset] == 0 &&
+ bytes.Equal(candidate[spec.offset+1:], seed[spec.offset+1:])
+ case kindAppend:
+ return len(candidate) == len(seed)+len(spec.data) &&
+ bytes.Equal(candidate[:len(seed)], seed) &&
+ bytes.Equal(candidate[len(seed):], spec.data)
+ default:
+ return false
+ }
+}
diff --git a/internal/mutate/mutate_test.go b/internal/mutate/mutate_test.go
new file mode 100644
index 0000000..93e06b4
--- /dev/null
+++ b/internal/mutate/mutate_test.go
@@ -0,0 +1,401 @@
+package mutate
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "reflect"
+ "runtime"
+ "testing"
+)
+
+type collectedCase struct {
+ id string
+ descriptor Descriptor
+ input []byte
+ length int64
+ hash string
+}
+
+func collect(t *testing.T, seed []byte) (Counts, []collectedCase) {
+ t.Helper()
+ var cases []collectedCase
+ counts, err := ForEach(seed, func(id string, descriptor Descriptor, candidate []byte, length int64, hash string) error {
+ cases = append(cases, collectedCase{
+ id: id,
+ descriptor: descriptor,
+ input: bytes.Clone(candidate),
+ length: length,
+ hash: hash,
+ })
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("ForEach() error = %v", err)
+ }
+ return counts, cases
+}
+
+func TestEmptySeedExactProfile(t *testing.T) {
+ counts, cases := collect(t, nil)
+ if want := (Counts{Planned: 4, Unique: 4}); counts != want {
+ t.Fatalf("counts = %+v, want %+v", counts, want)
+ }
+
+ wantInputs := [][]byte{
+ {0x00},
+ {0xff},
+ make([]byte, 8),
+ bytes.Repeat([]byte{0xff}, 8),
+ }
+ wantData := []string{"AA==", "/w==", "AAAAAAAAAAA=", "//////////8="}
+ for i := range cases {
+ assertCaseMetadata(t, cases[i], i, wantInputs[i])
+ assertDescriptor(t, cases[i].descriptor, kindAppend, nil, nil, nil, &wantData[i])
+ }
+
+ wantHashes := []string{
+ "6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d",
+ "a8100ae6aa1940d0b663bb31cd466142ebbdbd5187131b92d93818987832eb89",
+ "af5570f5a1810b7af78caf4bc70a660f0df51e42baf91d4de5b2328de0e83dfc",
+ "12a3ae445661ce5dee78d0650d33362dec29c4f82af05e7e57fb595bbbacf0ca",
+ }
+ for i := range cases {
+ if cases[i].hash != wantHashes[i] {
+ t.Errorf("case %d hash = %q, want %q", i, cases[i].hash, wantHashes[i])
+ }
+ }
+}
+
+func TestOneByteSeedNoOpAndDuplicateElimination(t *testing.T) {
+ counts, cases := collect(t, []byte{0x00})
+ wantCounts := Counts{Planned: 9, Unique: 7, SkippedUnchanged: 1, SkippedDuplicate: 1}
+ if counts != wantCounts {
+ t.Fatalf("counts = %+v, want %+v", counts, wantCounts)
+ }
+
+ want := []struct {
+ kind string
+ offset *int
+ newLength *int
+ mask *uint8
+ dataBase64 *string
+ input []byte
+ }{
+ {kind: kindTruncate, newLength: integer(0), input: []byte{}},
+ {kind: kindBitFlip, offset: integer(0), mask: u8(0x01), input: []byte{0x01}},
+ {kind: kindBitFlip, offset: integer(0), mask: u8(0x80), input: []byte{0x80}},
+ {kind: kindAppend, dataBase64: str("AA=="), input: []byte{0x00, 0x00}},
+ {kind: kindAppend, dataBase64: str("/w=="), input: []byte{0x00, 0xff}},
+ {kind: kindAppend, dataBase64: str("AAAAAAAAAAA="), input: make([]byte, 9)},
+ {kind: kindAppend, dataBase64: str("//////////8="), input: append([]byte{0x00}, bytes.Repeat([]byte{0xff}, 8)...)},
+ }
+ for i := range want {
+ assertCaseMetadata(t, cases[i], i, want[i].input)
+ assertDescriptor(t, cases[i].descriptor, want[i].kind, want[i].offset, want[i].newLength, want[i].mask, want[i].dataBase64)
+ }
+ if cases[0].hash != "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" {
+ t.Errorf("empty candidate hash = %q", cases[0].hash)
+ }
+}
+
+func TestAllZeroSeedExactOrderAndFiltering(t *testing.T) {
+ seed := make([]byte, 4)
+ counts, cases := collect(t, seed)
+ wantCounts := Counts{Planned: 24, Unique: 16, SkippedUnchanged: 4, SkippedDuplicate: 4}
+ if counts != wantCounts {
+ t.Fatalf("counts = %+v, want %+v", counts, wantCounts)
+ }
+
+ var wantInputs [][]byte
+ var wantDescriptors []Descriptor
+ for length := 0; length < 4; length++ {
+ wantInputs = append(wantInputs, make([]byte, length))
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindTruncate, NewLength: integer(length)})
+ }
+ for _, mask := range []byte{0x01, 0x80} {
+ for offset := 0; offset < 4; offset++ {
+ input := make([]byte, 4)
+ input[offset] = mask
+ wantInputs = append(wantInputs, input)
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindBitFlip, Offset: integer(offset), Mask: u8(mask)})
+ }
+ }
+ appendData := [][]byte{{0}, {0xff}, make([]byte, 8), bytes.Repeat([]byte{0xff}, 8)}
+ for _, data := range appendData {
+ wantInputs = append(wantInputs, append(bytes.Clone(seed), data...))
+ encoded := map[int]string{1: "AA==", 8: "AAAAAAAAAAA="}[len(data)]
+ if data[0] == 0xff {
+ encoded = map[int]string{1: "/w==", 8: "//////////8="}[len(data)]
+ }
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindAppend, DataBase64: str(encoded)})
+ }
+
+ if len(cases) != len(wantInputs) {
+ t.Fatalf("case count = %d, want %d", len(cases), len(wantInputs))
+ }
+ for i := range cases {
+ assertCaseMetadata(t, cases[i], i, wantInputs[i])
+ if !reflect.DeepEqual(cases[i].descriptor, wantDescriptors[i]) {
+ t.Errorf("case %d descriptor = %#v, want %#v", i, cases[i].descriptor, wantDescriptors[i])
+ }
+ }
+}
+
+func TestOrdinarySeedExactCandidateOrder(t *testing.T) {
+ seed := []byte("abcdefgh")
+ counts, cases := collect(t, seed)
+ wantCounts := Counts{Planned: MaxPlannedCases, Unique: 28, SkippedDuplicate: 1}
+ if counts != wantCounts {
+ t.Fatalf("counts = %+v, want %+v", counts, wantCounts)
+ }
+
+ var wantInputs [][]byte
+ var wantDescriptors []Descriptor
+ positions := []int{0, 2, 4, 6, 7}
+ for _, length := range positions {
+ wantInputs = append(wantInputs, bytes.Clone(seed[:length]))
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindTruncate, NewLength: integer(length)})
+ }
+ // Deleting the final byte duplicates truncation to length seven and is not retained.
+ for _, offset := range positions[:4] {
+ input := append(bytes.Clone(seed[:offset]), seed[offset+1:]...)
+ wantInputs = append(wantInputs, input)
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindDelete, Offset: integer(offset)})
+ }
+ for _, mask := range []byte{0x01, 0x80} {
+ for _, offset := range positions {
+ input := bytes.Clone(seed)
+ input[offset] ^= mask
+ wantInputs = append(wantInputs, input)
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindBitFlip, Offset: integer(offset), Mask: u8(mask)})
+ }
+ }
+ for _, offset := range positions {
+ input := bytes.Clone(seed)
+ input[offset] = 0
+ wantInputs = append(wantInputs, input)
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindZero, Offset: integer(offset)})
+ }
+ for _, item := range []struct {
+ data []byte
+ encoded string
+ }{
+ {[]byte{0x00}, "AA=="},
+ {[]byte{0xff}, "/w=="},
+ {make([]byte, 8), "AAAAAAAAAAA="},
+ {bytes.Repeat([]byte{0xff}, 8), "//////////8="},
+ } {
+ wantInputs = append(wantInputs, append(bytes.Clone(seed), item.data...))
+ wantDescriptors = append(wantDescriptors, Descriptor{Kind: kindAppend, DataBase64: str(item.encoded)})
+ }
+
+ if len(cases) != len(wantInputs) {
+ t.Fatalf("case count = %d, want %d", len(cases), len(wantInputs))
+ }
+ for i := range cases {
+ assertCaseMetadata(t, cases[i], i, wantInputs[i])
+ if !reflect.DeepEqual(cases[i].descriptor, wantDescriptors[i]) {
+ t.Errorf("case %d descriptor = %#v, want %#v", i, cases[i].descriptor, wantDescriptors[i])
+ }
+ }
+}
+
+func TestEveryMutationStartsFromOriginalSeed(t *testing.T) {
+ seed := []byte("abcdefgh")
+ _, cases := collect(t, seed)
+ for _, c := range cases {
+ if c.descriptor.Kind != kindBitFlip {
+ continue
+ }
+ offset := int(*c.descriptor.Offset)
+ for i := range seed {
+ want := seed[i]
+ if i == offset {
+ want ^= *c.descriptor.Mask
+ }
+ if c.input[i] != want {
+ t.Fatalf("%s is cumulative: byte %d = %#x, want %#x", c.id, i, c.input[i], want)
+ }
+ }
+ }
+}
+
+func TestDigestCollisionIndexStillUsesExactEquality(t *testing.T) {
+ seed := []byte("abcde")
+ var cases []collectedCase
+ counts, err := forEach(seed, func([]byte) [sha256.Size]byte { return [sha256.Size]byte{} }, func(id string, descriptor Descriptor, candidate []byte, length int64, hash string) error {
+ cases = append(cases, collectedCase{id: id, descriptor: descriptor, input: bytes.Clone(candidate), length: length, hash: hash})
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("forEach() error = %v", err)
+ }
+ wantCounts := Counts{Planned: MaxPlannedCases, Unique: 28, SkippedDuplicate: 1}
+ if counts != wantCounts {
+ t.Fatalf("counts = %+v, want %+v", counts, wantCounts)
+ }
+ seen := make(map[string]struct{}, len(cases))
+ for _, c := range cases {
+ key := string(c.input)
+ if _, exists := seen[key]; exists {
+ t.Fatalf("duplicate input retained for %s", c.id)
+ }
+ seen[key] = struct{}{}
+ if c.hash != hashHex(c.input) {
+ t.Errorf("%s reported forced index digest instead of SHA-256", c.id)
+ }
+ }
+}
+
+func TestMaximumPlannedCases(t *testing.T) {
+ for length := 0; length <= 64; length++ {
+ counts, _ := collect(t, make([]byte, length))
+ if counts.Planned > MaxPlannedCases {
+ t.Fatalf("length %d planned %d cases, maximum is %d", length, counts.Planned, MaxPlannedCases)
+ }
+ }
+ counts, _ := collect(t, []byte{1, 2, 3, 4, 5})
+ if counts.Planned != MaxPlannedCases {
+ t.Fatalf("five-byte seed planned %d cases, want %d", counts.Planned, MaxPlannedCases)
+ }
+}
+
+func TestStreamingCallbackIsSequentialAndCandidatesAreIndependent(t *testing.T) {
+ seed := bytes.Repeat([]byte{0x5a}, 1<<20)
+ callbackActive := false
+ callbacks := 0
+ _, err := ForEach(seed, func(_ string, _ Descriptor, candidate []byte, _ int64, _ string) error {
+ if callbackActive {
+ t.Fatal("callbacks overlapped")
+ }
+ callbackActive = true
+ callbacks++
+ if len(candidate) > 0 {
+ candidate[0] ^= 0xff
+ }
+ callbackActive = false
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("ForEach() error = %v", err)
+ }
+ if callbacks == 0 {
+ t.Fatal("no callbacks")
+ }
+ if !bytes.Equal(seed, bytes.Repeat([]byte{0x5a}, len(seed))) {
+ t.Fatal("callback mutation changed the original seed")
+ }
+ // The package retains only descriptors in its deduplication index; the
+ // large candidate is materialized only for the duration of each callback.
+}
+
+func TestLiveCandidateAllocationIsBounded(t *testing.T) {
+ const seedBytes = 4 << 20
+ seed := bytes.Repeat([]byte{0x5a}, seedBytes)
+ runtime.GC()
+ var baseline runtime.MemStats
+ runtime.ReadMemStats(&baseline)
+ peak := baseline.HeapAlloc
+
+ counts, err := ForEach(seed, func(_ string, _ Descriptor, candidate []byte, _ int64, _ string) error {
+ // Force unreachable candidates to be collected while keeping the current
+ // callback-scoped candidate live through the measurement.
+ runtime.GC()
+ var current runtime.MemStats
+ runtime.ReadMemStats(¤t)
+ if current.HeapAlloc > peak {
+ peak = current.HeapAlloc
+ }
+ runtime.KeepAlive(candidate)
+ return nil
+ })
+ runtime.KeepAlive(seed)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if counts.Unique == 0 {
+ t.Fatal("no mutation candidates were measured")
+ }
+
+ // A seed plus one current candidate requires roughly 8 MiB. Allow a wide
+ // margin for runtime/package bookkeeping, while remaining far below the
+ // memory needed to retain the profile's many full-size candidates.
+ const maximumAdditionalLiveHeap = 5 * seedBytes
+ if peak > baseline.HeapAlloc+maximumAdditionalLiveHeap {
+ t.Fatalf("additional live heap = %d bytes, want <= %d (baseline=%d peak=%d)", peak-baseline.HeapAlloc, maximumAdditionalLiveHeap, baseline.HeapAlloc, peak)
+ }
+}
+
+func TestCallbackErrorStopsIteration(t *testing.T) {
+ wantErr := errors.New("stop")
+ calls := 0
+ counts, err := ForEach([]byte("abcde"), func(string, Descriptor, []byte, int64, string) error {
+ calls++
+ return wantErr
+ })
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("error = %v, want %v", err, wantErr)
+ }
+ if calls != 1 || counts.Unique != 1 || counts.Planned != MaxPlannedCases {
+ t.Fatalf("calls = %d, counts = %+v", calls, counts)
+ }
+}
+
+func TestNilCallbackRejected(t *testing.T) {
+ counts, err := ForEach([]byte("seed"), nil)
+ if err == nil {
+ t.Fatal("ForEach() error = nil")
+ }
+ if counts != (Counts{}) {
+ t.Fatalf("counts = %+v, want zero", counts)
+ }
+}
+
+func TestDescriptorJSONFieldOrderAndNulls(t *testing.T) {
+ encoded, err := json.Marshal(Descriptor{Kind: kindDelete, Offset: integer(2)})
+ if err != nil {
+ t.Fatalf("json.Marshal() error = %v", err)
+ }
+ want := `{"kind":"delete","offset":2,"new_length":null,"mask":null,"data_base64":null}`
+ if string(encoded) != want {
+ t.Fatalf("descriptor JSON = %s, want %s", encoded, want)
+ }
+}
+
+func assertCaseMetadata(t *testing.T, got collectedCase, index int, wantInput []byte) {
+ t.Helper()
+ wantID := fmt.Sprintf("case-%04d", index+1)
+ if got.id != wantID {
+ t.Errorf("id = %q, want %q", got.id, wantID)
+ }
+ if !bytes.Equal(got.input, wantInput) {
+ t.Errorf("%s input = %x, want %x", got.id, got.input, wantInput)
+ }
+ if got.length != int64(len(wantInput)) {
+ t.Errorf("%s length = %d, want %d", got.id, got.length, len(wantInput))
+ }
+ if got.hash != hashHex(wantInput) {
+ t.Errorf("%s hash = %q, want %q", got.id, got.hash, hashHex(wantInput))
+ }
+}
+
+func assertDescriptor(t *testing.T, got Descriptor, kind string, offset, newLength *int, mask *uint8, dataBase64 *string) {
+ t.Helper()
+ want := Descriptor{Kind: kind, Offset: offset, NewLength: newLength, Mask: mask, DataBase64: dataBase64}
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("descriptor = %#v, want %#v", got, want)
+ }
+}
+
+func hashHex(data []byte) string {
+ digest := sha256.Sum256(data)
+ return hex.EncodeToString(digest[:])
+}
+
+func integer(value int) *int { return &value }
+func u8(value uint8) *uint8 { return &value }
+func str(value string) *string { return &value }
diff --git a/internal/observe/observe.go b/internal/observe/observe.go
new file mode 100644
index 0000000..e099930
--- /dev/null
+++ b/internal/observe/observe.go
@@ -0,0 +1,122 @@
+// Package observe defines exact rejection observations and their deterministic
+// equivalence-class identifiers.
+package observe
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "encoding/binary"
+ "encoding/hex"
+ "errors"
+ "sort"
+)
+
+const classDomain = "TELL\x00OBSERVATION\x00V1\x00"
+
+// ErrDigestCollision is returned rather than merging unequal observations
+// that happen to have the same class digest.
+var ErrDigestCollision = errors.New("observation class digest collision")
+
+// Observation is the complete equality input for a normally rejected case.
+type Observation struct {
+ ExitCode int
+ Stdout []byte
+ Stderr []byte
+}
+
+// Equal compares the exit code and both streams byte for byte.
+func (o Observation) Equal(other Observation) bool {
+ return o.ExitCode == other.ExitCode &&
+ bytes.Equal(o.Stdout, other.Stdout) &&
+ bytes.Equal(o.Stderr, other.Stderr)
+}
+
+// Class is one exact rejection equivalence class.
+type Class struct {
+ ID string
+ Value Observation
+ CaseIDs []string
+}
+
+// Set accumulates rejection classes. It is not safe for concurrent use; TELL
+// intentionally executes cases sequentially.
+type Set struct {
+ hasher func([]byte) [sha256.Size]byte
+ byID map[string]int
+ classes []Class
+}
+
+// NewSet creates an empty class set using SHA-256.
+func NewSet() *Set {
+ return newSet(sha256.Sum256)
+}
+
+func newSet(hasher func([]byte) [sha256.Size]byte) *Set {
+ return &Set{
+ hasher: hasher,
+ byID: make(map[string]int),
+ }
+}
+
+// Add establishes membership through exact equality and returns the class ID.
+func (s *Set) Add(caseID string, value Observation) (string, error) {
+ preimage := encode(value)
+ digest := s.hasher(preimage)
+ id := "obs-" + hex.EncodeToString(digest[:])
+ if index, ok := s.byID[id]; ok {
+ if !s.classes[index].Value.Equal(value) {
+ return "", ErrDigestCollision
+ }
+ s.classes[index].CaseIDs = append(s.classes[index].CaseIDs, caseID)
+ return id, nil
+ }
+
+ // Copy output because callers may reuse their capture buffers.
+ value.Stdout = append([]byte(nil), value.Stdout...)
+ value.Stderr = append([]byte(nil), value.Stderr...)
+ s.byID[id] = len(s.classes)
+ s.classes = append(s.classes, Class{
+ ID: id,
+ Value: value,
+ CaseIDs: []string{caseID},
+ })
+ return id, nil
+}
+
+// Classes returns a copy sorted lexicographically by class ID. Case IDs retain
+// insertion (and therefore mutation) order.
+func (s *Set) Classes() []Class {
+ classes := make([]Class, len(s.classes))
+ for i := range s.classes {
+ classes[i] = Class{
+ ID: s.classes[i].ID,
+ Value: s.classes[i].Value,
+ CaseIDs: append([]string(nil), s.classes[i].CaseIDs...),
+ }
+ }
+ sort.Slice(classes, func(i, j int) bool { return classes[i].ID < classes[j].ID })
+ return classes
+}
+
+// ClassID returns the deterministic identifier for one observation.
+func ClassID(value Observation) string {
+ digest := sha256.Sum256(encode(value))
+ return "obs-" + hex.EncodeToString(digest[:])
+}
+
+func encode(value Observation) []byte {
+ // The maximum captured streams are bounded by the runner. The append-based
+ // encoding keeps the exact bytes visible to the digest and is unambiguous.
+ preimage := make([]byte, 0, len(classDomain)+4+8+len(value.Stdout)+8+len(value.Stderr))
+ preimage = append(preimage, classDomain...)
+ var numbers [8]byte
+ binary.BigEndian.PutUint32(numbers[:4], uint32(value.ExitCode))
+ preimage = append(preimage, numbers[:4]...)
+ binary.BigEndian.PutUint64(numbers[:], uint64(len(value.Stdout)))
+ preimage = append(preimage, numbers[:]...)
+ preimage = append(preimage, value.Stdout...)
+ binary.BigEndian.PutUint64(numbers[:], uint64(len(value.Stderr)))
+ preimage = append(preimage, numbers[:]...)
+ preimage = append(preimage, value.Stderr...)
+ return preimage
+}
diff --git a/internal/observe/observe_test.go b/internal/observe/observe_test.go
new file mode 100644
index 0000000..4482bbd
--- /dev/null
+++ b/internal/observe/observe_test.go
@@ -0,0 +1,100 @@
+package observe
+
+import (
+ "crypto/sha256"
+ "errors"
+ "reflect"
+ "testing"
+)
+
+func TestObservationEqualityIsExact(t *testing.T) {
+ base := Observation{ExitCode: 7, Stdout: []byte{'o', 0, 0xff, '\n'}, Stderr: []byte("err\n")}
+ tests := []struct {
+ name string
+ value Observation
+ }{
+ {"exit code", Observation{ExitCode: 8, Stdout: base.Stdout, Stderr: base.Stderr}},
+ {"stdout", Observation{ExitCode: 7, Stdout: []byte{'o', 0, 0xfe, '\n'}, Stderr: base.Stderr}},
+ {"stderr", Observation{ExitCode: 7, Stdout: base.Stdout, Stderr: []byte("err")}},
+ {"swapped streams", Observation{ExitCode: 7, Stdout: base.Stderr, Stderr: base.Stdout}},
+ }
+ if !base.Equal(base) {
+ t.Fatal("observation does not equal itself")
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if base.Equal(test.value) {
+ t.Fatal("unequal observation compared equal")
+ }
+ if ClassID(base) == ClassID(test.value) {
+ t.Fatal("distinct test observations unexpectedly share a class ID")
+ }
+ })
+ }
+}
+
+func TestKnownClassDigest(t *testing.T) {
+ value := Observation{ExitCode: 7, Stdout: []byte{0, 0xff}, Stderr: []byte("err\n")}
+ const want = "obs-9b329a3ac1ec5905731539740bedbe62f4c963b1d94621d1eddb1a3abba8f2b6"
+ if got := ClassID(value); got != want {
+ t.Fatalf("ClassID() = %q, want %q", got, want)
+ }
+}
+
+func TestSetMembershipOrderingAndCopies(t *testing.T) {
+ set := NewSet()
+ one := Observation{ExitCode: 2, Stdout: []byte("one"), Stderr: []byte{0xff}}
+ two := Observation{ExitCode: 3, Stdout: []byte("two"), Stderr: []byte{0}}
+ twoID, err := set.Add("case-0001", two)
+ if err != nil {
+ t.Fatal(err)
+ }
+ oneID, err := set.Add("case-0002", one)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := set.Add("case-0003", two); err != nil {
+ t.Fatal(err)
+ }
+ // Verify Add retained exact bytes rather than aliases.
+ two.Stdout[0] = 'X'
+
+ classes := set.Classes()
+ if len(classes) != 2 {
+ t.Fatalf("len(Classes()) = %d, want 2", len(classes))
+ }
+ if classes[0].ID > classes[1].ID {
+ t.Fatalf("classes are not lexicographically sorted: %q, %q", classes[0].ID, classes[1].ID)
+ }
+ byID := map[string]Class{classes[0].ID: classes[0], classes[1].ID: classes[1]}
+ if got := byID[twoID].CaseIDs; !reflect.DeepEqual(got, []string{"case-0001", "case-0003"}) {
+ t.Fatalf("two case IDs = %#v", got)
+ }
+ if got := byID[oneID].CaseIDs; !reflect.DeepEqual(got, []string{"case-0002"}) {
+ t.Fatalf("one case IDs = %#v", got)
+ }
+ if got := string(byID[twoID].Value.Stdout); got != "two" {
+ t.Fatalf("stored stdout = %q, want two", got)
+ }
+
+ classes[0].CaseIDs[0] = "changed"
+ if set.Classes()[0].CaseIDs[0] == "changed" {
+ t.Fatal("Classes returned aliased case ID storage")
+ }
+}
+
+func TestSetRejectsDigestCollision(t *testing.T) {
+ zeroDigest := func([]byte) [sha256.Size]byte { return [sha256.Size]byte{} }
+ set := newSet(zeroDigest)
+ first := Observation{ExitCode: 1, Stdout: []byte("a")}
+ if _, err := set.Add("case-0001", first); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := set.Add("case-0002", first); err != nil {
+ t.Fatalf("equal observation rejected: %v", err)
+ }
+ _, err := set.Add("case-0003", Observation{ExitCode: 1, Stdout: []byte("b")})
+ if !errors.Is(err, ErrDigestCollision) {
+ t.Fatalf("collision error = %v, want %v", err, ErrDigestCollision)
+ }
+}
diff --git a/internal/report/report.go b/internal/report/report.go
new file mode 100644
index 0000000..9e34a8d
--- /dev/null
+++ b/internal/report/report.go
@@ -0,0 +1,263 @@
+// Package report defines and writes the deterministic tell-report-v1 format.
+package report
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+const (
+ Schema = "tell-report-v1"
+ ToolName = "tell"
+ ToolVersion = "1.0.0"
+)
+
+type Document struct {
+ Schema string `json:"schema"`
+ Tool Tool `json:"tool"`
+ Verdict string `json:"verdict"`
+ Reasons []string `json:"reasons"`
+ Configuration Configuration `json:"configuration"`
+ Command []string `json:"command"`
+ Seed Input `json:"seed"`
+ Baseline Execution `json:"baseline"`
+ MutationCounts MutationCounts `json:"mutation_counts"`
+ Cases []Case `json:"cases"`
+ RejectionClasses []RejectionClass `json:"rejection_classes"`
+}
+
+type Tool struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+}
+
+type Configuration struct {
+ Transport string `json:"transport"`
+ MutationProfile string `json:"mutation_profile"`
+ TimeoutMS int64 `json:"timeout_ms"`
+ MaxOutputBytesPerStream int `json:"max_output_bytes_per_stream"`
+}
+
+type Input struct {
+ ByteLength int `json:"byte_length"`
+ SHA256Hex string `json:"sha256_hex"`
+}
+
+type Execution struct {
+ Outcome string `json:"outcome"`
+ Termination Termination `json:"termination"`
+ Stdout Stream `json:"stdout"`
+ Stderr Stream `json:"stderr"`
+}
+
+type Termination struct {
+ Kind string `json:"kind"`
+ ExitCode *int `json:"exit_code"`
+ SignalNumber *int `json:"signal_number"`
+}
+
+type Stream struct {
+ CapturedByteLength int `json:"captured_byte_length"`
+ SHA256Hex string `json:"sha256_hex"`
+ DataBase64 string `json:"data_base64"`
+ Truncated bool `json:"truncated"`
+}
+
+type MutationCounts struct {
+ Planned int `json:"planned"`
+ Unique int `json:"unique"`
+ SkippedUnchanged int `json:"skipped_unchanged"`
+ SkippedDuplicate int `json:"skipped_duplicate"`
+}
+
+type Case struct {
+ ID string `json:"id"`
+ Mutation Mutation `json:"mutation"`
+ Input Input `json:"input"`
+ Execution Execution `json:"execution"`
+ ObservationClassID *string `json:"observation_class_id"`
+}
+
+type Mutation struct {
+ Kind string `json:"kind"`
+ Offset *int `json:"offset"`
+ NewLength *int `json:"new_length"`
+ Mask *uint8 `json:"mask"`
+ DataBase64 *string `json:"data_base64"`
+}
+
+type RejectionClass struct {
+ ID string `json:"id"`
+ ExitCode int `json:"exit_code"`
+ StdoutByteLength int `json:"stdout_byte_length"`
+ StdoutSHA256Hex string `json:"stdout_sha256_hex"`
+ StderrByteLength int `json:"stderr_byte_length"`
+ StderrSHA256Hex string `json:"stderr_sha256_hex"`
+ CaseIDs []string `json:"case_ids"`
+}
+
+// NewDocument initializes fixed schema and tool fields and all required arrays.
+func NewDocument() Document {
+ return Document{
+ Schema: Schema,
+ Tool: Tool{
+ Name: ToolName,
+ Version: ToolVersion,
+ },
+ Reasons: []string{},
+ Command: []string{},
+ Cases: []Case{},
+ RejectionClasses: []RejectionClass{},
+ }
+}
+
+// NewInput returns length and lowercase SHA-256 metadata without retaining the
+// input bytes.
+func NewInput(data []byte) Input {
+ digest := sha256.Sum256(data)
+ return Input{ByteLength: len(data), SHA256Hex: hex.EncodeToString(digest[:])}
+}
+
+// NewStream encodes captured bytes losslessly using padded standard Base64.
+func NewStream(data []byte, truncated bool) Stream {
+ digest := sha256.Sum256(data)
+ return Stream{
+ CapturedByteLength: len(data),
+ SHA256Hex: hex.EncodeToString(digest[:]),
+ DataBase64: base64.StdEncoding.EncodeToString(data),
+ Truncated: truncated,
+ }
+}
+
+// Marshal produces deterministic two-space-indented JSON with HTML escaping
+// disabled and exactly one trailing newline.
+func Marshal(document Document) ([]byte, error) {
+ ensureArrays(&document)
+ var output bytes.Buffer
+ encoder := json.NewEncoder(&output)
+ encoder.SetEscapeHTML(false)
+ encoder.SetIndent("", " ")
+ if err := encoder.Encode(document); err != nil {
+ return nil, fmt.Errorf("encode report: %w", err)
+ }
+ return output.Bytes(), nil
+}
+
+func ensureArrays(document *Document) {
+ if document.Reasons == nil {
+ document.Reasons = []string{}
+ }
+ if document.Command == nil {
+ document.Command = []string{}
+ }
+ if document.Cases == nil {
+ document.Cases = []Case{}
+ }
+ if document.RejectionClasses == nil {
+ document.RejectionClasses = []RejectionClass{}
+ }
+ for i := range document.RejectionClasses {
+ if document.RejectionClasses[i].CaseIDs == nil {
+ document.RejectionClasses[i].CaseIDs = []string{}
+ }
+ }
+}
+
+// WriteAtomic writes a private same-directory temporary file and renames it
+// only after the complete report has been written, synced, and closed.
+func WriteAtomic(path string, document Document) (err error) {
+ return WriteAtomicContext(context.Background(), path, document)
+}
+
+// WriteAtomicContext is WriteAtomic with interruption checks throughout
+// serialization and temporary-file publication. Cancellation before the final
+// rename removes the temporary file and leaves the destination untouched.
+func WriteAtomicContext(ctx context.Context, path string, document Document) (err error) {
+ if err := contextError(ctx); err != nil {
+ return err
+ }
+ data, err := Marshal(document)
+ if err != nil {
+ return err
+ }
+ if err := contextError(ctx); err != nil {
+ return err
+ }
+ if path == "" {
+ return errors.New("report path is empty")
+ }
+ directory := filepath.Dir(path)
+ base := filepath.Base(path)
+ temporary, err := os.CreateTemp(directory, "."+base+".tmp-*")
+ if err != nil {
+ return fmt.Errorf("create temporary report: %w", err)
+ }
+ temporaryPath := temporary.Name()
+ defer func() {
+ _ = temporary.Close()
+ _ = os.Remove(temporaryPath)
+ }()
+
+ if err := temporary.Chmod(0o600); err != nil {
+ return fmt.Errorf("set temporary report permissions: %w", err)
+ }
+ if err := writeContext(ctx, temporary, data); err != nil {
+ return fmt.Errorf("write temporary report: %w", err)
+ }
+ if err := contextError(ctx); err != nil {
+ return err
+ }
+ if err := temporary.Sync(); err != nil {
+ return fmt.Errorf("sync temporary report: %w", err)
+ }
+ if err := temporary.Close(); err != nil {
+ return fmt.Errorf("close temporary report: %w", err)
+ }
+ // Rename is the publication linearization point. A cancellation observed
+ // before it leaves the previous destination in place.
+ if err := contextError(ctx); err != nil {
+ return err
+ }
+ if err := os.Rename(temporaryPath, path); err != nil {
+ return fmt.Errorf("publish report: %w", err)
+ }
+ return nil
+}
+
+func writeContext(ctx context.Context, writer *os.File, data []byte) error {
+ const chunkSize = 64 * 1024
+ for len(data) > 0 {
+ if err := contextError(ctx); err != nil {
+ return err
+ }
+ chunk := data
+ if len(chunk) > chunkSize {
+ chunk = chunk[:chunkSize]
+ }
+ written, err := writer.Write(chunk)
+ if err != nil {
+ return err
+ }
+ if written == 0 {
+ return io.ErrShortWrite
+ }
+ data = data[written:]
+ }
+ return nil
+}
+
+func contextError(ctx context.Context) error {
+ if err := ctx.Err(); err != nil {
+ return fmt.Errorf("report publication canceled: %w", err)
+ }
+ return nil
+}
diff --git a/internal/report/report_test.go b/internal/report/report_test.go
new file mode 100644
index 0000000..7267a1b
--- /dev/null
+++ b/internal/report/report_test.go
@@ -0,0 +1,287 @@
+package report
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+func intPointer(value int) *int { return &value }
+func stringPointer(value string) *string { return &value }
+
+func TestGoldenReportBytes(t *testing.T) {
+ document := NewDocument()
+ document.Verdict = "fail"
+ document.Reasons = []string{"accepted_mutation"}
+ document.Configuration = Configuration{
+ Transport: "stdin",
+ MutationProfile: "tell-default-v1",
+ TimeoutMS: 2000,
+ MaxOutputBytesPerStream: 65536,
+ }
+ document.Command = []string{"fixture", "<&>"}
+ document.Seed = NewInput(nil)
+ document.Baseline = Execution{
+ Outcome: "accepted",
+ Termination: Termination{
+ Kind: "exit",
+ ExitCode: intPointer(0),
+ },
+ Stdout: NewStream([]byte{0, 0xff}, false),
+ Stderr: NewStream([]byte("err\n"), false),
+ }
+ document.MutationCounts = MutationCounts{Planned: 1, Unique: 1}
+ document.Cases = []Case{{
+ ID: "case-0001",
+ Mutation: Mutation{
+ Kind: "append",
+ DataBase64: stringPointer("AA=="),
+ },
+ Input: NewInput(nil),
+ Execution: Execution{
+ Outcome: "accepted",
+ Termination: Termination{
+ Kind: "exit",
+ ExitCode: intPointer(0),
+ },
+ Stdout: NewStream(nil, false),
+ Stderr: NewStream(nil, false),
+ },
+ }}
+
+ got, err := Marshal(document)
+ if err != nil {
+ t.Fatal(err)
+ }
+ const want = `{
+ "schema": "tell-report-v1",
+ "tool": {
+ "name": "tell",
+ "version": "1.0.0"
+ },
+ "verdict": "fail",
+ "reasons": [
+ "accepted_mutation"
+ ],
+ "configuration": {
+ "transport": "stdin",
+ "mutation_profile": "tell-default-v1",
+ "timeout_ms": 2000,
+ "max_output_bytes_per_stream": 65536
+ },
+ "command": [
+ "fixture",
+ "<&>"
+ ],
+ "seed": {
+ "byte_length": 0,
+ "sha256_hex": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "baseline": {
+ "outcome": "accepted",
+ "termination": {
+ "kind": "exit",
+ "exit_code": 0,
+ "signal_number": null
+ },
+ "stdout": {
+ "captured_byte_length": 2,
+ "sha256_hex": "06eb7d6a69ee19e5fbdf749018d3d2abfa04bcbd1365db312eb86dc7169389b8",
+ "data_base64": "AP8=",
+ "truncated": false
+ },
+ "stderr": {
+ "captured_byte_length": 4,
+ "sha256_hex": "2ccde4875ec595757efdf23d7b1336fcd69cf0fb869310b12a0d219c52817b20",
+ "data_base64": "ZXJyCg==",
+ "truncated": false
+ }
+ },
+ "mutation_counts": {
+ "planned": 1,
+ "unique": 1,
+ "skipped_unchanged": 0,
+ "skipped_duplicate": 0
+ },
+ "cases": [
+ {
+ "id": "case-0001",
+ "mutation": {
+ "kind": "append",
+ "offset": null,
+ "new_length": null,
+ "mask": null,
+ "data_base64": "AA=="
+ },
+ "input": {
+ "byte_length": 0,
+ "sha256_hex": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+ },
+ "execution": {
+ "outcome": "accepted",
+ "termination": {
+ "kind": "exit",
+ "exit_code": 0,
+ "signal_number": null
+ },
+ "stdout": {
+ "captured_byte_length": 0,
+ "sha256_hex": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "data_base64": "",
+ "truncated": false
+ },
+ "stderr": {
+ "captured_byte_length": 0,
+ "sha256_hex": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+ "data_base64": "",
+ "truncated": false
+ }
+ },
+ "observation_class_id": null
+ }
+ ],
+ "rejection_classes": []
+}
+`
+ if string(got) != want {
+ t.Fatalf("golden report mismatch\n--- got ---\n%s\n--- want ---\n%s", got, want)
+ }
+ if bytes.Contains(got, []byte(`\u003c`)) || bytes.Contains(got, []byte(`\u0026`)) {
+ t.Fatal("HTML escaping was enabled")
+ }
+ if !bytes.HasSuffix(got, []byte("\n")) || bytes.HasSuffix(got, []byte("\n\n")) {
+ t.Fatal("report must end with exactly one newline")
+ }
+
+ again, err := Marshal(document)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(got, again) {
+ t.Fatal("two marshals produced different bytes")
+ }
+}
+
+func TestMarshalRequiredArraysAreNeverNull(t *testing.T) {
+ data, err := Marshal(Document{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, field := range []string{`"reasons": []`, `"command": []`, `"cases": []`, `"rejection_classes": []`} {
+ if !bytes.Contains(data, []byte(field)) {
+ t.Fatalf("report does not contain %s:\n%s", field, data)
+ }
+ }
+}
+
+func TestWriteAtomicIsPrivateAndCleansTemporaryFiles(t *testing.T) {
+ directory := t.TempDir()
+ path := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(path, []byte("old"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ document := NewDocument()
+ if err := WriteAtomic(path, document); err != nil {
+ t.Fatal(err)
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := info.Mode().Perm(); got != 0o600 {
+ t.Fatalf("report mode = %#o, want 0600", got)
+ }
+ entries, err := os.ReadDir(directory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 1 || entries[0].Name() != "report.json" {
+ names := make([]string, 0, len(entries))
+ for _, entry := range entries {
+ names = append(names, entry.Name())
+ }
+ t.Fatalf("unexpected files after publication: %s", strings.Join(names, ", "))
+ }
+}
+
+func TestWriteFailureLeavesDestinationUntouchedAndCleansTemporaryFile(t *testing.T) {
+ directory := t.TempDir()
+ destination := filepath.Join(directory, "report.json")
+ if err := os.Mkdir(destination, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ sentinel := filepath.Join(destination, "sentinel")
+ if err := os.WriteFile(sentinel, []byte("keep"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if err := WriteAtomic(destination, NewDocument()); err == nil {
+ t.Fatal("WriteAtomic succeeded when destination was a non-empty directory")
+ }
+ data, err := os.ReadFile(sentinel)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != "keep" {
+ t.Fatalf("sentinel = %q, want keep", data)
+ }
+ entries, err := os.ReadDir(directory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 1 || entries[0].Name() != "report.json" {
+ t.Fatalf("temporary artifact remained: %#v", entries)
+ }
+}
+
+func TestCancellationDuringWriteLeavesDestinationUntouched(t *testing.T) {
+ directory := t.TempDir()
+ destination := filepath.Join(directory, "report.json")
+ if err := os.WriteFile(destination, []byte("existing"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ document := NewDocument()
+ document.Command = []string{strings.Repeat("x", 200_000)}
+ ctx := &cancelAfterChecks{cancelAt: 4}
+ err := WriteAtomicContext(ctx, destination, document)
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("WriteAtomicContext error = %v, want context cancellation", err)
+ }
+ data, err := os.ReadFile(destination)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(data) != "existing" {
+ t.Fatalf("destination = %q, want existing", data)
+ }
+ entries, err := os.ReadDir(directory)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 1 || entries[0].Name() != "report.json" {
+ t.Fatalf("temporary artifact remained: %#v", entries)
+ }
+}
+
+type cancelAfterChecks struct {
+ calls int
+ cancelAt int
+ canceled bool
+}
+
+func (c *cancelAfterChecks) Deadline() (time.Time, bool) { return time.Time{}, false }
+func (c *cancelAfterChecks) Done() <-chan struct{} { return nil }
+func (c *cancelAfterChecks) Value(any) any { return nil }
+
+func (c *cancelAfterChecks) Err() error {
+ c.calls++
+ if c.canceled || c.calls >= c.cancelAt {
+ c.canceled = true
+ return context.Canceled
+ }
+ return nil
+}
diff --git a/internal/runner/runner.go b/internal/runner/runner.go
new file mode 100644
index 0000000..82b5405
--- /dev/null
+++ b/internal/runner/runner.go
@@ -0,0 +1,109 @@
+// Package runner executes one target process with bounded, byte-exact I/O.
+package runner
+
+import (
+ "errors"
+ "fmt"
+ "time"
+ "unicode/utf8"
+)
+
+const (
+ // DefaultCleanupGrace is the fixed v1 grace period used to drain and close
+ // inherited process pipes after the direct child exits.
+ DefaultCleanupGrace = 250 * time.Millisecond
+ MinTimeout = 10 * time.Millisecond
+ MaxTimeout = 60 * time.Second
+ MaxOutputBytes = 1_048_576
+)
+
+// Outcome is the externally meaningful result of a successfully launched
+// target process.
+type Outcome string
+
+const (
+ OutcomeAccepted Outcome = "accepted"
+ OutcomeRejected Outcome = "rejected"
+ OutcomeSignaled Outcome = "signaled"
+ OutcomeTimedOut Outcome = "timed_out"
+ OutcomeOutputLimited Outcome = "output_limited"
+)
+
+// Config controls one target execution.
+type Config struct {
+ Timeout time.Duration
+ MaxOutputBytes int
+ CleanupGrace time.Duration
+}
+
+// Stream is one separately captured output stream. Data never exceeds the
+// configured cap. Truncated reports that byte cap+1 was observed.
+type Stream struct {
+ Data []byte
+ Truncated bool
+}
+
+// Result describes a target termination. Exactly one of ExitCode and
+// SignalNumber is set for a natural termination; induced timeout and output
+// limit terminations leave both nil.
+type Result struct {
+ Outcome Outcome
+ ExitCode *int
+ SignalNumber *int
+ Stdout Stream
+ Stderr Stream
+}
+
+var (
+ // ErrCanceled identifies a caller cancellation or interruption. Run still
+ // kills and reaps a successfully started process before returning it.
+ ErrCanceled = errors.New("runner canceled")
+ // ErrUnsupportedPlatform is returned by Run on non-Linux systems.
+ ErrUnsupportedPlatform = errors.New("tell process supervision is supported only on Linux")
+)
+
+// CanceledError retains the context cancellation cause while also matching
+// ErrCanceled through errors.Is.
+type CanceledError struct {
+ Cause error
+}
+
+func (e *CanceledError) Error() string {
+ if e.Cause == nil {
+ return ErrCanceled.Error()
+ }
+ return fmt.Sprintf("%s: %v", ErrCanceled, e.Cause)
+}
+
+func (e *CanceledError) Unwrap() error { return e.Cause }
+
+func (e *CanceledError) Is(target error) bool {
+ return target == ErrCanceled || errors.Is(e.Cause, target)
+}
+
+func validate(argv []string, cfg Config) (Config, error) {
+ if len(argv) == 0 || argv[0] == "" {
+ return Config{}, errors.New("runner: command argv is empty")
+ }
+ for i, arg := range argv {
+ if !utf8.ValidString(arg) {
+ return Config{}, fmt.Errorf("runner: argv[%d] is not valid UTF-8", i)
+ }
+ }
+ if cfg.Timeout < MinTimeout || cfg.Timeout > MaxTimeout {
+ return Config{}, fmt.Errorf("runner: timeout must be between %s and %s", MinTimeout, MaxTimeout)
+ }
+ if cfg.Timeout%time.Millisecond != 0 {
+ return Config{}, errors.New("runner: timeout must be a whole number of milliseconds")
+ }
+ if cfg.MaxOutputBytes < 0 || cfg.MaxOutputBytes > MaxOutputBytes {
+ return Config{}, fmt.Errorf("runner: maximum output bytes must be between 0 and %d", MaxOutputBytes)
+ }
+ if cfg.CleanupGrace == 0 {
+ cfg.CleanupGrace = DefaultCleanupGrace
+ }
+ if cfg.CleanupGrace != DefaultCleanupGrace {
+ return Config{}, fmt.Errorf("runner: cleanup grace must be %s", DefaultCleanupGrace)
+ }
+ return cfg, nil
+}
diff --git a/internal/runner/runner_linux.go b/internal/runner/runner_linux.go
new file mode 100644
index 0000000..cf48c6c
--- /dev/null
+++ b/internal/runner/runner_linux.go
@@ -0,0 +1,429 @@
+//go:build linux
+
+package runner
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "sync"
+ "sync/atomic"
+ "syscall"
+ "time"
+)
+
+type stopCause uint8
+
+const (
+ stopNone stopCause = iota
+ stopTimeout
+ stopOutputLimit
+ stopCanceled
+ stopInfrastructure
+)
+
+type stopper struct {
+ once sync.Once
+
+ mu sync.Mutex
+ cause stopCause
+ killErr error
+ pid int
+ process *os.Process
+}
+
+func newStopper(process *os.Process) *stopper {
+ return &stopper{pid: process.Pid, process: process}
+}
+
+func (s *stopper) stop(cause stopCause) {
+ s.once.Do(func() {
+ s.mu.Lock()
+ s.cause = cause
+ s.killErr = killForStop(s.process, s.pid)
+ s.mu.Unlock()
+ })
+}
+
+func killForStop(process *os.Process, pid int) error {
+ // The process-group signal is authoritative and always comes first. Killing
+ // the still-unreaped direct child as well prevents a target that moved itself
+ // to another process group from making Wait block forever; escaped
+ // descendants remain outside TELL's process-group guarantee.
+ groupErr := killProcessGroup(pid)
+ directErr := process.Kill()
+ if errors.Is(directErr, os.ErrProcessDone) || errors.Is(directErr, syscall.ESRCH) {
+ directErr = nil
+ }
+ if groupErr != nil {
+ return groupErr
+ }
+ if directErr != nil {
+ return fmt.Errorf("runner: kill direct child %d: %w", pid, directErr)
+ }
+ return nil
+}
+
+func (s *stopper) state() (stopCause, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.cause, s.killErr
+}
+
+func killProcessGroup(pid int) error {
+ if pid <= 0 {
+ return errors.New("runner: refusing to kill a nonpositive process group")
+ }
+ err := syscall.Kill(-pid, syscall.SIGKILL)
+ if err == nil || errors.Is(err, syscall.ESRCH) {
+ return nil
+ }
+ return fmt.Errorf("runner: kill process group %d: %w", pid, err)
+}
+
+type captureResult struct {
+ stream Stream
+ err error
+}
+
+type writeResult struct {
+ err error
+}
+
+// Run launches argv directly, sends input verbatim to stdin, and supervises
+// the new Linux process group. Every successful Start is followed by exactly
+// one Wait call before Run returns.
+func Run(ctx context.Context, argv []string, input []byte, cfg Config) (Result, error) {
+ cfg, err := validate(argv, cfg)
+ if err != nil {
+ return Result{}, err
+ }
+ if err := ctx.Err(); err != nil {
+ return Result{}, &CanceledError{Cause: err}
+ }
+
+ stdinR, stdinW, err := os.Pipe()
+ if err != nil {
+ return Result{}, fmt.Errorf("runner: create stdin pipe: %w", err)
+ }
+ stdoutR, stdoutW, err := os.Pipe()
+ if err != nil {
+ _ = stdinR.Close()
+ _ = stdinW.Close()
+ return Result{}, fmt.Errorf("runner: create stdout pipe: %w", err)
+ }
+ stderrR, stderrW, err := os.Pipe()
+ if err != nil {
+ _ = stdinR.Close()
+ _ = stdinW.Close()
+ _ = stdoutR.Close()
+ _ = stdoutW.Close()
+ return Result{}, fmt.Errorf("runner: create stderr pipe: %w", err)
+ }
+
+ cmd := exec.Command(argv[0], argv[1:]...)
+ cmd.Stdin = stdinR
+ cmd.Stdout = stdoutW
+ cmd.Stderr = stderrW
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ cmd.WaitDelay = cfg.CleanupGrace
+
+ if err := cmd.Start(); err != nil {
+ closePipeSet(stdinR, stdinW, stdoutR, stdoutW, stderrR, stderrW)
+ return Result{}, fmt.Errorf("runner: start target: %w", err)
+ }
+ startedAt := time.Now()
+ pid := cmd.Process.Pid
+ st := newStopper(cmd.Process)
+
+ // These descriptors belong only to the child after Start. Prompt closure is
+ // important: otherwise EOF and EPIPE cannot propagate correctly.
+ var infrastructureErr error
+ if err := stdinR.Close(); err != nil {
+ infrastructureErr = fmt.Errorf("runner: close child stdin read end: %w", err)
+ }
+ if err := stdoutW.Close(); err != nil && infrastructureErr == nil {
+ infrastructureErr = fmt.Errorf("runner: close child stdout write end: %w", err)
+ }
+ if err := stderrW.Close(); err != nil && infrastructureErr == nil {
+ infrastructureErr = fmt.Errorf("runner: close child stderr write end: %w", err)
+ }
+ if infrastructureErr != nil {
+ st.stop(stopInfrastructure)
+ }
+
+ stdoutDone := make(chan captureResult, 1)
+ stderrDone := make(chan captureResult, 1)
+ stdinDone := make(chan writeResult, 1)
+ var stdoutForced atomic.Bool
+ var stderrForced atomic.Bool
+ var stdinForced atomic.Bool
+ go func() {
+ stream, err := capture(stdoutR, cfg.MaxOutputBytes, func() { st.stop(stopOutputLimit) })
+ if err != nil && !stdoutForced.Load() {
+ st.stop(stopInfrastructure)
+ }
+ stdoutDone <- captureResult{stream: stream, err: err}
+ }()
+ go func() {
+ stream, err := capture(stderrR, cfg.MaxOutputBytes, func() { st.stop(stopOutputLimit) })
+ if err != nil && !stderrForced.Load() {
+ st.stop(stopInfrastructure)
+ }
+ stderrDone <- captureResult{stream: stream, err: err}
+ }()
+ go func() {
+ written := writeInput(stdinW, input)
+ if written.err != nil && !errors.Is(written.err, syscall.EPIPE) && !stdinForced.Load() {
+ st.stop(stopInfrastructure)
+ }
+ stdinDone <- written
+ }()
+
+ processDone := make(chan struct{})
+ watcherDone := make(chan struct{})
+ go func() {
+ defer close(watcherDone)
+ remaining := time.Until(startedAt.Add(cfg.Timeout))
+ if remaining <= 0 {
+ st.stop(stopTimeout)
+ return
+ }
+ timer := time.NewTimer(remaining)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ select {
+ case <-processDone:
+ return
+ default:
+ }
+ st.stop(stopCanceled)
+ case <-timer.C:
+ select {
+ case <-processDone:
+ return
+ default:
+ }
+ st.stop(stopTimeout)
+ case <-processDone:
+ }
+ }()
+
+ // This is the sole Wait call after the successful Start.
+ waitErr := cmd.Wait()
+ close(processDone)
+ <-watcherDone
+
+ // A child may have forked after Start. Kill its original process group even
+ // after the direct child is gone, then bound pipe cleanup in case a hostile
+ // descendant escaped that group while retaining a descriptor.
+ secondKillErr := killProcessGroup(pid)
+
+ stdoutCapture, stderrCapture, inputWrite, forcedClose, pipeCleanupErr := joinIO(
+ cfg.CleanupGrace,
+ stdoutR,
+ stderrR,
+ stdinW,
+ stdoutDone,
+ stderrDone,
+ stdinDone,
+ &stdoutForced,
+ &stderrForced,
+ &stdinForced,
+ )
+
+ cause, firstKillErr := st.state()
+ if infrastructureErr != nil {
+ return Result{}, infrastructureErr
+ }
+ if firstKillErr != nil {
+ return Result{}, firstKillErr
+ }
+ if secondKillErr != nil {
+ return Result{}, secondKillErr
+ }
+ if pipeCleanupErr != nil {
+ return Result{}, pipeCleanupErr
+ }
+ if stdoutCapture.err != nil && !forcedClose.stdout {
+ return Result{}, fmt.Errorf("runner: capture stdout: %w", stdoutCapture.err)
+ }
+ if stderrCapture.err != nil && !forcedClose.stderr {
+ return Result{}, fmt.Errorf("runner: capture stderr: %w", stderrCapture.err)
+ }
+ if inputWrite.err != nil && !errors.Is(inputWrite.err, syscall.EPIPE) && !forcedClose.stdin {
+ return Result{}, fmt.Errorf("runner: deliver stdin: %w", inputWrite.err)
+ }
+
+ result := Result{Stdout: stdoutCapture.stream, Stderr: stderrCapture.stream}
+ switch cause {
+ case stopCanceled:
+ return Result{}, &CanceledError{Cause: ctx.Err()}
+ case stopTimeout:
+ result.Outcome = OutcomeTimedOut
+ return result, nil
+ case stopOutputLimit:
+ result.Outcome = OutcomeOutputLimited
+ return result, nil
+ case stopInfrastructure:
+ return Result{}, errors.New("runner: process stopped after an infrastructure error")
+ }
+
+ if waitErr == nil {
+ code := 0
+ result.Outcome = OutcomeAccepted
+ result.ExitCode = &code
+ return result, nil
+ }
+ var exitErr *exec.ExitError
+ if !errors.As(waitErr, &exitErr) {
+ return Result{}, fmt.Errorf("runner: wait for target: %w", waitErr)
+ }
+ status, ok := exitErr.Sys().(syscall.WaitStatus)
+ if !ok {
+ return Result{}, errors.New("runner: target returned an unknown Linux wait status")
+ }
+ if status.Exited() {
+ code := status.ExitStatus()
+ result.Outcome = OutcomeRejected
+ result.ExitCode = &code
+ return result, nil
+ }
+ if status.Signaled() {
+ signal := int(status.Signal())
+ result.Outcome = OutcomeSignaled
+ result.SignalNumber = &signal
+ return result, nil
+ }
+ return Result{}, fmt.Errorf("runner: target returned unclassified wait status %#x", uint32(status))
+}
+
+func capture(r *os.File, limit int, overflow func()) (Stream, error) {
+ stream := Stream{Data: make([]byte, 0, min(limit, 32*1024))}
+ buf := make([]byte, 32*1024)
+ for {
+ n, err := r.Read(buf)
+ if n > 0 {
+ remaining := limit - len(stream.Data)
+ if remaining > n {
+ remaining = n
+ }
+ if remaining > 0 {
+ stream.Data = append(stream.Data, buf[:remaining]...)
+ }
+ if n > remaining && !stream.Truncated {
+ stream.Truncated = true
+ overflow()
+ }
+ }
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ return stream, nil
+ }
+ return stream, err
+ }
+ }
+}
+
+func writeInput(w *os.File, input []byte) writeResult {
+ var writeErr error
+ for len(input) > 0 {
+ n, err := w.Write(input)
+ if n > 0 {
+ input = input[n:]
+ }
+ if err != nil {
+ writeErr = err
+ break
+ }
+ if n == 0 {
+ writeErr = io.ErrShortWrite
+ break
+ }
+ }
+ if err := w.Close(); writeErr == nil && err != nil {
+ writeErr = err
+ }
+ return writeResult{err: writeErr}
+}
+
+type forcedIOClose struct {
+ stdout bool
+ stderr bool
+ stdin bool
+}
+
+func joinIO(
+ grace time.Duration,
+ stdoutR *os.File,
+ stderrR *os.File,
+ stdinW *os.File,
+ stdoutDone <-chan captureResult,
+ stderrDone <-chan captureResult,
+ stdinDone <-chan writeResult,
+ stdoutForced *atomic.Bool,
+ stderrForced *atomic.Bool,
+ stdinForced *atomic.Bool,
+) (captureResult, captureResult, writeResult, forcedIOClose, error) {
+ var stdout captureResult
+ var stderr captureResult
+ var stdin writeResult
+ var forced forcedIOClose
+ var cleanupErr error
+ outCh := stdoutDone
+ errCh := stderrDone
+ inCh := stdinDone
+ timer := time.NewTimer(grace)
+ defer timer.Stop()
+
+ for outCh != nil || errCh != nil || inCh != nil {
+ select {
+ case stdout = <-outCh:
+ outCh = nil
+ case stderr = <-errCh:
+ errCh = nil
+ case stdin = <-inCh:
+ inCh = nil
+ case <-timer.C:
+ if outCh != nil {
+ forced.stdout = true
+ stdoutForced.Store(true)
+ cleanupErr = joinCloseError(cleanupErr, "force-close stdout pipe", stdoutR.Close())
+ }
+ if errCh != nil {
+ forced.stderr = true
+ stderrForced.Store(true)
+ cleanupErr = joinCloseError(cleanupErr, "force-close stderr pipe", stderrR.Close())
+ }
+ if inCh != nil {
+ forced.stdin = true
+ stdinForced.Store(true)
+ cleanupErr = joinCloseError(cleanupErr, "force-close stdin pipe", stdinW.Close())
+ }
+ timer.Reset(grace)
+ }
+ }
+ cleanupErr = joinCloseError(cleanupErr, "close stdout pipe", stdoutR.Close())
+ cleanupErr = joinCloseError(cleanupErr, "close stderr pipe", stderrR.Close())
+ cleanupErr = joinCloseError(cleanupErr, "close stdin pipe", stdinW.Close())
+ return stdout, stderr, stdin, forced, cleanupErr
+}
+
+func joinCloseError(current error, operation string, closeErr error) error {
+ if closeErr == nil || errors.Is(closeErr, os.ErrClosed) {
+ return current
+ }
+ return errors.Join(current, fmt.Errorf("runner: %s: %w", operation, closeErr))
+}
+
+func closePipeSet(files ...*os.File) {
+ for _, file := range files {
+ if file != nil {
+ _ = file.Close()
+ }
+ }
+}
diff --git a/internal/runner/runner_linux_test.go b/internal/runner/runner_linux_test.go
new file mode 100644
index 0000000..5ed4a1f
--- /dev/null
+++ b/internal/runner/runner_linux_test.go
@@ -0,0 +1,678 @@
+//go:build linux
+
+package runner
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "syscall"
+ "testing"
+ "time"
+)
+
+const fixtureMarker = "__TELL_RUNNER_FIXTURE__"
+
+func fixtureCommand(mode string, args ...string) []string {
+ argv := []string{os.Args[0], "-test.run=^TestRunnerFixture$", "--", fixtureMarker, mode}
+ return append(argv, args...)
+}
+
+func testConfig(timeout time.Duration, outputBytes int) Config {
+ return Config{
+ Timeout: timeout,
+ MaxOutputBytes: outputBytes,
+ CleanupGrace: DefaultCleanupGrace,
+ }
+}
+
+func TestRunExactStdinAndEOF(t *testing.T) {
+ input := []byte{0x00, 0xff, 'a', '\n', 0x80, 0x00, 'z'}
+ result, err := Run(context.Background(), fixtureCommand("echo-stdin"), input, testConfig(2*time.Second, 1024))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeAccepted || result.ExitCode == nil || *result.ExitCode != 0 {
+ t.Fatalf("termination = %#v", result)
+ }
+ if !bytes.Equal(result.Stdout.Data, input) {
+ t.Fatalf("stdout = %x, want %x", result.Stdout.Data, input)
+ }
+ if len(result.Stderr.Data) != 0 || result.Stdout.Truncated || result.Stderr.Truncated {
+ t.Fatalf("unexpected streams: %#v", result)
+ }
+}
+
+func TestRunLiteralArgvAndArgvZero(t *testing.T) {
+ temp := t.TempDir()
+ alias := filepath.Join(temp, "fixture command")
+ fixturePath, err := filepath.Abs(os.Args[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(fixturePath, alias); err != nil {
+ t.Fatal(err)
+ }
+ shellSentinel := filepath.Join(temp, "shell-sentinel")
+ literals := []string{
+ "has spaces",
+ `double"quote`,
+ "single'quote",
+ "*",
+ "$HOME",
+ "semi;colon",
+ `back\\slash`,
+ fmt.Sprintf("$(touch %s)", shellSentinel),
+ }
+ argv := []string{alias, "-test.run=^TestRunnerFixture$", "--", fixtureMarker, "echo-argv"}
+ argv = append(argv, literals...)
+ result, err := Run(context.Background(), argv, nil, testConfig(2*time.Second, 4096))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ want, err := json.Marshal(argv)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(result.Stdout.Data, want) {
+ t.Fatalf("argv bytes = %s, want %s", result.Stdout.Data, want)
+ }
+ if _, err := os.Stat(shellSentinel); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("command-substitution text was executed: %v", err)
+ }
+}
+
+func TestRunInheritsWorkingDirectoryAndEnvironment(t *testing.T) {
+ const environmentValue = "exact inherited value"
+ t.Setenv("TELL_RUNNER_TEST_ENV", environmentValue)
+ workingDirectory, err := os.Getwd()
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, err := Run(context.Background(), fixtureCommand("cwd-env"), nil, testConfig(2*time.Second, 4096))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ want := append([]byte(workingDirectory), 0)
+ want = append(want, environmentValue...)
+ if !bytes.Equal(result.Stdout.Data, want) {
+ t.Fatalf("cwd/environment bytes = %q, want %q", result.Stdout.Data, want)
+ }
+}
+
+func TestRunExitAndSignalClassification(t *testing.T) {
+ tests := []struct {
+ name string
+ argv []string
+ outcome Outcome
+ exitCode *int
+ signal *int
+ }{
+ {name: "accepted", argv: fixtureCommand("exit", "0"), outcome: OutcomeAccepted, exitCode: intPointer(0)},
+ {name: "rejected", argv: fixtureCommand("exit", "23"), outcome: OutcomeRejected, exitCode: intPointer(23)},
+ {name: "normal exit 137", argv: fixtureCommand("exit", "137"), outcome: OutcomeRejected, exitCode: intPointer(137)},
+ {name: "natural signal", argv: fixtureCommand("signal", strconv.Itoa(int(syscall.SIGTERM))), outcome: OutcomeSignaled, signal: intPointer(int(syscall.SIGTERM))},
+ {name: "natural SIGKILL", argv: fixtureCommand("signal", strconv.Itoa(int(syscall.SIGKILL))), outcome: OutcomeSignaled, signal: intPointer(int(syscall.SIGKILL))},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ result, err := Run(context.Background(), test.argv, nil, testConfig(2*time.Second, 1024))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != test.outcome || !equalOptionalInt(result.ExitCode, test.exitCode) || !equalOptionalInt(result.SignalNumber, test.signal) {
+ t.Fatalf("result = %#v", result)
+ }
+ })
+ }
+}
+
+func TestRunTimeout(t *testing.T) {
+ started := time.Now()
+ result, err := Run(context.Background(), fixtureCommand("wait"), nil, testConfig(100*time.Millisecond, 1024))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeTimedOut || result.ExitCode != nil || result.SignalNumber != nil {
+ t.Fatalf("result = %#v", result)
+ }
+ if elapsed := time.Since(started); elapsed > 3*time.Second {
+ t.Fatalf("timeout cleanup took %v", elapsed)
+ }
+}
+
+func TestRunTimeoutKillsDirectChildThatChangesProcessGroup(t *testing.T) {
+ result, err := Run(context.Background(), fixtureCommand("move-group-and-wait"), nil, testConfig(150*time.Millisecond, 1024))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeTimedOut {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestRunCallerCancellation(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ time.AfterFunc(100*time.Millisecond, cancel)
+ _, err := Run(ctx, fixtureCommand("wait"), nil, testConfig(5*time.Second, 1024))
+ if !errors.Is(err, ErrCanceled) || !errors.Is(err, context.Canceled) {
+ t.Fatalf("error = %v, want cancellation", err)
+ }
+}
+
+func TestRunCallerDeadlineCancellation(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+ defer cancel()
+ _, err := Run(ctx, fixtureCommand("wait"), nil, testConfig(5*time.Second, 1024))
+ if !errors.Is(err, ErrCanceled) || !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("error = %v, want deadline cancellation", err)
+ }
+ if got := err.Error(); got == "" {
+ t.Fatal("cancellation error has an empty message")
+ }
+}
+
+func TestRunOutputLimits(t *testing.T) {
+ const capBytes = 64
+ tests := []struct {
+ name string
+ mode string
+ count int
+ outcome Outcome
+ stdoutTruncated bool
+ stderrTruncated bool
+ stdoutLength int
+ stderrLength int
+ }{
+ {name: "stdout exact cap", mode: "stdout", count: capBytes, outcome: OutcomeAccepted, stdoutLength: capBytes},
+ {name: "stderr exact cap", mode: "stderr", count: capBytes, outcome: OutcomeAccepted, stderrLength: capBytes},
+ {name: "stdout cap plus one", mode: "stdout", count: capBytes + 1, outcome: OutcomeOutputLimited, stdoutTruncated: true, stdoutLength: capBytes},
+ {name: "stderr cap plus one", mode: "stderr", count: capBytes + 1, outcome: OutcomeOutputLimited, stderrTruncated: true, stderrLength: capBytes},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ result, err := Run(context.Background(), fixtureCommand(test.mode, strconv.Itoa(test.count)), nil, testConfig(2*time.Second, capBytes))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != test.outcome || result.Stdout.Truncated != test.stdoutTruncated || result.Stderr.Truncated != test.stderrTruncated {
+ t.Fatalf("result = %#v", result)
+ }
+ if len(result.Stdout.Data) != test.stdoutLength || len(result.Stderr.Data) != test.stderrLength {
+ t.Fatalf("stream lengths = (%d, %d)", len(result.Stdout.Data), len(result.Stderr.Data))
+ }
+ })
+ }
+}
+
+func TestRunZeroOutputLimit(t *testing.T) {
+ for _, test := range []struct {
+ name string
+ count string
+ outcome Outcome
+ truncated bool
+ }{
+ {name: "empty", count: "0", outcome: OutcomeAccepted},
+ {name: "one byte", count: "1", outcome: OutcomeOutputLimited, truncated: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ result, err := Run(context.Background(), fixtureCommand("stdout", test.count), nil, testConfig(2*time.Second, 0))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != test.outcome || result.Stdout.Truncated != test.truncated || len(result.Stdout.Data) != 0 {
+ t.Fatalf("result = %#v", result)
+ }
+ })
+ }
+}
+
+func TestRunOutputLimitWinsOverInducedSIGKILL(t *testing.T) {
+ result, err := Run(context.Background(), fixtureCommand("stdout-and-wait", "65"), nil, testConfig(2*time.Second, 64))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeOutputLimited || !result.Stdout.Truncated || len(result.Stdout.Data) != 64 {
+ t.Fatalf("result = %#v", result)
+ }
+ if result.ExitCode != nil || result.SignalNumber != nil {
+ t.Fatalf("induced SIGKILL leaked into termination fields: %#v", result)
+ }
+}
+
+func TestRunDrainsStdoutAndStderrConcurrently(t *testing.T) {
+ const streamBytes = 256 * 1024
+ result, err := Run(
+ context.Background(),
+ fixtureCommand("both-streams", strconv.Itoa(streamBytes)),
+ nil,
+ testConfig(3*time.Second, streamBytes),
+ )
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeAccepted || result.Stdout.Truncated || result.Stderr.Truncated {
+ t.Fatalf("result = %#v", result)
+ }
+ if !bytes.Equal(result.Stdout.Data, bytes.Repeat([]byte{'o'}, streamBytes)) {
+ t.Fatal("stdout was not captured exactly")
+ }
+ if !bytes.Equal(result.Stderr.Data, bytes.Repeat([]byte{'e'}, streamBytes)) {
+ t.Fatal("stderr was not captured exactly")
+ }
+}
+
+func TestRunEarlyEPIPEIsNonfatal(t *testing.T) {
+ input := bytes.Repeat([]byte{0xa5}, 1<<20)
+ result, err := Run(context.Background(), fixtureCommand("exit", "0"), input, testConfig(2*time.Second, 1024))
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeAccepted {
+ t.Fatalf("result = %#v", result)
+ }
+}
+
+func TestRunTimeoutKillsDescendantProcessGroup(t *testing.T) {
+ temp := t.TempDir()
+ ready := filepath.Join(temp, "ready")
+ sentinel := filepath.Join(temp, "sentinel")
+ result, err := Run(
+ context.Background(),
+ fixtureCommand("spawn-delayed-sentinel", ready, sentinel, "900ms"),
+ nil,
+ testConfig(500*time.Millisecond, 1024),
+ )
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeTimedOut {
+ t.Fatalf("result = %#v", result)
+ }
+ if !pollUntil(2*time.Second, func() bool { _, err := os.Stat(ready); return err == nil }) {
+ t.Fatal("descendant never wrote readiness marker")
+ }
+ if !remainsAbsentFor(sentinel, 700*time.Millisecond) {
+ t.Fatal("timed-out descendant wrote sentinel")
+ }
+}
+
+func TestRunPostWaitCleanupKillsDescendantProcessGroup(t *testing.T) {
+ temp := t.TempDir()
+ ready := filepath.Join(temp, "ready")
+ sentinel := filepath.Join(temp, "sentinel")
+ result, err := Run(
+ context.Background(),
+ fixtureCommand("spawn-and-exit-delayed-sentinel", ready, sentinel, "3s"),
+ nil,
+ testConfig(2*time.Second, 1024),
+ )
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeAccepted {
+ t.Fatalf("result = %#v", result)
+ }
+ if !pollUntil(2*time.Second, func() bool { _, err := os.Stat(ready); return err == nil }) {
+ t.Fatal("descendant never wrote readiness marker")
+ }
+ if !remainsAbsentFor(sentinel, 4*time.Second) {
+ t.Fatal("descendant survived post-Wait process-group cleanup")
+ }
+}
+
+func TestRunEscapedPipeHolderCannotHang(t *testing.T) {
+ temp := t.TempDir()
+ ready := filepath.Join(temp, "ready")
+ done := filepath.Join(temp, "done")
+ started := time.Now()
+ result, err := Run(
+ context.Background(),
+ fixtureCommand("spawn-escaped-pipe-holder", ready, done, "3s"),
+ bytes.Repeat([]byte{0x5a}, 1<<20),
+ testConfig(2*time.Second, 1024),
+ )
+ if err != nil {
+ t.Fatalf("Run: %v", err)
+ }
+ if result.Outcome != OutcomeAccepted {
+ t.Fatalf("result = %#v", result)
+ }
+ if elapsed := time.Since(started); elapsed > 2*time.Second {
+ t.Fatalf("inherited pipe delayed Run for %v", elapsed)
+ }
+ if !pollUntil(4*time.Second, func() bool { _, err := os.Stat(done); return err == nil }) {
+ t.Fatal("escaped fixture did not exit normally")
+ }
+}
+
+func TestRunLaunchErrors(t *testing.T) {
+ if _, err := Run(context.Background(), []string{filepath.Join(t.TempDir(), "missing")}, nil, testConfig(time.Second, 1024)); err == nil {
+ t.Fatal("missing executable succeeded")
+ }
+ nonExecutable := filepath.Join(t.TempDir(), "not-executable")
+ if err := os.WriteFile(nonExecutable, []byte("not an executable"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Run(context.Background(), []string{nonExecutable}, nil, testConfig(time.Second, 1024)); err == nil {
+ t.Fatal("non-executable command succeeded")
+ }
+}
+
+func TestRunRejectsInvalidConfigurationAndArgv(t *testing.T) {
+ valid := fixtureCommand("exit", "0")
+ tests := []struct {
+ name string
+ argv []string
+ cfg Config
+ }{
+ {name: "empty argv", cfg: testConfig(time.Second, 1)},
+ {name: "empty command", argv: []string{""}, cfg: testConfig(time.Second, 1)},
+ {name: "invalid utf8", argv: []string{os.Args[0], string([]byte{0xff})}, cfg: testConfig(time.Second, 1)},
+ {name: "short timeout", argv: valid, cfg: testConfig(time.Millisecond, 1)},
+ {name: "long timeout", argv: valid, cfg: testConfig(61*time.Second, 1)},
+ {name: "fractional millisecond", argv: valid, cfg: testConfig(10*time.Millisecond+time.Nanosecond, 1)},
+ {name: "negative cap", argv: valid, cfg: testConfig(time.Second, -1)},
+ {name: "large cap", argv: valid, cfg: testConfig(time.Second, MaxOutputBytes+1)},
+ {name: "wrong cleanup grace", argv: valid, cfg: Config{Timeout: time.Second, MaxOutputBytes: 1, CleanupGrace: time.Second}},
+ }
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ if _, err := Run(context.Background(), test.argv, nil, test.cfg); err == nil {
+ t.Fatal("Run succeeded")
+ }
+ })
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := Run(ctx, valid, nil, testConfig(time.Second, 1)); !errors.Is(err, ErrCanceled) {
+ t.Fatalf("pre-start cancellation = %v", err)
+ }
+}
+
+func TestRunDoesNotLeakLocalDescriptorsOrGoroutines(t *testing.T) {
+ beforeFDs := countFDs(t)
+ beforeGoroutines := runtime.NumGoroutine()
+ for range 20 {
+ result, err := Run(context.Background(), fixtureCommand("exit", "0"), nil, testConfig(5*time.Second, 16))
+ if err != nil || result.Outcome != OutcomeAccepted {
+ t.Fatalf("Run = (%#v, %v)", result, err)
+ }
+ }
+ if result, err := Run(context.Background(), fixtureCommand("wait"), nil, testConfig(100*time.Millisecond, 16)); err != nil || result.Outcome != OutcomeTimedOut {
+ t.Fatalf("timeout cleanup = (%#v, %v)", result, err)
+ }
+ if result, err := Run(context.Background(), fixtureCommand("stdout", "17"), nil, testConfig(2*time.Second, 16)); err != nil || result.Outcome != OutcomeOutputLimited {
+ t.Fatalf("output-limit cleanup = (%#v, %v)", result, err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancelTimer := time.AfterFunc(100*time.Millisecond, cancel)
+ if _, err := Run(ctx, fixtureCommand("wait"), nil, testConfig(2*time.Second, 16)); !errors.Is(err, ErrCanceled) {
+ t.Fatalf("cancellation cleanup error = %v", err)
+ }
+ cancelTimer.Stop()
+ cancel()
+ if result, err := Run(context.Background(), fixtureCommand("exit", "0"), bytes.Repeat([]byte{0xa5}, 1<<20), testConfig(2*time.Second, 16)); err != nil || result.Outcome != OutcomeAccepted {
+ t.Fatalf("EPIPE cleanup = (%#v, %v)", result, err)
+ }
+ temp := t.TempDir()
+ ready := filepath.Join(temp, "ready")
+ done := filepath.Join(temp, "done")
+ if result, err := Run(context.Background(), fixtureCommand("spawn-escaped-pipe-holder", ready, done, "2s"), nil, testConfig(3*time.Second, 16)); err != nil || result.Outcome != OutcomeAccepted {
+ t.Fatalf("forced-pipe cleanup = (%#v, %v)", result, err)
+ }
+ if !pollUntil(4*time.Second, func() bool { _, err := os.Stat(done); return err == nil }) {
+ t.Fatal("escaped pipe-holder did not finish")
+ }
+ if !pollUntil(2*time.Second, func() bool { return runtime.NumGoroutine() <= beforeGoroutines+2 }) {
+ t.Fatalf("goroutines grew from %d to %d", beforeGoroutines, runtime.NumGoroutine())
+ }
+ afterFDs := countFDs(t)
+ if afterFDs != beforeFDs {
+ t.Fatalf("file descriptor count grew from %d to %d", beforeFDs, afterFDs)
+ }
+}
+
+func intPointer(value int) *int { return &value }
+
+func equalOptionalInt(left, right *int) bool {
+ if left == nil || right == nil {
+ return left == nil && right == nil
+ }
+ return *left == *right
+}
+
+func pollUntil(limit time.Duration, condition func() bool) bool {
+ deadline := time.Now().Add(limit)
+ for {
+ if condition() {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func remainsAbsentFor(path string, observationWindow time.Duration) bool {
+ deadline := time.Now().Add(observationWindow)
+ for time.Now().Before(deadline) {
+ if _, err := os.Stat(path); err == nil || !errors.Is(err, os.ErrNotExist) {
+ return false
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ return true
+}
+
+func countFDs(t *testing.T) int {
+ t.Helper()
+ entries, err := os.ReadDir("/proc/self/fd")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return len(entries)
+}
+
+// TestRunnerFixture turns the Go test binary into the actual subprocess used
+// by the integration tests. It intentionally avoids external interpreters and
+// committed fixture executables.
+func TestRunnerFixture(t *testing.T) {
+ index := -1
+ for i, arg := range os.Args {
+ if arg == fixtureMarker {
+ index = i
+ break
+ }
+ }
+ if index < 0 {
+ return
+ }
+ args := os.Args[index+1:]
+ if len(args) == 0 {
+ fixtureFail("missing fixture mode")
+ }
+ mode := args[0]
+ args = args[1:]
+ switch mode {
+ case "echo-stdin":
+ data, err := io.ReadAll(os.Stdin)
+ if err != nil {
+ fixtureFail("read stdin: %v", err)
+ }
+ if _, err := os.Stdout.Write(data); err != nil {
+ fixtureFail("write stdout: %v", err)
+ }
+ case "echo-argv":
+ data, err := json.Marshal(os.Args)
+ if err != nil {
+ fixtureFail("marshal argv: %v", err)
+ }
+ if _, err := os.Stdout.Write(data); err != nil {
+ fixtureFail("write argv: %v", err)
+ }
+ case "cwd-env":
+ workingDirectory, err := os.Getwd()
+ if err != nil {
+ fixtureFail("get working directory: %v", err)
+ }
+ data := append([]byte(workingDirectory), 0)
+ data = append(data, os.Getenv("TELL_RUNNER_TEST_ENV")...)
+ if _, err := os.Stdout.Write(data); err != nil {
+ fixtureFail("write cwd and environment: %v", err)
+ }
+ case "exit":
+ requireFixtureArgs(mode, args, 1)
+ code, err := strconv.Atoi(args[0])
+ if err != nil {
+ fixtureFail("parse exit code: %v", err)
+ }
+ os.Exit(code)
+ case "signal":
+ requireFixtureArgs(mode, args, 1)
+ number, err := strconv.Atoi(args[0])
+ if err != nil {
+ fixtureFail("parse signal: %v", err)
+ }
+ if err := syscall.Kill(os.Getpid(), syscall.Signal(number)); err != nil {
+ fixtureFail("signal self: %v", err)
+ }
+ time.Sleep(time.Second)
+ fixtureFail("signal did not terminate process")
+ case "wait":
+ for {
+ time.Sleep(time.Hour)
+ }
+ case "move-group-and-wait":
+ parentGroup, err := syscall.Getpgid(os.Getppid())
+ if err != nil {
+ fixtureFail("get parent process group: %v", err)
+ }
+ if err := syscall.Setpgid(0, parentGroup); err != nil {
+ fixtureFail("move process group: %v", err)
+ }
+ for {
+ time.Sleep(time.Hour)
+ }
+ case "stdout", "stderr":
+ requireFixtureArgs(mode, args, 1)
+ count, err := strconv.Atoi(args[0])
+ if err != nil {
+ fixtureFail("parse output count: %v", err)
+ }
+ destination := io.Writer(os.Stdout)
+ if mode == "stderr" {
+ destination = os.Stderr
+ }
+ if _, err := destination.Write(bytes.Repeat([]byte{'x'}, count)); err != nil {
+ fixtureFail("write %s: %v", mode, err)
+ }
+ case "both-streams":
+ requireFixtureArgs(mode, args, 1)
+ count, err := strconv.Atoi(args[0])
+ if err != nil {
+ fixtureFail("parse output count: %v", err)
+ }
+ if _, err := os.Stdout.Write(bytes.Repeat([]byte{'o'}, count)); err != nil {
+ fixtureFail("write stdout: %v", err)
+ }
+ if _, err := os.Stderr.Write(bytes.Repeat([]byte{'e'}, count)); err != nil {
+ fixtureFail("write stderr: %v", err)
+ }
+ case "stdout-and-wait":
+ requireFixtureArgs(mode, args, 1)
+ count, err := strconv.Atoi(args[0])
+ if err != nil {
+ fixtureFail("parse output count: %v", err)
+ }
+ if _, err := os.Stdout.Write(bytes.Repeat([]byte{'x'}, count)); err != nil {
+ fixtureFail("write stdout: %v", err)
+ }
+ for {
+ time.Sleep(time.Hour)
+ }
+ case "spawn-delayed-sentinel":
+ requireFixtureArgs(mode, args, 3)
+ child := exec.Command(os.Args[0], "-test.run=^TestRunnerFixture$", "--", fixtureMarker, "delayed-sentinel", args[0], args[1], args[2])
+ if err := child.Start(); err != nil {
+ fixtureFail("start descendant: %v", err)
+ }
+ waitForFixtureFile(args[0])
+ for {
+ time.Sleep(time.Hour)
+ }
+ case "spawn-and-exit-delayed-sentinel":
+ requireFixtureArgs(mode, args, 3)
+ child := exec.Command(os.Args[0], "-test.run=^TestRunnerFixture$", "--", fixtureMarker, "delayed-sentinel", args[0], args[1], args[2])
+ if err := child.Start(); err != nil {
+ fixtureFail("start descendant: %v", err)
+ }
+ waitForFixtureFile(args[0])
+ case "delayed-sentinel":
+ requireFixtureArgs(mode, args, 3)
+ if err := os.WriteFile(args[0], []byte("ready"), 0o600); err != nil {
+ fixtureFail("write readiness marker: %v", err)
+ }
+ delay, err := time.ParseDuration(args[2])
+ if err != nil {
+ fixtureFail("parse delay: %v", err)
+ }
+ time.Sleep(delay)
+ if err := os.WriteFile(args[1], []byte("escaped"), 0o600); err != nil {
+ fixtureFail("write sentinel: %v", err)
+ }
+ case "spawn-escaped-pipe-holder":
+ requireFixtureArgs(mode, args, 3)
+ child := exec.Command(os.Args[0], "-test.run=^TestRunnerFixture$", "--", fixtureMarker, "pipe-holder", args[0], args[1], args[2])
+ child.Stdin = os.Stdin
+ child.Stdout = os.Stdout
+ child.Stderr = os.Stderr
+ child.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
+ if err := child.Start(); err != nil {
+ fixtureFail("start pipe holder: %v", err)
+ }
+ waitForFixtureFile(args[0])
+ case "pipe-holder":
+ requireFixtureArgs(mode, args, 3)
+ if err := os.WriteFile(args[0], []byte("ready"), 0o600); err != nil {
+ fixtureFail("write readiness marker: %v", err)
+ }
+ delay, err := time.ParseDuration(args[2])
+ if err != nil {
+ fixtureFail("parse delay: %v", err)
+ }
+ time.Sleep(delay)
+ if err := os.WriteFile(args[1], []byte("done"), 0o600); err != nil {
+ fixtureFail("write completion marker: %v", err)
+ }
+ default:
+ fixtureFail("unknown fixture mode %q", mode)
+ }
+ os.Exit(0)
+}
+
+func requireFixtureArgs(mode string, args []string, count int) {
+ if len(args) != count {
+ fixtureFail("%s received %d args, want %d", mode, len(args), count)
+ }
+}
+
+func waitForFixtureFile(path string) {
+ if !pollUntil(2*time.Second, func() bool { _, err := os.Stat(path); return err == nil }) {
+ fixtureFail("timed out waiting for %s", path)
+ }
+}
+
+func fixtureFail(format string, args ...any) {
+ _, _ = fmt.Fprintf(os.Stderr, format+"\n", args...)
+ os.Exit(125)
+}
diff --git a/internal/runner/runner_unsupported.go b/internal/runner/runner_unsupported.go
new file mode 100644
index 0000000..86af0ab
--- /dev/null
+++ b/internal/runner/runner_unsupported.go
@@ -0,0 +1,14 @@
+//go:build !linux
+
+package runner
+
+import "context"
+
+// Run reports the platform limitation while keeping the package buildable on
+// non-Linux systems.
+func Run(_ context.Context, argv []string, _ []byte, cfg Config) (Result, error) {
+ if _, err := validate(argv, cfg); err != nil {
+ return Result{}, err
+ }
+ return Result{}, ErrUnsupportedPlatform
+}