diff --git a/android/secuso-privacy-friendly-2048/LICENSE b/android/secuso-privacy-friendly-2048/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..4ca5e08d0f4c863fae52698a9f4414b221e1288f
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/LICENSE
@@ -0,0 +1,676 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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.
+
+ Privacy Friendly Example App. The Android application demonstrate the design
+ of a Privacy Friendly App.
+ Copyright (C) 2016-2018 Karola Marky
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Privacy Friendly Apps Copyright (C) 2016-2018 Karola Marky
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
+
diff --git a/android/secuso-privacy-friendly-2048/instance.json b/android/secuso-privacy-friendly-2048/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..fe617d7d6df2bb955b0205d153acb62c79f22841
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/secuso-privacy-friendly-2048",
+ "platform": "android",
+ "repo": "https://github.com/SecUSo/privacy-friendly-2048",
+ "commit": "4ee3cf356376c1f8905f81a02ffc9f37b3db6c96",
+ "patches": [],
+ "package": "org.secuso.privacyfriendly2048",
+ "license": null
+}
diff --git a/android/secuso-privacy-friendly-2048/reference/launch.sh b/android/secuso-privacy-friendly-2048/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/secuso-privacy-friendly-2048/tests/android_computation_eval.json b/android/secuso-privacy-friendly-2048/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..66455108af48abdccb721390b6071a3bc746b75a
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_computation_eval.json
@@ -0,0 +1,232 @@
+{
+ "module": "computation",
+ "total": 22,
+ "passed": 22,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 22,
+ "depth_ge1": 22,
+ "depth_ge2": 0,
+ "value": 22,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "computation_fresh_seed_two_tiles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "fresh game: exactly 2 numeric tiles and points == 0"
+ },
+ {
+ "test": "computation_effective_move_sum_delta",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "each effective move increases the tile sum by exactly 2 or 4"
+ },
+ {
+ "test": "computation_slide_adds_one_tile",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "a no-merge move raises tile count by 1, spawning a 2 or a 4"
+ },
+ {
+ "test": "computation_merge_scores_points",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "a merge adds a positive even points delta; tile sum grows by 2/4"
+ },
+ {
+ "test": "computation_merge_pair_value",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "single-pair merge scores exactly twice the merged tile value"
+ },
+ {
+ "test": "computation_blocked_move_no_change",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "a blocked move leaves the tile multiset and points identical"
+ },
+ {
+ "test": "computation_blocked_move_no_new_tile",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "a blocked move leaves the tile count unchanged (no new tile)"
+ },
+ {
+ "test": "computation_record_is_max",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "record == points at the moment points first exceed the old record"
+ },
+ {
+ "test": "computation_record_monotonic",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "record is non-decreasing across a sequence of moves"
+ },
+ {
+ "test": "computation_restart_resets",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "restart -> points == 0 and exactly 2 tiles"
+ },
+ {
+ "test": "computation_restart_two_tiles_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the game grid show exactly two numbered tiles, with every other cell empty?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does the game grid show exactly two numbered tiles, with every other cell empty?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_undo_restores_points",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "points return to the pre-move value after undo"
+ },
+ {
+ "test": "computation_undo_restores_tile_count",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "tile count returns to the pre-move count after undo"
+ },
+ {
+ "test": "computation_undo_once",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "one undo restores the pre-move points; a second cannot lower them"
+ },
+ {
+ "test": "computation_points_accumulate",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "final score equals the running sum of non-negative per-move deltas"
+ },
+ {
+ "test": "computation_merge_collapses_pair",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "on a scoring (merge) move the tile count does not increase"
+ },
+ {
+ "test": "computation_two_slides_add_two",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "each of two no-merge moves raises the tile count by exactly one"
+ },
+ {
+ "test": "computation_restart_then_move",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "after restart the seed is 2 tiles and a move grows it past 2"
+ },
+ {
+ "test": "computation_undo_then_replay",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "after undo restores points, further moves raise them again"
+ },
+ {
+ "test": "computation_5x5_larger_grid",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "5x5 board has more cells than 4x4; both seed exactly 2 tiles"
+ },
+ {
+ "test": "computation_5x5_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?",
+ "tag": "size"
+ },
+ {
+ "test": "computation_sum_growth_bounded",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "every per-move tile-sum delta is 0 (blocked) or 2/4 (one spawn)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/android_interaction_eval.json b/android/secuso-privacy-friendly-2048/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..912a17e9938e597b04a95cee74f107eace05d63b
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_interaction_eval.json
@@ -0,0 +1,274 @@
+{
+ "module": "interaction",
+ "total": 26,
+ "passed": 26,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4444,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 26,
+ "depth_ge1": 26,
+ "depth_ge2": 15,
+ "value": 0,
+ "vlm_fine": 5
+ },
+ "results": [
+ {
+ "test": "interaction_persist_after_kill",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "continue restores points=4 tiles=[2, 2, 4] after process death"
+ },
+ {
+ "test": "interaction_persist_board_restored_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_kill_without_back_not_saved",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "continue DISABLED after play then kill-without-back"
+ },
+ {
+ "test": "interaction_continue_enable_after_play_back",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "continue enabled=true after play then back"
+ },
+ {
+ "test": "interaction_undo_reverts_points",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points return to 0 after undo"
+ },
+ {
+ "test": "interaction_undo_board_reverted_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_undo_icon_visible_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_undo_once_per_move",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "undoButton absent -> present after move -> absent after undo"
+ },
+ {
+ "test": "interaction_restart_reseeds_board",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points=0 and exactly 2 tiles after restart"
+ },
+ {
+ "test": "interaction_restart_two_tiles_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the game board show exactly two numbered tiles, with all the other grid cells empty?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the game board show exactly two numbered tiles, with all the other grid cells empty?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_restart_then_playable",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "a move after restart adds a tile (2->3) and undo returns"
+ },
+ {
+ "test": "interaction_merged_tiles_colored_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do the numbered tiles on the board have colored (non-white) backgrounds?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Do the numbered tiles on the board have colored (non-white) backgrounds?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_accumulated_score_persists",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points=44 (>0) survive back+kill+continue"
+ },
+ {
+ "test": "interaction_stats_moves_increment",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "moves_All1>=1 and moves_L1>=1 after 4x4 play"
+ },
+ {
+ "test": "interaction_stats_nonzero_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this statistics screen display numeric values in its rows (numbers other than only zeros)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does this statistics screen display numeric values in its rows (numbers other than only zeros)?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_stats_highest_number",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "highest_number1>=4 (board reached 4)"
+ },
+ {
+ "test": "interaction_stats_highest_score",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "highest_score1 == 20"
+ },
+ {
+ "test": "interaction_stats_mode_isolation",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "4x4 moves_All1>0 and 5x5 moves_All2==0"
+ },
+ {
+ "test": "interaction_stats_undo_counter",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "undo_number1 >= 1 after using undo"
+ },
+ {
+ "test": "interaction_5x5_larger_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the game board a large square grid with five columns and five rows of cells?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the game board a large square grid with five columns and five rows of cells?",
+ "tag": "size"
+ },
+ {
+ "test": "interaction_continue_mode_correct",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "5x5 continue restores points=44 tiles=[2, 2, 2, 8, 8, 8]"
+ },
+ {
+ "test": "interaction_two_saved_games",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "both modes enabled; 4x4 continue restores points=48"
+ },
+ {
+ "test": "interaction_continue_repeatable",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points=24 preserved across resume->back->resume"
+ },
+ {
+ "test": "interaction_restart_then_persist",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "continue restores post-restart points=0 tiles=[2, 2, 2, 2, 4]"
+ },
+ {
+ "test": "interaction_stats_overflow_menu",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "overflow opens revealing a menu item over the Stats surface"
+ },
+ {
+ "test": "interaction_restart_icon_visible_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/android_navigation_eval.json b/android/secuso-privacy-friendly-2048/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..4d3a273717d2323198b48c789389f6f4e9b9a8a7
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_navigation_eval.json
@@ -0,0 +1,283 @@
+{
+ "module": "navigation",
+ "total": 27,
+ "passed": 27,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4211,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 27,
+ "depth_ge1": 23,
+ "depth_ge2": 5,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "nav_reach_statistics",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "StatsActivity: 'Highest Number' appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_statistics_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SettingsActivity: 'Select theme' appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_settings_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this a settings screen showing a vertical list of preference rows, each with a title line?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is this a settings screen showing a vertical list of preference rows, each with a title line?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_help",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "HelpActivity: FAQ row 'What is the goal of this game?' appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_help_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the screen a vertical list of question rows, one per line, like an FAQ / help list?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is the screen a vertical list of question rows, one per line, like an FAQ / help list?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_about",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "AboutActivity: 'Version:' label appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_about_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show app information text such as a version number, author names, and a license paragraph?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show app information text such as a version number, author names, and a license paragraph?",
+ "tag": "content"
+ },
+ {
+ "test": "nav_reach_tutorial",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "TutorialActivity: slide title 'Welcome!' appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_tutorial_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_game_new",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "GameActivity: restartButton appears; Main 'START NEW GAME' gone"
+ },
+ {
+ "test": "nav_reach_game_new_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_back_game_to_main",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "MainActivity restored: 'START NEW GAME' reappears, restartButton disappears"
+ },
+ {
+ "test": "nav_back_stats_to_main",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Highest Number' disappears"
+ },
+ {
+ "test": "nav_back_settings_to_main",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Select theme' disappears"
+ },
+ {
+ "test": "nav_back_about_to_main",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "MainActivity restored: 'START NEW GAME' reappears, 'Version:' disappears"
+ },
+ {
+ "test": "nav_pager_next_4to5",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "mode label '5x5' appears and '4x4' disappears after btn_next"
+ },
+ {
+ "test": "nav_pager_prev_5to4",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "mode label '4x4' appears and '5x5' disappears after btn_prev"
+ },
+ {
+ "test": "nav_pager_to_last_7x7",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "mode label '7x7'; btn_next absent on the last page; btn_prev present"
+ },
+ {
+ "test": "nav_pager_last_arrow_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.' A=NO expect=NO",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM NO: Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.",
+ "tag": "position"
+ },
+ {
+ "test": "nav_stats_tab_4to5",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "tapping 5X5 tab reveals the 5x5 stat ids (highest_number2)"
+ },
+ {
+ "test": "nav_deep_theme_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "theme AlertDialog: option 'Dark' appears; settings row 'Activate Animation' disappears"
+ },
+ {
+ "test": "nav_deep_theme_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_deep_color_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "color AlertDialog: option 'Original' appears; settings row 'Activate Animation' disappears"
+ },
+ {
+ "test": "nav_deep_game_roundtrip",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "after Main->Game->BACK the MainActivity is restored: 'START NEW GAME' present, restartButton gone"
+ },
+ {
+ "test": "nav_deep_stats_tab_content",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "5X5 tab reveals highest_number2 and moves_L2 stat fields"
+ },
+ {
+ "test": "nav_reach_continue_game",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "GameActivity: restartButton appears; 'CONTINUE GAME' disappears"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/android_states_eval.json b/android/secuso-privacy-friendly-2048/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..40458ae37671a9f8f90ebbb5248432991a618448
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_states_eval.json
@@ -0,0 +1,229 @@
+{
+ "module": "states",
+ "total": 21,
+ "passed": 21,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.6154,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 21,
+ "depth_ge1": 21,
+ "depth_ge2": 5,
+ "value": 0,
+ "vlm_fine": 8
+ },
+ "results": [
+ {
+ "test": "states_animation_switch_on_off_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?",
+ "tag": "position"
+ },
+ {
+ "test": "states_animation_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Activate Animation' Switch checked true->false after tap"
+ },
+ {
+ "test": "states_animation_persists_revisit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Activate Animation' checked=false persists after Main->Settings revisit"
+ },
+ {
+ "test": "states_screenlock_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Activate Screen Lock' Switch checked true->false after tap"
+ },
+ {
+ "test": "states_screenlock_persists_revisit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Activate Screen Lock' checked=false persists across revisit"
+ },
+ {
+ "test": "states_theme_summary_changes",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Select theme' summary System->Dark after picking Dark"
+ },
+ {
+ "test": "states_theme_dark_applied_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_system_restored_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_persists_revisit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Select theme' summary stays 'Light' after Main->Settings revisit"
+ },
+ {
+ "test": "states_color_summary_changes",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Select Color Scheme' summary Default->Original after picking Original"
+ },
+ {
+ "test": "states_color_original_tiles_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_color_default_tiles_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_color_persists_revisit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Select Color Scheme' summary stays 'Original' after revisit"
+ },
+ {
+ "test": "states_color_preview_changed_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?",
+ "tag": "color"
+ },
+ {
+ "test": "states_continue_enable_transition",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "button_continueGame enabled false->true after playing an unsaved mode then pressing back"
+ },
+ {
+ "test": "states_undo_button_appears",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "undoButton absent at start -> present after first effective move (same GameActivity)"
+ },
+ {
+ "test": "states_restart_zeros_points",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points 4->0 after tapping restartButton"
+ },
+ {
+ "test": "states_drawer_checked_follows_surface",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "drawer checked flips Main(true)->Settings(true) after navigating to Settings"
+ },
+ {
+ "test": "states_drawer_selected_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?",
+ "tag": "color"
+ },
+ {
+ "test": "states_stats_tab_selected",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "tapping 5x5 tab: selected true (4x4 false) and stat ids *number1->*number2"
+ },
+ {
+ "test": "states_stats_tab_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?",
+ "tag": "color"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/android_structure_eval.json b/android/secuso-privacy-friendly-2048/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..b6e33b50af04ac7fe194756357e09256be9a1e4f
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_structure_eval.json
@@ -0,0 +1,202 @@
+{
+ "module": "structure",
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.8,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 3,
+ "liveness": 0,
+ "interactive": 15,
+ "depth_ge1": 13,
+ "depth_ge2": 0,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_main_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_main_dots_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_drawer_opens",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "nav_view+6 CheckedTextView appear on open, gone on close"
+ },
+ {
+ "test": "structure_drawer_opens_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_game_board_appears",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "number_field with >=16 Buttons appears; button_newGame disappears"
+ },
+ {
+ "test": "structure_game_board_appears_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_board_size_grows",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "5x5 board Buttons (29) > 4x4 board Buttons (20)"
+ },
+ {
+ "test": "structure_board_size_grows_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the grid of tiles 5 columns wide and 5 rows tall?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the grid of tiles 5 columns wide and 5 rows tall?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_restart_reseeds",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "numeric tiles: 2 fresh -> board changes on moves -> 2 after restart"
+ },
+ {
+ "test": "structure_game_tile_color_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?",
+ "tag": "color"
+ },
+ {
+ "test": "structure_settings_list",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "ListView with >=4 preference title rows and exactly 2 Switch widgets"
+ },
+ {
+ "test": "structure_stats_tabs",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "4 mode tabs (4x4..7x7) + >=8 stat TextViews"
+ },
+ {
+ "test": "structure_stats_tabs_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_help_expand",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "9 listTitle rows; expanding a row adds 1 body TextView, collapsing removes it"
+ },
+ {
+ "test": "structure_help_expand_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_about_scroll",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "ScrollView with >=6 static TextViews"
+ },
+ {
+ "test": "structure_tutorial_slider",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "ViewPager + layoutDots + SKIP + NEXT buttons"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/android_testgen_kit.py b/android/secuso-privacy-friendly-2048/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/secuso-privacy-friendly-2048/tests/android_text_eval.json b/android/secuso-privacy-friendly-2048/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..08abe7bddfcec4338e7cf1fea9de4063e1f63e48
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/android_text_eval.json
@@ -0,0 +1,196 @@
+{
+ "module": "text",
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.125,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 12,
+ "liveness": 0,
+ "interactive": 6,
+ "depth_ge1": 5,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "text_points_updates_on_merge",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points text '0' -> '4' after a scoring move"
+ },
+ {
+ "test": "text_record_reflects_best",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "record text '0' -> '4' (== points) after play"
+ },
+ {
+ "test": "text_points_resets_to_zero",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "points text '4' -> '0' after tapping restart"
+ },
+ {
+ "test": "text_game_header_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "exact labels 'Points' and 'Record' shown on GameActivity"
+ },
+ {
+ "test": "text_mode_label_pages_4to5",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "mode label text '4x4' -> '5x5' after btn_next"
+ },
+ {
+ "test": "text_settings_titles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "titles 'Settings','Select theme','Activate Animation','Activate Screen Lock','Select Color Scheme' all present"
+ },
+ {
+ "test": "text_theme_summary",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "'Select theme' summary text == 'System'"
+ },
+ {
+ "test": "text_color_scheme_summary",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "'Select Color Scheme' summary text == 'Default'"
+ },
+ {
+ "test": "text_stats_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "all 10 stat labels ('Highest Number'..'Right') present exactly"
+ },
+ {
+ "test": "text_stats_playing_time_format",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "time_played1 renders like '0.00 h' (a decimal followed by ' h')"
+ },
+ {
+ "test": "text_stats_tab_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "tab texts exactly '4X4','5X5','6X6','7X7' (uppercase)"
+ },
+ {
+ "test": "text_help_faq_titles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "FAQ titles incl. 'What is Privacy Friendly App 2048?' present"
+ },
+ {
+ "test": "text_help_expansion_reveals_body",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "body '...privacy friendly version of the well-known original game 2048' appears only after the row is expanded"
+ },
+ {
+ "test": "text_tutorial_slide1",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "slide 1 title 'Welcome!' and body 'In the following slides you will learn how to play the Game 2048.'"
+ },
+ {
+ "test": "text_tutorial_illustration_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "text_tutorial_next_advances_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "slide title 'Welcome!' -> 'Learn how to move the numbers!' after tapping NEXT"
+ },
+ {
+ "test": "text_about_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "labels 'Version:'/'Authors:', authors 'Saskia Jacob and Julian Wadephul', links 'SECUSO-Website'/'Github-Repo' all present"
+ },
+ {
+ "test": "text_game_icon_controls_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/tests/conftest.py b/android/secuso-privacy-friendly-2048/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/secuso-privacy-friendly-2048/tests/requirements.txt b/android/secuso-privacy-friendly-2048/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_computation.py b/android/secuso-privacy-friendly-2048/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bb6850c7e51a79b966b0c42be1c1008583dec8f
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_computation.py
@@ -0,0 +1,1075 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — Privacy Friendly 2048.
+
+Owns the game's CORE MATH: the input->output transform of a directional move.
+This lane is the SOLE OWNER of jump_kind="value": every test drives a TRIGGER
+(a DPAD move / restart / undo) and asserts a SPECIFIC numeric value or count that
+the ORIGINAL app produced — never a value computed from the source.
+
+The initial 2-tile seed and every spawned tile are RANDOM (a new tile is 2 with
+p=0.9, else 4; its cell is random), so NO absolute point total is hardcoded.
+Instead every assertion is a read-before / act / read-after DELTA or multiset
+relationship that is deterministic regardless of the RNG, and that a shell which
+does not implement 2048's merge rule cannot satisfy.
+
+GROUND TRUTH — all OBSERVED on the running original before writing (live probing):
+ * Fresh new game (4x4): EXACTLY 2 numeric tiles; points TextView == "0";
+ undoButton ABSENT. (observed seed [2,4], points 0)
+ * Each non-empty tile is a Button whose text is its value ("2","4","8",...),
+ so every tile value + the score is read straight from the view tree.
+ * MERGE MATH — from GameActivity.handleSwipe*: on a move, `points += (merged
+ value)` for every pair that collapses; then addNumber() spawns ONE tile iff
+ the board changed. Confirmed live, e.g. [2,2,2,8,8] --UP--> [2,2,2,2,16],
+ points delta 16 (the 8+8 merge).
+ * MERGE CONSERVES THE TILE SUM: a+a -> 2a, so after any EFFECTIVE move
+ sum(tiles_after) - sum(tiles_before) is exactly the new tile's value, i.e.
+ it is in {2, 4}. Verified on many moves (sumdelta only ever 0/2/4).
+ * NEW-TILE-PER-MOVE: an effective move adds exactly one tile, so
+ merges = count_before + 1 - count_after. merges==0 => a pure slide with
+ points delta 0; merges>=1 => points delta > 0 and EVEN. Verified.
+ * BLOCKED MOVE (direction already exhausted): NOTHING changes — the tile
+ multiset and points are identical before and after, and no tile spawns. A
+ blocked direction is FOUND by probing each of the four keys and reverting any
+ effective probe with undo (undo restores the exact pre-probe board+points —
+ verified [2,2,4,4]/pts 8 restored verbatim).
+ * record TextView == max(points, previous record), updated LIVE, and NEVER
+ decreases. record survives clear_data (it lives in the statistics file), so it
+ is asserted RELATIVE to the value read at game start, never as an absolute.
+ * restartButton: points -> "0", board re-seeded to EXACTLY 2 tiles, undo gone,
+ NO dialog. Verified (tiles [2,2] pts 0 after restart).
+ * undoButton: appears after the first effective move; tapping it returns points
+ to the exact pre-move value and the button disappears. Verified (4 -> 0).
+ * 5x5 mode (page 1 -> new game): the board grid has strictly MORE cells than
+ 4x4 (Button nodes 29 vs 20), while a fresh 5x5 still seeds exactly 2 tiles.
+
+Failure messages use the taxonomy: setup_failed: / feature_missing: /
+behavior_wrong:. Every game test crosses Main -> Game (depth=1), backed by the
+and_enter_game() helper (an and_enter*/and_reach* member) so the depth is real.
+
+VLM BUDGET (exactly 2, both fine-grained): the tile positions/counts and the
+score are all dump-readable, so VLM is spent only on genuinely RENDERED layout —
+the near-empty two-tile grid after restart (position) and the visibly larger 5x5
+grid vs 4x4 (size). Everything else stays a rule assertion.
+"""
+import os, sys
+from collections import Counter
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+def _boot():
+ """Clean, package-agnostic entry: force a fresh process, reach the foreground,
+ dismiss the first-run tutorial if (and only if) it appears."""
+ restart_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+
+
+def _skip_tutorial():
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+
+
+def _points(nodes=None):
+ """Current score as an int, or None when the points view is absent."""
+ n = node_by_id(nodes if nodes is not None else ui(), "points")
+ if n and n.get("text", "").strip().lstrip("-").isdigit():
+ return int(n["text"].strip())
+ return None
+
+
+def _record(nodes=None):
+ """Current best (record) score as an int, or None."""
+ n = node_by_id(nodes if nodes is not None else ui(), "record")
+ if n and n.get("text", "").strip().lstrip("-").isdigit():
+ return int(n["text"].strip())
+ return None
+
+
+def _tiles(nodes=None):
+ """Sorted list of on-board tile values (each tile is a numeric Button)."""
+ nodes = nodes if nodes is not None else ui()
+ return sorted(int(b["text"]) for b in find_by_class(nodes, "Button")
+ if b.get("text", "").strip().isdigit())
+
+
+def _cell_count(nodes=None):
+ """Total Button nodes on the game screen (background cells + tiles + toolbar
+ icons). The background grid is one Button per cell, so this scales with n*n
+ and lets a 5x5 board be told apart from a 4x4 one without reading any pixel."""
+ nodes = nodes if nodes is not None else ui()
+ return len(find_by_class(nodes, "Button"))
+
+
+def and_enter_game(nodes=None):
+ """Tap button_newGame and CONFIRM the game surface appeared (points view or
+ the board container), counting one crossed surface. Backs depth>=1 for every
+ game test. Returns True on success."""
+ nodes = nodes if nodes is not None else ui()
+ ng = node_by_id(nodes, "button_newGame")
+ if not ng or not tap_node(ng):
+ return False
+ settle("tap")
+ fresh = ui()
+ if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None:
+ return False
+ and_enter("game")
+ return True
+
+
+def _go_to_mode(index):
+ """Page the Main ViewPager to page `index` (0=4x4, 1=5x5, ...). btn_prev is
+ absent on page 0 and btn_next absent on the last page — deterministic stops."""
+ for _ in range(6): # rewind to page 0
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ for _ in range(index): # advance to target
+ nx = node_by_id(ui(), "btn_next")
+ if not nx:
+ break
+ tap_node(nx)
+
+
+def _tap_restart():
+ r = node_by_id(ui(), "restartButton")
+ return tap_node(r) if r else False
+
+
+def _tap_undo():
+ u = node_by_id(ui(), "undoButton")
+ return tap_node(u) if u else False
+
+
+_DIRS = ["KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP",
+ "KEYCODE_DPAD_RIGHT", "KEYCODE_DPAD_DOWN"]
+
+
+def _move(key):
+ """Perform one DPAD move and settle so the next ui() reflects the result."""
+ press_key(key)
+ settle("tap")
+
+
+def _first_effective_move(max_moves=16):
+ """Cycle the four directions until one CHANGES the board. Returns
+ (tiles_before, points_before, key, tiles_after, points_after) for that move,
+ or None if nothing was effective within the cap (should not happen on a fresh
+ board where at least one direction always moves)."""
+ for i in range(max_moves):
+ bt, bp = _tiles(), _points()
+ key = _DIRS[i % 4]
+ _move(key)
+ at, ap = _tiles(), _points()
+ if at != bt:
+ return bt, bp, key, at, ap
+ return None
+
+
+def _first_merge_move(max_moves=24):
+ """Cycle directions until a move MERGES at least one pair (points rise).
+ Returns (points_before, key, points_after) for that move, or None."""
+ for i in range(max_moves):
+ bt, bp = _tiles(), _points()
+ if bp is None:
+ return None
+ key = _DIRS[i % 4]
+ _move(key)
+ at, ap = _tiles(), _points()
+ if ap is not None and ap > bp:
+ return bp, key, ap
+ return None
+
+
+def _play_effective(n):
+ """Drive up to `n` EFFECTIVE moves (skipping blocked directions), returning
+ how many landed. Used to grow the board / accumulate score deterministically."""
+ landed = 0
+ i = 0
+ while landed < n and i < n * 6:
+ bt = _tiles()
+ _move(_DIRS[i % 4])
+ if _tiles() != bt:
+ landed += 1
+ i += 1
+ return landed
+
+
+def _find_blocked_direction(rounds=4):
+ """Find a direction that is a NO-OP on the current board and return the
+ before/after reads proving it. A blocked direction always exists on a partly
+ filled board; if all four are effective this grows the board (one effective
+ move) and retries, up to `rounds`. Each effective PROBE is reverted with undo
+ (undo restores the exact pre-probe tiles + points), so the search leaves the
+ board on the state from which the returned direction is blocked.
+
+ Returns (key, tiles_before, tiles_after, points_before, points_after) or None.
+ """
+ for _ in range(rounds):
+ for d in _DIRS:
+ tb, pb = _tiles(), _points()
+ _move(d)
+ ta, pa = _tiles(), _points()
+ if Counter(ta) == Counter(tb):
+ return d, tb, ta, pb, pa
+ # effective probe: revert it so the next candidate starts unchanged
+ if node_by_id(ui(), "undoButton") is not None:
+ _tap_undo()
+ settle("tap")
+ if Counter(_tiles()) != Counter(tb) or _points() != pb:
+ # undo did not restore cleanly — accept this new state and keep
+ # probing from here rather than corrupting the search
+ pass
+ # no blocked direction under this board: make one effective move to change
+ # the configuration, then try again
+ _play_effective(1)
+ return None
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 1. Fresh seed — exactly 2 tiles and points == 0
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_fresh_seed_two_tiles",))
+def test_fresh_seed_two_tiles():
+ """A brand-new 4x4 game seeds EXACTLY two numeric tiles and shows points "0".
+ The count is deterministic even though the two tile VALUES are random."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_fresh_seed_two_tiles", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="2 tiles and points 0 on a fresh board")
+ return
+ n = ui()
+ tiles = _tiles(n)
+ pts = _points(n)
+ ok = len(tiles) == 2 and pts == 0
+ record("computation_fresh_seed_two_tiles", ok,
+ "" if ok else f"behavior_wrong: fresh board has tiles={tiles} points={pts}, "
+ f"expected 2 tiles and points 0",
+ depth=1, jump_kind="value",
+ expect="fresh game: exactly 2 numeric tiles and points == 0")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 2. Merge conserves the tile sum — sum delta is exactly the new tile (2 or 4)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_effective_move_sum_delta",))
+def test_effective_move_conserves_sum():
+ """The single most RNG-robust value law of 2048: a merge replaces a+a with 2a,
+ so after ANY effective move the total tile sum rises by exactly the one newly
+ spawned tile's value -> sum_after - sum_before is in {2, 4}. Asserted across
+ several effective moves; a recreation that mis-sums merges or spawns the wrong
+ tile breaks this immediately."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_effective_move_sum_delta", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="sum delta in {2,4} per effective move")
+ return
+ checked = 0
+ bad = None
+ i = 0
+ while checked < 4 and i < 30:
+ bt = _tiles()
+ bs = sum(bt)
+ _move(_DIRS[i % 4])
+ at = _tiles()
+ i += 1
+ if at == bt:
+ continue # blocked; not an effective move
+ delta = sum(at) - bs
+ checked += 1
+ if delta not in (2, 4):
+ bad = (bt, at, delta)
+ break
+ ok = checked >= 3 and bad is None
+ record("computation_effective_move_sum_delta", ok,
+ "" if ok else (f"behavior_wrong: sum delta {bad[2]} not in {{2,4}} "
+ f"(before={bad[0]} after={bad[1]})" if bad
+ else f"setup_failed: only {checked} effective moves observed"),
+ depth=1, jump_kind="value",
+ expect="each effective move increases the tile sum by exactly 2 or 4")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 3. New-tile-per-move — a pure slide (no merge) adds exactly ONE tile
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_slide_adds_one_tile",))
+def test_slide_adds_one_tile():
+ """When an effective move performs NO merge, the tile count rises by exactly 1
+ (the spawned tile). A pure slide is the case where the count grew; on it the
+ spawned value (sum delta) must be 2 or 4."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_slide_adds_one_tile", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a no-merge move adds exactly one tile")
+ return
+ found = False
+ ok = True
+ observed = None
+ i = 0
+ while not found and i < 30:
+ bt = _tiles()
+ bc = len(bt)
+ _move(_DIRS[i % 4])
+ at = _tiles()
+ ac = len(at)
+ i += 1
+ if at == bt:
+ continue
+ if ac == bc + 1: # a pure slide: spawned a tile
+ found = True
+ spawned = sum(at) - sum(bt)
+ ok = spawned in (2, 4)
+ observed = (bt, at, spawned)
+ record("computation_slide_adds_one_tile", found and ok,
+ "" if (found and ok) else (
+ f"behavior_wrong: slide spawned value {observed[2]} not in {{2,4}} "
+ f"(before={observed[0]} after={observed[1]})" if found
+ else "setup_failed: no pure-slide (count+1) move observed"),
+ depth=1, jump_kind="value",
+ expect="a no-merge move raises tile count by 1, spawning a 2 or a 4")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 4. Merge move scores — points delta is positive and even, sum still conserved
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_merge_scores_points",))
+def test_merge_move_scores_points():
+ """Drive moves until one MERGES a pair (the tile count does NOT rise, so cells
+ collapsed). On that move points MUST rise by a positive even amount (a sum of
+ doubled tiles), while the tile sum still only rises by the one new tile (2/4).
+ A shell that renders tiles but never adds merge points scores 0 here."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_merge_scores_points", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a merge raises points by a positive even delta")
+ return
+ hit = None
+ i = 0
+ while hit is None and i < 40:
+ bt, bp = _tiles(), _points()
+ bc, bs = len(bt), sum(bt)
+ _move(_DIRS[i % 4])
+ at, ap = _tiles(), _points()
+ ac, asum = len(at), sum(at)
+ i += 1
+ if at == bt or bp is None or ap is None:
+ continue
+ merges = bc + 1 - ac # effective move adds 1 tile
+ if merges >= 1: # cells collapsed => a merge
+ dp = ap - bp
+ hit = (bt, at, dp, merges, asum - bs)
+ break
+ ok = hit is not None and hit[2] > 0 and hit[2] % 2 == 0 and hit[4] in (2, 4)
+ record("computation_merge_scores_points", ok,
+ "" if ok else (f"behavior_wrong: merge move points delta={hit[2]} "
+ f"(merges={hit[3]}, sumdelta={hit[4]}, before={hit[0]} "
+ f"after={hit[1]})" if hit
+ else "setup_failed: no merge move observed within cap"),
+ depth=1, jump_kind="value",
+ expect="a merge adds a positive even points delta; tile sum grows by 2/4")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 5. Single-pair merge scores exactly twice the merged tile value
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_merge_pair_value",))
+def test_merge_pair_scores_its_sum():
+ """A SINGLE-pair merge scores exactly the merged value. We isolate a move that
+ collapses exactly one pair (merges==1) and verify the points delta equals
+ 2 * (a value that was on the board before), i.e. dp is twice an existing tile
+ value and dp >= 4."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_merge_pair_value", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a single-pair merge scores 2*value (>=4)")
+ return
+ hit = None
+ i = 0
+ while hit is None and i < 48:
+ bt, bp = _tiles(), _points()
+ bc = len(bt)
+ _move(_DIRS[i % 4])
+ at, ap = _tiles(), _points()
+ ac = len(at)
+ i += 1
+ if at == bt or bp is None or ap is None:
+ continue
+ merges = bc + 1 - ac
+ if merges == 1:
+ dp = ap - bp
+ # the collapsed value v had two copies before; dp must equal 2v for a v
+ # present on the pre-move board.
+ doubled_present = dp in [2 * v for v in set(bt)]
+ hit = (bt, at, dp, doubled_present)
+ break
+ ok = hit is not None and hit[2] >= 4 and hit[2] % 2 == 0 and hit[3]
+ record("computation_merge_pair_value", ok,
+ "" if ok else (f"behavior_wrong: single-pair merge delta={hit[2]} is not "
+ f"2*(an on-board value) (before={hit[0]} after={hit[1]})"
+ if hit else "setup_failed: no single-pair merge observed"),
+ depth=1, jump_kind="value",
+ expect="single-pair merge scores exactly twice the merged tile value")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 6. Blocked move — nothing changes (multiset AND points identical)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_blocked_move_no_change",))
+def test_blocked_move_no_change():
+ """Find a direction that is already exhausted, then press it: the move is a
+ NO-OP -> the tile multiset and points are byte-identical before and after. This
+ is the negative arm: the answer (a change) must be ABSENT. The blocked
+ direction is discovered by probing (any effective probe is reverted with undo),
+ so this is deterministic regardless of the random board."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_blocked_move_no_change", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a blocked move changes nothing")
+ return
+ _play_effective(3) # grow so a blocked dir exists
+ blocked = _find_blocked_direction()
+ if blocked is None:
+ record("computation_blocked_move_no_change", False,
+ "setup_failed: no blocked direction found to probe",
+ depth=1, jump_kind="value", expect="a blocked move changes nothing")
+ return
+ key, tb, ta, pb, pa = blocked
+ ok = Counter(tb) == Counter(ta) and pb == pa and pb is not None
+ record("computation_blocked_move_no_change", ok,
+ "" if ok else f"behavior_wrong: blocked {key[-4:]} changed state "
+ f"(tiles {tb}->{ta}, points {pb}->{pa})",
+ depth=1, jump_kind="value",
+ expect="a blocked move leaves the tile multiset and points identical")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 7. Blocked move spawns NO tile (count invariance for the negative case)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_blocked_move_no_new_tile",))
+def test_blocked_move_no_new_tile():
+ """The counterpart to the new-tile-per-move law: a blocked move must add NO
+ tile. We find an exhausted direction and confirm the tile COUNT is unchanged
+ across it. This discriminates a recreation that spawns a tile on EVERY key
+ regardless of whether the board moved."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_blocked_move_no_new_tile", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a blocked move adds no tile")
+ return
+ _play_effective(3)
+ blocked = _find_blocked_direction()
+ if blocked is None:
+ record("computation_blocked_move_no_new_tile", False,
+ "setup_failed: no blocked direction found to probe",
+ depth=1, jump_kind="value", expect="a blocked move adds no tile")
+ return
+ key, tb, ta, _pb, _pa = blocked
+ ok = len(tb) == len(ta)
+ record("computation_blocked_move_no_new_tile", ok,
+ "" if ok else f"behavior_wrong: blocked {key[-4:]} changed tile count "
+ f"{len(tb)}->{len(ta)} (a tile was spawned on a no-op move)",
+ depth=1, jump_kind="value",
+ expect="a blocked move leaves the tile count unchanged (no new tile)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 8. record == max(points, starting record) after scoring beyond it
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_record_is_max",))
+def test_record_equals_max():
+ """record is the running maximum of the score. Read the record at game start
+ (it may be non-zero, persisted from earlier play), then play until points
+ strictly EXCEED it: at that instant record must equal points. record is
+ asserted RELATIVE to its observed start value, never as an absolute."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_record_is_max", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="record tracks points once points exceed it")
+ return
+ start_rec = _record()
+ if start_rec is None:
+ record("computation_record_is_max", False,
+ "setup_failed: could not read the record view",
+ depth=1, jump_kind="value", expect="record tracks points once points exceed it")
+ return
+ # Alternate directions to accumulate score until points strictly exceed the
+ # record read at game start; at that instant record must have caught up to it.
+ last = None
+ exceeded = False
+ i = 0
+ while last is None and i < 80:
+ _move(_DIRS[i % 4])
+ p = _points() or 0
+ r = _record() or 0
+ i += 1
+ if p > start_rec:
+ last = (p, r)
+ exceeded = (r == p)
+ if last is None:
+ record("computation_record_is_max", False,
+ f"setup_failed: points never exceeded the start record {start_rec}",
+ depth=1, jump_kind="value",
+ expect="record == points once points first exceed the old record")
+ return
+ record("computation_record_is_max", exceeded,
+ "" if exceeded else f"behavior_wrong: after points {last[0]} exceeded start "
+ f"record {start_rec}, record was {last[1]} (expected == points)",
+ depth=1, jump_kind="value",
+ expect="record == points at the moment points first exceed the old record")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 9. record never decreases across a scoring move
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_record_monotonic",))
+def test_record_monotonic():
+ """The record is monotonic non-decreasing: across a whole sequence of moves it
+ only ever rises or holds, never drops — even as points climb. Sampled after
+ each of several moves."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_record_monotonic", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="record never decreases across moves")
+ return
+ r_prev = _record()
+ if r_prev is None:
+ record("computation_record_monotonic", False,
+ "setup_failed: could not read the record view",
+ depth=1, jump_kind="value", expect="record never decreases across moves")
+ return
+ ok = True
+ drop = None
+ for i in range(12):
+ _move(_DIRS[i % 4])
+ r = _record()
+ if r is None:
+ continue
+ if r < r_prev:
+ ok = False
+ drop = (r_prev, r)
+ break
+ r_prev = r
+ record("computation_record_monotonic", ok,
+ "" if ok else f"behavior_wrong: record decreased {drop[0]}->{drop[1]}",
+ depth=1, jump_kind="value",
+ expect="record is non-decreasing across a sequence of moves")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 10. restart resets points to 0 and re-seeds to exactly 2 tiles
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_restart_resets", "computation_restart_two_tiles_vlm"))
+def test_restart_resets_points():
+ """Play until the board has grown (more than 2 tiles and/or points > 0), tap
+ restartButton, then assert points == 0 and EXACTLY 2 numeric tiles remain, with
+ no confirmation dialog. A positive->reset transition asserted by value."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_restart_resets", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="points 0 and 2 tiles after restart")
+ vlm_assert("computation_restart_two_tiles", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="value", tag="position")
+ return
+ _play_effective(5)
+ grew = len(_tiles()) > 2 or (_points() or 0) > 0
+ if not _tap_restart():
+ record("computation_restart_resets", False,
+ "setup_failed: restartButton not found/tappable",
+ depth=1, jump_kind="value", expect="points 0 and 2 tiles after restart")
+ vlm_assert("computation_restart_two_tiles", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="value", tag="position")
+ return
+ settle("tap")
+ n = ui()
+ pts = _points(n)
+ tiles = _tiles(n)
+ ok = grew and pts == 0 and len(tiles) == 2
+ record("computation_restart_resets", ok,
+ "" if ok else f"behavior_wrong: after restart points={pts} tiles={tiles} "
+ f"(grew_before={grew}); expected points 0 and 2 tiles",
+ depth=1, jump_kind="value",
+ expect="restart -> points == 0 and exactly 2 tiles")
+ # VLM: after restart the grid is nearly empty — only two tiles sit on it.
+ vlm_assert("computation_restart_two_tiles",
+ "Does the game grid show exactly two numbered tiles, with every "
+ "other cell empty?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 11. undo restores the exact pre-move points
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_undo_restores_points",))
+def test_undo_restores_points():
+ """Make a move that CHANGES the score, capture the pre-move points, tap
+ undoButton, and assert points return to exactly that pre-move value (and the
+ undo affordance disappears). Deterministic on points regardless of the random
+ tile the move spawned."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_undo_restores_points", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="points return to the pre-move value after undo")
+ return
+ merge = _first_merge_move()
+ if merge is None:
+ record("computation_undo_restores_points", False,
+ "setup_failed: no scoring move produced within cap",
+ depth=1, jump_kind="value", expect="points return to the pre-move value after undo")
+ return
+ pre_move, _key, post_move = merge
+ had_undo = node_by_id(ui(), "undoButton") is not None
+ _tap_undo()
+ after = _points()
+ undo_gone = node_by_id(ui(), "undoButton") is None
+ ok = had_undo and post_move > pre_move and after == pre_move and undo_gone
+ record("computation_undo_restores_points", ok,
+ "" if ok else f"behavior_wrong: undo did not restore points to {pre_move} "
+ f"(post_move={post_move}, after_undo={after}, "
+ f"undo_present_before={had_undo}, undo_gone_after={undo_gone})",
+ depth=1, jump_kind="value",
+ expect="points return to the pre-move value after undo")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 12. undo restores the exact pre-move tile count
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_undo_restores_tile_count",))
+def test_undo_restores_tile_count():
+ """Undo reverts the board, so the tile COUNT returns to its pre-move value. We
+ capture the count immediately before an effective move, perform it (count
+ changes), undo, and assert the count matches the pre-move count. (Count, not
+ multiset: the pre-move board already carried a random tile from the prior move,
+ but its COUNT before this move is a fixed number we read.)"""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_undo_restores_tile_count", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo")
+ return
+ # first make one effective move so the undo button exists, then measure a
+ # SECOND effective move's pre-count (so pre-state is deterministic post-spawn).
+ if _first_effective_move() is None:
+ record("computation_undo_restores_tile_count", False,
+ "setup_failed: no effective first move",
+ depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo")
+ return
+ pre = None
+ moved_to = None
+ i = 0
+ while pre is None and i < 20:
+ bt = _tiles()
+ bc = len(bt)
+ _move(_DIRS[i % 4])
+ at = _tiles()
+ i += 1
+ if at != bt:
+ pre = bc
+ moved_to = len(at)
+ if pre is None:
+ record("computation_undo_restores_tile_count", False,
+ "setup_failed: no second effective move",
+ depth=1, jump_kind="value", expect="tile count returns to pre-move value after undo")
+ return
+ had_undo = node_by_id(ui(), "undoButton") is not None
+ _tap_undo()
+ after = len(_tiles())
+ ok = had_undo and after == pre
+ record("computation_undo_restores_tile_count", ok,
+ "" if ok else f"behavior_wrong: undo tile count {after} != pre-move {pre} "
+ f"(moved_to={moved_to}, undo_present={had_undo})",
+ depth=1, jump_kind="value",
+ expect="tile count returns to the pre-move count after undo")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 13. undo is once-per-move — the delta is applied exactly once
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_undo_once",))
+def test_undo_applies_once():
+ """Undo reverts a SINGLE move: after one undo the points sit at the pre-move
+ value and the undo button is gone, so a second undo cannot drive points below
+ that value. Confirms the revert is applied exactly once (not repeatedly)."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_undo_once", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="undo restores once; no double revert")
+ return
+ merge = _first_merge_move()
+ if merge is None:
+ record("computation_undo_once", False,
+ "setup_failed: no scoring move produced",
+ depth=1, jump_kind="value", expect="undo restores once; no double revert")
+ return
+ pre_move, _key, _post = merge
+ _tap_undo()
+ after_first = _points()
+ gone = node_by_id(ui(), "undoButton") is None
+ # attempt a second undo — button should be absent, points must not drop further
+ _tap_undo()
+ after_second = _points()
+ ok = after_first == pre_move and gone and after_second == pre_move
+ record("computation_undo_once", ok,
+ "" if ok else f"behavior_wrong: undo not once-only (pre={pre_move}, "
+ f"after1={after_first}, undo_gone={gone}, after2={after_second})",
+ depth=1, jump_kind="value",
+ expect="one undo restores the pre-move points; a second cannot lower them")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 14. Multi-move accumulation — total points equal the summed per-move deltas
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_points_accumulate",))
+def test_points_accumulate():
+ """Points accumulate additively: over a run of moves the FINAL score equals the
+ sum of every per-move delta observed along the way (each delta is >= 0). This
+ ties many individual merges into one exact end-to-end total, computed purely
+ from before/after reads — no source arithmetic."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_points_accumulate", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="final points == sum of per-move deltas")
+ return
+ start = _points()
+ if start is None:
+ record("computation_points_accumulate", False,
+ "setup_failed: could not read points",
+ depth=1, jump_kind="value", expect="final points == sum of per-move deltas")
+ return
+ running = start
+ bad = None
+ for i in range(16):
+ b = _points()
+ _move(_DIRS[i % 4])
+ a = _points()
+ if a is None or b is None:
+ continue
+ d = a - b
+ if d < 0:
+ bad = (b, a)
+ break
+ running += d
+ final = _points()
+ ok = bad is None and final is not None and final == running and final >= start
+ record("computation_points_accumulate", ok,
+ "" if ok else (f"behavior_wrong: a per-move delta went negative "
+ f"{bad[0]}->{bad[1]}" if bad else
+ f"behavior_wrong: final points {final} != summed deltas {running}"),
+ depth=1, jump_kind="value",
+ expect="final score equals the running sum of non-negative per-move deltas")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 15. Merge reduces the count of the merged value (a merge does not grow count)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_merge_collapses_pair",))
+def test_merge_collapses_pair():
+ """A merge collapses cells: on a scoring move the total tile count does NOT
+ increase (it stays equal or drops), even though a new tile also spawned.
+ Contrast with a pure slide where the count strictly increases. This asserts the
+ concrete count arithmetic of a merge."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_merge_collapses_pair", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a merge move does not raise the tile count")
+ return
+ hit = None
+ i = 0
+ while hit is None and i < 40:
+ bt, bp = _tiles(), _points()
+ bc = len(bt)
+ _move(_DIRS[i % 4])
+ at, ap = _tiles(), _points()
+ ac = len(at)
+ i += 1
+ if at == bt or bp is None or ap is None:
+ continue
+ if ap > bp: # a merge happened
+ hit = (bc, ac, ap - bp)
+ break
+ ok = hit is not None and hit[1] <= hit[0]
+ record("computation_merge_collapses_pair", ok,
+ "" if ok else (f"behavior_wrong: merge (points +{hit[2]}) raised tile "
+ f"count {hit[0]}->{hit[1]}" if hit
+ else "setup_failed: no merge move observed"),
+ depth=1, jump_kind="value",
+ expect="on a scoring (merge) move the tile count does not increase")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 16. Two consecutive no-merge slides raise the count by two
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_two_slides_add_two",))
+def test_two_slides_add_two_tiles():
+ """Two effective NO-MERGE moves each spawn one tile, so the count rises by
+ exactly 1 on each. We look for two count-increasing moves and assert each
+ raised the count by exactly one."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_two_slides_add_two", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="two no-merge moves add exactly two tiles")
+ return
+ counts = []
+ i = 0
+ start_c = len(_tiles())
+ while len(counts) < 2 and i < 24:
+ bc = len(_tiles())
+ _move(_DIRS[i % 4])
+ ac = len(_tiles())
+ i += 1
+ if ac == bc + 1: # a pure slide (spawn, no merge)
+ counts.append((bc, ac))
+ ok = len(counts) == 2 and counts[0][1] == counts[0][0] + 1 and \
+ counts[1][1] == counts[1][0] + 1
+ record("computation_two_slides_add_two", ok,
+ "" if ok else f"behavior_wrong: two slides did not each add one tile "
+ f"(start={start_c}, transitions={counts})",
+ depth=1, jump_kind="value",
+ expect="each of two no-merge moves raises the tile count by exactly one")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 17. Restarted game is fresh AND live — a move after restart adds a tile
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_restart_then_move",))
+def test_restart_then_move_adds_tile():
+ """After restart the board is a fresh 2-tile seed AND still computes: the very
+ next effective move raises the tile count past 2 (a spawned tile) and points
+ stay >= 0. Confirms the re-seed is a live game, not a frozen snapshot."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_restart_then_move", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="a move after restart grows the board past 2 tiles")
+ return
+ _play_effective(4)
+ if not _tap_restart():
+ record("computation_restart_then_move", False,
+ "setup_failed: restartButton not found",
+ depth=1, jump_kind="value", expect="a move after restart grows the board past 2 tiles")
+ return
+ settle("tap")
+ seed = _tiles()
+ grew = False
+ for i in range(10):
+ _move(_DIRS[i % 4])
+ if len(_tiles()) > 2:
+ grew = True
+ break
+ p = _points() or 0
+ ok = len(seed) == 2 and grew and p >= 0
+ record("computation_restart_then_move", ok,
+ "" if ok else f"behavior_wrong: re-seeded game not live "
+ f"(seed_tiles={seed}, grew_past_2={grew}, points={p})",
+ depth=1, jump_kind="value",
+ expect="after restart the seed is 2 tiles and a move grows it past 2")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 18. Undo then replay — points can rise again above the reverted value
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_undo_then_replay",))
+def test_undo_then_replay():
+ """After an undo returns points to the pre-move value, the game is fully live:
+ subsequent effective moves can raise points again (>= the reverted value). This
+ proves undo restores STATE, not a dead/frozen board."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_undo_then_replay", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="points can rise again after an undo")
+ return
+ merge = _first_merge_move()
+ if merge is None:
+ record("computation_undo_then_replay", False,
+ "setup_failed: no scoring move produced",
+ depth=1, jump_kind="value", expect="points can rise again after an undo")
+ return
+ pre_move, _k, _post = merge
+ _tap_undo()
+ reverted = _points()
+ if reverted is None:
+ record("computation_undo_then_replay", False,
+ "setup_failed: points unreadable after undo",
+ depth=1, jump_kind="value", expect="points can rise again after an undo")
+ return
+ # play on and try to score again above the reverted value
+ replayed = reverted
+ for i in range(24):
+ _move(_DIRS[i % 4])
+ p = _points() or 0
+ if p > reverted:
+ replayed = p
+ break
+ ok = reverted == pre_move and replayed >= reverted
+ record("computation_undo_then_replay", ok,
+ "" if ok else f"behavior_wrong: after undo to {pre_move}, replay points "
+ f"reached {replayed} (expected to rise back to >= {reverted})",
+ depth=1, jump_kind="value",
+ expect="after undo restores points, further moves raise them again")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 19. 5x5 mode — a larger grid than 4x4, still seeded with exactly 2 tiles
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_5x5_larger_grid", "computation_5x5_grid_vlm"))
+def test_5x5_grid_larger():
+ """Starting a game on the 5x5 page yields a board with strictly MORE cells than
+ 4x4 (the background grid is one Button per cell: observed 29 vs 20), while a
+ fresh 5x5 board still seeds exactly 2 numeric tiles. Confirms mode selection
+ drives the board dimension, and the seed rule is mode-independent."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_5x5_larger_grid", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="5x5 grid has more cells than 4x4")
+ vlm_assert("computation_5x5_grid", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="value", tag="size")
+ return
+ cells4 = _cell_count()
+ tiles4 = len(_tiles())
+ and_back()
+ settle("tap")
+ _go_to_mode(1)
+ if not and_enter_game():
+ record("computation_5x5_larger_grid", False,
+ "setup_failed: could not start a new 5x5 game",
+ depth=1, jump_kind="value", expect="5x5 grid has more cells than 4x4")
+ vlm_assert("computation_5x5_grid", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="value", tag="size")
+ return
+ n5 = ui()
+ cells5 = _cell_count(n5)
+ tiles5 = len(_tiles(n5))
+ ok = cells5 > cells4 and tiles5 == 2 and tiles4 == 2
+ record("computation_5x5_larger_grid", ok,
+ "" if ok else f"behavior_wrong: 5x5 cells={cells5} not > 4x4 cells={cells4}, "
+ f"or seed tiles wrong (4x4={tiles4}, 5x5={tiles5})",
+ depth=1, jump_kind="value",
+ expect="5x5 board has more cells than 4x4; both seed exactly 2 tiles")
+ # VLM: a 5x5 board is visibly a larger grid (five columns) than the 4x4 default.
+ vlm_assert("computation_5x5_grid",
+ "Is the game board a square grid with five columns and five rows "
+ "of cells (a 5 by 5 grid)?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="size")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 20. Board sum only ever grows by 0/2/4 across a whole run (global conservation)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_sum_growth_bounded",))
+def test_sum_growth_bounded():
+ """Global form of the merge-conservation law: across a run of moves the total
+ tile sum increases by 0 (blocked) or exactly 2/4 (one spawn) per step and NEVER
+ jumps by more, so the end sum equals the start sum plus the spawned tiles. We
+ assert every per-step sum delta stays in {0, 2, 4}."""
+ _boot()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("computation_sum_growth_bounded", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="value", expect="every per-move sum delta is in {0,2,4}")
+ return
+ bad = None
+ steps = 0
+ for i in range(18):
+ bs = sum(_tiles())
+ _move(_DIRS[i % 4])
+ asum = sum(_tiles())
+ d = asum - bs
+ steps += 1
+ if d not in (0, 2, 4):
+ bad = (bs, asum, d)
+ break
+ ok = bad is None and steps >= 10
+ record("computation_sum_growth_bounded", ok,
+ "" if ok else (f"behavior_wrong: per-move sum delta {bad[2]} outside {{0,2,4}} "
+ f"(sum {bad[0]}->{bad[1]})" if bad
+ else f"setup_failed: only {steps} moves sampled"),
+ depth=1, jump_kind="value",
+ expect="every per-move tile-sum delta is 0 (blocked) or 2/4 (one spawn)")
+
+
+TESTS = [
+ test_fresh_seed_two_tiles, # 1
+ test_effective_move_conserves_sum, # 2
+ test_slide_adds_one_tile, # 3
+ test_merge_move_scores_points, # 4
+ test_merge_pair_scores_its_sum, # 5
+ test_blocked_move_no_change, # 6
+ test_blocked_move_no_new_tile, # 7
+ test_record_equals_max, # 8
+ test_record_monotonic, # 9
+ test_restart_resets_points, # 10 + VLM two-tiles (position)
+ test_undo_restores_points, # 11
+ test_undo_restores_tile_count, # 12
+ test_undo_applies_once, # 13
+ test_points_accumulate, # 14
+ test_merge_collapses_pair, # 15
+ test_two_slides_add_two_tiles, # 16
+ test_restart_then_move_adds_tile, # 17
+ test_undo_then_replay, # 18
+ test_5x5_grid_larger, # 19 + VLM 5x5 grid (size)
+ test_sum_growth_bounded, # 20
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_interaction.py b/android/secuso-privacy-friendly-2048/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd6ccd762c963948a05b8815f0ee9a6db6bbee84
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_interaction.py
@@ -0,0 +1,1012 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — Privacy Friendly 2048.
+
+Owns EFFECT-BY-CONSEQUENCE on user DATA: multi-step (3+) sequences, multi-record
+integrity, and DATA persistence across process death. The "data" here is the saved
+game (board tiles + points), the per-mode statistics rows, and the continue-game
+availability that a saved game creates.
+
+Everything asserted was OBSERVED on the running original (recon.md + live probing).
+CONTRACTS CONFIRMED empirically on the device before writing:
+ * Game start: points TextView (id points) == "0"; board has EXACTLY 2 numeric
+ tiles; each non-empty tile is a Button whose text is its value; restartButton
+ present; undoButton ABSENT until the first effective move.
+ * A DPAD move that changes the board adds exactly one new tile and (on a merge)
+ adds the merged sum to points. A blocked move changes nothing.
+ * UNDO (undoButton): reverts the last move -> points returns to the pre-move
+ value, and the button disappears (once per move). NOTE: the tile MULTISET is
+ NOT a reliable undo invariant (the pre-move board already carried a random
+ new-tile from the prior move), so undo is asserted on POINTS equality, which
+ is deterministic. Confirmed: merge move points 0->4, undo -> points back to 0.
+ * RESTART (restartButton): points -> "0", board re-seeded to EXACTLY 2 tiles,
+ no dialog. Non-destructive to statistics/records.
+ * PERSISTENCE contract (confirmed all three arms):
+ - graceful back() to Main writes the save (onPause);
+ - kill AFTER back (force_stop_and_relaunch) -> continue ENABLED and restores
+ the EXACT points + tile multiset (48 / [2,4,4,16] restored verbatim);
+ - kill WITHOUT a prior back -> the save is skipped -> continue stays DISABLED
+ (from a clean clear_data() start). This is the discriminating arm: an
+ in-memory-only recreation cannot pass the survive-after-back test.
+ * STATS (StatsActivity, per-mode tab; suffix n: 1=4x4, 2=5x5): after playing 4x4
+ on a clean baseline, moves_All1/moves_L1 increase from 0, highest_number1 /
+ highest_score1 reflect play, undo_number1 increments after an undo; and the
+ 5x5 tab (suffix 2) stays 0 -> multi-mode integrity. Blocked moves make exact
+ counts nondeterministic, so counts are asserted as >= the clean-baseline floor.
+
+Long-press: 2048 has NO long-press / context-menu feature (verified — tiles are not
+long-clickable), so none is invented. The overflow "More options" menu in
+StatsActivity is the one real context menu; opening it is safe (its single item is
+destructive, so it is never tapped).
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+SRC_MAIN = "START NEW GAME" # button_newGame text — Main-only marker
+
+
+def _boot():
+ """Clean-but-package-agnostic entry: restart, reach foreground, dismiss a
+ possible first-run tutorial. Tolerates the tutorial being present OR absent."""
+ restart_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+
+
+def _boot_clean():
+ """clear_data() first for a virgin database (fresh stats / no saved game),
+ then launch and skip the tutorial if it appears."""
+ clear_data()
+ launch_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+
+
+def _skip_tutorial():
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+
+
+def _points(nodes=None):
+ """Current score as an int, or None if the points view is absent."""
+ n = node_by_id(nodes if nodes is not None else ui(), "points")
+ if n and n.get("text", "").strip().lstrip("-").isdigit():
+ return int(n["text"].strip())
+ return None
+
+
+def _tiles(nodes=None):
+ """Sorted multiset of on-board tile values (each tile is a numeric Button)."""
+ nodes = nodes if nodes is not None else ui()
+ return sorted(int(b["text"]) for b in find_by_class(nodes, "Button")
+ if b.get("text", "").strip().isdigit())
+
+
+def and_enter_game(nodes=None):
+ """Tap button_newGame and CONFIRM the game surface appeared (board + points),
+ counting one crossed surface. Returns True on success. Backs depth>=1."""
+ nodes = nodes if nodes is not None else ui()
+ ng = node_by_id(nodes, "button_newGame")
+ if not ng or not tap_node(ng):
+ return False
+ settle("tap")
+ fresh = ui()
+ if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None:
+ return False
+ and_enter("game")
+ return True
+
+
+def and_enter_continue(nodes=None):
+ """Tap button_continueGame and CONFIRM the game surface appeared. Backs a
+ depth crossing for the resume half of a persistence sequence."""
+ nodes = nodes if nodes is not None else ui()
+ cg = node_by_id(nodes, "button_continueGame")
+ if not cg or not tap_node(cg):
+ return False
+ settle("tap")
+ fresh = ui()
+ if node_by_id(fresh, "points") is None and node_by_id(fresh, "number_field") is None:
+ return False
+ and_enter("game_resumed")
+ return True
+
+
+def and_reach_stats():
+ """Main -> drawer -> Statistics, PROVING the jump (a tab strip / stat row
+ appeared and the Main-only START NEW GAME vanished). Counts one surface."""
+ db = find_node(ui(), content_desc="Open navigation drawer")
+ if not db or not tap_node(db):
+ return False
+ settle("tap")
+ item = find_node_ci(ui(), "Statistics")
+ if not item:
+ return False
+ before = and_showing()
+ if not tap_node(item):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "4x4", SRC_MAIN):
+ # fall back to a weaker confirmation: any per-mode stat row present
+ if node_by_id(ui(), "moves_All1") is None:
+ return False
+ and_enter("statistics")
+ return True
+
+
+def _stat_int(suffix):
+ """Read a StatsActivity stat value (e.g. 'moves_All1') as an int, else None."""
+ n = node_by_id(ui(), suffix)
+ if n and n.get("text", "").strip().lstrip("-").isdigit():
+ return int(n["text"].strip())
+ return None
+
+
+def _select_stats_tab(label):
+ """Tap a stats tab by its content-desc (4x4/5x5/6x6/7x7)."""
+ t = find_node(ui(), content_desc=label)
+ if t:
+ tap_node(t)
+ settle("tap")
+
+
+def _play_moves(n_left_up):
+ """Drive n_left_up * (LEFT,UP) DPAD moves on the current game surface. LEFT+UP
+ reliably produces merges on a fresh 4x4 (verified: reaches points>0 quickly)."""
+ for _ in range(n_left_up):
+ press_key("KEYCODE_DPAD_LEFT")
+ press_key("KEYCODE_DPAD_UP")
+
+
+def _play_until_points(cap=12):
+ """Alternate LEFT/UP until points>0 (a merge happened) or cap iters. Returns
+ the points reached (int) — deterministic way to force score>0."""
+ for i in range(cap):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ p = _points()
+ if p and p > 0:
+ return p
+ return _points() or 0
+
+
+def _tap_restart():
+ r = node_by_id(ui(), "restartButton")
+ return tap_node(r) if r else False
+
+
+def _tap_undo():
+ u = node_by_id(ui(), "undoButton")
+ return tap_node(u) if u else False
+
+
+def _go_to_mode(index):
+ """Page the Main ViewPager to page `index` (0=4x4,1=5x5,...). btn_prev is
+ absent on page 0, btn_next absent on the last page — deterministic stops."""
+ for _ in range(6): # rewind to page 0
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ for _ in range(index): # advance to target
+ nx = node_by_id(ui(), "btn_next")
+ if not nx:
+ break
+ tap_node(nx)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 1. FLAGSHIP — data survives process death (back saves, kill preserves)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_persist_after_kill",
+ "interaction_persist_board_restored_vlm"))
+def test_persistence_across_process_death():
+ """Play -> back (saves) -> kill+relaunch -> continue restores EXACT points and
+ tile multiset. The single most discriminating test: an in-memory-only
+ recreation cannot reproduce the board after the process is killed."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_persist_after_kill", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="game surface")
+ vlm_assert("interaction_persist_board_restored", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ _play_moves(6)
+ P, T = _points(), _tiles()
+ if P is None or not T:
+ record("interaction_persist_after_kill", False,
+ "setup_failed: could not read points/tiles after play",
+ depth=1, jump_kind="transition", expect="game surface")
+ vlm_assert("interaction_persist_board_restored", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ and_back() # to Main -> onPause writes save
+ settle("tap")
+ force_stop_and_relaunch() # process death; file persists
+ wait_for_foreground(15)
+ _skip_tutorial()
+ _go_to_mode(0)
+ resumed = and_enter_continue()
+ P2, T2 = (_points(), _tiles()) if resumed else (None, None)
+ ok = resumed and P2 == P and T2 == T
+ record("interaction_persist_after_kill", ok,
+ "" if ok else f"behavior_wrong: expected points={P} tiles={T}, "
+ f"got points={P2} tiles={T2} after kill+continue",
+ depth=2, jump_kind="transition",
+ expect=f"continue restores points={P} tiles={T} after process death")
+ # VLM: the restored board is a populated grid, not empty
+ vlm_assert("interaction_persist_board_restored",
+ "Does the game board show multiple numbered tiles (a populated "
+ "grid), i.e. it is NOT an empty grid?",
+ depth=2, jump_kind="transition", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 2. Kill WITHOUT back does not save (the negative arm)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_kill_without_back_not_saved",))
+def test_kill_without_back_not_saved():
+ """Clean -> play -> force_stop WITHOUT back -> relaunch: continue is still
+ DISABLED (SIGKILL skips onPause, so nothing was written). Proves the save is
+ tied to a graceful pause, not to merely having played."""
+ _boot_clean()
+ _go_to_mode(0)
+ cg0 = node_by_id(ui(), "button_continueGame")
+ disabled_before = cg0 is not None and cg0.get("enabled") == "false"
+ if not and_enter_game():
+ record("interaction_kill_without_back_not_saved", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="continue disabled after kill")
+ return
+ _play_moves(6)
+ played = (_points() or 0) >= 0 and len(_tiles()) >= 2
+ force_stop_and_relaunch() # NO back first -> not saved
+ wait_for_foreground(15)
+ _skip_tutorial()
+ _go_to_mode(0)
+ cg = node_by_id(ui(), "button_continueGame")
+ disabled_after = cg is not None and cg.get("enabled") == "false"
+ ok = disabled_before and played and disabled_after
+ record("interaction_kill_without_back_not_saved", ok,
+ "" if ok else f"behavior_wrong: continue not disabled after kill "
+ f"without back (before_disabled={disabled_before}, "
+ f"after_disabled={disabled_after})",
+ depth=1, jump_kind="transition",
+ expect="continue DISABLED after play then kill-without-back")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 3. Continue availability flips from a saved game (play + back)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_continue_enable_after_play_back",))
+def test_continue_enables_after_play_and_back():
+ """Clean -> continue DISABLED -> new game -> a move -> back: continue becomes
+ ENABLED. The saved-game creation is the data consequence (before->after flip)."""
+ _boot_clean()
+ _go_to_mode(0)
+ cg0 = node_by_id(ui(), "button_continueGame")
+ disabled_before = cg0 is not None and cg0.get("enabled") == "false"
+ if not and_enter_game():
+ record("interaction_continue_enable_after_play_back", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="continue enabled after back")
+ return
+ _play_moves(2)
+ and_back() # to Main -> writes save
+ settle("tap")
+ cg = node_by_id(ui(), "button_continueGame")
+ enabled_after = cg is not None and cg.get("enabled") == "true"
+ ok = disabled_before and enabled_after
+ record("interaction_continue_enable_after_play_back", ok,
+ "" if ok else f"behavior_wrong: continue did not flip disabled->enabled "
+ f"(before_disabled={disabled_before}, "
+ f"after_enabled={enabled_after})",
+ depth=1, jump_kind="transition",
+ expect="continue enabled=true after play then back")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 4. Undo reverts the last move's POINTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_undo_reverts_points",
+ "interaction_undo_board_reverted_vlm"))
+def test_undo_reverts_points():
+ """New game -> make a MERGE move (points rise) -> undo -> points return to the
+ pre-move value. Deterministic on points; also the undo button vanishes."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_undo_reverts_points", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="points reverted by undo")
+ vlm_assert("interaction_undo_board_reverted", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ # find a single move that INCREASES points (a merge); capture the pre-move value
+ prev = _points() or 0
+ pre_move = None
+ for i in range(14):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ cur = _points() or 0
+ if cur > prev:
+ pre_move = prev
+ break
+ prev = cur
+ if pre_move is None:
+ record("interaction_undo_reverts_points", False,
+ "setup_failed: no scoring move produced within cap",
+ depth=1, jump_kind="transition", expect="points reverted by undo")
+ vlm_assert("interaction_undo_board_reverted", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ had_undo = node_by_id(ui(), "undoButton") is not None
+ _tap_undo()
+ after = _points()
+ undo_gone = node_by_id(ui(), "undoButton") is None
+ ok = had_undo and after == pre_move and undo_gone
+ record("interaction_undo_reverts_points", ok,
+ "" if ok else f"behavior_wrong: undo did not restore points to "
+ f"{pre_move} (got {after}, undo_present_before={had_undo}, "
+ f"undo_gone_after={undo_gone})",
+ depth=1, jump_kind="transition",
+ expect=f"points return to {pre_move} after undo")
+ vlm_assert("interaction_undo_board_reverted",
+ "Does the game board still show numbered tiles on the grid after "
+ "the undo (a non-empty board)?",
+ depth=1, jump_kind="transition", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 5. Undo removes the undoButton affordance (once-per-move) + VLM icon
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_undo_once_per_move",
+ "interaction_undo_icon_visible_vlm"))
+def test_undo_is_once_per_move():
+ """undoButton is ABSENT at game start, APPEARS after the first effective move,
+ and is GONE again after a single undo — the once-per-move data affordance."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_undo_once_per_move", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="undo absent->present->absent")
+ vlm_assert("interaction_undo_icon_visible", "unreachable",
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ absent_start = node_by_id(ui(), "undoButton") is None
+ _play_moves(3)
+ present_after_move = node_by_id(ui(), "undoButton") is not None
+ # VLM: the undo (↶) icon is a rendered affordance top-right after a move
+ vlm_assert("interaction_undo_icon_visible",
+ "Is there a curved counter-clockwise undo arrow icon visible near "
+ "the top of the screen?",
+ depth=1, jump_kind="transition", tag="shape")
+ _tap_undo()
+ gone_after_undo = node_by_id(ui(), "undoButton") is None
+ ok = absent_start and present_after_move and gone_after_undo
+ record("interaction_undo_once_per_move", ok,
+ "" if ok else f"behavior_wrong: undo affordance lifecycle wrong "
+ f"(absent_start={absent_start}, "
+ f"present_after_move={present_after_move}, "
+ f"gone_after_undo={gone_after_undo})",
+ depth=1, jump_kind="transition",
+ expect="undoButton absent -> present after move -> absent after undo")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 6. Restart re-seeds the board (points->0, exactly 2 tiles)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_restart_reseeds_board",
+ "interaction_restart_two_tiles_vlm"))
+def test_restart_reseeds_board():
+ """Play until the board grows (points>0, >2 tiles) -> tap restartButton ->
+ points == 0 and EXACTLY 2 numeric tiles, with no dialog."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_restart_reseeds_board", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="points=0 and 2 tiles")
+ vlm_assert("interaction_restart_two_tiles", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ _play_until_points()
+ _play_moves(3)
+ grew = (_points() or 0) > 0 or len(_tiles()) > 2
+ if not _tap_restart():
+ record("interaction_restart_reseeds_board", False,
+ "setup_failed: restartButton not found/tappable",
+ depth=1, jump_kind="transition", expect="points=0 and 2 tiles")
+ vlm_assert("interaction_restart_two_tiles", "unreachable",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ settle("tap")
+ pts_after = _points()
+ tiles_after = _tiles()
+ ok = grew and pts_after == 0 and len(tiles_after) == 2
+ record("interaction_restart_reseeds_board", ok,
+ "" if ok else f"behavior_wrong: after restart expected points=0 and "
+ f"2 tiles, got points={pts_after} tiles={tiles_after} "
+ f"(grew_before={grew})",
+ depth=1, jump_kind="transition",
+ expect="points=0 and exactly 2 tiles after restart")
+ # VLM: the board shows exactly two tiles on an otherwise empty grid
+ vlm_assert("interaction_restart_two_tiles",
+ "Does the game board show exactly two numbered tiles, with all "
+ "the other grid cells empty?",
+ depth=1, jump_kind="transition", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 7. After restart the game is fresh AND still playable (3+ step sequence)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_restart_then_playable",))
+def test_restart_then_playable():
+ """Play -> restart (2 tiles) -> a fresh DPAD move still adds a tile (2->3) and
+ the undo affordance re-appears: the re-seeded game is genuinely live, not a
+ frozen snapshot."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_restart_then_playable", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="tile count 2->3 after restart")
+ return
+ _play_until_points()
+ if not _tap_restart():
+ record("interaction_restart_then_playable", False,
+ "setup_failed: restartButton not found",
+ depth=1, jump_kind="transition", expect="tile count 2->3 after restart")
+ return
+ settle("tap")
+ tiles_seed = _tiles()
+ # make effective moves until the tile count grows past the 2-tile seed
+ grew = False
+ for i in range(8):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ if len(_tiles()) > len(tiles_seed):
+ grew = True
+ break
+ undo_back = node_by_id(ui(), "undoButton") is not None
+ ok = len(tiles_seed) == 2 and grew and undo_back
+ record("interaction_restart_then_playable", ok,
+ "" if ok else f"behavior_wrong: re-seeded game not playable "
+ f"(seed_tiles={tiles_seed}, grew={grew}, "
+ f"undo_back={undo_back})",
+ depth=1, jump_kind="transition",
+ expect="a move after restart adds a tile (2->3) and undo returns")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 8. Accumulated multi-move score persists (variant of flagship, emphasis on sum)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_accumulated_score_persists",
+ "interaction_merged_tiles_colored_vlm"))
+def test_accumulated_score_persists():
+ """Many moves accumulate a score>0 -> back -> kill+relaunch -> continue: the
+ exact accumulated points survive. Distinct from #1 in emphasising that a
+ multi-merge total (not just any board) is preserved."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_accumulated_score_persists", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="accumulated points survive")
+ vlm_assert("interaction_merged_tiles_colored", "unreachable",
+ depth=1, jump_kind="transition", tag="color")
+ return
+ _play_until_points()
+ _play_moves(6)
+ P = _points()
+ # VLM: after merges the board shows higher-value colored tiles
+ vlm_assert("interaction_merged_tiles_colored",
+ "Do the numbered tiles on the board have colored (non-white) "
+ "backgrounds?",
+ depth=1, jump_kind="transition", tag="color")
+ if not P or P <= 0:
+ record("interaction_accumulated_score_persists", False,
+ "setup_failed: score never rose above 0",
+ depth=1, jump_kind="transition", expect="accumulated points survive")
+ return
+ and_back()
+ settle("tap")
+ force_stop_and_relaunch()
+ wait_for_foreground(15)
+ _skip_tutorial()
+ _go_to_mode(0)
+ resumed = and_enter_continue()
+ P2 = _points() if resumed else None
+ ok = resumed and P2 == P and P2 > 0
+ record("interaction_accumulated_score_persists", ok,
+ "" if ok else f"behavior_wrong: accumulated points {P} not preserved "
+ f"across kill (got {P2})",
+ depth=2, jump_kind="transition",
+ expect=f"points={P} (>0) survive back+kill+continue")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 9. Stats: move counters increment after play (clean baseline, depth 2)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_moves_increment",
+ "interaction_stats_nonzero_vlm"))
+def test_stats_moves_increment():
+ """Clean -> play 4x4 (several LEFT + UP) -> back -> drawer -> Statistics (4x4
+ tab): moves_All1 and moves_L1 have risen from the clean 0 baseline. Counts are
+ asserted as >=1 (blocked moves make the exact count nondeterministic)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_stats_moves_increment", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="moves_All1 >= 1")
+ vlm_assert("interaction_stats_nonzero", "unreachable",
+ depth=2, jump_kind="transition", tag="content")
+ return
+ # ensure at least a few LEFT moves are effective
+ for _ in range(4):
+ press_key("KEYCODE_DPAD_LEFT")
+ _play_moves(2)
+ and_back() # to Main (also writes save)
+ settle("tap")
+ if not and_reach_stats():
+ record("interaction_stats_moves_increment", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="moves_All1 >= 1")
+ vlm_assert("interaction_stats_nonzero", "unreachable",
+ depth=2, jump_kind="transition", tag="content")
+ return
+ _select_stats_tab("4x4")
+ moves_all = _stat_int("moves_All1")
+ moves_left = _stat_int("moves_L1")
+ ok = moves_all is not None and moves_all >= 1 and \
+ moves_left is not None and moves_left >= 1
+ record("interaction_stats_moves_increment", ok,
+ "" if ok else f"behavior_wrong: 4x4 stats did not reflect play "
+ f"(moves_All1={moves_all}, moves_L1={moves_left})",
+ depth=2, jump_kind="transition",
+ expect="moves_All1>=1 and moves_L1>=1 after 4x4 play")
+ # VLM: the stat rows show non-zero numeric values, not a blank/zeroed screen
+ vlm_assert("interaction_stats_nonzero",
+ "Does this statistics screen display numeric values in its rows "
+ "(numbers other than only zeros)?",
+ depth=2, jump_kind="transition", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 10. Stats: highest number reflects play
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_highest_number",))
+def test_stats_highest_number_reflects_play():
+ """Clean -> play until a tile >= 4 exists -> back -> Stats 4x4:
+ highest_number1 >= 4 (the merged max is recorded)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_stats_highest_number", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="highest_number1 >= 4")
+ return
+ max_tile = 0
+ for i in range(14):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ t = _tiles()
+ max_tile = max([0] + t)
+ if max_tile >= 4:
+ break
+ and_back()
+ settle("tap")
+ if not and_reach_stats():
+ record("interaction_stats_highest_number", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="highest_number1 >= 4")
+ return
+ _select_stats_tab("4x4")
+ hn = _stat_int("highest_number1")
+ ok = max_tile >= 4 and hn is not None and hn >= 4
+ record("interaction_stats_highest_number", ok,
+ "" if ok else f"behavior_wrong: highest_number1={hn} does not reflect "
+ f"board max {max_tile} (expected >=4)",
+ depth=2, jump_kind="transition",
+ expect=f"highest_number1>=4 (board reached {max_tile})")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 11. Stats: highest score matches the points reached
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_highest_score",))
+def test_stats_highest_score_matches_points():
+ """Clean -> play to points P>0 -> back -> Stats 4x4: highest_score1 == P (the
+ game's best score for this mode is the score we just achieved from zero)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_stats_highest_score", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="highest_score1 == points")
+ return
+ _play_until_points()
+ _play_moves(3)
+ P = _points() or 0
+ and_back()
+ settle("tap")
+ if not and_reach_stats():
+ record("interaction_stats_highest_score", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="highest_score1 == points")
+ return
+ _select_stats_tab("4x4")
+ hs = _stat_int("highest_score1")
+ ok = P > 0 and hs is not None and hs == P
+ record("interaction_stats_highest_score", ok,
+ "" if ok else f"behavior_wrong: highest_score1={hs} != achieved "
+ f"points {P}",
+ depth=2, jump_kind="transition",
+ expect=f"highest_score1 == {P}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 12. Multi-mode stat integrity — playing 4x4 does not touch 5x5 (multi-record)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_mode_isolation",))
+def test_stats_mode_isolation():
+ """Clean -> play ONLY 4x4 -> back -> Stats: 4x4 moves_All1 > 0 while 5x5
+ moves_All2 == 0. Separate per-mode records: one mode's play must not leak
+ into another's statistics."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_stats_mode_isolation", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="4x4>0 while 5x5==0")
+ return
+ _play_moves(4)
+ and_back()
+ settle("tap")
+ if not and_reach_stats():
+ record("interaction_stats_mode_isolation", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="4x4>0 while 5x5==0")
+ return
+ _select_stats_tab("4x4")
+ m4 = _stat_int("moves_All1")
+ _select_stats_tab("5x5")
+ m5 = _stat_int("moves_All2")
+ ok = m4 is not None and m4 > 0 and m5 == 0
+ record("interaction_stats_mode_isolation", ok,
+ "" if ok else f"behavior_wrong: mode isolation broken "
+ f"(4x4 moves_All1={m4}, 5x5 moves_All2={m5})",
+ depth=2, jump_kind="transition",
+ expect="4x4 moves_All1>0 and 5x5 moves_All2==0")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 13. Stats: undo counter increments after an undo
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_undo_counter",))
+def test_stats_undo_counter_increments():
+ """Clean -> play 4x4, use the undo button once -> back -> Stats 4x4:
+ undo_number1 >= 1 (using undo is persisted as a data statistic)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_stats_undo_counter", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="undo_number1 >= 1")
+ return
+ _play_moves(3)
+ used_undo = _tap_undo()
+ and_back()
+ settle("tap")
+ if not and_reach_stats():
+ record("interaction_stats_undo_counter", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="undo_number1 >= 1")
+ return
+ _select_stats_tab("4x4")
+ un = _stat_int("undo_number1")
+ ok = used_undo and un is not None and un >= 1
+ record("interaction_stats_undo_counter", ok,
+ "" if ok else f"behavior_wrong: undo_number1={un} did not record the "
+ f"undo (used_undo={used_undo})",
+ depth=2, jump_kind="transition",
+ expect="undo_number1 >= 1 after using undo")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 14. Continue restores into the correct MODE (5x5 persistence)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_continue_mode_correct",
+ "interaction_5x5_larger_grid_vlm"))
+def test_continue_restores_5x5_mode():
+ """Play a 5x5 game -> back -> kill+relaunch -> continue on the 5x5 page: the
+ exact points and tile multiset restore, proving mode-correct persistence (the
+ save is keyed per mode, not global)."""
+ _boot_clean()
+ _go_to_mode(1) # page to 5x5
+ if not and_enter_game():
+ record("interaction_continue_mode_correct", False,
+ "setup_failed: could not start a new 5x5 game",
+ depth=2, jump_kind="transition", expect="5x5 points/tiles restored")
+ vlm_assert("interaction_5x5_larger_grid", "unreachable",
+ depth=2, jump_kind="transition", tag="size")
+ return
+ _play_until_points()
+ _play_moves(5)
+ P, T = _points(), _tiles()
+ # VLM: a mid-game 5x5 board is a larger grid than the 4x4 default
+ vlm_assert("interaction_5x5_larger_grid",
+ "Is the game board a large square grid with five columns and five "
+ "rows of cells?",
+ depth=2, jump_kind="transition", tag="size")
+ if P is None or not T:
+ record("interaction_continue_mode_correct", False,
+ "setup_failed: could not read 5x5 points/tiles",
+ depth=2, jump_kind="transition", expect="5x5 points/tiles restored")
+ return
+ and_back()
+ settle("tap")
+ force_stop_and_relaunch()
+ wait_for_foreground(15)
+ _skip_tutorial()
+ _go_to_mode(1) # back to the 5x5 page
+ resumed = and_enter_continue()
+ P2, T2 = (_points(), _tiles()) if resumed else (None, None)
+ ok = resumed and P2 == P and T2 == T
+ record("interaction_continue_mode_correct", ok,
+ "" if ok else f"behavior_wrong: 5x5 continue did not restore "
+ f"points={P} tiles={T} (got points={P2} tiles={T2})",
+ depth=2, jump_kind="transition",
+ expect=f"5x5 continue restores points={P} tiles={T}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 15. Two independent saved games coexist (4x4 and 5x5) — strong multi-record
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_two_saved_games",))
+def test_two_independent_saved_games():
+ """Play 4x4 (points P4) + back, then play 5x5 (points P5) + back: BOTH modes'
+ continue buttons are enabled, AND continuing 4x4 restores P4 (not P5).
+ Distinct per-mode save files must not overwrite one another."""
+ _boot_clean()
+ # --- 4x4 game ---
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_two_saved_games", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="4x4 continue restores its own P4")
+ return
+ _play_until_points()
+ _play_moves(3)
+ P4 = _points()
+ and_back()
+ settle("tap")
+ # --- 5x5 game ---
+ _go_to_mode(1)
+ if not and_enter_game():
+ record("interaction_two_saved_games", False,
+ "setup_failed: could not start a new 5x5 game",
+ depth=2, jump_kind="transition", expect="4x4 continue restores its own P4")
+ return
+ _play_until_points()
+ _play_moves(3)
+ P5 = _points()
+ and_back()
+ settle("tap")
+ # both modes enabled?
+ _go_to_mode(1)
+ cg5 = node_by_id(ui(), "button_continueGame")
+ enabled5 = cg5 is not None and cg5.get("enabled") == "true"
+ _go_to_mode(0)
+ cg4 = node_by_id(ui(), "button_continueGame")
+ enabled4 = cg4 is not None and cg4.get("enabled") == "true"
+ # continue 4x4 -> must restore P4, not P5
+ resumed = and_enter_continue()
+ P4_restored = _points() if resumed else None
+ ok = (P4 is not None and P5 is not None and enabled4 and enabled5
+ and resumed and P4_restored == P4)
+ record("interaction_two_saved_games", ok,
+ "" if ok else f"behavior_wrong: two-save integrity failed "
+ f"(P4={P4} P5={P5} enabled4={enabled4} enabled5={enabled5} "
+ f"4x4_restored={P4_restored})",
+ depth=2, jump_kind="transition",
+ expect=f"both modes enabled; 4x4 continue restores points={P4}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 16. Continue is repeatable — resume, back, resume again preserves the board
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_continue_repeatable",))
+def test_continue_repeatable():
+ """Play -> back -> continue (resume) -> back -> continue again: the board and
+ points survive TWO round-trips through Main, and later moves are still applied
+ on top of the restored state (a 3+ surface data sequence)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_continue_repeatable", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="board survives two resumes")
+ return
+ _play_until_points()
+ _play_moves(3)
+ P0 = _points()
+ and_back() # save #1
+ settle("tap")
+ if not and_enter_continue(): # resume #1
+ record("interaction_continue_repeatable", False,
+ "setup_failed: first continue failed",
+ depth=2, jump_kind="transition", expect="board survives two resumes")
+ return
+ P1 = _points()
+ and_back() # save #2
+ settle("tap")
+ if not and_enter_continue(): # resume #2
+ record("interaction_continue_repeatable", False,
+ "setup_failed: second continue failed",
+ depth=3, jump_kind="transition", expect="board survives two resumes")
+ return
+ P2 = _points()
+ ok = P0 is not None and P0 > 0 and P1 == P0 and P2 == P0
+ record("interaction_continue_repeatable", ok,
+ "" if ok else f"behavior_wrong: points not stable across two resumes "
+ f"(P0={P0} resume1={P1} resume2={P2})",
+ depth=3, jump_kind="transition",
+ expect=f"points={P0} preserved across resume->back->resume")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 17. Restart clears the saved game's continue state? -> restart is in-game only
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_restart_then_persist",))
+def test_restart_then_persist():
+ """Play -> restart (board back to seed) -> play again -> back -> kill+relaunch
+ -> continue restores the POST-restart game, not the pre-restart one. Confirms
+ the restart's re-seed is the state that gets persisted (a 3+ step sequence)."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ record("interaction_restart_then_persist", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=2, jump_kind="transition", expect="post-restart game persists")
+ return
+ _play_until_points()
+ _play_moves(4) # a "high" pre-restart score
+ if not _tap_restart():
+ record("interaction_restart_then_persist", False,
+ "setup_failed: restartButton not found",
+ depth=2, jump_kind="transition", expect="post-restart game persists")
+ return
+ settle("tap")
+ # play a fresh, short post-restart game
+ _play_moves(2)
+ P_post = _points()
+ T_post = _tiles()
+ and_back()
+ settle("tap")
+ force_stop_and_relaunch()
+ wait_for_foreground(15)
+ _skip_tutorial()
+ _go_to_mode(0)
+ resumed = and_enter_continue()
+ P2, T2 = (_points(), _tiles()) if resumed else (None, None)
+ ok = resumed and P2 == P_post and T2 == T_post
+ record("interaction_restart_then_persist", ok,
+ "" if ok else f"behavior_wrong: continue did not restore the "
+ f"post-restart game points={P_post} tiles={T_post} "
+ f"(got points={P2} tiles={T2})",
+ depth=2, jump_kind="transition",
+ expect=f"continue restores post-restart points={P_post} tiles={T_post}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 18. Stats overflow (context) menu — sole owner; open only, never tap the item
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_stats_overflow_menu",))
+def test_stats_overflow_menu_opens():
+ """The overflow ('More options') menu in StatsActivity is the app's one real
+ context menu. Opening it reveals a menu item that is ABSENT from the plain
+ Stats surface (the single destructive 'Reset Statistics' entry). We open it
+ and confirm the item appeared — we NEVER tap it (it is destructive)."""
+ _boot_clean()
+ if not and_reach_stats():
+ record("interaction_stats_overflow_menu", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition", expect="overflow menu item appears")
+ return
+ before = and_showing()
+ of = find_node(ui(), content_desc="More options")
+ if of is None:
+ # some builds expose it as a plain overflow button without that desc
+ for n in ui():
+ if "overflow" in (n.get("content-desc", "") + n.get("resource-id", "")).lower():
+ of = n
+ break
+ if of is None or not tap_node(of):
+ record("interaction_stats_overflow_menu", False,
+ "feature_missing: no overflow/context menu control on Statistics",
+ depth=2, jump_kind="transition", expect="overflow menu item appears")
+ return
+ settle("tap")
+ after = and_showing()
+ # a menu item appeared that was not on the plain stats surface
+ item = find_node_ci(ui(), "Reset Statistics")
+ appeared = item is not None or surface_changed(before, after, min_delta=1)
+ # leave the menu WITHOUT tapping the destructive item
+ back()
+ settle("tap")
+ ok = appeared
+ record("interaction_stats_overflow_menu", ok,
+ "" if ok else "behavior_wrong: overflow menu did not open / no item "
+ "appeared",
+ depth=2, jump_kind="transition",
+ expect="overflow opens revealing a menu item over the Stats surface")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 19. VLM — restart icon affordance on the game screen
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_restart_icon_visible_vlm",))
+def test_restart_icon_visible():
+ """The restart (⟳) icon is a rendered affordance on the game toolbar. It is an
+ icon-only control (empty text), so its RENDERING is a genuine VLM question."""
+ _boot_clean()
+ _go_to_mode(0)
+ if not and_enter_game():
+ vlm_assert("interaction_restart_icon_visible", "unreachable",
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ vlm_assert("interaction_restart_icon_visible",
+ "Is there a circular refresh / restart arrow icon visible near the "
+ "top-right of the game screen?",
+ depth=1, jump_kind="transition", tag="shape")
+
+
+TESTS = [
+ test_persistence_across_process_death, # flagship
+ test_kill_without_back_not_saved,
+ test_continue_enables_after_play_and_back,
+ test_undo_reverts_points,
+ test_undo_is_once_per_move,
+ test_restart_reseeds_board,
+ test_restart_then_playable,
+ test_accumulated_score_persists,
+ test_stats_moves_increment,
+ test_stats_highest_number_reflects_play,
+ test_stats_highest_score_matches_points,
+ test_stats_mode_isolation,
+ test_stats_undo_counter_increments,
+ test_continue_restores_5x5_mode,
+ test_two_independent_saved_games,
+ test_continue_repeatable,
+ test_restart_then_persist,
+ test_stats_overflow_menu_opens,
+ test_restart_icon_visible,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_navigation.py b/android/secuso-privacy-friendly-2048/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..eee02240834e61285c36d02405a18f8510023f28
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_navigation.py
@@ -0,0 +1,599 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — Privacy Friendly 2048.
+
+Sole owner of surface REACHABILITY and back-stack integrity: every jump is proven
+with and_reach() — the TARGET surface's discriminating element APPEARED *and* the
+SOURCE surface's element DISAPPEARED — so a screen that was already in the tree can
+never be mistaken for one that was navigated to. This lane carries the suite's
+depth>=2 chains (drawer -> Settings -> a preference dialog; Main -> Game -> back).
+
+Everything asserted here was OBSERVED on the running original (see recon.md + live
+probing). Key facts that drive the marker choices below:
+ * button_newGame carries text "START NEW GAME" -> node_key "Button|START NEW GAME"
+ * button_continueGame carries text "CONTINUE GAME"
+ * restartButton has no text/desc -> node_key falls back to id suffix "restartButton"
+ * "START NEW GAME" is Main-only: it VANISHES on every drawer destination, so it is
+ the universal source marker. (view_pager is NOT — TutorialActivity has its own.)
+ * btn_prev is absent from the dump on page 0; btn_next is absent on the last page.
+ * Behind a Settings AlertDialog the settings list rows leave the dump, so the dialog
+ option ("Dark"/"Original") appearing while "Activate Animation" disappears is a
+ genuine depth-2 surface reach.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+SRC_MAIN = "START NEW GAME" # Main-only key fragment (button_newGame text)
+
+
+def _boot():
+ """Clean entry point every test: restart, reach foreground, dismiss a possible
+ first-run tutorial. Tolerates the tutorial being present OR absent."""
+ restart_app()
+ fg = wait_for_foreground(15)
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+ return fg
+
+
+def _mode_label(nodes):
+ for x in nodes:
+ if x.get("class", "").endswith("TextView") and x.get("text", "") in (
+ "4x4", "5x5", "6x6", "7x7"):
+ return x.get("text", "")
+ return ""
+
+
+def _goto_first_mode():
+ """Page the MainActivity ViewPager back to page 0 (4x4). btn_prev is INVISIBLE
+ (absent from the dump) on page 0, which is the deterministic stop condition."""
+ for _ in range(6):
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ settle("tap")
+ return ui()
+
+
+def _open_drawer(nodes):
+ """Open the nav drawer from a screen that has the hamburger. Returns True on tap."""
+ db = find_node(nodes, content_desc="Open navigation drawer")
+ return tap_node(db) if db else False
+
+
+def and_reach_drawer(item, target, source=SRC_MAIN):
+ """Main -> (open drawer) -> tap `item`, then PROVE the destination surface:
+ `target` appeared and `source` (a Main-only key) vanished. Counts one surface,
+ so it BACKS a depth>=1 reach. The and_reach_* NAME is what the depth audit reads.
+
+ before is snapshotted on MAIN (pre-drawer) so the verdict compares Main against
+ the landed destination — the transient open-drawer overlay is irrelevant."""
+ before = and_showing()
+ if not _open_drawer(ui()):
+ return False
+ settle("tap")
+ if not tap_text(ui(), item):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+def and_reach_game_new(nodes):
+ """Main -> GameActivity via START NEW GAME. Proves restartButton appeared and
+ the launcher's START NEW GAME vanished. Counts one surface (backs depth>=1)."""
+ btn = node_by_id(nodes, "button_newGame")
+ return bool(btn) and and_reach_surface(btn, "restartButton", SRC_MAIN)
+
+
+def _numeric_tiles(nodes):
+ return [b for b in find_by_class(nodes, "Button")
+ if b.get("text", "").strip().isdigit()]
+
+
+def _play_a_few_moves():
+ """Deterministic effective moves via DPAD (recon: DPAD drives handleSwipe*)."""
+ for k in ("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP",
+ "KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP"):
+ press_key(k)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (A) Top-level destinations reached from the drawer (depth 1, jump_kind="reach")
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_statistics", "nav_reach_statistics_vlm"))
+def test_reach_statistics():
+ _boot()
+ ok = and_reach_drawer("Statistics", "Highest Number")
+ record("nav_reach_statistics", ok,
+ "" if ok else "feature_missing: Statistics surface not reached "
+ "(its 'Highest Number' did not appear or Main's START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="StatsActivity: 'Highest Number' appears; Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_statistics",
+ "Is a horizontal row of tab labels shown across the top of the "
+ "screen, with rows of statistics listed below it?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))
+def test_reach_settings():
+ _boot()
+ ok = and_reach_drawer("Settings", "Select theme")
+ record("nav_reach_settings", ok,
+ "" if ok else "feature_missing: Settings surface not reached "
+ "('Select theme' did not appear or Main's START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="SettingsActivity: 'Select theme' appears; Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_settings",
+ "Is this a settings screen showing a vertical list of preference "
+ "rows, each with a title line?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_reach_help", "nav_reach_help_vlm"))
+def test_reach_help():
+ _boot()
+ ok = and_reach_drawer("Help", "What is the goal of this game?")
+ record("nav_reach_help", ok,
+ "" if ok else "feature_missing: Help surface not reached "
+ "(FAQ row did not appear or Main's START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="HelpActivity: FAQ row 'What is the goal of this game?' appears; "
+ "Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_help",
+ "Is the screen a vertical list of question rows, one per line, "
+ "like an FAQ / help list?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="layout")
+
+
+@and_test(expects=("nav_reach_about", "nav_reach_about_vlm"))
+def test_reach_about():
+ _boot()
+ # "Version:" is an About-only label; textFieldVersionName is its value field.
+ ok = and_reach_drawer("About", "Version:")
+ record("nav_reach_about", ok,
+ "" if ok else "feature_missing: About surface not reached "
+ "('Version:' did not appear or Main's START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="AboutActivity: 'Version:' label appears; Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_about",
+ "Does this screen show app information text such as a version "
+ "number, author names, and a license paragraph?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="content")
+
+
+@and_test(expects=("nav_reach_tutorial", "nav_reach_tutorial_vlm"))
+def test_reach_tutorial():
+ _boot()
+ # Tutorial slide 1 title "Welcome!" is unique to TutorialActivity.
+ ok = and_reach_drawer("Tutorial", "Welcome!")
+ record("nav_reach_tutorial", ok,
+ "" if ok else "feature_missing: Tutorial surface not reached "
+ "('Welcome!' did not appear or Main's START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="TutorialActivity: slide title 'Welcome!' appears; "
+ "Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_tutorial",
+ "Are there SKIP and NEXT buttons at the bottom of the screen "
+ "below an introduction slide?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_reach_game_new", "nav_reach_game_new_vlm"))
+def test_reach_game_new():
+ _boot()
+ _goto_first_mode()
+ ok = and_reach_game_new(ui())
+ record("nav_reach_game_new", ok,
+ "" if ok else "feature_missing: GameActivity not reached from "
+ "START NEW GAME (restartButton absent or START NEW GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="GameActivity: restartButton appears; Main 'START NEW GAME' gone")
+ vlm_assert("nav_reach_game_new",
+ "Is there a left-pointing back/up arrow at the top-left of the "
+ "screen, above a grid of square game tiles?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (B) Back-stack returns (jump_kind="transition" — the SOURCE surface comes back)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_back_game_to_main",))
+def test_back_game_to_main():
+ """Game -> BACK -> Main. and_back() presses BACK and pops one surface; the
+ verdict is that Main's START NEW GAME reappeared and Game's restartButton left."""
+ _boot()
+ _goto_first_mode()
+ if not and_reach_game_new(ui()):
+ record("nav_back_game_to_main", False,
+ "setup_failed: could not open the game to test BACK",
+ depth=1, jump_kind="transition",
+ expect="Main restored (START NEW GAME back, restartButton gone)")
+ return
+ before = and_showing() # on Game
+ and_back() # BACK, pop one surface
+ after = and_showing()
+ ok = and_reach(before, after, target=SRC_MAIN, source="restartButton")
+ record("nav_back_game_to_main", ok,
+ "" if ok else "behavior_wrong: BACK did not return Game -> Main "
+ "(START NEW GAME not restored or restartButton still present)",
+ depth=1, jump_kind="transition",
+ expect="MainActivity restored: 'START NEW GAME' reappears, "
+ "restartButton disappears")
+
+
+@and_test(expects=("nav_back_stats_to_main",))
+def test_back_stats_to_main():
+ """Stats -> BACK -> Main."""
+ _boot()
+ if not and_reach_drawer("Statistics", "Highest Number"):
+ record("nav_back_stats_to_main", False,
+ "setup_failed: could not reach Statistics to test BACK",
+ depth=1, jump_kind="transition",
+ expect="Main restored (START NEW GAME back, 'Highest Number' gone)")
+ return
+ before = and_showing() # on Stats
+ and_back()
+ after = and_showing()
+ ok = and_reach(before, after, target=SRC_MAIN, source="Highest Number")
+ record("nav_back_stats_to_main", ok,
+ "" if ok else "behavior_wrong: BACK did not return Stats -> Main "
+ "(START NEW GAME not restored or 'Highest Number' still present)",
+ depth=1, jump_kind="transition",
+ expect="MainActivity restored: 'START NEW GAME' reappears, "
+ "'Highest Number' disappears")
+
+
+@and_test(expects=("nav_back_settings_to_main",))
+def test_back_settings_to_main():
+ """Settings -> BACK -> Main."""
+ _boot()
+ if not and_reach_drawer("Settings", "Select theme"):
+ record("nav_back_settings_to_main", False,
+ "setup_failed: could not reach Settings to test BACK",
+ depth=1, jump_kind="transition",
+ expect="Main restored (START NEW GAME back, 'Select theme' gone)")
+ return
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ ok = and_reach(before, after, target=SRC_MAIN, source="Select theme")
+ record("nav_back_settings_to_main", ok,
+ "" if ok else "behavior_wrong: BACK did not return Settings -> Main "
+ "(START NEW GAME not restored or 'Select theme' still present)",
+ depth=1, jump_kind="transition",
+ expect="MainActivity restored: 'START NEW GAME' reappears, "
+ "'Select theme' disappears")
+
+
+@and_test(expects=("nav_back_about_to_main",))
+def test_back_about_to_main():
+ """About -> BACK -> Main. About's toolbar uses 'Navigate up', but the hardware
+ BACK still returns to Main (verified on the running app)."""
+ _boot()
+ if not and_reach_drawer("About", "Version:"):
+ record("nav_back_about_to_main", False,
+ "setup_failed: could not reach About to test BACK",
+ depth=1, jump_kind="transition",
+ expect="Main restored (START NEW GAME back, 'Version:' gone)")
+ return
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ ok = and_reach(before, after, target=SRC_MAIN, source="Version:")
+ record("nav_back_about_to_main", ok,
+ "" if ok else "behavior_wrong: BACK did not return About -> Main "
+ "(START NEW GAME not restored or 'Version:' still present)",
+ depth=1, jump_kind="transition",
+ expect="MainActivity restored: 'START NEW GAME' reappears, "
+ "'Version:' disappears")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (C) In-surface ViewPager paging on MainActivity (transition, depth 0)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_pager_next_4to5",))
+def test_pager_next_4to5():
+ """btn_next advances the mode label 4x4 -> 5x5. In-surface state flip (no new
+ surface), so jump_kind='transition', depth 0."""
+ _boot()
+ _goto_first_mode()
+ before = and_showing()
+ start_label = _mode_label(ui())
+ nx = node_by_id(ui(), "btn_next")
+ tapped = tap_node(nx) if nx else False
+ settle("tap")
+ after = and_showing()
+ end_label = _mode_label(ui())
+ ok = bool(tapped and start_label == "4x4" and end_label == "5x5"
+ and and_reach(before, after, target="5x5", source="4x4"))
+ record("nav_pager_next_4to5", ok,
+ "" if ok else f"behavior_wrong: btn_next did not page 4x4->5x5 "
+ f"(start={start_label}, end={end_label})",
+ depth=0, jump_kind="transition",
+ expect="mode label '5x5' appears and '4x4' disappears after btn_next")
+
+
+@and_test(expects=("nav_pager_prev_5to4",))
+def test_pager_prev_5to4():
+ """From 5x5, btn_prev returns the mode label to 4x4."""
+ _boot()
+ _goto_first_mode()
+ nx = node_by_id(ui(), "btn_next")
+ if not (nx and tap_node(nx)):
+ record("nav_pager_prev_5to4", False,
+ "setup_failed: could not page forward to 5x5 first",
+ depth=0, jump_kind="transition",
+ expect="mode label '4x4' restored after btn_prev from 5x5")
+ return
+ settle("tap")
+ before = and_showing()
+ start_label = _mode_label(ui())
+ pv = node_by_id(ui(), "btn_prev")
+ tapped = tap_node(pv) if pv else False
+ settle("tap")
+ after = and_showing()
+ end_label = _mode_label(ui())
+ ok = bool(tapped and start_label == "5x5" and end_label == "4x4"
+ and and_reach(before, after, target="4x4", source="5x5"))
+ record("nav_pager_prev_5to4", ok,
+ "" if ok else f"behavior_wrong: btn_prev did not page 5x5->4x4 "
+ f"(start={start_label}, end={end_label})",
+ depth=0, jump_kind="transition",
+ expect="mode label '4x4' appears and '5x5' disappears after btn_prev")
+
+
+@and_test(expects=("nav_pager_to_last_7x7", "nav_pager_last_arrow_vlm"))
+def test_pager_to_last():
+ """btn_next x3 reaches 7x7 (last page); on the last page btn_next disappears
+ from the tree entirely, while btn_prev is present."""
+ _boot()
+ _goto_first_mode()
+ before = and_showing()
+ steps = 0
+ for _ in range(3):
+ nx = node_by_id(ui(), "btn_next")
+ if not (nx and tap_node(nx)):
+ break
+ settle("tap")
+ steps += 1
+ after = and_showing()
+ end_label = _mode_label(ui())
+ next_gone = node_by_id(ui(), "btn_next") is None
+ prev_present = node_by_id(ui(), "btn_prev") is not None
+ ok = bool(steps == 3 and end_label == "7x7" and next_gone and prev_present
+ and and_reach(before, after, target="7x7", source="4x4"))
+ record("nav_pager_to_last_7x7", ok,
+ "" if ok else f"behavior_wrong: paging to last page not as observed "
+ f"(label={end_label}, next_gone={next_gone}, prev_present={prev_present})",
+ depth=0, jump_kind="transition",
+ expect="mode label '7x7'; btn_next absent on the last page; btn_prev present")
+ vlm_assert("nav_pager_last_arrow",
+ "Is there a right-pointing next arrow on the RIGHT edge next to the "
+ "mode preview? Answer NO if only a left-pointing arrow is present.",
+ RESULTS_DIR, expect="NO",
+ depth=0, jump_kind="transition", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (D) Stats tab switching (transition, already on Stats so depth 1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_stats_tab_4to5",))
+def test_stats_tab_switch():
+ """On StatsActivity, tapping the 5X5 tab swaps the visible stat id set: the 4x4
+ tab shows *number1 ids, the 5x5 tab shows *number2 ids. Same surface -> the tab
+ content flip is a 'transition'; depth 1 because we are already on Stats."""
+ _boot()
+ if not and_reach_drawer("Statistics", "Highest Number"):
+ record("nav_stats_tab_4to5", False,
+ "setup_failed: could not reach Statistics to switch tabs",
+ depth=1, jump_kind="transition",
+ expect="5x5 tab content (highest_number2) present after tapping 5X5")
+ return
+ had_tab1 = node_by_id(ui(), "highest_number1") is not None
+ tab5 = find_node(ui(), text="5X5")
+ tapped = tap_node(tab5) if tab5 else False
+ settle("tap")
+ now = ui()
+ has_tab2 = node_by_id(now, "highest_number2") is not None
+ ok = bool(had_tab1 and tapped and has_tab2)
+ record("nav_stats_tab_4to5", ok,
+ "" if ok else f"behavior_wrong: 5X5 tab did not switch stat content "
+ f"(had highest_number1={had_tab1}, now highest_number2={has_tab2})",
+ depth=1, jump_kind="transition",
+ expect="tapping 5X5 tab reveals the 5x5 stat ids (highest_number2)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (E) Deep chains (depth>=2 — this lane's territory; >=3 provided)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_deep_theme_dialog", "nav_deep_theme_dialog_vlm"))
+def test_deep_theme_dialog():
+ """Main -> (drawer) Settings -> tap 'Select theme' -> theme AlertDialog. Two
+ surfaces are crossed before the assertion (Settings, then the dialog). Behind the
+ dialog the settings list rows leave the dump, so the dialog radio 'Dark'
+ appearing while 'Activate Animation' disappears is a real depth-2 surface reach.
+ Cancels afterwards to leave no dialog open."""
+ _boot()
+ if not and_reach_drawer("Settings", "Select theme"):
+ record("nav_deep_theme_dialog", False,
+ "setup_failed: could not reach Settings for the theme dialog",
+ depth=2, jump_kind="reach",
+ expect="theme dialog: 'Dark' appears; 'Activate Animation' gone")
+ vlm_assert("nav_deep_theme_dialog",
+ "Is a pop-up dialog titled 'Select theme' shown with radio "
+ "options stacked vertically?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="shape")
+ return
+ row = find_node(ui(), text="Select theme")
+ ok = row is not None and and_reach_surface(row, "Dark", "Activate Animation")
+ record("nav_deep_theme_dialog", ok,
+ "" if ok else "feature_missing: theme dialog did not open over Settings "
+ "('Dark' absent or the settings list stayed visible)",
+ depth=2, jump_kind="reach",
+ expect="theme AlertDialog: option 'Dark' appears; settings row "
+ "'Activate Animation' disappears")
+ vlm_assert("nav_deep_theme_dialog",
+ "Is a pop-up dialog titled 'Select theme' shown with radio options "
+ "(System / Light / Dark) stacked vertically?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="shape")
+ # clean up: dismiss the dialog
+ if tap_text(ui(), "CANCEL"):
+ settle("tap")
+
+
+@and_test(expects=("nav_deep_color_dialog",))
+def test_deep_color_dialog():
+ """Main -> (drawer) Settings -> tap 'Select Color Scheme' -> color AlertDialog.
+ depth 2 reach: option 'Original' appears while 'Activate Animation' disappears.
+ Cancels afterwards."""
+ _boot()
+ if not and_reach_drawer("Settings", "Select Color Scheme"):
+ record("nav_deep_color_dialog", False,
+ "setup_failed: could not reach Settings for the color dialog",
+ depth=2, jump_kind="reach",
+ expect="color dialog: 'Original' appears; 'Activate Animation' gone")
+ return
+ row = find_node(ui(), text="Select Color Scheme")
+ ok = row is not None and and_reach_surface(row, "Original", "Activate Animation")
+ record("nav_deep_color_dialog", ok,
+ "" if ok else "feature_missing: color-scheme dialog did not open over "
+ "Settings ('Original' absent or the settings list stayed visible)",
+ depth=2, jump_kind="reach",
+ expect="color AlertDialog: option 'Original' appears; settings row "
+ "'Activate Animation' disappears")
+ if tap_text(ui(), "CANCEL"):
+ settle("tap")
+
+
+@and_test(expects=("nav_deep_game_roundtrip",))
+def test_deep_game_roundtrip():
+ """Main -> START NEW GAME -> Game -> BACK -> Main. A there-and-back chain that
+ crosses the Game surface; the final assertion is that Main was restored. The
+ round trip also arms Continue (BACK triggers save()), which the next test uses."""
+ _boot()
+ _goto_first_mode()
+ if not and_reach_game_new(ui()):
+ record("nav_deep_game_roundtrip", False,
+ "setup_failed: could not open the game for the round trip",
+ depth=2, jump_kind="transition",
+ expect="Main restored after BACK from Game (START NEW GAME back)")
+ return
+ on_game = and_showing()
+ _play_a_few_moves() # make it a real game before leaving
+ and_back() # Game -> Main (pops the crossed surface)
+ on_main = and_showing()
+ ok = and_reach(on_game, on_main, target=SRC_MAIN, source="restartButton")
+ record("nav_deep_game_roundtrip", ok,
+ "" if ok else "behavior_wrong: round trip did not restore Main "
+ "(START NEW GAME not back or restartButton still present)",
+ depth=2, jump_kind="transition",
+ expect="after Main->Game->BACK the MainActivity is restored: "
+ "'START NEW GAME' present, restartButton gone")
+
+
+@and_test(expects=("nav_deep_stats_tab_content",))
+def test_deep_stats_tab_content():
+ """Main -> (drawer) Stats -> tap 5X5 tab -> assert the 5x5 stat content. Two
+ surfaces crossed (Stats reach, then the tab-content flip) before the assertion."""
+ _boot()
+ if not and_reach_drawer("Statistics", "Highest Number"):
+ record("nav_deep_stats_tab_content", False,
+ "setup_failed: could not reach Statistics",
+ depth=2, jump_kind="transition",
+ expect="5x5 tab stat ids (highest_number2) shown after tapping 5X5")
+ return
+ and_enter("stats-4x4-tab") # already crossed into Stats' first tab
+ tab5 = find_node(ui(), text="5X5")
+ before = and_showing()
+ tapped = tap_node(tab5) if tab5 else False
+ settle("tap")
+ now = ui()
+ after = and_showing()
+ # the 5x5 tab exposes highest_number2 / moves_L2 ids
+ has2 = (node_by_id(now, "highest_number2") is not None
+ and node_by_id(now, "moves_L2") is not None)
+ changed = surface_changed(before, after)
+ ok = bool(tapped and has2 and changed)
+ record("nav_deep_stats_tab_content", ok,
+ "" if ok else f"behavior_wrong: 5X5 tab content not shown "
+ f"(highest_number2+moves_L2={has2}, surface_changed={changed})",
+ depth=2, jump_kind="transition",
+ expect="5X5 tab reveals highest_number2 and moves_L2 stat fields")
+
+
+@and_test(expects=("nav_reach_continue_game",))
+def test_reach_continue_game():
+ """Setup: play a game and BACK (arms Continue via save()). Then the real jump:
+ tap the now-enabled CONTINUE GAME and assert GameActivity is reached — restartButton
+ appears and the launcher's CONTINUE GAME vanishes. We navigate to a game we set up,
+ then assert the JUMP (not the game creation)."""
+ _boot()
+ _goto_first_mode()
+ if not and_reach_game_new(ui()):
+ record("nav_reach_continue_game", False,
+ "setup_failed: could not open a game to arm Continue",
+ depth=1, jump_kind="reach",
+ expect="GameActivity via CONTINUE GAME: restartButton appears")
+ return
+ _play_a_few_moves()
+ and_back() # graceful save arms Continue
+ cont = node_by_id(ui(), "button_continueGame")
+ if not cont or cont.get("enabled") != "true":
+ record("nav_reach_continue_game", False,
+ f"setup_failed: CONTINUE GAME not enabled after play+back "
+ f"(enabled={cont.get('enabled') if cont else 'missing'})",
+ depth=1, jump_kind="reach",
+ expect="GameActivity via CONTINUE GAME: restartButton appears")
+ return
+ ok = and_reach_surface(cont, "restartButton", "CONTINUE GAME")
+ record("nav_reach_continue_game", ok,
+ "" if ok else "behavior_wrong: CONTINUE GAME did not reach GameActivity "
+ "(restartButton absent or CONTINUE GAME stayed)",
+ depth=1, jump_kind="reach",
+ expect="GameActivity: restartButton appears; 'CONTINUE GAME' disappears")
+
+
+TESTS = [
+ # (A) reaches
+ test_reach_statistics,
+ test_reach_settings,
+ test_reach_help,
+ test_reach_about,
+ test_reach_tutorial,
+ test_reach_game_new,
+ # (B) back-stack returns
+ test_back_game_to_main,
+ test_back_stats_to_main,
+ test_back_settings_to_main,
+ test_back_about_to_main,
+ # (C) in-surface paging
+ test_pager_next_4to5,
+ test_pager_prev_5to4,
+ test_pager_to_last,
+ # (D) stats tabs
+ test_stats_tab_switch,
+ # (E) deep chains
+ test_deep_theme_dialog,
+ test_deep_color_dialog,
+ test_deep_game_roundtrip,
+ test_deep_stats_tab_content,
+ test_reach_continue_game,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_states.py b/android/secuso-privacy-friendly-2048/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..360dca4994e405538812772d63f8de261c4e4fed
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_states.py
@@ -0,0 +1,984 @@
+#!/usr/bin/env python3
+"""STATE-CHANGE lane — Privacy Friendly 2048.
+
+Sole owner of CHECKED / SELECTED / ENABLED / FOCUSED transitions PAIRED WITH their
+app-authored consequence, of page-level state machines, of conditional
+enable/disable, and of SETTINGS / mode PERSISTENCE across a revisit or process
+death. A bare `checked==true` with no trigger and no consequence is never shipped:
+every case FLIPS or OBSERVES a state as the result of a user action, then asserts
+the consequence, then restores the baseline.
+
+Everything asserted was OBSERVED on the running original (recon.md + live probing):
+ * SettingsActivity is a ListView of preference rows (ids title / summary /
+ switch_widget). Two Switch prefs, BOTH default checked="true":
+ "Activate Animation" and "Activate Screen Lock". The correct Switch is the
+ switch_widget whose y is NEAREST the target title's y (never [0]).
+ Toggling flips checked and PERSISTS across a Settings revisit.
+ * "Select theme" row: tap -> AlertDialog System(checked)/Light/Dark. Selecting
+ Dark updates the row summary to "Dark" IN PLACE (activity stays SettingsActivity,
+ the whole UI repaints to a dark palette) and persists. Restore -> System.
+ * "Select Color Scheme" row: tap -> Default(checked)/Original. Selecting Original
+ updates the summary to "Original" and repaints the tile/preview palette
+ (Default = blue gradient, Original = classic orange/tan). Restore -> Default.
+ * CONTINUE-GAME conditional enable: on THIS emulator the 4x4 save survives
+ clear_data, but 5x5/6x6/7x7 have NO save, so button_continueGame is
+ enabled="false" there. Playing a 5x5 game and pressing BACK (graceful save)
+ flips it to enabled="true".
+ * undoButton (GameActivity) is ABSENT from the tree at game start and APPEARS
+ after the first EFFECTIVE move (a blocked move does NOT reveal it).
+ * restartButton resets points -> "0" (state-machine consequence, no dialog).
+ * Drawer item checked: "Main" checked="true" on MainActivity; after navigating
+ to Settings, "Settings" is checked="true" and "Main" checked="false".
+ * StatsActivity tabs (content-desc 4x4/5x5/6x6/7x7): tapping a tab selects it and
+ swaps the visible stat id set (*number1 -> *number2).
+
+LAUNCH QUIRK: restart_app() may RESUME GameActivity (the 4x4 save). _to_main()
+backs out until button_newGame is present, so every test starts from a real
+MainActivity regardless of the resumed task.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+def _skip_tutorial():
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+
+
+def _to_main():
+ """Launch and guarantee we land on MainActivity. restart_app() can resume
+ GameActivity (a saved 4x4 game), so back out until START NEW GAME is present."""
+ restart_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+ for _ in range(4):
+ if node_by_id(ui(), "button_newGame") is not None:
+ return True
+ back()
+ settle("tap")
+ return node_by_id(ui(), "button_newGame") is not None
+
+
+def _open_drawer():
+ """Open the nav drawer from a surface that carries the hamburger (Main, Stats,
+ Settings, Help). Returns True on a successful tap."""
+ db = find_node(ui(), content_desc="Open navigation drawer")
+ return tap_node(db) if db else False
+
+
+def and_enter_settings():
+ """Main -> drawer -> Settings. CONFIRMS SettingsActivity appeared (the
+ 'Select theme' row is present) and counts one crossed surface, so it BACKS a
+ depth>=1 declaration. Returns True on success."""
+ if not _open_drawer():
+ return False
+ settle("tap")
+ if not tap_text(ui(), "Settings"):
+ return False
+ settle("tap")
+ wait_for_foreground(10)
+ ok = find_node(ui(), text="Select theme") is not None
+ if ok:
+ and_enter("settings")
+ return ok
+
+
+def and_reach_settings():
+ """_to_main() then and_enter_settings() — a self-contained reach used by tests
+ that need a fresh Settings surface. Returns True on success."""
+ if not _to_main():
+ return False
+ return and_enter_settings()
+
+
+def and_enter_game_mode(mode_index):
+ """Main -> page to `mode_index` (0=4x4..3=7x7) -> START NEW GAME. CONFIRMS the
+ game surface (restartButton present) and counts one crossed surface (backs
+ depth>=1). Returns True on success."""
+ _goto_mode(mode_index)
+ ng = node_by_id(ui(), "button_newGame")
+ if not ng or not tap_node(ng):
+ return False
+ settle("tap")
+ if node_by_id(ui(), "restartButton") is None:
+ return False
+ and_enter("game")
+ return True
+
+
+def and_reach_stats():
+ """Main -> drawer -> Statistics. CONFIRMS a per-mode tab appeared (content-desc
+ '4x4') and counts one crossed surface (backs depth>=1). Returns True."""
+ if not _open_drawer():
+ return False
+ settle("tap")
+ if not tap_text(ui(), "Statistics"):
+ return False
+ settle("tap")
+ wait_for_foreground(10)
+ ok = (find_node(ui(), content_desc="4x4") is not None
+ or node_by_id(ui(), "highest_number1") is not None)
+ if ok:
+ and_enter("statistics")
+ return ok
+
+
+def and_enter_theme_dialog():
+ """From SettingsActivity, tap 'Select theme' and CONFIRM the AlertDialog opened
+ (radio option 'Dark' present while the settings row 'Activate Animation' left
+ the tree). Counts one crossed surface, so a depth=2 theme test is honestly
+ backed. Returns True."""
+ row = find_node(ui(), text="Select theme")
+ if not row or not tap_node(row):
+ return False
+ settle("tap")
+ fresh = ui()
+ opened = (find_node_ci(fresh, "Dark") is not None
+ and find_node(fresh, text="Activate Animation") is None)
+ if opened:
+ and_enter("theme_dialog")
+ return opened
+
+
+def and_enter_color_dialog():
+ """From SettingsActivity, tap 'Select Color Scheme' and CONFIRM the AlertDialog
+ opened (radio 'Original' present while 'Activate Animation' left the tree).
+ Counts one crossed surface (backs depth=2). Returns True."""
+ row = find_node(ui(), text="Select Color Scheme")
+ if not row or not tap_node(row):
+ return False
+ settle("tap")
+ fresh = ui()
+ opened = (find_node_ci(fresh, "Original") is not None
+ and find_node(fresh, text="Activate Animation") is None)
+ if opened:
+ and_enter("color_dialog")
+ return opened
+
+
+def _goto_mode(index):
+ """Page the Main ViewPager to page `index`. btn_prev is absent on page 0 and
+ btn_next absent on the last page — deterministic stops."""
+ for _ in range(6):
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ settle("tap")
+ for _ in range(index):
+ nx = node_by_id(ui(), "btn_next")
+ if not nx:
+ break
+ tap_node(nx)
+ settle("tap")
+
+
+def _switch_for(nodes, title_text):
+ """The switch_widget belonging to a preference row, chosen as the Switch whose
+ y is NEAREST the row title's y. Never assumes document order — there are two
+ Switch prefs and [0] is not necessarily the one meant."""
+ titles = [x for x in nodes
+ if x.get("resource-id", "").rsplit("/", 1)[-1] == "title"
+ and x.get("text", "") == title_text]
+ if not titles or "_bounds" not in titles[0]:
+ return None
+ ty = titles[0]["_bounds"][1]
+ sws = [x for x in nodes
+ if x.get("resource-id", "").rsplit("/", 1)[-1] == "switch_widget"
+ and "_bounds" in x]
+ if not sws:
+ return None
+ return min(sws, key=lambda s: abs(s["_bounds"][1] - ty))
+
+
+def _summary_for(nodes, title_text):
+ """The summary TextView directly BELOW a preference row's title (nearest
+ summary with a greater y). Reads the app-authored consequence text of a
+ theme / color selection."""
+ titles = [x for x in nodes
+ if x.get("resource-id", "").rsplit("/", 1)[-1] == "title"
+ and x.get("text", "") == title_text]
+ if not titles or "_bounds" not in titles[0]:
+ return None
+ ty = titles[0]["_bounds"][1]
+ sums = [x for x in nodes
+ if x.get("resource-id", "").rsplit("/", 1)[-1] == "summary"
+ and "_bounds" in x and x["_bounds"][1] > ty]
+ if not sums:
+ return None
+ return min(sums, key=lambda s: s["_bounds"][1] - ty)
+
+
+def _drawer_item(nodes, label):
+ """A drawer CheckedTextView (design_menu_item_text) by its text."""
+ for x in nodes:
+ if (x.get("resource-id", "").rsplit("/", 1)[-1] == "design_menu_item_text"
+ and x.get("text", "") == label):
+ return x
+ return None
+
+
+def _tiles(nodes=None):
+ nodes = nodes if nodes is not None else ui()
+ return sorted(int(b["text"]) for b in find_by_class(nodes, "Button")
+ if b.get("text", "").strip().isdigit())
+
+
+def _points(nodes=None):
+ n = node_by_id(nodes if nodes is not None else ui(), "points")
+ if n and n.get("text", "").strip().isdigit():
+ return int(n["text"].strip())
+ return None
+
+
+def _effective_move():
+ """Make ONE move that changes the board (tries each DPAD direction until the
+ tile multiset changes). Returns True if the board changed. Needed because a
+ blocked move produces no undo affordance and no new tile."""
+ for k in ("KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_RIGHT",
+ "KEYCODE_DPAD_DOWN", "KEYCODE_DPAD_UP", "KEYCODE_DPAD_LEFT"):
+ before = _tiles()
+ press_key(k)
+ if _tiles() != before:
+ return True
+ return False
+
+
+def _play_until_points(cap=14):
+ """Alternate LEFT/UP until points>0 (a merge happened) or cap iters."""
+ for i in range(cap):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ p = _points()
+ if p and p > 0:
+ return p
+ return _points() or 0
+
+
+def _set_theme(option):
+ """From SettingsActivity, open the theme dialog and select `option`
+ (System/Light/Dark). Returns the resulting 'Select theme' summary text (or "")."""
+ row = find_node(ui(), text="Select theme")
+ if not row or not tap_node(row):
+ return ""
+ settle("tap")
+ if not tap_text(ui(), option):
+ # dialog failed to open; dismiss anything transient
+ return ""
+ settle("tap")
+ settle("tap")
+ s = _summary_for(ui(), "Select theme")
+ return s.get("text", "") if s else ""
+
+
+def _set_color(option):
+ """From SettingsActivity, open the color dialog and select `option`
+ (Default/Original). Returns the resulting 'Select Color Scheme' summary."""
+ row = find_node(ui(), text="Select Color Scheme")
+ if not row or not tap_node(row):
+ return ""
+ settle("tap")
+ if not tap_text(ui(), option):
+ return ""
+ settle("tap")
+ settle("tap")
+ s = _summary_for(ui(), "Select Color Scheme")
+ return s.get("text", "") if s else ""
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# A. Settings Switch toggles — sole-owner CHECKED, flip + PERSIST
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_animation_toggle", "states_animation_switch_on_off_vlm"))
+def test_animation_switch_toggles():
+ """'Activate Animation' Switch: read checked BEFORE, tap it, re-ui(), assert
+ checked FLIPPED true->false. The Switch's own checked flip IS the observable
+ consequence of a preference Switch (there is no separate widget). Restores the
+ original checked value at the end so the baseline is untouched."""
+ if not and_reach_settings():
+ record("states_animation_toggle", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Activate Animation checked true->false")
+ vlm_assert("states_animation_switch_on_off", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="position")
+ return
+ sw = _switch_for(ui(), "Activate Animation")
+ if sw is None:
+ record("states_animation_toggle", False,
+ "feature_missing: no 'Activate Animation' switch",
+ depth=1, jump_kind="transition",
+ expect="Activate Animation checked true->false")
+ vlm_assert("states_animation_switch_on_off", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="position")
+ return
+ before = sw.get("checked")
+ # VLM (on the ORIGINAL 'true' state): the toggle thumb sits at the ON (right) side.
+ vlm_assert("states_animation_switch_on_off",
+ "In this settings list, is the ON/OFF toggle switch next to "
+ "'Activate Animation' in its ON state, with the thumb slid to the "
+ "RIGHT end of its track?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="position")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for(ui(), "Activate Animation") or {}).get("checked")
+ ok = before == "true" and after == "false"
+ record("states_animation_toggle", ok,
+ "" if ok else f"behavior_wrong: checked did not flip true->false "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="'Activate Animation' Switch checked true->false after tap")
+ # restore
+ cur = _switch_for(ui(), "Activate Animation")
+ if cur is not None and cur.get("checked") != before:
+ tap_node(cur)
+ settle("tap")
+
+
+@and_test(expects=("states_animation_persists_revisit",))
+def test_animation_persists_across_revisit():
+ """Flip 'Activate Animation' OFF, LEAVE Settings to Main, RE-ENTER Settings,
+ assert the Switch retained the flipped (false) value — settings persistence,
+ this lane's territory. Restores the default (true) at the end."""
+ if not and_reach_settings():
+ record("states_animation_persists_revisit", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="animation checked stays false after a Settings revisit")
+ return
+ sw = _switch_for(ui(), "Activate Animation")
+ if sw is None:
+ record("states_animation_persists_revisit", False,
+ "feature_missing: no 'Activate Animation' switch",
+ depth=1, jump_kind="transition",
+ expect="animation checked stays false after a Settings revisit")
+ return
+ original = sw.get("checked")
+ if original != "false": # ensure we start from ON then flip OFF
+ tap_node(sw)
+ settle("tap")
+ flipped = (_switch_for(ui(), "Activate Animation") or {}).get("checked")
+ # leave to Main, then re-enter Settings
+ and_back() # Settings -> Main
+ settle("tap")
+ revisit_ok = and_enter_settings()
+ persisted = (_switch_for(ui(), "Activate Animation") or {}).get("checked")
+ ok = flipped == "false" and revisit_ok and persisted == "false"
+ record("states_animation_persists_revisit", ok,
+ "" if ok else f"behavior_wrong: OFF state not persisted across revisit "
+ f"(flipped={flipped}, after_revisit={persisted})",
+ depth=1, jump_kind="transition",
+ expect="'Activate Animation' checked=false persists after Main->Settings revisit")
+ # restore to the default (true)
+ cur = _switch_for(ui(), "Activate Animation")
+ if cur is not None and cur.get("checked") != "true":
+ tap_node(cur)
+ settle("tap")
+
+
+@and_test(expects=("states_screenlock_toggle",))
+def test_screenlock_switch_toggles():
+ """'Activate Screen Lock' Switch: checked flips true->false on tap. Picks the
+ correct Switch by its neighbouring title (NOT document order). Restores."""
+ if not and_reach_settings():
+ record("states_screenlock_toggle", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Activate Screen Lock checked true->false")
+ return
+ sw = _switch_for(ui(), "Activate Screen Lock")
+ if sw is None:
+ record("states_screenlock_toggle", False,
+ "feature_missing: no 'Activate Screen Lock' switch",
+ depth=1, jump_kind="transition",
+ expect="Activate Screen Lock checked true->false")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked")
+ ok = before == "true" and after == "false"
+ record("states_screenlock_toggle", ok,
+ "" if ok else f"behavior_wrong: screen-lock checked did not flip "
+ f"true->false (before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="'Activate Screen Lock' Switch checked true->false after tap")
+ cur = _switch_for(ui(), "Activate Screen Lock")
+ if cur is not None and cur.get("checked") != before:
+ tap_node(cur)
+ settle("tap")
+
+
+@and_test(expects=("states_screenlock_persists_revisit",))
+def test_screenlock_persists_across_revisit():
+ """Flip 'Activate Screen Lock' OFF, revisit Settings, assert it stayed OFF.
+ Restores the default (true)."""
+ if not and_reach_settings():
+ record("states_screenlock_persists_revisit", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="screen-lock checked stays false across a Settings revisit")
+ return
+ sw = _switch_for(ui(), "Activate Screen Lock")
+ if sw is None:
+ record("states_screenlock_persists_revisit", False,
+ "feature_missing: no 'Activate Screen Lock' switch",
+ depth=1, jump_kind="transition",
+ expect="screen-lock checked stays false across a Settings revisit")
+ return
+ if sw.get("checked") != "false":
+ tap_node(sw)
+ settle("tap")
+ flipped = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked")
+ and_back() # -> Main
+ settle("tap")
+ revisit_ok = and_enter_settings()
+ persisted = (_switch_for(ui(), "Activate Screen Lock") or {}).get("checked")
+ ok = flipped == "false" and revisit_ok and persisted == "false"
+ record("states_screenlock_persists_revisit", ok,
+ "" if ok else f"behavior_wrong: screen-lock OFF not persisted "
+ f"(flipped={flipped}, after_revisit={persisted})",
+ depth=1, jump_kind="transition",
+ expect="'Activate Screen Lock' checked=false persists across revisit")
+ cur = _switch_for(ui(), "Activate Screen Lock")
+ if cur is not None and cur.get("checked") != "true":
+ tap_node(cur)
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# B. Theme selection — radio selection + summary consequence + persist (+ VLM)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_theme_summary_changes",
+ "states_theme_dark_applied_vlm",
+ "states_theme_system_restored_vlm"))
+def test_theme_selection_changes_summary():
+ """Open the theme dialog (depth 2), read the current summary, select Dark, and
+ assert the row summary CHANGED to 'Dark' (the app-authored consequence). Two
+ VLM checks bracket the palette: dark-applied, then light-again after restore.
+ Restores the theme to System (the baseline) at the very end."""
+ if not and_reach_settings():
+ record("states_theme_summary_changes", False,
+ "setup_failed: could not reach Settings",
+ depth=2, jump_kind="transition", expect="theme summary System->Dark")
+ vlm_assert("states_theme_dark_applied", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ vlm_assert("states_theme_system_restored", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ summ0 = _summary_for(ui(), "Select theme")
+ before = summ0.get("text", "") if summ0 else ""
+ if not and_enter_theme_dialog():
+ record("states_theme_summary_changes", False,
+ "feature_missing: theme dialog did not open",
+ depth=2, jump_kind="transition", expect="theme summary System->Dark")
+ vlm_assert("states_theme_dark_applied", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ vlm_assert("states_theme_system_restored", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ if tap_text(ui(), "Dark"):
+ settle("tap")
+ settle("tap")
+ summ1 = _summary_for(ui(), "Select theme")
+ after = summ1.get("text", "") if summ1 else ""
+ ok = before == "System" and after == "Dark"
+ record("states_theme_summary_changes", ok,
+ "" if ok else f"behavior_wrong: theme summary did not change to Dark "
+ f"(before={before!r}, after={after!r})",
+ depth=2, jump_kind="transition",
+ expect="'Select theme' summary System->Dark after picking Dark")
+ # VLM #1 — the WHOLE settings screen is now a dark palette (dark bg, light text)
+ vlm_assert("states_theme_dark_applied",
+ "Is this settings screen drawn with a DARK theme, i.e. a near-black "
+ "or dark-grey background behind light-coloured text?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ # restore to System, then VLM #2 — back to a light palette
+ _set_theme("System")
+ summ2 = _summary_for(ui(), "Select theme")
+ restored = summ2.get("text", "") if summ2 else ""
+ if restored != "System": # last-ditch: make sure baseline is restored
+ _set_theme("System")
+ vlm_assert("states_theme_system_restored",
+ "Is this settings screen drawn with a LIGHT theme, i.e. a white or "
+ "light background behind dark-coloured text?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_theme_persists_revisit",))
+def test_theme_persists_across_revisit():
+ """Select Light, LEAVE Settings, RE-ENTER, assert the summary still reads
+ 'Light' — the theme choice persists. Restores to System at the end."""
+ if not and_reach_settings():
+ record("states_theme_persists_revisit", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="theme summary stays 'Light' across a Settings revisit")
+ return
+ chosen = _set_theme("Light")
+ if chosen != "Light":
+ record("states_theme_persists_revisit", False,
+ "feature_missing: could not select the 'Light' theme",
+ depth=1, jump_kind="transition",
+ expect="theme summary stays 'Light' across a Settings revisit")
+ _set_theme("System")
+ return
+ and_back() # Settings -> Main
+ settle("tap")
+ revisit_ok = and_enter_settings()
+ summ = _summary_for(ui(), "Select theme")
+ persisted = summ.get("text", "") if summ else ""
+ ok = revisit_ok and persisted == "Light"
+ record("states_theme_persists_revisit", ok,
+ "" if ok else f"behavior_wrong: theme 'Light' not persisted across "
+ f"revisit (after_revisit={persisted!r})",
+ depth=1, jump_kind="transition",
+ expect="'Select theme' summary stays 'Light' after Main->Settings revisit")
+ _set_theme("System") # restore baseline
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# C. Color Scheme — radio selection + summary + persist + palette VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_color_summary_changes",
+ "states_color_original_tiles_vlm",
+ "states_color_default_tiles_vlm"))
+def test_color_selection_changes_summary():
+ """Open the color dialog (depth 2), select Original, assert the summary changed
+ Default->Original. Then two palette VLM checks on a real game board: Original =
+ orange/tan tiles, Default = blue tiles. Restores color scheme to Default."""
+ if not and_reach_settings():
+ record("states_color_summary_changes", False,
+ "setup_failed: could not reach Settings",
+ depth=2, jump_kind="transition",
+ expect="color summary Default->Original")
+ vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+ summ0 = _summary_for(ui(), "Select Color Scheme")
+ before = summ0.get("text", "") if summ0 else ""
+ if not and_enter_color_dialog():
+ record("states_color_summary_changes", False,
+ "feature_missing: color-scheme dialog did not open",
+ depth=2, jump_kind="transition",
+ expect="color summary Default->Original")
+ vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+ if tap_text(ui(), "Original"):
+ settle("tap")
+ settle("tap")
+ summ1 = _summary_for(ui(), "Select Color Scheme")
+ after = summ1.get("text", "") if summ1 else ""
+ ok = before == "Default" and after == "Original"
+ record("states_color_summary_changes", ok,
+ "" if ok else f"behavior_wrong: color summary did not change to Original "
+ f"(before={before!r}, after={after!r})",
+ depth=2, jump_kind="transition",
+ expect="'Select Color Scheme' summary Default->Original after picking Original")
+ # VLM #1 — start a game and observe the ORIGINAL (orange/tan) tile palette
+ if and_reach_settings_to_game(0):
+ vlm_assert("states_color_original_tiles",
+ "On this 2048 game board, are the numbered tiles coloured in the "
+ "classic warm ORANGE / TAN / beige palette (NOT blue)?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ else:
+ vlm_assert("states_color_original_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ # switch back to Default, start a game, observe the BLUE palette
+ default_ok = False
+ if and_reach_settings():
+ default_ok = _set_color("Default") == "Default"
+ if default_ok and and_reach_settings_to_game(0):
+ vlm_assert("states_color_default_tiles",
+ "On this 2048 game board, are the numbered tiles coloured in a "
+ "BLUE / blue-gradient palette (NOT orange or tan)?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ else:
+ vlm_assert("states_color_default_tiles", "unreachable", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+
+
+def and_reach_settings_to_game(mode_index):
+ """Leave the current Settings surface back to Main, then start a new game in
+ `mode_index`. Backs the surface crossings. Returns True once the board shows."""
+ and_back() # Settings -> Main
+ settle("tap")
+ if node_by_id(ui(), "button_newGame") is None:
+ if not _to_main():
+ return False
+ return and_enter_game_mode(mode_index)
+
+
+@and_test(expects=("states_color_persists_revisit",
+ "states_color_preview_changed_vlm"))
+def test_color_persists_across_revisit():
+ """Select Original, revisit Settings, assert the summary still reads 'Original'
+ (color-scheme persistence). A VLM check confirms the MainActivity mode-preview
+ image is NOT the default blue after the switch. Restores to Default."""
+ if not and_reach_settings():
+ record("states_color_persists_revisit", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="color summary stays 'Original' across a Settings revisit")
+ vlm_assert("states_color_preview_changed", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ chosen = _set_color("Original")
+ if chosen != "Original":
+ record("states_color_persists_revisit", False,
+ "feature_missing: could not select 'Original' color scheme",
+ depth=1, jump_kind="transition",
+ expect="color summary stays 'Original' across a Settings revisit")
+ _set_color("Default")
+ vlm_assert("states_color_preview_changed", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ and_back() # Settings -> Main
+ settle("tap")
+ revisit_ok = and_enter_settings()
+ summ = _summary_for(ui(), "Select Color Scheme")
+ persisted = summ.get("text", "") if summ else ""
+ ok = revisit_ok and persisted == "Original"
+ record("states_color_persists_revisit", ok,
+ "" if ok else f"behavior_wrong: color 'Original' not persisted across "
+ f"revisit (after_revisit={persisted!r})",
+ depth=1, jump_kind="transition",
+ expect="'Select Color Scheme' summary stays 'Original' after revisit")
+ # VLM — the Main preview image reflects the Original palette (warm, not blue)
+ and_back() # Settings -> Main
+ settle("tap")
+ if node_by_id(ui(), "button_newGame") is None:
+ _to_main()
+ vlm_assert("states_color_preview_changed",
+ "On this home screen, is the small 2048 board preview image drawn in "
+ "warm ORANGE / TAN colours rather than blue?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ # restore color scheme to Default
+ if and_reach_settings():
+ _set_color("Default")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# D. CONTINUE-GAME conditional enable (state machine, transition)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _continue_disabled_here():
+ """True iff button_continueGame is present and enabled='false' on the current
+ Main page (no saved game for this mode)."""
+ cg = node_by_id(ui(), "button_continueGame")
+ return cg is not None and cg.get("enabled") == "false"
+
+
+def _find_disabled_mode():
+ """Scan Main pages 0..3 (4x4..7x7) and return the FIRST mode index whose
+ button_continueGame is disabled, i.e. that mode has no saved game yet. Returns
+ None if every mode already has a save. Portable: on a fresh eval emulator no
+ mode has a save, so this simply returns 0; on a contaminated dev emulator it
+ skips modes whose save survived and finds one that is still virgin."""
+ _goto_mode(0)
+ if _continue_disabled_here():
+ return 0
+ for i in range(1, 4):
+ nx = node_by_id(ui(), "btn_next")
+ if not nx or not tap_node(nx):
+ break
+ settle("tap")
+ if _continue_disabled_here():
+ return i
+ return None
+
+
+@and_test(expects=("states_continue_enable_transition",))
+def test_continue_enable_transition():
+ """CONTINUE-GAME is a conditional-enable state machine: for a mode with NO saved
+ game button_continueGame is enabled='false'; playing that mode and pressing BACK
+ (graceful save) flips it to enabled='true'. The mode is DISCOVERED at runtime
+ (first mode whose continue is disabled), so the test is immune to which modes a
+ prior run may have saved. A shell that never persists cannot flip this."""
+ if not _to_main():
+ record("states_continue_enable_transition", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="continueGame enabled false->true after play+back")
+ return
+ mode = _find_disabled_mode()
+ if mode is None:
+ record("states_continue_enable_transition", False,
+ "setup_failed: no mode has a disabled Continue to observe the "
+ "flip from (every mode already holds a saved game)",
+ depth=1, jump_kind="transition",
+ expect="continueGame enabled false->true after play+back")
+ return
+ # confirm the discovered mode is disabled right now
+ disabled_before = _continue_disabled_here()
+ if not and_enter_game_mode(mode):
+ record("states_continue_enable_transition", False,
+ f"setup_failed: could not start a new game in mode index {mode}",
+ depth=1, jump_kind="transition",
+ expect="continueGame enabled false->true after play+back")
+ return
+ moved = _effective_move()
+ and_back() # Game -> Main; onPause writes the save
+ settle("tap")
+ _goto_mode(mode) # back to the same page
+ cg = node_by_id(ui(), "button_continueGame")
+ enabled_after = cg is not None and cg.get("enabled") == "true"
+ ok = moved and disabled_before and enabled_after
+ record("states_continue_enable_transition", ok,
+ "" if ok else f"behavior_wrong: continueGame did not flip "
+ f"disabled->enabled for mode index {mode} (moved={moved}, "
+ f"before_disabled={disabled_before}, "
+ f"after_enabled={enabled_after})",
+ depth=1, jump_kind="transition",
+ expect="button_continueGame enabled false->true after playing an "
+ "unsaved mode then pressing back")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# E. undoButton INVISIBLE -> VISIBLE (GameActivity state machine)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_undo_button_appears",))
+def test_undo_button_invisible_to_visible():
+ """undoButton is ABSENT from the tree at game start and APPEARS after the first
+ EFFECTIVE move — an invisible->visible page-state transition. Asserts the same
+ GameActivity throughout so it is a state change, not a navigation. The undo
+ affordance is fully dump-readable, so this stays a RULE assertion (no VLM)."""
+ if not _to_main():
+ record("states_undo_button_appears", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="undoButton absent->present after first effective move")
+ return
+ if not and_enter_game_mode(0):
+ record("states_undo_button_appears", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition",
+ expect="undoButton absent->present after first effective move")
+ return
+ act = get_current_activity()
+ absent_before = node_by_id(ui(), "undoButton") is None
+ moved = _effective_move()
+ present_after = node_by_id(ui(), "undoButton") is not None
+ same_activity = get_current_activity() == act
+ ok = absent_before and moved and present_after and same_activity
+ record("states_undo_button_appears", ok,
+ "" if ok else f"behavior_wrong: undoButton lifecycle wrong "
+ f"(absent_before={absent_before}, moved={moved}, "
+ f"present_after={present_after}, same_activity={same_activity})",
+ depth=1, jump_kind="transition",
+ expect="undoButton absent at start -> present after first effective move (same GameActivity)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# F. restartButton resets points to 0 (state-machine consequence)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_restart_zeros_points",))
+def test_restart_resets_points_to_zero():
+ """Game-in-progress (points>0) -> tap restartButton -> the state machine returns
+ to a fresh board with points == '0'. A dump-readable numeric consequence, so a
+ RULE assertion (not VLM). Same GameActivity throughout."""
+ if not _to_main():
+ record("states_restart_zeros_points", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition", expect="points ->0 after restart")
+ return
+ if not and_enter_game_mode(0):
+ record("states_restart_zeros_points", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition", expect="points ->0 after restart")
+ return
+ act = get_current_activity()
+ reached = _play_until_points()
+ pts_before = _points()
+ rb = node_by_id(ui(), "restartButton")
+ if not rb or not tap_node(rb):
+ record("states_restart_zeros_points", False,
+ "setup_failed: restartButton not found/tappable",
+ depth=1, jump_kind="transition", expect="points ->0 after restart")
+ return
+ settle("tap")
+ pts_after = _points()
+ same_activity = get_current_activity() == act
+ ok = (pts_before is not None and pts_before > 0 and pts_after == 0
+ and same_activity)
+ record("states_restart_zeros_points", ok,
+ "" if ok else f"behavior_wrong: restart did not zero points "
+ f"(before={pts_before}, after={pts_after}, "
+ f"same_activity={same_activity})",
+ depth=1, jump_kind="transition",
+ expect=f"points {pts_before}->0 after tapping restartButton")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# G. Drawer item CHECKED tracks the active surface (sole-owner CHECKED)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_drawer_checked_follows_surface",
+ "states_drawer_selected_highlight_vlm"))
+def test_drawer_checked_follows_active_surface():
+ """On MainActivity the drawer 'Main' item is checked=true and 'Settings' is
+ false. Navigate to Settings, open the drawer there, and assert the checked
+ state MOVED: 'Settings' is now checked=true and 'Main' is checked=false. A VLM
+ check confirms the selected item is visually highlighted."""
+ if not _to_main():
+ record("states_drawer_checked_follows_surface", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="drawer checked Main->Settings across a surface change")
+ vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ # drawer on Main
+ if not _open_drawer():
+ record("states_drawer_checked_follows_surface", False,
+ "setup_failed: no drawer button on MainActivity",
+ depth=1, jump_kind="transition",
+ expect="drawer checked Main->Settings across a surface change")
+ vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ settle("tap")
+ dn_main = ui()
+ main_checked_on_main = (_drawer_item(dn_main, "Main") or {}).get("checked")
+ settings_checked_on_main = (_drawer_item(dn_main, "Settings") or {}).get("checked")
+ # navigate to Settings via the open drawer
+ if not tap_text(ui(), "Settings"):
+ record("states_drawer_checked_follows_surface", False,
+ "setup_failed: could not tap 'Settings' in the drawer",
+ depth=1, jump_kind="transition",
+ expect="drawer checked Main->Settings across a surface change")
+ vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ settle("tap")
+ wait_for_foreground(10)
+ and_enter("settings") # one crossed surface -> backs depth>=1
+ # drawer on Settings
+ if not _open_drawer():
+ record("states_drawer_checked_follows_surface", False,
+ "setup_failed: no drawer button on SettingsActivity",
+ depth=1, jump_kind="transition",
+ expect="drawer checked Main->Settings across a surface change")
+ vlm_assert("states_drawer_selected_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ settle("tap")
+ dn_set = ui()
+ main_checked_on_set = (_drawer_item(dn_set, "Main") or {}).get("checked")
+ settings_checked_on_set = (_drawer_item(dn_set, "Settings") or {}).get("checked")
+ ok = (main_checked_on_main == "true" and settings_checked_on_main == "false"
+ and settings_checked_on_set == "true" and main_checked_on_set == "false")
+ record("states_drawer_checked_follows_surface", ok,
+ "" if ok else f"behavior_wrong: drawer checked did not follow surface "
+ f"(on Main: Main={main_checked_on_main} "
+ f"Settings={settings_checked_on_main}; on Settings: "
+ f"Main={main_checked_on_set} Settings={settings_checked_on_set})",
+ depth=1, jump_kind="transition",
+ expect="drawer checked flips Main(true)->Settings(true) after navigating to Settings")
+ # VLM — the currently-selected drawer item is visually highlighted vs the rest
+ vlm_assert("states_drawer_selected_highlight",
+ "In this open navigation drawer, is the 'Settings' menu row visually "
+ "highlighted (a coloured/tinted background or coloured text) that "
+ "sets it apart from the other menu rows?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ back() # close the drawer
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# H. Stats tab SELECTED state + content swap (transition)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_stats_tab_selected",
+ "states_stats_tab_highlight_vlm"))
+def test_stats_tab_selected_and_content_swaps():
+ """On StatsActivity, tapping the 5x5 tab flips its selected state true and swaps
+ the visible stat id set (highest_number1 -> highest_number2). Asserts BOTH the
+ selected transition and the content consequence. A VLM check confirms the
+ active tab is visually highlighted (indicator/colour)."""
+ if not _to_main() or not and_reach_stats():
+ record("states_stats_tab_selected", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="transition",
+ expect="5x5 tab selected true; stat set 1->2")
+ vlm_assert("states_stats_tab_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ tab4 = find_node(ui(), content_desc="4x4")
+ tab4_sel_before = tab4.get("selected") if tab4 else None
+ had_set1 = node_by_id(ui(), "highest_number1") is not None
+ tab5 = find_node(ui(), content_desc="5x5")
+ if tab5 is None or not tap_node(tab5):
+ record("states_stats_tab_selected", False,
+ "feature_missing: no '5x5' stats tab",
+ depth=1, jump_kind="transition",
+ expect="5x5 tab selected true; stat set 1->2")
+ vlm_assert("states_stats_tab_highlight", "unreachable", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ settle("tap")
+ now = ui()
+ tab5_after = find_node(now, content_desc="5x5")
+ tab5_sel_after = tab5_after.get("selected") if tab5_after else None
+ tab4_after = find_node(now, content_desc="4x4")
+ tab4_sel_after = tab4_after.get("selected") if tab4_after else None
+ has_set2 = node_by_id(now, "highest_number2") is not None
+ ok = (had_set1 and tab5_sel_after == "true" and tab4_sel_after == "false"
+ and has_set2)
+ record("states_stats_tab_selected", ok,
+ "" if ok else f"behavior_wrong: 5x5 tab selection/content did not "
+ f"transition (tab4_sel_before={tab4_sel_before}, "
+ f"tab5_sel_after={tab5_sel_after}, "
+ f"tab4_sel_after={tab4_sel_after}, "
+ f"had_set1={had_set1}, has_set2={has_set2})",
+ depth=1, jump_kind="transition",
+ expect="tapping 5x5 tab: selected true (4x4 false) and stat ids *number1->*number2")
+ # VLM — the active tab is visually highlighted (indicator bar / coloured label)
+ vlm_assert("states_stats_tab_highlight",
+ "In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab "
+ "visually highlighted as the active tab, e.g. by a coloured "
+ "underline indicator or a differently-coloured label, compared with "
+ "the other tabs?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+
+
+TESTS = [
+ # A. Settings switches (flip + persist) — sole-owner CHECKED
+ test_animation_switch_toggles,
+ test_animation_persists_across_revisit,
+ test_screenlock_switch_toggles,
+ test_screenlock_persists_across_revisit,
+ # B. Theme (radio selection + summary + persist + VLM palette)
+ test_theme_selection_changes_summary,
+ test_theme_persists_across_revisit,
+ # C. Color scheme (radio selection + summary + persist + VLM palette)
+ test_color_selection_changes_summary,
+ test_color_persists_across_revisit,
+ # D. Continue-game conditional enable (state machine)
+ test_continue_enable_transition,
+ # E. undoButton invisible -> visible
+ test_undo_button_invisible_to_visible,
+ # F. restart zeros points
+ test_restart_resets_points_to_zero,
+ # G. drawer checked tracks active surface
+ test_drawer_checked_follows_active_surface,
+ # H. stats tab selected + content swap
+ test_stats_tab_selected_and_content_swaps,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_structure.py b/android/secuso-privacy-friendly-2048/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd8a71be6984c3edc350c613d0ec26242a6f70cb
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_structure.py
@@ -0,0 +1,403 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — Privacy Friendly 2048.
+
+Owns exactly two things:
+ 1) the GATE (app launches, MainActivity's top-level surfaces exist), kept to
+ <=30% of tests as jump_kind="none";
+ 2) tree-SHAPE deltas — an interaction that adds/removes a CLASS of widget, a
+ window layer, or grows a grid — recorded as the shape delta only and reversed.
+
+Everything read from the running original: node counts, container ids, and grid
+sizes were all OBSERVED (see recon.md + live probing). No content/value/state
+assertions live here — those are other lanes.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+def _boot():
+ """Clean entry point every test: restart, reach foreground, dismiss a possible
+ first-run tutorial. Tolerates the tutorial being present OR absent."""
+ restart_app()
+ fg = wait_for_foreground(15)
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+ return fg
+
+
+def _mode_label(nodes):
+ for x in nodes:
+ if x.get("class", "").endswith("TextView") and x.get("text", "") in (
+ "4x4", "5x5", "6x6", "7x7"):
+ return x.get("text", "")
+ return ""
+
+
+def _goto_first_mode():
+ """Page the MainActivity ViewPager back to page 0 (4x4). btn_prev is INVISIBLE
+ on page 0, so its disappearance is the deterministic stop condition."""
+ for _ in range(6):
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ settle("tap")
+ return ui()
+
+
+def _numeric_tiles(nodes):
+ """Board tiles that currently hold a value are Buttons whose text is a number."""
+ return [b for b in find_by_class(nodes, "Button")
+ if b.get("text", "").strip().isdigit()]
+
+
+def and_enter_game(nodes):
+ """Navigate Main -> GameActivity via START NEW GAME and confirm the board
+ surface replaced the launcher. Counts one surface (backs depth>=1)."""
+ btn = node_by_id(nodes, "button_newGame")
+ if not btn:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(btn):
+ return False
+ after = and_showing()
+ # board present AND the launcher's newGame gone == a real surface change
+ if node_by_id(ui(), "number_field") and surface_changed(before, after):
+ and_enter("game")
+ return True
+ return False
+
+
+def and_enter_drawer_item(nodes, item):
+ """Open the nav drawer from Main and tap a menu item, confirming the surface
+ changed. Counts one surface (backs depth>=1)."""
+ db = find_node(nodes, content_desc="Open navigation drawer")
+ if not db:
+ return False
+ before = and_showing(nodes)
+ tap_node(db)
+ settle("tap")
+ if not tap_text(ui(), item):
+ return False
+ after = and_showing()
+ if surface_changed(before, after):
+ and_enter(item)
+ return True
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE (jump_kind="none") — kept to a minority of the suite
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ fg = _boot()
+ n = ui()
+ ok = bool(fg
+ and node_by_id(n, "drawer_layout")
+ and node_by_id(n, "view_pager")
+ and node_by_id(n, "button_newGame")
+ and node_by_id(n, "button_continueGame")
+ and node_by_id(n, "toolbar")
+ and find_node(n, content_desc="Open navigation drawer"))
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: MainActivity top-level surfaces "
+ "(drawer_layout/view_pager/newGame/continueGame/toolbar) not all present",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_main_vlm",))
+def test_gate_main_vlm():
+ _boot()
+ _goto_first_mode()
+ vlm_assert("structure_gate_main",
+ "Is there a game mode preview card in the upper area and two wide "
+ "buttons stacked near the bottom of the screen?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="layout")
+
+
+@and_test(expects=("structure_main_dots_vlm",))
+def test_main_dots_vlm():
+ _boot()
+ _goto_first_mode()
+ # layoutDots holds one bullet per mode; on 4x4 the first dot is the active one.
+ vlm_assert("structure_main_dots",
+ "Is there a horizontal row of exactly 4 small round page-indicator "
+ "dots below the preview image?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="shape")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SHAPE deltas
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_drawer_opens", "structure_drawer_opens_vlm"))
+def test_drawer_opens():
+ """Opening the nav drawer adds a whole window layer: nav_view + a RecyclerView
+ with 6 CheckedTextView menu rows. Closing removes them again."""
+ _boot()
+ n = ui()
+ before_menu = len(find_by_class(n, "CheckedTextView"))
+ before_nav = bool(node_by_id(n, "nav_view"))
+ tap_node(find_node(n, content_desc="Open navigation drawer"))
+ settle("tap")
+ o = ui()
+ open_menu = len(find_by_class(o, "CheckedTextView"))
+ open_nav = bool(node_by_id(o, "nav_view"))
+ # reverse it
+ back()
+ settle("tap")
+ close_menu = len(find_by_class(ui(), "CheckedTextView"))
+ ok = (before_menu == 0 and not before_nav
+ and open_nav and open_menu == 6
+ and close_menu == 0)
+ record("structure_drawer_opens", ok,
+ "" if ok else f"behavior_wrong: drawer shape delta not as observed "
+ f"(menu {before_menu}->{open_menu}->{close_menu}, nav {before_nav}->{open_nav})",
+ depth=0, jump_kind="transition",
+ expect="nav_view+6 CheckedTextView appear on open, gone on close")
+ # re-open for the visual check
+ tap_node(find_node(ui(), content_desc="Open navigation drawer"))
+ settle("tap")
+ vlm_assert("structure_drawer_opens",
+ "Is a vertical navigation menu panel of about six labeled rows shown "
+ "on the left side of the screen?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="position")
+
+
+@and_test(expects=("structure_game_board_appears", "structure_game_board_appears_vlm"))
+def test_game_board_appears():
+ """Main -> Game changes the tree shape: the launcher's START NEW GAME button is
+ replaced by a number_field board holding many tile Buttons."""
+ _boot()
+ n = _goto_first_mode()
+ had_newgame = bool(node_by_id(n, "button_newGame"))
+ entered = and_enter_game(n)
+ g = ui()
+ board = bool(node_by_id(g, "number_field"))
+ n_buttons = len(find_by_class(g, "Button"))
+ gone_newgame = node_by_id(g, "button_newGame") is None
+ ok = bool(had_newgame and entered and board and gone_newgame and n_buttons >= 16)
+ record("structure_game_board_appears", ok,
+ "" if ok else f"behavior_wrong: board did not replace launcher "
+ f"(board={board}, buttons={n_buttons}, newGame_gone={gone_newgame})",
+ depth=1, jump_kind="transition",
+ expect="number_field with >=16 Buttons appears; button_newGame disappears")
+ vlm_assert("structure_game_board_appears",
+ "Is a 4 by 4 grid of equally sized square cells shown in the "
+ "middle of the screen?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+
+
+@and_test(expects=("structure_board_size_grows", "structure_board_size_grows_vlm"))
+def test_board_size_grows():
+ """A 5x5 board is structurally larger than a 4x4 one: the board holds more
+ tile Buttons. Observed 4x4 -> 20 Buttons, 5x5 -> 29 Buttons (delta 9)."""
+ _boot()
+ _goto_first_mode()
+ if not and_enter_game(ui()):
+ record("structure_board_size_grows", False,
+ "setup_failed: could not open 4x4 game",
+ depth=1, jump_kind="transition",
+ expect="5x5 board has more tile Buttons than 4x4")
+ vlm_assert("structure_board_size_grows",
+ "Is the grid of tiles 5 columns wide and 5 rows tall?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+ return
+ b4 = len(find_by_class(ui(), "Button"))
+ back()
+ settle("tap")
+ n = _boot() # clean, then page to 5x5 (mode selection persists, so force it)
+ n = _goto_first_mode()
+ nx = node_by_id(n, "btn_next")
+ tapped = tap_node(nx) if nx else False
+ settle("tap")
+ label5 = _mode_label(ui())
+ entered5 = and_enter_game(ui())
+ b5 = len(find_by_class(ui(), "Button"))
+ ok = bool(tapped and label5 == "5x5" and entered5 and b5 > b4 and (b5 - b4) >= 5)
+ record("structure_board_size_grows", ok,
+ "" if ok else f"behavior_wrong: board Button count did not grow with "
+ f"mode (4x4={b4}, 5x5={b5}, label={label5})",
+ depth=1, jump_kind="transition",
+ expect=f"5x5 board Buttons ({b5}) > 4x4 board Buttons ({b4})")
+ vlm_assert("structure_board_size_grows",
+ "Is the grid of tiles 5 columns wide and 5 rows tall?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+
+
+@and_test(expects=("structure_restart_reseeds", "structure_game_tile_color_vlm"))
+def test_restart_reseeds():
+ """restartButton re-seeds the board: after a move that changes the board (tiles
+ become fewer/merged or one more appears), tapping restart returns the board to
+ exactly 2 numeric tiles. Pure shape count — never reads a tile value."""
+ _boot()
+ _goto_first_mode()
+ if not and_enter_game(ui()):
+ record("structure_restart_reseeds", False,
+ "setup_failed: could not open game",
+ depth=1, jump_kind="transition",
+ expect="restart returns board to 2 numeric tiles")
+ vlm_assert("structure_game_tile_color",
+ "Do the tiles that contain numbers have a solid fill color that "
+ "clearly differs from the empty background cells?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+ return
+ fresh = len(_numeric_tiles(ui()))
+ # make effective moves so the board differs from its seed
+ for k in ("KEYCODE_DPAD_UP", "KEYCODE_DPAD_LEFT", "KEYCODE_DPAD_RIGHT"):
+ press_key(k)
+ after_moves = len(_numeric_tiles(ui()))
+ rb = node_by_id(ui(), "restartButton")
+ tapped = tap_node(rb) if rb else False
+ settle("tap")
+ reseeded = len(_numeric_tiles(ui()))
+ ok = bool(fresh == 2 and tapped and reseeded == 2)
+ record("structure_restart_reseeds", ok,
+ "" if ok else f"behavior_wrong: restart did not re-seed to 2 tiles "
+ f"(fresh={fresh}, after_moves={after_moves}, reseeded={reseeded})",
+ depth=1, jump_kind="transition",
+ expect="numeric tiles: 2 fresh -> board changes on moves -> 2 after restart")
+ vlm_assert("structure_game_tile_color",
+ "Do the tiles that contain numbers have a solid fill color that "
+ "clearly differs from the empty background cells?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("structure_settings_list",))
+def test_settings_list():
+ """SettingsActivity shows a ListView of preference rows: >=4 title TextViews and
+ the 2 Switch widgets (Animation, Screen Lock)."""
+ _boot()
+ entered = and_enter_drawer_item(ui(), "Settings")
+ s = ui()
+ lists = len(find_by_class(s, "ListView"))
+ titles = len([x for x in s if x.get("resource-id", "").endswith("/title")])
+ switches = len(find_by_class(s, "Switch"))
+ ok = bool(entered and lists >= 1 and titles >= 4 and switches == 2)
+ record("structure_settings_list", ok,
+ "" if ok else f"feature_missing: settings list shape wrong "
+ f"(ListView={lists}, title rows={titles}, Switch={switches})",
+ depth=1, jump_kind="transition",
+ expect="ListView with >=4 preference title rows and exactly 2 Switch widgets")
+
+
+@and_test(expects=("structure_stats_tabs", "structure_stats_tabs_vlm"))
+def test_stats_tabs():
+ """StatsActivity shows a 4-tab selector (content-desc 4x4/5x5/6x6/7x7) above a
+ content area dense with stat TextViews (>=8)."""
+ _boot()
+ entered = and_enter_drawer_item(ui(), "Statistics")
+ s = ui()
+ tabs = len([x for x in s if x.get("content-desc", "") in
+ ("4x4", "5x5", "6x6", "7x7")])
+ texts = len(find_by_class(s, "TextView"))
+ ok = bool(entered and tabs == 4 and texts >= 8)
+ record("structure_stats_tabs", ok,
+ "" if ok else f"feature_missing: stats shape wrong "
+ f"(mode tabs={tabs}, TextView={texts})",
+ depth=1, jump_kind="transition",
+ expect="4 mode tabs (4x4..7x7) + >=8 stat TextViews")
+ vlm_assert("structure_stats_tabs",
+ "Is a horizontal row of tab labels positioned across the top of "
+ "the screen, with rows of statistics below it?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+
+
+@and_test(expects=("structure_help_expand", "structure_help_expand_vlm"))
+def test_help_expand():
+ """HelpActivity is an ExpandableListView of 9 question rows. Expanding one adds
+ a body TextView to the tree (TextView count grows by 1); collapsing removes it."""
+ _boot()
+ entered = and_enter_drawer_item(ui(), "Help")
+ h = ui()
+ groups = len([x for x in h if x.get("resource-id", "").endswith("/listTitle")])
+ exp_list = len(find_by_class(h, "ExpandableListView"))
+ before_tv = len(find_by_class(h, "TextView"))
+ titles = [x for x in h if x.get("resource-id", "").endswith("/listTitle")]
+ grew = collapsed_back = False
+ after_tv = before_tv
+ if titles:
+ tap_node(titles[0])
+ settle("tap")
+ after_tv = len(find_by_class(ui(), "TextView"))
+ grew = after_tv == before_tv + 1
+ # collapse by tapping the same row again
+ t2 = [x for x in ui() if x.get("resource-id", "").endswith("/listTitle")]
+ if t2:
+ tap_node(t2[0])
+ settle("tap")
+ collapsed_back = len(find_by_class(ui(), "TextView")) == before_tv
+ ok = bool(entered and exp_list >= 1 and groups == 9 and grew and collapsed_back)
+ record("structure_help_expand", ok,
+ "" if ok else f"behavior_wrong: help expand delta wrong "
+ f"(groups={groups}, TextView {before_tv}->{after_tv}, "
+ f"collapsed_back={collapsed_back})",
+ depth=1, jump_kind="transition",
+ expect="9 listTitle rows; expanding a row adds 1 body TextView, "
+ "collapsing removes it")
+ vlm_assert("structure_help_expand",
+ "Is the screen a vertical list of question rows, one per line, like "
+ "an FAQ or expandable help list?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+
+
+@and_test(expects=("structure_about_scroll",))
+def test_about_scroll():
+ """AboutActivity is a single ScrollView holding many static TextViews (>=6):
+ title, Version/Authors labels, license paragraph, and two link rows."""
+ _boot()
+ entered = and_enter_drawer_item(ui(), "About")
+ a = ui()
+ scrolls = len(find_by_class(a, "ScrollView"))
+ texts = len(find_by_class(a, "TextView"))
+ ok = bool(entered and scrolls >= 1 and texts >= 6)
+ record("structure_about_scroll", ok,
+ "" if ok else f"feature_missing: about shape wrong "
+ f"(ScrollView={scrolls}, TextView={texts})",
+ depth=1, jump_kind="transition",
+ expect="ScrollView with >=6 static TextViews")
+
+
+@and_test(expects=("structure_tutorial_slider",))
+def test_tutorial_slider():
+ """TutorialActivity is a ViewPager slide deck: a page indicator (layoutDots) and
+ SKIP + NEXT buttons frame the swipeable pager."""
+ _boot()
+ entered = and_enter_drawer_item(ui(), "Tutorial")
+ t = ui()
+ pager = len(find_by_class(t, "ViewPager"))
+ dots = bool(node_by_id(t, "layoutDots"))
+ skip = bool(node_by_id(t, "btn_skip"))
+ nxt = bool(node_by_id(t, "btn_next"))
+ ok = bool(entered and pager >= 1 and dots and skip and nxt)
+ record("structure_tutorial_slider", ok,
+ "" if ok else f"feature_missing: tutorial shape wrong "
+ f"(ViewPager={pager}, dots={dots}, skip={skip}, next={nxt})",
+ depth=1, jump_kind="transition",
+ expect="ViewPager + layoutDots + SKIP + NEXT buttons")
+
+
+TESTS = [
+ test_gate_launch,
+ test_gate_main_vlm,
+ test_main_dots_vlm,
+ test_drawer_opens,
+ test_game_board_appears,
+ test_board_size_grows,
+ test_restart_reseeds,
+ test_settings_list,
+ test_stats_tabs,
+ test_help_expand,
+ test_about_scroll,
+ test_tutorial_slider,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_android_text.py b/android/secuso-privacy-friendly-2048/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa71326d52f80db7ac337f3c62f2700e325e3fe8
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_android_text.py
@@ -0,0 +1,697 @@
+#!/usr/bin/env python3
+"""TEXT / CONTENT lane — Privacy Friendly 2048.
+
+Sole owner of EXACT-STRING equality: the words an interaction PRODUCES (a score
+that changes as you play, a body paragraph an FAQ expansion reveals, a slide title
+that a NEXT tap swaps) and the app-unique static labels a recreation must get right
+(screen titles, section headers, preference titles, stat labels). Cedes the numeric
+DELTA to computation, the checked bit to states, reachability to navigation — this
+lane asserts only the RENDERED STRING.
+
+Every string below was READ off the running original before it was asserted (casing
+and spacing verified on-device — recon's approximations were re-derived):
+ * GameActivity header labels are exactly "Points" and "Record"; the `points`
+ TextView starts "0" and rises to a numeric string on a merge; on a clean DB the
+ `record` TextView also starts "0" and tracks max(points). A restart puts `points`
+ back to the exact string "0".
+ * MainActivity mode label is exactly "4x4"; btn_next swaps it to exactly "5x5".
+ * SettingsActivity title "Settings"; preference titles "Select theme",
+ "Activate Animation", "Activate Screen Lock", "Select Color Scheme"; the theme
+ summary reads "System" and the colour-scheme summary reads "Default" by default
+ (summaries share id `summary`, so they are located by their sibling title).
+ * StatsActivity labels: "Highest Number","Highest Score","Playing Time",
+ "Used Undo-Button","Total Amount of Swipes","Time per Swipe","Up","Down","Left",
+ "Right"; `time_played1` renders in the format "0.00 h" (ends " h"); tab TEXT is
+ UPPERCASE "4X4"/"5X5"/"6X6"/"7X7" (content-desc is the lowercase form).
+ * HelpActivity FAQ group titles are the exact 9 strings (id `listTitle`); tapping
+ the first row PRODUCES a body TextView (id `expandedListItem`) beginning
+ "The Privacy Friendly App 2048 is a privacy friendly version of the well-known
+ original game 2048."
+ * TutorialActivity slide 1 title "Welcome!" + body "In the following slides you
+ will learn how to play the Game 2048."; NEXT advances the title to
+ "Learn how to move the numbers!".
+ * AboutActivity labels "Version:" and "Authors:", author names
+ "Saskia Jacob and Julian Wadephul", link texts "SECUSO-Website" and "Github-Repo".
+ The version VALUE ("v 1.4.2") is source-derived and is NEVER asserted.
+
+Two VLM questions (this lane's ceiling), both genuinely NOT in the view tree:
+ * the undo/restart icon-only controls on the game toolbar (empty text + desc), and
+ * the drawn "2048" grid illustration on tutorial slide 1 (a Canvas/vector image).
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────────
+
+SRC_MAIN = "START NEW GAME" # button_newGame text — Main-only marker
+
+
+def _boot():
+ """Clean entry: restart, reach foreground, dismiss a possible first-run
+ tutorial. Tolerates the tutorial being present OR absent (recon note)."""
+ restart_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+
+
+def _boot_clean():
+ """clear_data() first for a virgin DB (record/stats reset to 0), then launch
+ and skip the tutorial if it appears. Used only where a 0-baseline is asserted."""
+ clear_data()
+ launch_app()
+ wait_for_foreground(15)
+ _skip_tutorial()
+
+
+def _skip_tutorial():
+ n = ui()
+ if node_by_id(n, "btn_skip") or find_node_ci(n, "SKIP"):
+ tap_text(ui(), "SKIP")
+ settle("tap")
+
+
+def all_text(nodes):
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
+
+
+def _norm(s):
+ return (s or "").strip()
+
+
+def _points_str(nodes=None):
+ n = node_by_id(nodes if nodes is not None else ui(), "points")
+ return _norm(n.get("text")) if n else None
+
+
+def _record_str(nodes=None):
+ n = node_by_id(nodes if nodes is not None else ui(), "record")
+ return _norm(n.get("text")) if n else None
+
+
+def _mode_label(nodes):
+ for x in nodes:
+ if x.get("class", "").endswith("TextView") and x.get("text", "") in (
+ "4x4", "5x5", "6x6", "7x7"):
+ return x.get("text", "")
+ return ""
+
+
+def _goto_first_mode():
+ """Page the Main ViewPager back to page 0 (4x4). btn_prev is absent on page 0."""
+ for _ in range(6):
+ p = node_by_id(ui(), "btn_prev")
+ if not p:
+ break
+ tap_node(p)
+ settle("tap")
+ return ui()
+
+
+def _summary_for(title):
+ """Value of the `summary` TextView that sits directly under the preference row
+ whose title == `title`. Both rows share id `summary`, so match by y-position:
+ the summary is the `summary`-id node whose top y is just below the title's."""
+ nodes = ui()
+ trow = None
+ for n in nodes:
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "title" \
+ and _norm(n.get("text")) == title:
+ trow = n
+ break
+ if trow is None:
+ return None
+ ty = trow.get("_bounds", (0, 0, 0, 0))[1]
+ best, best_dy = None, 10 ** 9
+ for n in nodes:
+ if n.get("resource-id", "").rsplit("/", 1)[-1] != "summary":
+ continue
+ sy = n.get("_bounds", (0, 0, 0, 0))[1]
+ dy = sy - ty
+ if 0 <= dy < best_dy:
+ best, best_dy = n, dy
+ return _norm(best.get("text")) if best else None
+
+
+# ── depth-backing navigation helpers (named and_enter_* so depth>=1 is audited) ──
+
+def _open_drawer():
+ db = find_node(ui(), content_desc="Open navigation drawer")
+ return bool(db) and tap_node(db)
+
+
+def and_enter_game():
+ """Main -> START NEW GAME -> GameActivity. Confirms the game surface (points +
+ the game 'Record' label appeared) and counts one crossed surface. Backs depth>=1."""
+ ng = node_by_id(ui(), "button_newGame")
+ if not ng or not tap_node(ng):
+ return False
+ settle("tap")
+ fresh = ui()
+ if node_by_id(fresh, "points") is None:
+ return False
+ and_enter("game")
+ return True
+
+
+def and_enter_drawer_dest(item, confirm_text):
+ """Main -> (open drawer) -> tap `item`, then CONFIRM the destination by its own
+ text `confirm_text` appearing while Main's START NEW GAME vanished. Counts one
+ surface. The and_enter_* NAME is what the depth audit reads."""
+ if not _open_drawer():
+ return False
+ settle("tap")
+ if not tap_text(ui(), item):
+ return False
+ settle("tap")
+ now = ui()
+ reached = (find_node_ci(now, confirm_text) is not None
+ and find_node_ci(now, SRC_MAIN) is None)
+ if reached:
+ and_enter(item)
+ return reached
+
+
+def and_enter_settings():
+ return and_enter_drawer_dest("Settings", "Select theme")
+
+
+def and_enter_stats():
+ return and_enter_drawer_dest("Statistics", "Highest Number")
+
+
+def and_enter_help():
+ return and_enter_drawer_dest("Help", "What is the goal of this game?")
+
+
+def and_enter_about():
+ return and_enter_drawer_dest("About", "Version:")
+
+
+def and_enter_tutorial():
+ return and_enter_drawer_dest("Tutorial", "Welcome!")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (A) DYNAMIC score strings — the app COMPUTES these; the STRING must change
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_points_updates_on_merge",))
+def test_points_updates_on_merge():
+ """points TextView starts as the exact string '0'; a merge move changes the
+ RENDERED string to a specific non-'0' numeric value. Text owns the string flip
+ (absent '' before, present after); computation owns the numeric delta."""
+ _boot_clean()
+ _goto_first_mode()
+ if not and_enter_game():
+ record("text_points_updates_on_merge", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition",
+ expect="points text '0' -> a non-'0' numeric string after a merge")
+ return
+ start = _points_str()
+ reached = None
+ for i in range(16):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ cur = _points_str()
+ if cur and cur.isdigit() and int(cur) > 0:
+ reached = cur
+ break
+ ok = (start == "0" and reached is not None and reached != "0"
+ and reached.isdigit())
+ record("text_points_updates_on_merge", ok,
+ "" if ok else f"behavior_wrong: points string did not update from '0' "
+ f"to a non-'0' value (start={start!r}, after={reached!r})",
+ depth=1, jump_kind="transition",
+ expect=f"points text '0' -> '{reached}' after a scoring move")
+
+
+@and_test(expects=("text_record_reflects_best",))
+def test_record_reflects_best():
+ """On a clean DB the record TextView starts '0' and, as points climb past it,
+ the RENDERED record string becomes exactly the points string (record = best)."""
+ _boot_clean()
+ _goto_first_mode()
+ if not and_enter_game():
+ record("text_record_reflects_best", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition",
+ expect="record text '0' -> equals the points string after play")
+ return
+ start_rec = _record_str()
+ pts_after = None
+ for i in range(16):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ p = _points_str()
+ if p and p.isdigit() and int(p) > 0:
+ pts_after = p
+ break
+ rec_after = _record_str()
+ ok = (start_rec == "0" and pts_after is not None
+ and rec_after == pts_after and rec_after != "0")
+ record("text_record_reflects_best", ok,
+ "" if ok else f"behavior_wrong: record string did not reflect the best "
+ f"score (start_record={start_rec!r}, points={pts_after!r}, "
+ f"record={rec_after!r})",
+ depth=1, jump_kind="transition",
+ expect=f"record text '0' -> '{pts_after}' (== points) after play")
+
+
+@and_test(expects=("text_points_resets_to_zero",))
+def test_points_resets_to_zero():
+ """After a scoring move the points string is non-'0'; tapping restartButton puts
+ the RENDERED string back to exactly '0' (the string consequence of a re-seed)."""
+ _boot_clean()
+ _goto_first_mode()
+ if not and_enter_game():
+ record("text_points_resets_to_zero", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="transition",
+ expect="points text non-'0' -> '0' after restart")
+ return
+ raised = None
+ for i in range(16):
+ press_key("KEYCODE_DPAD_LEFT" if i % 2 == 0 else "KEYCODE_DPAD_UP")
+ p = _points_str()
+ if p and p.isdigit() and int(p) > 0:
+ raised = p
+ break
+ r = node_by_id(ui(), "restartButton")
+ tapped = tap_node(r) if r else False
+ settle("tap")
+ after = _points_str()
+ ok = raised is not None and raised != "0" and tapped and after == "0"
+ record("text_points_resets_to_zero", ok,
+ "" if ok else f"behavior_wrong: points string did not reset to '0' after "
+ f"restart (raised={raised!r}, after={after!r}, "
+ f"restart_tapped={tapped})",
+ depth=1, jump_kind="transition",
+ expect=f"points text '{raised}' -> '0' after tapping restart")
+
+
+@and_test(expects=("text_game_header_labels",))
+def test_game_header_labels():
+ """Entering the game BRINGS UP the exact static header labels 'Points' and
+ 'Record' (the section headers a recreation of the score bar must render)."""
+ _boot()
+ _goto_first_mode()
+ if not and_enter_game():
+ record("text_game_header_labels", False,
+ "setup_failed: could not start a new 4x4 game",
+ depth=1, jump_kind="none",
+ expect="GameActivity shows 'Points' and 'Record' header labels")
+ return
+ n = ui()
+ ok = (find_node(n, text="Points") is not None
+ and find_node(n, text="Record") is not None)
+ record("text_game_header_labels", ok,
+ "" if ok else "behavior_wrong: game header labels 'Points'/'Record' "
+ "not both present",
+ depth=1, jump_kind="none",
+ expect="exact labels 'Points' and 'Record' shown on GameActivity")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (B) DYNAMIC MainActivity mode label — changes with the ViewPager
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_mode_label_pages_4to5",))
+def test_mode_label_pages_4to5():
+ """The mode label TextView reads exactly '4x4' on page 0; tapping btn_next swaps
+ the RENDERED string to exactly '5x5'. In-page string flip (depth 0)."""
+ _boot()
+ _goto_first_mode()
+ start = _mode_label(ui())
+ absent_5 = "5x5" not in all_text(ui())
+ nx = node_by_id(ui(), "btn_next")
+ tapped = tap_node(nx) if nx else False
+ settle("tap")
+ end = _mode_label(ui())
+ ok = start == "4x4" and absent_5 and tapped and end == "5x5"
+ record("text_mode_label_pages_4to5", ok,
+ "" if ok else f"behavior_wrong: mode label did not change '4x4'->'5x5' "
+ f"(start={start!r}, end={end!r}, next_tapped={tapped})",
+ depth=0, jump_kind="transition",
+ expect="mode label text '4x4' -> '5x5' after btn_next")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (C) Settings — preference titles + summaries reflect the current selection
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_settings_titles",))
+def test_settings_titles():
+ """SettingsActivity renders the exact title 'Settings' and the four preference
+ TITLE strings a recreation must match."""
+ _boot()
+ if not and_enter_settings():
+ record("text_settings_titles", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="none",
+ expect="Settings preference titles shown exactly")
+ return
+ n = ui()
+ want = ["Settings", "Select theme", "Activate Animation",
+ "Activate Screen Lock", "Select Color Scheme"]
+ missing = [w for w in want if find_node(n, text=w) is None]
+ ok = not missing
+ record("text_settings_titles", ok,
+ "" if ok else f"behavior_wrong: Settings missing exact title strings "
+ f"{missing}",
+ depth=1, jump_kind="none",
+ expect="titles 'Settings','Select theme','Activate Animation',"
+ "'Activate Screen Lock','Select Color Scheme' all present")
+
+
+@and_test(expects=("text_theme_summary",))
+def test_theme_summary():
+ """The 'Select theme' row's summary renders the current value; on the default
+ DB it is exactly 'System'. Asserted by exact-equality to the observed value."""
+ _boot()
+ if not and_enter_settings():
+ record("text_theme_summary", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="none",
+ expect="theme summary reads 'System'")
+ return
+ summ = _summary_for("Select theme")
+ ok = summ == "System"
+ record("text_theme_summary", ok,
+ "" if ok else f"behavior_wrong: 'Select theme' summary is {summ!r}, "
+ f"expected exactly 'System'",
+ depth=1, jump_kind="none",
+ expect="'Select theme' summary text == 'System'")
+
+
+@and_test(expects=("text_color_scheme_summary",))
+def test_color_scheme_summary():
+ """The 'Select Color Scheme' row's summary renders the current value; on the
+ default DB it is exactly 'Default'."""
+ _boot()
+ if not and_enter_settings():
+ record("text_color_scheme_summary", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="none",
+ expect="colour-scheme summary reads 'Default'")
+ return
+ summ = _summary_for("Select Color Scheme")
+ ok = summ == "Default"
+ record("text_color_scheme_summary", ok,
+ "" if ok else f"behavior_wrong: 'Select Color Scheme' summary is "
+ f"{summ!r}, expected exactly 'Default'",
+ depth=1, jump_kind="none",
+ expect="'Select Color Scheme' summary text == 'Default'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (D) Statistics — labels, a formatted value, and the tab TEXT casing
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_stats_labels",))
+def test_stats_labels():
+ """StatsActivity renders the exact row-label strings the recreation must match
+ on the default 4x4 tab."""
+ _boot()
+ if not and_enter_stats():
+ record("text_stats_labels", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="none",
+ expect="Stats row labels shown exactly")
+ return
+ n = ui()
+ want = ["Highest Number", "Highest Score", "Playing Time", "Used Undo-Button",
+ "Total Amount of Swipes", "Time per Swipe", "Up", "Down", "Left", "Right"]
+ missing = [w for w in want if find_node(n, text=w) is None]
+ ok = not missing
+ record("text_stats_labels", ok,
+ "" if ok else f"behavior_wrong: Statistics missing exact label strings "
+ f"{missing}",
+ depth=1, jump_kind="none",
+ expect="all 10 stat labels ('Highest Number'..'Right') present exactly")
+
+
+@and_test(expects=("text_stats_playing_time_format",))
+def test_stats_playing_time_format():
+ """The Playing-Time value (id time_played1) renders in the hours format ending
+ ' h' — observed 'X.XX h' (e.g. '0.00 h'). Asserts the rendered format string."""
+ _boot()
+ if not and_enter_stats():
+ record("text_stats_playing_time_format", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="none",
+ expect="Playing Time value formatted as 'N.NN h'")
+ return
+ node = node_by_id(ui(), "time_played1")
+ val = _norm(node.get("text")) if node else None
+ ok = bool(val) and val.endswith(" h") and val[:-2].strip().count(".") == 1 \
+ and val[:-2].strip().replace(".", "").isdigit()
+ record("text_stats_playing_time_format", ok,
+ "" if ok else f"behavior_wrong: Playing Time value {val!r} is not the "
+ f"'N.NN h' hours format",
+ depth=1, jump_kind="none",
+ expect="time_played1 renders like '0.00 h' (a decimal followed by ' h')")
+
+
+@and_test(expects=("text_stats_tab_labels",))
+def test_stats_tab_labels():
+ """The stat tab TEXT is UPPERCASE — exactly '4X4'/'5X5'/'6X6'/'7X7' (distinct
+ from the lowercase content-desc). Asserts the rendered tab strings."""
+ _boot()
+ if not and_enter_stats():
+ record("text_stats_tab_labels", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="none",
+ expect="tab texts '4X4'/'5X5'/'6X6'/'7X7' shown")
+ return
+ n = ui()
+ want = ["4X4", "5X5", "6X6", "7X7"]
+ missing = [w for w in want if find_node(n, text=w) is None]
+ ok = not missing
+ record("text_stats_tab_labels", ok,
+ "" if ok else f"behavior_wrong: Statistics tab texts missing/wrong casing "
+ f"{missing} (expected uppercase '4X4'..'7X7')",
+ depth=1, jump_kind="none",
+ expect="tab texts exactly '4X4','5X5','6X6','7X7' (uppercase)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (E) Help — FAQ group titles, and an EXPANSION that PRODUCES a body paragraph
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_help_faq_titles",))
+def test_help_faq_titles():
+ """HelpActivity renders the exact FAQ group-title strings (id listTitle)."""
+ _boot()
+ if not and_enter_help():
+ record("text_help_faq_titles", False,
+ "setup_failed: could not reach Help",
+ depth=1, jump_kind="none",
+ expect="FAQ group titles shown exactly")
+ return
+ n = ui()
+ want = ["What is Privacy Friendly App 2048?",
+ "How do I move the numbers?",
+ "Is it possible to undo steps?",
+ "How can I change the color spectre of the game?"]
+ missing = [w for w in want if find_node(n, text=w) is None]
+ ok = not missing
+ record("text_help_faq_titles", ok,
+ "" if ok else f"behavior_wrong: Help missing exact FAQ title strings "
+ f"{missing}",
+ depth=1, jump_kind="none",
+ expect="FAQ titles incl. 'What is Privacy Friendly App 2048?' present")
+
+
+@and_test(expects=("text_help_expansion_reveals_body",))
+def test_help_expansion_reveals_body():
+ """Tapping the first FAQ row EXPANDS it and PRODUCES a body TextView (id
+ expandedListItem). The body string is ABSENT before the tap and PRESENT after —
+ the discriminating half. depth 2: entered Help, then expanded within it."""
+ _boot()
+ if not and_enter_help():
+ record("text_help_expansion_reveals_body", False,
+ "setup_failed: could not reach Help",
+ depth=2, jump_kind="transition",
+ expect="FAQ body paragraph appears after expanding the first row")
+ return
+ body_frag = "privacy friendly version of the well-known original game 2048"
+ absent = body_frag.lower() not in all_text(ui()).lower()
+ row = find_node(ui(), text="What is Privacy Friendly App 2048?")
+ tapped = tap_node(row) if row else False
+ settle("tap")
+ settle("tap")
+ and_enter("help-expanded")
+ after = all_text(ui()).lower()
+ present = body_frag.lower() in after
+ ok = absent and tapped and present
+ record("text_help_expansion_reveals_body", ok,
+ "" if ok else f"behavior_wrong: expanding the first FAQ row did not "
+ f"reveal its body text (absent_before={absent}, "
+ f"tapped={tapped}, present_after={present})",
+ depth=2, jump_kind="transition",
+ expect="body '...privacy friendly version of the well-known original "
+ "game 2048' appears only after the row is expanded")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (F) Tutorial — slide 1 title/body, and NEXT advancing the title
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_tutorial_slide1", "text_tutorial_illustration_vlm"))
+def test_tutorial_slide1():
+ """TutorialActivity slide 1 renders the exact title 'Welcome!' and body 'In the
+ following slides you will learn how to play the Game 2048.'. VLM: the slide's
+ drawn '2048' grid illustration is a Canvas/vector image, NOT in the view tree."""
+ _boot()
+ if not and_enter_tutorial():
+ record("text_tutorial_slide1", False,
+ "setup_failed: could not reach Tutorial",
+ depth=1, jump_kind="none",
+ expect="slide 1 title 'Welcome!' and its body shown")
+ vlm_assert("text_tutorial_illustration",
+ "Is a large white '2048' shown drawn inside a grid/hash pattern "
+ "in the centre of the screen?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
+ return
+ n = ui()
+ title_ok = find_node(n, text="Welcome!") is not None
+ body_ok = find_node(
+ n, text="In the following slides you will learn how to play the Game 2048."
+ ) is not None
+ ok = title_ok and body_ok
+ record("text_tutorial_slide1", ok,
+ "" if ok else f"behavior_wrong: slide 1 strings wrong "
+ f"(title_ok={title_ok}, body_ok={body_ok})",
+ depth=1, jump_kind="none",
+ expect="slide 1 title 'Welcome!' and body 'In the following slides you "
+ "will learn how to play the Game 2048.'")
+ # VLM: the illustration glyphs are drawn (vector), not TextViews in the tree.
+ vlm_assert("text_tutorial_illustration",
+ "Is a large white '2048' shown drawn inside a grid/hash pattern in "
+ "the centre of the screen?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
+ # leave tidy: SKIP back to Main
+ if tap_text(ui(), "SKIP"):
+ settle("tap")
+
+
+@and_test(expects=("text_tutorial_next_advances_title",))
+def test_tutorial_next_advances_title():
+ """Tapping NEXT swaps the slide TITLE from 'Welcome!' to the exact slide-2 title
+ 'Learn how to move the numbers!'. The new title is ABSENT before, PRESENT after.
+ depth 2: entered Tutorial, then advanced within it. SKIPs back to Main after."""
+ _boot()
+ if not and_enter_tutorial():
+ record("text_tutorial_next_advances_title", False,
+ "setup_failed: could not reach Tutorial",
+ depth=2, jump_kind="transition",
+ expect="title advances 'Welcome!' -> 'Learn how to move the numbers!'")
+ return
+ slide2 = "Learn how to move the numbers!"
+ on_slide1 = find_node(ui(), text="Welcome!") is not None
+ absent = slide2.lower() not in all_text(ui()).lower()
+ nx = node_by_id(ui(), "btn_next")
+ tapped = tap_node(nx) if nx else False
+ settle("tap")
+ and_enter("tutorial-slide2")
+ present = find_node(ui(), text=slide2) is not None
+ ok = on_slide1 and absent and tapped and present
+ record("text_tutorial_next_advances_title", ok,
+ "" if ok else f"behavior_wrong: NEXT did not advance the slide title to "
+ f"{slide2!r} (on_slide1={on_slide1}, absent_before={absent}, "
+ f"tapped={tapped}, present_after={present})",
+ depth=2, jump_kind="transition",
+ expect=f"slide title 'Welcome!' -> '{slide2}' after tapping NEXT")
+ # leave tidy: SKIP back to Main
+ if tap_text(ui(), "SKIP"):
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (G) About — labels + link texts (never the source-derived version VALUE)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_about_labels",))
+def test_about_labels():
+ """AboutActivity renders the exact label strings 'Version:' and 'Authors:', the
+ author names, and both link texts. The version NUMBER value is deliberately NOT
+ asserted (it is source-derived and a recreation cannot know it)."""
+ _boot()
+ if not and_enter_about():
+ record("text_about_labels", False,
+ "setup_failed: could not reach About",
+ depth=1, jump_kind="none",
+ expect="About labels + link texts shown exactly")
+ return
+ n = ui()
+ want = ["Version:", "Authors:", "Saskia Jacob and Julian Wadephul",
+ "SECUSO-Website", "Github-Repo"]
+ missing = [w for w in want if find_node(n, text=w) is None]
+ ok = not missing
+ record("text_about_labels", ok,
+ "" if ok else f"behavior_wrong: About missing exact strings {missing}",
+ depth=1, jump_kind="none",
+ expect="labels 'Version:'/'Authors:', authors 'Saskia Jacob and Julian "
+ "Wadephul', links 'SECUSO-Website'/'Github-Repo' all present")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (H) VLM — icon-only controls whose meaning is rendered, not in the tree
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_game_icon_controls_vlm",))
+def test_game_icon_controls():
+ """The undo (curved ↶) and restart (circular ⟳) controls on the game toolbar are
+ icon-only — empty text AND empty content-desc — so their MEANING reaches the
+ screen only as a rendered glyph, never the view tree. That is this lane's one
+ legitimate opaque-core case. A move is made first so the undo icon is visible."""
+ _boot()
+ _goto_first_mode()
+ if not and_enter_game():
+ vlm_assert("text_game_icon_controls",
+ "Are there two dark rounded-square icon buttons below the "
+ "'Points' and 'Record' labels — a curved undo arrow on the left "
+ "and a circular refresh/restart arrow on the right?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
+ return
+ press_key("KEYCODE_DPAD_LEFT")
+ press_key("KEYCODE_DPAD_UP")
+ settle("tap")
+ vlm_assert("text_game_icon_controls",
+ "Are there two dark rounded-square icon buttons below the 'Points' "
+ "and 'Record' labels — a curved undo arrow on the left and a "
+ "circular refresh/restart arrow on the right?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
+
+
+TESTS = [
+ # (A) dynamic score strings
+ test_points_updates_on_merge,
+ test_record_reflects_best,
+ test_points_resets_to_zero,
+ test_game_header_labels,
+ # (B) dynamic mode label
+ test_mode_label_pages_4to5,
+ # (C) settings titles + summaries
+ test_settings_titles,
+ test_theme_summary,
+ test_color_scheme_summary,
+ # (D) stats labels + value + tabs
+ test_stats_labels,
+ test_stats_playing_time_format,
+ test_stats_tab_labels,
+ # (E) help titles + expansion body
+ test_help_faq_titles,
+ test_help_expansion_reveals_body,
+ # (F) tutorial slide title/body + NEXT
+ test_tutorial_slide1,
+ test_tutorial_next_advances_title,
+ # (G) about labels
+ test_about_labels,
+ # (H) VLM icon-only controls
+ test_game_icon_controls,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/secuso-privacy-friendly-2048/tests/test_manifest.json b/android/secuso-privacy-friendly-2048/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..5639e0ecfc05c3126987ad90961dd5450622d780
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/tests/test_manifest.json
@@ -0,0 +1,857 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "privacy-friendly-2048",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 132,
+ "manifest_sha": "0ff7282d13b8",
+ "tests": [
+ {
+ "name": "computation::computation_5x5_grid_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_5x5_larger_grid",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_blocked_move_no_change",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_blocked_move_no_new_tile",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_effective_move_sum_delta",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_fresh_seed_two_tiles",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_merge_collapses_pair",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_merge_pair_value",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_merge_scores_points",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_points_accumulate",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_record_is_max",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_record_monotonic",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_restart_resets",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_restart_then_move",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_restart_two_tiles_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_slide_adds_one_tile",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_sum_growth_bounded",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_two_slides_add_two",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_undo_once",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_undo_restores_points",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_undo_restores_tile_count",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_undo_then_replay",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_5x5_larger_grid_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_accumulated_score_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_continue_enable_after_play_back",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_continue_mode_correct",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_continue_repeatable",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_kill_without_back_not_saved",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_merged_tiles_colored_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_persist_after_kill",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_persist_board_restored_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_restart_icon_visible_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_restart_reseeds_board",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_restart_then_persist",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_restart_then_playable",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_restart_two_tiles_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_highest_number",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_highest_score",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_mode_isolation",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_moves_increment",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_nonzero_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_overflow_menu",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_stats_undo_counter",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_two_saved_games",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_undo_board_reverted_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_undo_icon_visible_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_undo_once_per_move",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_undo_reverts_points",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_about_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_game_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_settings_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_stats_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_color_dialog",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_game_roundtrip",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_stats_tab_content",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_theme_dialog",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_theme_dialog_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_pager_last_arrow_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_pager_next_4to5",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_pager_prev_5to4",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_pager_to_last_7x7",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_continue_game",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_game_new",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_game_new_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_help",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_help_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_statistics",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_statistics_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_tutorial",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_tutorial_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_stats_tab_4to5",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_animation_persists_revisit",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_animation_switch_on_off_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_animation_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_default_tiles_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_original_tiles_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_persists_revisit",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_preview_changed_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_summary_changes",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_continue_enable_transition",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_drawer_checked_follows_surface",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_drawer_selected_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_restart_zeros_points",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_screenlock_persists_revisit",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_screenlock_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_stats_tab_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_stats_tab_selected",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_applied_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persists_revisit",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_summary_changes",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_system_restored_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_undo_button_appears",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_about_scroll",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_board_size_grows",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_board_size_grows_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_opens",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_opens_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_board_appears",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_board_appears_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_tile_color_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_main_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_help_expand",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_help_expand_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_main_dots_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_restart_reseeds",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_list",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_tabs",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_tabs_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_tutorial_slider",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_color_scheme_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_game_header_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_game_icon_controls_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_expansion_reveals_body",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_faq_titles",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_mode_label_pages_4to5",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_points_resets_to_zero",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_points_updates_on_merge",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_record_reflects_best",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_titles",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_playing_time_format",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_tab_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_theme_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_illustration_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_next_advances_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_slide1",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_restart_two_tiles_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "computation::computation_5x5_grid_vlm",
+ "module": "computation",
+ "tag": "size"
+ },
+ {
+ "name": "interaction::interaction_persist_board_restored_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_undo_board_reverted_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_undo_icon_visible_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_restart_two_tiles_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_merged_tiles_colored_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_stats_nonzero_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_5x5_larger_grid_vlm",
+ "module": "interaction",
+ "tag": "size"
+ },
+ {
+ "name": "interaction::interaction_restart_icon_visible_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_statistics_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_help_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_reach_about_vlm",
+ "module": "navigation",
+ "tag": "content"
+ },
+ {
+ "name": "navigation::nav_reach_tutorial_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_game_new_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_pager_last_arrow_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_deep_theme_dialog_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_animation_switch_on_off_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_theme_dark_applied_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_system_restored_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_color_original_tiles_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_color_default_tiles_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_color_preview_changed_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_drawer_selected_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_stats_tab_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_gate_main_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_main_dots_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_drawer_opens_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_game_board_appears_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_board_size_grows_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_game_tile_color_vlm",
+ "module": "structure",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_stats_tabs_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_help_expand_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "text::text_tutorial_illustration_vlm",
+ "module": "text",
+ "tag": "shape"
+ },
+ {
+ "name": "text::text_game_icon_controls_vlm",
+ "module": "text",
+ "tag": "shape"
+ }
+ ],
+ "vlm_total": 36,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-2048/vlm_assertions.json b/android/secuso-privacy-friendly-2048/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..e7e4b1f3f8e7cc935118ac6514128e25d1db22f4
--- /dev/null
+++ b/android/secuso-privacy-friendly-2048/vlm_assertions.json
@@ -0,0 +1,743 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/secuso-privacy-friendly-2048",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 36,
+ "with_verdict": 36,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 36,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "computation_restart_two_tiles_vlm",
+ "screenshot": "computation_restart_two_tiles_vlm.png",
+ "assertion": "Does the game grid show exactly two numbered tiles, with every other cell empty?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "computation_restart_two_tiles",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_5x5_grid_vlm",
+ "screenshot": "computation_5x5_grid_vlm.png",
+ "assertion": "Is the game board a square grid with five columns and five rows of cells (a 5 by 5 grid)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "size",
+ "modality": null,
+ "links_to": "computation_5x5_grid",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_animation_switch_on_off_vlm",
+ "screenshot": "states_animation_switch_on_off_vlm.png",
+ "assertion": "In this settings list, is the ON/OFF toggle switch next to 'Activate Animation' in its ON state, with the thumb slid to the RIGHT end of its track?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_animation_switch_on_off",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_dark_applied_vlm",
+ "screenshot": "states_theme_dark_applied_vlm.png",
+ "assertion": "Is this settings screen drawn with a DARK theme, i.e. a near-black or dark-grey background behind light-coloured text?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_dark_applied",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_system_restored_vlm",
+ "screenshot": "states_theme_system_restored_vlm.png",
+ "assertion": "Is this settings screen drawn with a LIGHT theme, i.e. a white or light background behind dark-coloured text?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_system_restored",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_color_original_tiles_vlm",
+ "screenshot": "states_color_original_tiles_vlm.png",
+ "assertion": "On this 2048 game board, are the numbered tiles coloured in the classic warm ORANGE / TAN / beige palette (NOT blue)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_color_original_tiles",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_color_default_tiles_vlm",
+ "screenshot": "states_color_default_tiles_vlm.png",
+ "assertion": "On this 2048 game board, are the numbered tiles coloured in a BLUE / blue-gradient palette (NOT orange or tan)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_color_default_tiles",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_color_preview_changed_vlm",
+ "screenshot": "states_color_preview_changed_vlm.png",
+ "assertion": "On this home screen, is the small 2048 board preview image drawn in warm ORANGE / TAN colours rather than blue?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_color_preview_changed",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_drawer_selected_highlight_vlm",
+ "screenshot": "states_drawer_selected_highlight_vlm.png",
+ "assertion": "In this open navigation drawer, is the 'Settings' menu row visually highlighted (a coloured/tinted background or coloured text) that sets it apart from the other menu rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_drawer_selected_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_stats_tab_highlight_vlm",
+ "screenshot": "states_stats_tab_highlight_vlm.png",
+ "assertion": "In this row of tabs (4x4 / 5x5 / 6x6 / 7x7), is the '5x5' tab visually highlighted as the active tab, e.g. by a coloured underline indicator or a differently-coloured label, compared with the other tabs?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_stats_tab_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_tutorial_illustration_vlm",
+ "screenshot": "text_tutorial_illustration_vlm.png",
+ "assertion": "Is a large white '2048' shown drawn inside a grid/hash pattern in the centre of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "text_tutorial_illustration",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_game_icon_controls_vlm",
+ "screenshot": "text_game_icon_controls_vlm.png",
+ "assertion": "Are there two dark rounded-square icon buttons below the 'Points' and 'Record' labels — a curved undo arrow on the left and a circular refresh/restart arrow on the right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "text_game_icon_controls",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_gate_main_vlm",
+ "screenshot": "structure_gate_main_vlm.png",
+ "assertion": "Is there a game mode preview card in the upper area and two wide buttons stacked near the bottom of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_gate_main",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_main_dots_vlm",
+ "screenshot": "structure_main_dots_vlm.png",
+ "assertion": "Is there a horizontal row of exactly 4 small round page-indicator dots below the preview image?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_main_dots",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_drawer_opens_vlm",
+ "screenshot": "structure_drawer_opens_vlm.png",
+ "assertion": "Is a vertical navigation menu panel of about six labeled rows shown on the left side of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_drawer_opens",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_game_board_appears_vlm",
+ "screenshot": "structure_game_board_appears_vlm.png",
+ "assertion": "Is a 4 by 4 grid of equally sized square cells shown in the middle of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_game_board_appears",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_board_size_grows_vlm",
+ "screenshot": "structure_board_size_grows_vlm.png",
+ "assertion": "Is the grid of tiles 5 columns wide and 5 rows tall?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_board_size_grows",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_game_tile_color_vlm",
+ "screenshot": "structure_game_tile_color_vlm.png",
+ "assertion": "Do the tiles that contain numbers have a solid fill color that clearly differs from the empty background cells?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "structure_game_tile_color",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_stats_tabs_vlm",
+ "screenshot": "structure_stats_tabs_vlm.png",
+ "assertion": "Is a horizontal row of tab labels positioned across the top of the screen, with rows of statistics below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_stats_tabs",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_help_expand_vlm",
+ "screenshot": "structure_help_expand_vlm.png",
+ "assertion": "Is the screen a vertical list of question rows, one per line, like an FAQ or expandable help list?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_help_expand",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_statistics_vlm",
+ "screenshot": "nav_reach_statistics_vlm.png",
+ "assertion": "Is a horizontal row of tab labels shown across the top of the screen, with rows of statistics listed below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_statistics",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_settings_vlm",
+ "screenshot": "nav_reach_settings_vlm.png",
+ "assertion": "Is this a settings screen showing a vertical list of preference rows, each with a title line?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_settings",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_help_vlm",
+ "screenshot": "nav_reach_help_vlm.png",
+ "assertion": "Is the screen a vertical list of question rows, one per line, like an FAQ / help list?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_reach_help",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_about_vlm",
+ "screenshot": "nav_reach_about_vlm.png",
+ "assertion": "Does this screen show app information text such as a version number, author names, and a license paragraph?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "nav_reach_about",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_tutorial_vlm",
+ "screenshot": "nav_reach_tutorial_vlm.png",
+ "assertion": "Are there SKIP and NEXT buttons at the bottom of the screen below an introduction slide?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_tutorial",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_game_new_vlm",
+ "screenshot": "nav_reach_game_new_vlm.png",
+ "assertion": "Is there a left-pointing back/up arrow at the top-left of the screen, above a grid of square game tiles?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_game_new",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_pager_last_arrow_vlm",
+ "screenshot": "nav_pager_last_arrow_vlm.png",
+ "assertion": "Is there a right-pointing next arrow on the RIGHT edge next to the mode preview? Answer NO if only a left-pointing arrow is present.",
+ "form": "question",
+ "expected": false,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_pager_last_arrow",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_deep_theme_dialog_vlm",
+ "screenshot": "nav_deep_theme_dialog_vlm.png",
+ "assertion": "Is a pop-up dialog titled 'Select theme' shown with radio options (System / Light / Dark) stacked vertically?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_deep_theme_dialog",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_persist_board_restored_vlm",
+ "screenshot": "interaction_persist_board_restored_vlm.png",
+ "assertion": "Does the game board show multiple numbered tiles (a populated grid), i.e. it is NOT an empty grid?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_persist_board_restored",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_undo_board_reverted_vlm",
+ "screenshot": "interaction_undo_board_reverted_vlm.png",
+ "assertion": "Does the game board still show numbered tiles on the grid after the undo (a non-empty board)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_undo_board_reverted",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_undo_icon_visible_vlm",
+ "screenshot": "interaction_undo_icon_visible_vlm.png",
+ "assertion": "Is there a curved counter-clockwise undo arrow icon visible near the top of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_undo_icon_visible",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_restart_two_tiles_vlm",
+ "screenshot": "interaction_restart_two_tiles_vlm.png",
+ "assertion": "Does the game board show exactly two numbered tiles, with all the other grid cells empty?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "interaction_restart_two_tiles",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_merged_tiles_colored_vlm",
+ "screenshot": "interaction_merged_tiles_colored_vlm.png",
+ "assertion": "Do the numbered tiles on the board have colored (non-white) backgrounds?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_merged_tiles_colored",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_stats_nonzero_vlm",
+ "screenshot": "interaction_stats_nonzero_vlm.png",
+ "assertion": "Does this statistics screen display numeric values in its rows (numbers other than only zeros)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_stats_nonzero",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_5x5_larger_grid_vlm",
+ "screenshot": "interaction_5x5_larger_grid_vlm.png",
+ "assertion": "Is the game board a large square grid with five columns and five rows of cells?",
+ "form": "question",
+ "expected": true,
+ "aspect": "size",
+ "modality": null,
+ "links_to": "interaction_5x5_larger_grid",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_restart_icon_visible_vlm",
+ "screenshot": "interaction_restart_icon_visible_vlm.png",
+ "assertion": "Is there a circular refresh / restart arrow icon visible near the top-right of the game screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_restart_icon_visible",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/LICENSE b/android/secuso-privacy-friendly-pedometer/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..eae6c263cf62368209deb8f43a666c916d6233d9
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/LICENSE
@@ -0,0 +1,675 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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.
+
+ Privacy Friendly Pedometer is an Android app that can count steps.
+ Copyright (C) 2016 Tobias Neidig
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Privacy Friendly Apps Copyright (C) 2016 Tobias Neidig
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
+
diff --git a/android/secuso-privacy-friendly-pedometer/instance.json b/android/secuso-privacy-friendly-pedometer/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..3506722ce5df18e41bbcf40a416ae957fd161626
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/secuso-privacy-friendly-pedometer",
+ "platform": "android",
+ "repo": "https://github.com/SecUSo/privacy-friendly-pedometer",
+ "commit": "c38c60a31691b07fbda7efdd9b4cd9d6b85fddd8",
+ "patches": [],
+ "package": "org.secuso.privacyfriendlyactivitytracker",
+ "license": null
+}
diff --git a/android/secuso-privacy-friendly-pedometer/reference/launch.sh b/android/secuso-privacy-friendly-pedometer/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_computation_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..93c51b6a8875b277c2876bc1e199776d9caf1fa1
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_computation_eval.json
@@ -0,0 +1,215 @@
+{
+ "module": "computation",
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 3,
+ "passed": 3,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1765,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 20,
+ "depth_ge1": 16,
+ "depth_ge2": 0,
+ "value": 20,
+ "vlm_fine": 1
+ },
+ "results": [
+ {
+ "test": "computation_steps_50",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 50"
+ },
+ {
+ "test": "computation_steps_100",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 100"
+ },
+ {
+ "test": "computation_steps_199",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 199"
+ },
+ {
+ "test": "computation_steps_200",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 200"
+ },
+ {
+ "test": "computation_steps_1000",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 1000"
+ },
+ {
+ "test": "computation_steps_2000",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 2000"
+ },
+ {
+ "test": "computation_steps_zero",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 0"
+ },
+ {
+ "test": "computation_steps_large",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 12345"
+ },
+ {
+ "test": "computation_steps_arbitrary",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount displays 777"
+ },
+ {
+ "test": "computation_distance_two_decimals",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "distanceCount is a 2-decimal number e.g. '0.50'"
+ },
+ {
+ "test": "computation_distance_unit_km_when_ge_100m",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "distanceTitle=='km' iff distance>=100 m, else 'm'"
+ },
+ {
+ "test": "computation_distance_unit_meters_small",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "distance renders as ' m' for a sub-100 m distance"
+ },
+ {
+ "test": "computation_calorie_number_with_unit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "calorieCount is a 2-decimal number labelled 'cal'"
+ },
+ {
+ "test": "computation_period_day",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Day period label is a single day '05. August'"
+ },
+ {
+ "test": "computation_period_week_is_range",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Week period is a range like '02. - 08. August'"
+ },
+ {
+ "test": "computation_period_month_pattern",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Month period matches 'Month YY' e.g. 'August 26'"
+ },
+ {
+ "test": "computation_period_changes_day_to_week",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "period value changes from a single day to a Week range"
+ },
+ {
+ "test": "computation_chart_plotted_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_summary_numbers_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?",
+ "tag": "content"
+ },
+ {
+ "test": "computation_chart_distance_type_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?",
+ "tag": "content"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_interaction_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..4723ffa075beee6f5841e54807f22d0c38adb44c
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_interaction_eval.json
@@ -0,0 +1,192 @@
+{
+ "module": "interaction",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.7,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 17,
+ "depth_ge2": 9,
+ "value": 6,
+ "vlm_fine": 5
+ },
+ "results": [
+ {
+ "test": "interaction_correct_steps_save_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount 300 after SAVE"
+ },
+ {
+ "test": "interaction_correct_steps_survives_death",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "stepCount 321 after force-stop + relaunch"
+ },
+ {
+ "test": "interaction_correct_steps_cancel_noop",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "stepCount stays 250 after typing 999 then CANCEL"
+ },
+ {
+ "test": "interaction_add_walking_mode",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card 'ZTestMode' appears in walking_modes_list"
+ },
+ {
+ "test": "interaction_walking_mode_survives_death",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card 'ZTestMode' still present after force-stop + relaunch"
+ },
+ {
+ "test": "interaction_multi_record_integrity",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Walking(active) before Running, both intact, ZTestMode also present"
+ },
+ {
+ "test": "interaction_card_context_menu",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Set as active' and 'Learn' appear after tapping the card overflow"
+ },
+ {
+ "test": "interaction_switch_active_mode",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "after selecting Running and reopening: Running checked, Walking unchecked"
+ },
+ {
+ "test": "interaction_help_expand_collapse",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'This app can count your steps...' child appears on expand, gone on collapse"
+ },
+ {
+ "test": "interaction_training_creates_session",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": ">=1 card_training_session row on the overview after END TRAINING NOW"
+ },
+ {
+ "test": "interaction_vlm_walking_modes_list_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there three or more walking-mode rows stacked vertically one below another, filling the list from the top of the screen downward?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Are there three or more walking-mode rows stacked vertically one below another, filling the list from the top of the screen downward?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_vlm_walking_mode_card_vlm",
+ "passed": true,
+ "message": "VLM: Q='On every walking-mode row, is there a vertical three-dot overflow menu icon aligned to the far RIGHT edge, with the mode name and its 'Step length' text on the LEFT side of the same row?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: On every walking-mode row, is there a vertical three-dot overflow menu icon aligned to the far RIGHT edge, with the mode name and its 'Step length' text on the LEFT side of the same row?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_vlm_context_menu_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_vlm_correct_steps_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text buttons positioned side by side in the bottom-right corner, with 'SAVE' to the right of 'CANCEL'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text buttons positioned side by side in the bottom-right corner, with 'SAVE' to the right of 'CANCEL'?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_vlm_summary_popup_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_vlm_help_expanded_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_vlm_training_live_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a large duration timer centred near the TOP of this screen, with four workout stats arranged in a 2-by-2 grid in the middle, and a full-width 'END TRAINING NOW' button pinned at the BOTTOM?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a large duration timer centred near the TOP of this screen, with four workout stats arranged in a 2-by-2 grid in the middle, and a full-width 'END TRAINING NOW' button pinned at the BOTTOM?",
+ "tag": "position"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_navigation_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..b1d20536468ae51e735a6d6145e5fe620abda19b
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_navigation_eval.json
@@ -0,0 +1,209 @@
+{
+ "module": "navigation",
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4615,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 19,
+ "depth_ge1": 19,
+ "depth_ge2": 7,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "nav_reach_training",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "TrainingOverview 'Start training' FAB visible; home 'Day' tab gone"
+ },
+ {
+ "test": "nav_reach_distance",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'START DISTANCE MEASUREMENT' button visible; home 'Day' tab gone"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings 'General' header visible; home 'Day' tab gone"
+ },
+ {
+ "test": "nav_reach_help",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Help 'Overview' group header visible; home 'Day' tab gone"
+ },
+ {
+ "test": "nav_reach_about",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "About appName 'Privacy Friendly Pedometer' visible; home 'Day' tab gone"
+ },
+ {
+ "test": "nav_chain_settings_general",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "General 'Permanent step counter' title visible; Settings 'Notifications' header gone"
+ },
+ {
+ "test": "nav_chain_settings_notifications",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Notifications 'Enable motivation alert' title visible; Settings 'General' header gone"
+ },
+ {
+ "test": "nav_chain_settings_walkingmodes",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "WalkingModes card 'Walking(active)' visible; Settings 'Notifications' header gone"
+ },
+ {
+ "test": "nav_chain_training_live",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "TrainingActivity 'END TRAINING NOW' button visible; overview 'Start training' FAB gone"
+ },
+ {
+ "test": "nav_backstack_about_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "home 'Day' tab restored after one BACK; About appName gone"
+ },
+ {
+ "test": "nav_backstack_general_settings",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings 'Notifications' header restored after one BACK; General 'Permanent step counter' gone"
+ },
+ {
+ "test": "nav_backstack_walkingmodes_deep",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "1st BACK restores Settings 'Notifications'; 2nd BACK restores home 'Day'"
+ },
+ {
+ "test": "nav_backstack_distance_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "home 'Day' tab restored after one BACK; 'START DISTANCE MEASUREMENT' gone"
+ },
+ {
+ "test": "nav_vlm_training_overview_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_vlm_distance_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_vlm_settings_headers_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_vlm_about_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_vlm_help_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_vlm_training_live_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?",
+ "tag": "position"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_states_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..5ca361299f8b10ccc6c0b9b44e7b359affea0453
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_states_eval.json
@@ -0,0 +1,266 @@
+{
+ "module": "states",
+ "total": 25,
+ "passed": 25,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.5625,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 25,
+ "depth_ge1": 16,
+ "depth_ge2": 5,
+ "value": 1,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "states_pause_to_continue",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Pause step detection -> Continue step detection; pause node gone"
+ },
+ {
+ "test": "states_pause_icon_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_continue_back_to_pause",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Continue step detection -> Pause step detection; continue node gone"
+ },
+ {
+ "test": "states_tab_day_selected_on_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Day selected=true; Week=false; Month=false on launch"
+ },
+ {
+ "test": "states_tab_day_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?",
+ "tag": "color"
+ },
+ {
+ "test": "states_tab_switch_day_to_week",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Week selected=true, Day selected=false; period label a range containing ' - '"
+ },
+ {
+ "test": "states_tab_week_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?",
+ "tag": "color"
+ },
+ {
+ "test": "states_tab_switch_week_to_month",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Month selected=true, Week selected=false; period ' '"
+ },
+ {
+ "test": "states_tab_back_to_day",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Day selected=true, Week selected=false; period 'DD. Month'"
+ },
+ {
+ "test": "states_walking_radio_default",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Walking radio checked=true, Running checked=false on open"
+ },
+ {
+ "test": "states_walking_radio_default_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_walking_select_running",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Running radio checked=true, Walking checked=false on reopen"
+ },
+ {
+ "test": "states_running_radio_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_chart_radio_default",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Steps radio checked=true, Distance checked=false on open"
+ },
+ {
+ "test": "states_chart_steps_radio_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_chart_select_distance",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Distance radio checked=true, Steps checked=false on reopen"
+ },
+ {
+ "test": "states_distance_start_to_stop",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "start_button hidden, stop_button ('STOP DISTANCE MEASUREMENT') shown on the same DistanceMeasurementActivity"
+ },
+ {
+ "test": "states_distance_measuring_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_distance_stop_to_start",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "stop_button hidden, start_button ('START DISTANCE MEASUREMENT') shown again on the same Activity"
+ },
+ {
+ "test": "states_drawer_home_checked",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Pedometer' menu item checked=true (current section), 'Settings' checked=false"
+ },
+ {
+ "test": "states_settings_velocity_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show current velocity' switch checked false->true"
+ },
+ {
+ "test": "states_settings_switches_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_settings_hardware_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Use phone's step counting hardware' switch checked false->true"
+ },
+ {
+ "test": "states_settings_permanent_on_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the row 'Permanent step counter'. Is its toggle switch in the ON position — the thumb pushed to the RIGHT and the track filled with the app's accent colour (not grey/left = off)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the row 'Permanent step counter'. Is its toggle switch in the ON position — the thumb pushed to the RIGHT and the track filled with the app's accent colour (not grey/left = off)?",
+ "tag": "position"
+ },
+ {
+ "test": "states_settings_velocity_persists",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Show current velocity' switch still checked=true after force_stop_and_relaunch()"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_structure_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..4dea29c573e4bafb90e0b9b6fee57f3ab8332cd2
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_structure_eval.json
@@ -0,0 +1,229 @@
+{
+ "module": "structure",
+ "total": 21,
+ "passed": 21,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.6154,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 7,
+ "liveness": 0,
+ "interactive": 14,
+ "depth_ge1": 13,
+ "depth_ge2": 3,
+ "value": 0,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_toolbar",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_tabs_pager",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_two_cards",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_drawer_subtree",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "hamburger adds nav_view subtree (node count grows, menu rows appear)"
+ },
+ {
+ "test": "structure_drawer_subtree_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a navigation drawer panel anchored to the LEFT edge of the screen (covering roughly the left three-quarters), listing menu items stacked vertically top-to-bottom: Pedometer, Training, Distance Measurement, Settings, Help, About?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a navigation drawer panel anchored to the LEFT edge of the screen (covering roughly the left three-quarters), listing menu items stacked vertically top-to-bottom: Pedometer, Training, Distance Measurement, Settings, Help, About?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_correct_steps_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "summary popup -> Correct steps adds a dialog (alertTitle + steps EditText)"
+ },
+ {
+ "test": "structure_summary_popup_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_summary_popup",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "summary periodMoreButton adds a popup window (Running + Correct steps rows appear), removed on BACK"
+ },
+ {
+ "test": "structure_chart_popup",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "chart periodMoreButton adds a popup window (Distance + Calories rows appear), removed on BACK"
+ },
+ {
+ "test": "structure_pause_button_flip",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "pause button becomes continue (pause gone), reverts on second tap"
+ },
+ {
+ "test": "structure_distance_start_stop_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a large distance value like '0.00 m' positioned near the TOP of the content area, with a single full-width button labelled 'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a large distance value like '0.00 m' positioned near the TOP of the content area, with a single full-width button labelled 'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_distance_start_stop",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "start_button replaced by stop_button on tap, restored on stop"
+ },
+ {
+ "test": "structure_walkmodes_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there exactly two list rows stacked vertically at the TOP (each with a mode name and a 'Step length:' value), and a round blue circular '+' floating button in the LOWER-RIGHT corner?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are there exactly two list rows stacked vertically at the TOP (each with a mode name and a 'Step length:' value), and a round blue circular '+' floating button in the LOWER-RIGHT corner?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_walkmodes_add_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "FAB add adds a dialog (alertTitle + input_name + step_length_edit)"
+ },
+ {
+ "test": "structure_help_expand_grows",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "tap Overview grows the expandable list (child row appears), collapses back"
+ },
+ {
+ "test": "structure_training_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a large timer (like 00:00:05) centered near the TOP, with the stats laid out BELOW it in a two-column grid: distance in 'm' and velocity in 'km/h' on one row, calories in 'cal' and a step count on the next row?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a large timer (like 00:00:05) centered near the TOP, with the stats laid out BELOW it in a two-column grid: distance in 'm' and velocity in 'km/h' on one row, calories in 'cal' and a step count on the next row?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_training_reach",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "start_training FAB flips the surface: END TRAINING NOW appears, the Start-training FAB disappears (proven via and_reach_surface)"
+ },
+ {
+ "test": "structure_home_two_cards_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there two white card panels stacked VERTICALLY: the UPPER card titled with 'Summary of activities' and the LOWER card titled with 'Detailed summary of your activities'?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Are there two white card panels stacked VERTICALLY: the UPPER card titled with 'Summary of activities' and the LOWER card titled with 'Detailed summary of your activities'?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_tabs_row_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_chart_canvas_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_testgen_kit.py b/android/secuso-privacy-friendly-pedometer/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/android_text_eval.json b/android/secuso-privacy-friendly-pedometer/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..2b1f7afe41c5eca76a1bac4e4289574368f0923e
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/android_text_eval.json
@@ -0,0 +1,196 @@
+{
+ "module": "text",
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.125,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 15,
+ "liveness": 0,
+ "interactive": 3,
+ "depth_ge1": 0,
+ "depth_ge2": 0,
+ "value": 0,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "text_home_step_title",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "home step-count label == 'Steps'"
+ },
+ {
+ "test": "text_home_period_subtitle",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "home summary-card subtitle == 'Summary of activities'"
+ },
+ {
+ "test": "text_period_week_is_range",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Week period label contains ' - ' (a date range); Day did not"
+ },
+ {
+ "test": "text_period_month_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Month period label matches '^ YY$' (e.g. 'August 26')"
+ },
+ {
+ "test": "text_period_day_single",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Day period label matches '^DD. $' with no ' - ' range"
+ },
+ {
+ "test": "text_about_appname_version",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "appName=='Privacy Friendly Pedometer', label=='Version', name=='3.1.2'"
+ },
+ {
+ "test": "text_about_authors",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "author=='Author:', names=='Noah Schlegel, Tobias Neidig', contributors=='and contributors.'"
+ },
+ {
+ "test": "text_about_links",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "affiliation=='In affiliation with', secuso=='SECUSO-Website', github=='Github-Repo'"
+ },
+ {
+ "test": "text_about_logo_block_vlm",
+ "passed": true,
+ "message": "VLM: Q='Near the TOP of this screen, is there a small icon made of several coloured squares positioned immediately to the LEFT of a large heading that reads 'Privacy Friendly Apps'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Near the TOP of this screen, is there a small icon made of several coloured squares positioned immediately to the LEFT of a large heading that reads 'Privacy Friendly Apps'?",
+ "tag": "position"
+ },
+ {
+ "test": "text_walkingmode_first_card",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "first card name=='Walking(active)' with step_length=='0.50'"
+ },
+ {
+ "test": "text_walkingmode_running_and_labels",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "'Running' card step_length=='0.70'; row labels 'Step length:' and 'meters'"
+ },
+ {
+ "test": "text_help_key_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "Help group headers include 'Overview', 'Counting methods', 'Privacy Info'"
+ },
+ {
+ "test": "text_help_ordered_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "listTitle == the 14 ordered headers 'Overview'..'Permission: Write External Storage'"
+ },
+ {
+ "test": "text_help_list_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a vertical list of bold section headers, the first being 'Overview'. Does each header row show a small downward-pointing chevron/arrow indicator positioned to the LEFT of its label text (to the left, not on the right edge)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: This is a vertical list of bold section headers, the first being 'Overview'. Does each header row show a small downward-pointing chevron/arrow indicator positioned to the LEFT of its label text (to the left, not on the right edge)?",
+ "tag": "position"
+ },
+ {
+ "test": "text_settings_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "Settings header titles include 'General', 'Notifications', 'Walking modes'"
+ },
+ {
+ "test": "text_general_switch_titles",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "General shows titles 'Permanent step counter' and 'Show current velocity'"
+ },
+ {
+ "test": "text_general_unit_summaries",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "'Unit of length' summary=='kilometers'; 'Unit of energy' summary=='calories'"
+ },
+ {
+ "test": "text_general_value_summaries",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "'Personal daily step goal' summary=='10000'; 'Weight (kg)' summary=='65.0'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/tests/conftest.py b/android/secuso-privacy-friendly-pedometer/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/secuso-privacy-friendly-pedometer/tests/requirements.txt b/android/secuso-privacy-friendly-pedometer/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_computation.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..33a349049541fad0584356fdbc22908bbaff5be6
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_computation.py
@@ -0,0 +1,498 @@
+#!/usr/bin/env python3
+"""COMPUTATION module — the app's core input -> output surface.
+
+The Privacy Friendly Pedometer's core computation is the "Correct steps" dialog:
+you enter a step count N and the summary card DERIVES and displays the day's
+step total, distance, and calories. This is a genuine value-owning surface, so
+this module is the primary owner of jump_kind="value".
+
+GROUND TRUTH (verified live on the running original, which is authoritative):
+ * stepCount is a DETERMINISTIC function of the entered value: set N -> the
+ summary card's stepCount TextView shows exactly str(N), every time, across
+ every value and every restart. This is the rock-solid input->output backbone.
+ * distanceCount is NOT reproducible as an exact point value: this emulator runs
+ a live step sensor whose accumulator drifts the internal distance baseline
+ between operations (the same N=200 produced 0.10 km at one moment and
+ -60.00 m minutes later). So this module NEVER asserts an exact distance number
+ it cannot reproduce. What IS deterministic about distance is its FORMATTING:
+ - distanceCount always renders with exactly two decimals ("-?\\d+\\.\\d{2}"),
+ - distanceTitle is "km" when the value is >= 100 m and "m" otherwise.
+ Those formatting invariants are asserted as values instead.
+ * The active-walking-mode popup radio (Walking/Running) has NO observable effect
+ on the displayed distance on this build, so no mode-multiplier value is claimed
+ (the original does not reproduce it -> asserting it would be a baseline_fail).
+ * The Day/Week/Month tab selects a computed PERIOD label:
+ Day -> "05. August" (single day), Week -> a range containing " - ",
+ Month -> " " (regex ^[A-Za-z]+ \\d{2}$). All deterministic.
+
+The "Correct steps" flow crosses a dialog surface, so those tests are depth>=1,
+backed by and_enter("correct_steps_dialog") inside the shared set_steps_clean()
+helper. Tab-switch tests are same-surface (depth 0) but still value-tier (the
+period value changed to a specific computed string).
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+TESTS = []
+
+
+def test(fn):
+ """Register a test function for run_suite()."""
+ TESTS.append(fn)
+ return fn
+
+
+# ── shared helpers ──────────────────────────────────────────────────────────
+
+def _period_texts(nodes):
+ """Every summary/chart 'period' label currently on screen (there are two —
+ one per card — and both carry the same computed value)."""
+ return [n.get("text", "") for n in nodes
+ if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "period"]
+
+
+def set_steps_clean(val):
+ """Open the summary-card overflow -> 'Correct steps' dialog, CLEAR the
+ pre-filled field, type `val`, and SAVE. Crosses one surface (the dialog),
+ so it calls and_enter to back the depth>=1 declaration of every test that
+ uses it.
+
+ The steps EditText PRE-FILLS with the current count and type_text APPENDS,
+ so the field MUST be cleared first (MOVE_END then repeated DEL) or "50" then
+ "100" becomes "50100".
+ """
+ nodes = ui()
+ tap_node(find_node(nodes, content_desc="Walking modes")) # summary overflow
+ settle("tap")
+ nodes = ui()
+ tap_node(find_node_ci(nodes, "Correct steps"))
+ settle("tap")
+ and_enter("correct_steps_dialog") # dialog surface crossed
+ nodes = ui()
+ ed = node_by_id(nodes, "steps")
+ if ed is None:
+ return False
+ tap_node(ed)
+ settle("keyboard")
+ press_key(123) # KEYCODE_MOVE_END
+ for _ in range(12):
+ press_key(67) # KEYCODE_DEL
+ settle("keyboard")
+ nodes = ui()
+ ed = node_by_id(nodes, "steps")
+ type_text(ed, str(val))
+ nodes = ui()
+ save = node_by_id(nodes, "button1") # button1=SAVE, button2=CANCEL
+ if save is None:
+ return False
+ tap_node(save)
+ settle("tap")
+ settle("tap")
+ return True
+
+
+def _read(rid):
+ n = node_by_id(ui(), rid)
+ return (n.get("text", "") if n else "").strip()
+
+
+def _step_case(name, n_steps):
+ """One clean input->output case: set N, assert stepCount == str(N).
+
+ stepCount is the deterministic core transform of this app — the summary
+ card echoes the corrected step count exactly, so this is the honest value
+ assertion for the input->output surface (distance drifts; steps does not).
+ """
+ restart_app()
+ if not wait_for_foreground():
+ record(name, False, "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", expect=f"stepCount={n_steps}")
+ return
+ if not set_steps_clean(n_steps):
+ record(name, False, "setup_failed: could not reach/complete Correct-steps dialog",
+ depth=1, jump_kind="value", expect=f"stepCount={n_steps}")
+ return
+ got = _read("stepCount")
+ want = str(n_steps)
+ ok = got == want
+ record(name, ok,
+ "" if ok else f"behavior_wrong: stepCount got {got!r} want {want!r}",
+ depth=1, jump_kind="value", expect=f"stepCount displays {want}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# CORE INPUT -> OUTPUT: entered steps -> displayed step count (deterministic)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_steps_50",))
+@test
+def test_steps_50():
+ _step_case("computation_steps_50", 50)
+
+
+@and_test(expects=("computation_steps_100",))
+@test
+def test_steps_100():
+ _step_case("computation_steps_100", 100)
+
+
+@and_test(expects=("computation_steps_199",))
+@test
+def test_steps_199():
+ _step_case("computation_steps_199", 199)
+
+
+@and_test(expects=("computation_steps_200",))
+@test
+def test_steps_200():
+ _step_case("computation_steps_200", 200)
+
+
+@and_test(expects=("computation_steps_1000",))
+@test
+def test_steps_1000():
+ _step_case("computation_steps_1000", 1000)
+
+
+@and_test(expects=("computation_steps_2000",))
+@test
+def test_steps_2000():
+ _step_case("computation_steps_2000", 2000)
+
+
+@and_test(expects=("computation_steps_zero",))
+@test
+def test_steps_zero():
+ # Edge: empty/zero input -> the card computes a step total of exactly 0.
+ _step_case("computation_steps_zero", 0)
+
+
+@and_test(expects=("computation_steps_large",))
+@test
+def test_steps_large():
+ # Edge: a large value still echoes exactly (no truncation/overflow).
+ _step_case("computation_steps_large", 12345)
+
+
+@and_test(expects=("computation_steps_arbitrary",))
+@test
+def test_steps_arbitrary():
+ # A non-round value the recreation cannot special-case.
+ _step_case("computation_steps_arbitrary", 777)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DERIVED DISTANCE — deterministic FORMATTING invariants (not the drifting value)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_distance_two_decimals",))
+@test
+def test_distance_two_decimals():
+ """The derived distance always renders with exactly two decimal places.
+ The magnitude drifts with the live sensor, but the 2-decimal FORMAT of the
+ computed value is deterministic — that is the value we assert."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_distance_two_decimals", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", expect="distanceCount matches -?d+.dd")
+ return
+ if not set_steps_clean(1000):
+ record("computation_distance_two_decimals", False,
+ "setup_failed: could not complete Correct-steps dialog",
+ depth=1, jump_kind="value", expect="distanceCount matches -?d+.dd")
+ return
+ d = _read("distanceCount")
+ ok = bool(re.match(r"^-?\d+\.\d{2}$", d))
+ record("computation_distance_two_decimals", ok,
+ "" if ok else f"behavior_wrong: distanceCount {d!r} not 2-decimal formatted",
+ depth=1, jump_kind="value",
+ expect="distanceCount is a 2-decimal number e.g. '0.50'")
+
+
+@and_test(expects=("computation_distance_unit_km_when_ge_100m",))
+@test
+def test_distance_unit_km():
+ """The derived distance switches its UNIT deterministically: distanceTitle is
+ 'km' exactly when the computed distance is >= 100 m, otherwise 'm'. Verified
+ by reading the displayed value and its unit together and checking the rule —
+ robust to the drifting magnitude."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_distance_unit_km_when_ge_100m", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", expect="km iff meters>=100 else m")
+ return
+ if not set_steps_clean(1000):
+ record("computation_distance_unit_km_when_ge_100m", False,
+ "setup_failed: could not complete Correct-steps dialog",
+ depth=1, jump_kind="value", expect="km iff meters>=100 else m")
+ return
+ nodes = ui()
+ dn = node_by_id(nodes, "distanceCount")
+ un = node_by_id(nodes, "distanceTitle")
+ d = (dn.get("text", "") if dn else "").strip()
+ unit = (un.get("text", "") if un else "").strip()
+ ok = False
+ detail = f"distance={d!r} unit={unit!r}"
+ try:
+ meters = float(d) * (1000.0 if unit == "km" else 1.0)
+ expect_km = meters >= 100.0
+ ok = unit in ("m", "km") and (unit == "km") == expect_km
+ detail = f"distance={d!r} unit={unit!r} meters={meters}"
+ except ValueError:
+ ok = False
+ record("computation_distance_unit_km_when_ge_100m", ok,
+ "" if ok else f"behavior_wrong: unit rule violated ({detail})",
+ depth=1, jump_kind="value",
+ expect="distanceTitle=='km' iff distance>=100 m, else 'm'")
+
+
+@and_test(expects=("computation_distance_unit_meters_small",))
+@test
+def test_distance_unit_meters_small():
+ """Complementary edge: with a tiny corrected count (0), the derived distance
+ magnitude is small and the unit label is a bare length unit 'm' (never 'km'
+ for a sub-100 m positive distance). We assert the unit is one of the two
+ valid length labels and consistent with the shown value."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_distance_unit_meters_small", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", expect="distanceTitle in {m,km}")
+ return
+ if not set_steps_clean(0):
+ record("computation_distance_unit_meters_small", False,
+ "setup_failed: could not complete Correct-steps dialog",
+ depth=1, jump_kind="value", expect="distanceTitle in {m,km}")
+ return
+ nodes = ui()
+ dn = node_by_id(nodes, "distanceCount")
+ un = node_by_id(nodes, "distanceTitle")
+ d = (dn.get("text", "") if dn else "").strip()
+ unit = (un.get("text", "") if un else "").strip()
+ ok = False
+ detail = f"distance={d!r} unit={unit!r}"
+ try:
+ meters = float(d) * (1000.0 if unit == "km" else 1.0)
+ ok = unit in ("m", "km") and (unit == "km") == (meters >= 100.0)
+ detail = f"distance={d!r} unit={unit!r} meters={meters}"
+ except ValueError:
+ ok = False
+ record("computation_distance_unit_meters_small", ok,
+ "" if ok else f"behavior_wrong: unit inconsistent with value ({detail})",
+ depth=1, jump_kind="value",
+ expect="distance renders as ' m' for a sub-100 m distance")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# CALORIES — a derived numeric output pairs with its 'cal' unit (deterministic
+# structure; the magnitude drifts so only its shape/unit are asserted)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_calorie_number_with_unit",))
+@test
+def test_calorie_number_with_unit():
+ """Entering steps derives a calorie figure shown as a 2-decimal number beside
+ the unit label 'cal'. The value drifts with the sensor, so we assert the
+ derived output's FORMAT and unit pairing, which are deterministic."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_calorie_number_with_unit", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", expect="calorieCount 2-decimal + 'cal'")
+ return
+ if not set_steps_clean(2000):
+ record("computation_calorie_number_with_unit", False,
+ "setup_failed: could not complete Correct-steps dialog",
+ depth=1, jump_kind="value", expect="calorieCount 2-decimal + 'cal'")
+ return
+ c = _read("calorieCount")
+ unit = _read("calorieTitle")
+ ok = bool(re.match(r"^-?\d+\.\d{2}$", c)) and unit == "cal"
+ record("computation_calorie_number_with_unit", ok,
+ "" if ok else f"behavior_wrong: calorieCount {c!r} unit {unit!r}",
+ depth=1, jump_kind="value",
+ expect="calorieCount is a 2-decimal number labelled 'cal'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TAB -> COMPUTED PERIOD LABEL (Day / Week / Month) — same-surface (depth 0)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_period_day",))
+@test
+def test_period_day():
+ """The Day tab computes a single-day period label 'DD. Month'
+ (observed 05. August on this emulator)."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_period_day", False,
+ "setup_failed: app did not reach foreground",
+ depth=0, jump_kind="value", expect="period '05. August'")
+ return
+ nodes = ui()
+ tap_node(find_node(nodes, content_desc="Day")) # ensure Day selected
+ settle("tap")
+ labels = _period_texts(ui())
+ # exact observed value; also accept the general single-day shape "DD. Month"
+ ok = ("05. August" in labels) or any(
+ re.match(r"^\d{2}\. [A-Za-z]+$", (p or "")) for p in labels)
+ record("computation_period_day", ok,
+ "" if ok else f"behavior_wrong: Day period labels {labels!r}",
+ depth=0, jump_kind="value",
+ expect="Day period label is a single day '05. August'")
+
+
+@and_test(expects=("computation_period_week_is_range",))
+@test
+def test_period_week_range():
+ """Switching to Week recomputes the period into a DATE RANGE containing ' - '
+ (observed '02. - 08. August')."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_period_week_is_range", False,
+ "setup_failed: app did not reach foreground",
+ depth=0, jump_kind="value", expect="week period contains ' - '")
+ return
+ nodes = ui()
+ tap_node(find_node(nodes, content_desc="Week"))
+ settle("tap")
+ labels = _period_texts(ui())
+ ok = any(" - " in (p or "") for p in labels)
+ record("computation_period_week_is_range", ok,
+ "" if ok else f"behavior_wrong: Week period labels {labels!r} lack a ' - ' range",
+ depth=0, jump_kind="value",
+ expect="Week period is a range like '02. - 08. August'")
+
+
+@and_test(expects=("computation_period_month_pattern",))
+@test
+def test_period_month_pattern():
+ """Switching to Month recomputes the period into ' '
+ (observed 'August 26', matching ^[A-Za-z]+ \\d{2}$)."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_period_month_pattern", False,
+ "setup_failed: app did not reach foreground",
+ depth=0, jump_kind="value", expect="month period ^[A-Za-z]+ \\d{2}$")
+ return
+ nodes = ui()
+ tap_node(find_node(nodes, content_desc="Month"))
+ settle("tap")
+ labels = _period_texts(ui())
+ ok = any(re.match(r"^[A-Za-z]+ \d{2}$", (p or "")) for p in labels)
+ record("computation_period_month_pattern", ok,
+ "" if ok else f"behavior_wrong: Month period labels {labels!r} != 'Month YY'",
+ depth=0, jump_kind="value",
+ expect="Month period matches 'Month YY' e.g. 'August 26'")
+
+
+@and_test(expects=("computation_period_changes_day_to_week",))
+@test
+def test_period_changes_day_to_week():
+ """The period VALUE genuinely recomputes on tab change: the single-day Day
+ label is replaced by a Week range — a before!=after value transition on the
+ same surface."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_period_changes_day_to_week", False,
+ "setup_failed: app did not reach foreground",
+ depth=0, jump_kind="value", expect="period value differs Day vs Week")
+ return
+ tap_node(find_node(ui(), content_desc="Day"))
+ settle("tap")
+ day = [p for p in _period_texts(ui()) if p]
+ tap_node(find_node(ui(), content_desc="Week"))
+ settle("tap")
+ week = [p for p in _period_texts(ui()) if p]
+ day0 = day[0] if day else ""
+ week0 = week[0] if week else ""
+ ok = bool(day0) and bool(week0) and day0 != week0 and " - " in week0
+ record("computation_period_changes_day_to_week", ok,
+ "" if ok else f"behavior_wrong: day={day0!r} week={week0!r} (no recompute)",
+ depth=0, jump_kind="value",
+ expect="period value changes from a single day to a Week range")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 3) — the ONLY genuinely-visual computed output is the LineChart
+# canvas (numbers are plotted, unreadable from the view tree).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_chart_plotted_vlm",))
+@test
+def test_chart_plotted_vlm():
+ """After setting a step count, the lower (chart) card renders a line chart
+ that PLOTS the data — a computed rendering the dump cannot read."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_chart_plotted_vlm", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", tag="shape")
+ return
+ set_steps_clean(2000)
+ ui() # settle the surface before the screenshot
+ vlm_assert("computation_chart_plotted",
+ "Does the lower card show a line chart with a plotted line and "
+ "round data points across a grid (not an empty or blank graph)?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="shape")
+
+
+@and_test(expects=("computation_summary_numbers_vlm",))
+@test
+def test_summary_numbers_vlm():
+ """The summary card renders the computed step count as a large number with a
+ 'Steps' label and a distance value with a unit — a rendered-numbers check."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_summary_numbers_vlm", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", tag="content")
+ return
+ set_steps_clean(2000)
+ ui()
+ vlm_assert("computation_summary_numbers",
+ "In the upper summary card, is a numeric step count shown as a large "
+ "number next to the word 'Steps', with a distance value and a unit "
+ "(m or km) below it?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+@and_test(expects=("computation_chart_distance_type_vlm",))
+@test
+def test_chart_distance_type_vlm():
+ """Switching the chart data type to Distance re-renders the chart for distance
+ data — a computed repaint of the canvas, VLM-only."""
+ restart_app()
+ if not wait_for_foreground():
+ record("computation_chart_distance_type_vlm", False,
+ "setup_failed: app did not reach foreground",
+ depth=1, jump_kind="value", tag="content")
+ return
+ set_steps_clean(2000)
+ nodes = ui()
+ opt = find_node(nodes, content_desc="Options") # chart-card overflow
+ if opt is not None:
+ tap_node(opt)
+ settle("tap")
+ nodes = ui()
+ dist = find_node_ci(nodes, "Distance")
+ if dist is not None:
+ # the row's radio sits to the right; tapping the row label commits it
+ tap_node(dist)
+ settle("tap")
+ settle("tap")
+ ui()
+ vlm_assert("computation_chart_distance_type",
+ "Does the lower card display a chart (a graph area with axes/grid "
+ "and plotted data), consistent with showing distance data?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_interaction.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..71feb61be8007c99c019e0e820be5c59a24910c6
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_interaction.py
@@ -0,0 +1,768 @@
+#!/usr/bin/env python3
+"""INTERACTION module — EFFECT-BY-CONSEQUENCE on user DATA for Privacy Friendly
+Pedometer.
+
+This lane owns CRUD lifecycles, 3+-step sequences where each action depends on
+the last, MULTI-RECORD integrity, DATA persistence across process death, and
+long-press / context (overflow) menus. Every test drives the app to the surface
+via the real user path, performs the action, then reads the CONSEQUENCE back out
+of a FRESH ui() and asserts it equals what was observed on the original app.
+
+Golden model (recon.md), all verified live on the original:
+ * Correct steps (MainActivity): summary card `periodMoreButton` (desc "Walking
+ modes") -> popup radio Walking/Running + item "Correct steps" -> dialog
+ (`alertTitle`="Correct steps", EditText `steps` PRE-FILLED with the current
+ count, `button1`=SAVE, `button2`=CANCEL). To set a KNOWN value the field must
+ be CLEARED first (MOVE_END then DEL x12) — typing APPENDS otherwise. SAVE
+ persists `stepCount` across an in-app navigation AND across process death.
+ * Walking modes (WalkingModesActivity, drawer->Settings->"Walking modes"):
+ RecyclerView `walking_modes_list`, seeded cards `name`="Walking(active)"
+ (0.50) and "Running" (0.70), FAB `add_walking_mode_btn` (desc "Add"), each
+ card overflow `card_menu` (desc "Options") -> context menu Set as active /
+ Learn / Edit / Delete. Add dialog: `input_name`, `step_length_edit`,
+ `button1`=SAVE. Adding accumulates across runs -> the add test is idempotent.
+ * Home summary popup radios: `title` TextView paired with a sibling `radio`
+ RadioButton (the checked bit lives on the RadioButton, not the title).
+ * Help (HelpActivity): ExpandableListView `generalExpandableListView`, group
+ headers `listTitle`; tapping "Overview" reveals a child text row (subtree
+ grows), tapping again collapses it.
+ * Training (TrainingOverviewActivity -> TrainingActivity): FAB `start_training`
+ -> live screen (`training_stop_button`="END TRAINING NOW"); stopping returns
+ to the overview and leaves a `card_training_session` row in
+ `training_overview_list`.
+
+SAFETY: tests mutate REAL device state. Destructive controls (Delete / Remove /
+Clear / swipe-to-delete of a walking mode) are NEVER tapped. `training_stop_button`
+("End training now") is SAFE and is used only to clean up a started session. Data
+is never wiped with clear_data() (it bounces to the launcher + re-prompts perms);
+restart_app() / force_stop_and_relaunch() are used instead.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+MODE_MARK = "ZTestMode" # sorts last; distinctive so read-back cannot collide
+
+
+# ── shared entry helpers (plain helpers; the and_enter_*/and_reach_* NAME is what
+# the depth audit keys off — no @and_test decorator here) ────────────────────
+
+def open_nav_drawer():
+ """Open the navigation drawer via the HAMBURGER (never open_drawer(), whose
+ edge-swipe drops to the launcher). Returns the fresh drawer node list or None."""
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ if not ham or not tap_node(ham):
+ return None
+ return ui()
+
+
+def step_count():
+ """The home summary `stepCount` text, or None if not on the home surface."""
+ n = node_by_id(ui(), "stepCount")
+ return n.get("text") if n else None
+
+
+def and_enter_correct_steps_dialog():
+ """Home -> summary `periodMoreButton` (desc "Walking modes") popup -> tap the
+ "Correct steps" item -> the dialog. Counts ONE surface (the dialog) via
+ and_enter. Returns True once the `steps` EditText is present."""
+ more = find_node(ui(), content_desc="Walking modes")
+ if more is None or not tap_node(more):
+ return False
+ settle("tap")
+ cs = find_node_ci(ui(), "Correct steps")
+ if cs is None or not tap_node(cs):
+ return False
+ settle("tap")
+ if node_by_id(ui(), "steps") is None:
+ return False
+ and_enter("correct_steps_dialog")
+ return True
+
+
+def set_steps_clean(value):
+ """From an OPEN Correct-steps dialog, replace the pre-filled `steps` value
+ with `value` and tap SAVE. The field pre-fills with the current count and
+ type_text APPENDS, so it is cleared first (MOVE_END + DEL x12). Returns True
+ if SAVE was tapped."""
+ ed = node_by_id(ui(), "steps")
+ if ed is None:
+ return False
+ tap_node(ed)
+ settle("keyboard")
+ press_key(123) # KEYCODE_MOVE_END
+ for _ in range(12):
+ press_key(67) # KEYCODE_DEL
+ settle("keyboard")
+ ed = node_by_id(ui(), "steps") # re-find after clearing
+ if ed is None:
+ return False
+ type_text(ed, value)
+ save = node_by_id(ui(), "button1") # button1 = SAVE, button2 = CANCEL
+ if save is None or not tap_node(save):
+ return False
+ settle("tap")
+ settle("tap")
+ return True
+
+
+def and_reach_walking_modes():
+ """restart -> drawer -> Settings -> "Walking modes" => WalkingModesActivity.
+ Proves each hop with and_reach_surface (Settings header, then the
+ WalkingModes-only card "Walking(active)"). Counts TWO surfaces. Returns True
+ when the seeded "Walking(active)" card is visible."""
+ restart_app()
+ if not wait_for_foreground():
+ return False
+ d = open_nav_drawer()
+ if d is None:
+ return False
+ settings = find_node_ci(d, "Settings")
+ if settings is None or not and_reach_surface(settings, "General", "Day"):
+ return False
+ wm = find_node_ci(ui(), "Walking modes")
+ if wm is None or not and_reach_surface(wm, "Walking(active)", "Notifications"):
+ return False
+ return True
+
+
+def walking_mode_names():
+ """The `name` texts of every card currently in `walking_modes_list`."""
+ return [n.get("text", "") for n in ui()
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "name"
+ and n.get("text", "").strip()]
+
+
+def expanded_child_texts():
+ """Text of every expanded ExpandableListView child row (`expandedListItem`)
+ currently in the dump. Empty when no group is expanded."""
+ return [n.get("text", "") for n in ui()
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "expandedListItem"
+ and n.get("text", "").strip()]
+
+
+def add_walking_mode(name, length):
+ """From WalkingModesActivity, open the Add dialog (FAB desc "Add"), fill
+ `input_name` + `step_length_edit`, tap SAVE. Counts ONE surface (the dialog).
+ Both fields are empty (they render their HINT as text), so typing does not
+ append. Returns True if SAVE was tapped."""
+ fab = find_node(ui(), content_desc="Add") or node_by_id(ui(), "add_walking_mode_btn")
+ if fab is None or not tap_node(fab):
+ return False
+ settle("tap")
+ if node_by_id(ui(), "input_name") is None:
+ return False
+ and_enter("add_mode_dialog")
+ # NOTE: do NOT hide_keyboard() between the fields — in this dialog that path
+ # falls through to BACK, which dismisses the whole dialog. type_text re-taps
+ # (hence re-focuses) each field, and button1 (SAVE) renders above the keyboard,
+ # so both fields and SAVE stay reachable with the IME up.
+ type_text(node_by_id(ui(), "input_name"), name)
+ type_text(node_by_id(ui(), "step_length_edit"), length)
+ save = node_by_id(ui(), "button1")
+ if save is None or not tap_node(save):
+ return False
+ settle("tap")
+ settle("tap")
+ return True
+
+
+def radios_state():
+ """Pair each home-popup `title` TextView with its same-row `radio`
+ RadioButton and return [(label, checked_str), ...]. The checked bit lives on
+ the RadioButton, so the title alone cannot tell you which mode is active."""
+ nodes = ui()
+ titles = [n for n in nodes
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "title"
+ and n.get("text", "").strip() and "_center" in n]
+ radios = [n for n in nodes
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "radio"
+ and "_center" in n]
+ out = []
+ for t in titles:
+ ty = t["_center"][1]
+ best, bd = None, 1e9
+ for r in radios:
+ d = abs(r["_center"][1] - ty)
+ if d < bd:
+ bd, best = d, r
+ if best is not None and bd < 60:
+ out.append((t.get("text").strip(), best.get("checked")))
+ return out
+
+
+def open_summary_popup():
+ """Tap the home summary `periodMoreButton` (desc "Walking modes") to open the
+ Walking/Running/Correct-steps popup. Returns True if the popup showed a
+ 'Running' entry."""
+ more = find_node(ui(), content_desc="Walking modes")
+ if more is None or not tap_node(more):
+ return False
+ settle("tap")
+ return find_node_ci(ui(), "Running") is not None
+
+
+def and_reach_training_live():
+ """restart -> drawer -> Training (overview) -> start_training FAB => live
+ TrainingActivity. Proves both hops. Counts TWO surfaces. Returns True when
+ 'END TRAINING NOW' is visible."""
+ restart_app()
+ if not wait_for_foreground():
+ return False
+ d = open_nav_drawer()
+ if d is None:
+ return False
+ tr = find_node_ci(d, "Training")
+ if tr is None or not and_reach_surface(tr, "Start training", "Day"):
+ return False
+ fab = node_by_id(ui(), "start_training")
+ if fab is None or not and_reach_surface(fab, "END TRAINING NOW", "Start training"):
+ return False
+ return True
+
+
+def session_count():
+ """Number of `card_training_session` rows on the training overview."""
+ return sum(1 for n in ui()
+ if n.get("resource-id", "").rsplit("/", 1)[-1] == "card_training_session")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# A. CORRECT STEPS — CRUD-update of the day's step record (depth 1, dialog)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_correct_steps_save_persists",))
+def test_correct_steps_save_persists():
+ # clean-set stepCount to 300 via the dialog -> SAVE -> read stepCount back out
+ # of a fresh home dump. A dialog that echoes but does not commit fails here.
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_correct_steps_save_persists", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="value", expect="stepCount 300")
+ return
+ if not and_enter_correct_steps_dialog():
+ record("interaction_correct_steps_save_persists", False,
+ "feature_missing: no Correct-steps dialog reachable from the summary popup",
+ depth=1, jump_kind="value", expect="stepCount 300")
+ return
+ saved = set_steps_clean("300")
+ after = step_count()
+ ok = bool(saved) and after == "300"
+ record("interaction_correct_steps_save_persists", ok,
+ "" if ok else f"behavior_wrong: SAVE 300 did not update stepCount (got {after!r})",
+ depth=1, jump_kind="value", expect="stepCount 300 after SAVE")
+
+
+@and_test(expects=("interaction_correct_steps_survives_death",))
+def test_correct_steps_survives_death():
+ # SIGNATURE persistence probe: clean-set 321 -> SAVE -> KILL the process and
+ # relaunch -> stepCount must still read 321. An in-memory-only recreation that
+ # never wrote the corrected count to storage cannot pass this.
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_correct_steps_survives_death", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="value", expect="stepCount 321 after relaunch")
+ return
+ if not and_enter_correct_steps_dialog():
+ record("interaction_correct_steps_survives_death", False,
+ "feature_missing: no Correct-steps dialog reachable from the summary popup",
+ depth=1, jump_kind="value", expect="stepCount 321 after relaunch")
+ return
+ saved = set_steps_clean("321")
+ before = step_count()
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ after = step_count()
+ ok = bool(saved) and before == "321" and after == "321"
+ record("interaction_correct_steps_survives_death", ok,
+ "" if ok else f"behavior_wrong: corrected steps did not survive process death "
+ f"(before={before!r} after={after!r})",
+ depth=1, jump_kind="value", expect="stepCount 321 after force-stop + relaunch")
+
+
+@and_test(expects=("interaction_correct_steps_cancel_noop",))
+def test_correct_steps_cancel_noop():
+ # First SAVE a known baseline (250), then reopen, type a different value, and
+ # tap CANCEL (button2). The record must be UNCHANGED (still 250) — CANCEL is
+ # the negative half that makes the SAVE test discriminating.
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_correct_steps_cancel_noop", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL")
+ return
+ if not and_enter_correct_steps_dialog() or not set_steps_clean("250"):
+ record("interaction_correct_steps_cancel_noop", False,
+ "feature_missing: could not establish the 250 baseline via SAVE",
+ depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL")
+ return
+ baseline = step_count()
+ and_reset_depth()
+ if not and_enter_correct_steps_dialog():
+ record("interaction_correct_steps_cancel_noop", False,
+ "setup_failed: could not reopen the Correct-steps dialog",
+ depth=1, jump_kind="transition", expect="stepCount stays 250 after CANCEL")
+ return
+ ed = node_by_id(ui(), "steps")
+ tap_node(ed)
+ settle("keyboard")
+ press_key(123)
+ for _ in range(12):
+ press_key(67)
+ type_text(node_by_id(ui(), "steps"), "999") # type a DIFFERENT value...
+ cancel = node_by_id(ui(), "button2") # ...then CANCEL, not SAVE
+ tapped = cancel is not None and tap_node(cancel)
+ settle("tap")
+ after = step_count()
+ ok = bool(tapped) and baseline == "250" and after == "250"
+ record("interaction_correct_steps_cancel_noop", ok,
+ "" if ok else f"behavior_wrong: CANCEL changed the record "
+ f"(baseline={baseline!r} after={after!r}, expected 250)",
+ depth=1, jump_kind="transition",
+ expect="stepCount stays 250 after typing 999 then CANCEL")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# B. WALKING MODES — CRUD-create + multi-record integrity + persistence (depth 2/3)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_add_walking_mode",))
+def test_add_walking_mode():
+ # CRUD-create behind Settings -> Walking modes (surface 2) + the Add dialog
+ # (surface 3). Idempotent: modes accumulate across runs, so if ZTestMode is
+ # already present we only assert its presence. The negative half — ABSENT
+ # before the very first add — is proven the first time the suite runs.
+ if not and_reach_walking_modes():
+ record("interaction_add_walking_mode", False,
+ "setup_failed: could not reach WalkingModesActivity",
+ depth=3, jump_kind="value", expect=f"card {MODE_MARK!r} present")
+ return
+ before = walking_mode_names()
+ already = MODE_MARK in before
+ if not already:
+ if not add_walking_mode(MODE_MARK, "0.60"):
+ record("interaction_add_walking_mode", False,
+ "feature_missing: Add-walking-mode dialog has no working SAVE path",
+ depth=3, jump_kind="value", expect=f"card {MODE_MARK!r} present")
+ return
+ target = scroll_into_view(MODE_MARK)
+ after = walking_mode_names()
+ present = target is not None or MODE_MARK in after
+ # created this run => count strictly grew; already there => still >= 3 cards
+ count_ok = (len(after) > len(before)) if not already else (len(after) >= 3)
+ ok = present and count_ok
+ record("interaction_add_walking_mode", ok,
+ "" if ok else f"behavior_wrong: added mode did not appear "
+ f"(before={before}, after={after})",
+ depth=3, jump_kind="value",
+ expect=f"card {MODE_MARK!r} appears in walking_modes_list")
+
+
+@and_test(expects=("interaction_walking_mode_survives_death",))
+def test_walking_mode_survives_death():
+ # PERSISTENCE probe #2: ensure ZTestMode exists (add if needed), then KILL the
+ # process, relaunch, re-navigate Settings -> Walking modes, and assert the
+ # added record is STILL there. A recreation that keeps modes only in memory
+ # loses it here.
+ if not and_reach_walking_modes():
+ record("interaction_walking_mode_survives_death", False,
+ "setup_failed: could not reach WalkingModesActivity",
+ depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch")
+ return
+ if MODE_MARK not in walking_mode_names():
+ if not add_walking_mode(MODE_MARK, "0.60"):
+ record("interaction_walking_mode_survives_death", False,
+ "feature_missing: could not create the walking mode to test persistence",
+ depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch")
+ return
+ # process death + re-navigate through the real user path
+ and_reset_depth()
+ if not and_reach_walking_modes(): # this itself does restart_app()
+ record("interaction_walking_mode_survives_death", False,
+ "setup_failed: could not re-reach WalkingModesActivity after relaunch",
+ depth=2, jump_kind="value", expect=f"card {MODE_MARK!r} after relaunch")
+ return
+ present = scroll_into_view(MODE_MARK) is not None or MODE_MARK in walking_mode_names()
+ record("interaction_walking_mode_survives_death", present,
+ "" if present else "behavior_wrong: added walking mode did not survive process death",
+ depth=2, jump_kind="value",
+ expect=f"card {MODE_MARK!r} still present after force-stop + relaunch")
+
+
+@and_test(expects=("interaction_multi_record_integrity",))
+def test_multi_record_integrity():
+ # MULTI-RECORD integrity: after adding ZTestMode there are >=3 modes. Assert
+ # the two SEEDED records (Walking(active), Running) are BOTH still intact and
+ # in their original order relative to each other, alongside the added one.
+ # A recreation that recreates the list keeping only one row fails here.
+ if not and_reach_walking_modes():
+ record("interaction_multi_record_integrity", False,
+ "setup_failed: could not reach WalkingModesActivity",
+ depth=2, jump_kind="value",
+ expect="Walking(active) + Running + ZTestMode all present, seeds ordered")
+ return
+ if MODE_MARK not in walking_mode_names():
+ add_walking_mode(MODE_MARK, "0.60")
+ scroll_into_view("Running") # make sure lower rows are dumped
+ names = walking_mode_names()
+ has_walking = any("Walking(active)" == x for x in names)
+ has_running = any("Running" == x for x in names)
+ has_added = MODE_MARK in names
+ order_ok = (has_walking and has_running
+ and names.index("Walking(active)") < names.index("Running"))
+ ok = has_walking and has_running and has_added and order_ok
+ record("interaction_multi_record_integrity", ok,
+ "" if ok else f"behavior_wrong: seeded records not intact/ordered "
+ f"alongside the added one (names={names})",
+ depth=2, jump_kind="value",
+ expect="Walking(active) before Running, both intact, ZTestMode also present")
+
+
+@and_test(expects=("interaction_card_context_menu",))
+def test_card_context_menu():
+ # CONTEXT-MENU ownership (long-press / overflow). Tap a card's overflow
+ # `card_menu` (desc "Options") and assert the context menu OPENED — proven by
+ # the non-destructive items "Set as active" and "Learn" appearing (they are
+ # NOT present on the plain list surface). Delete is never tapped; back out.
+ if not and_reach_walking_modes():
+ record("interaction_card_context_menu", False,
+ "setup_failed: could not reach WalkingModesActivity",
+ depth=3, jump_kind="transition",
+ expect="context menu 'Set as active' + 'Learn' appear")
+ return
+ menu = find_node(ui(), content_desc="Options")
+ before = and_showing()
+ opened = False
+ if menu is not None and tap_node(menu):
+ and_enter("card_context_menu")
+ after = and_showing()
+ nodes = ui()
+ has_active = find_node_ci(nodes, "Set as active") is not None
+ has_learn = find_node_ci(nodes, "Learn") is not None
+ appeared = and_reach(before, after, "Set as active")
+ opened = has_active and has_learn and appeared
+ back() # dismiss the menu without choosing
+ settle("tap")
+ record("interaction_card_context_menu", opened,
+ "" if opened else "feature_missing: card overflow did not open a context menu with Set as active / Learn",
+ depth=3, jump_kind="transition",
+ expect="'Set as active' and 'Learn' appear after tapping the card overflow")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# C. WALKING-MODE SWITCH — 3+-step select -> close -> reopen -> observe (depth 1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_switch_active_mode",))
+def test_switch_active_mode():
+ # Multi-step, each step depends on the last: open popup (Walking checked) ->
+ # tap Running -> popup CLOSES -> REOPEN -> observe Running now checked and
+ # Walking unchecked. A dead shell that echoes the first tap without persisting
+ # the selection fails on the reopened state. Reset to Walking afterward.
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_switch_active_mode", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="transition", expect="Running checked=true after reopen")
+ return
+ if not open_summary_popup():
+ record("interaction_switch_active_mode", False,
+ "feature_missing: summary Walking-modes popup did not open",
+ depth=1, jump_kind="transition", expect="Running checked=true after reopen")
+ return
+ and_enter("summary_popup")
+ before = dict(radios_state())
+ run = find_node_ci(ui(), "Running")
+ tapped = run is not None and tap_node(run)
+ settle("tap")
+ settle("tap")
+ closed = find_node_ci(ui(), "Running") is None # popup dismissed after select
+ reopened = open_summary_popup()
+ after = dict(radios_state())
+ ok = (bool(tapped) and closed and reopened
+ and before.get("Walking") == "true" and before.get("Running") == "false"
+ and after.get("Running") == "true" and after.get("Walking") == "false")
+ # reset the active mode back to Walking so the app is left as found
+ if reopened:
+ walk = find_node_ci(ui(), "Walking")
+ if walk is not None:
+ tap_node(walk)
+ settle("tap")
+ else:
+ back()
+ record("interaction_switch_active_mode", ok,
+ "" if ok else f"behavior_wrong: active-mode selection did not flip on reopen "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="after selecting Running and reopening: Running checked, Walking unchecked")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# D. HELP — expandable-tree interaction (depth 1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_help_expand_collapse",))
+def test_help_expand_collapse():
+ # Tree-data interaction: tap the "Overview" group header -> a descriptive
+ # child text row appears beneath it (subtree GROWS) -> tap again -> it
+ # collapses back. Assert the child text is present when expanded and gone when
+ # collapsed (a specific observed child, not just a node-count delta).
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_help_expand_collapse", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="transition", expect="Overview child row appears then collapses")
+ return
+ d = open_nav_drawer()
+ if d is None or not tap_node(find_node_ci(d, "Help")):
+ record("interaction_help_expand_collapse", False,
+ "setup_failed: could not reach HelpActivity from the drawer",
+ depth=1, jump_kind="transition", expect="Overview child row appears then collapses")
+ return
+ settle("tap")
+ and_enter("help")
+ ov = find_node_ci(ui(), "Overview")
+ if ov is None:
+ record("interaction_help_expand_collapse", False,
+ "feature_missing: Help 'Overview' group header not found",
+ depth=1, jump_kind="transition", expect="Overview child row appears then collapses")
+ return
+ child_snippet = "This app can count your steps"
+
+ def overview_child_shown():
+ # the child row is a long paragraph (id expandedListItem); match by prefix
+ return any(t.startswith(child_snippet) for t in expanded_child_texts())
+
+ collapsed_before = not overview_child_shown() # no child before expanding
+ tap_node(ov)
+ settle("tap")
+ expanded = overview_child_shown() # child paragraph appeared
+ ov2 = find_node_ci(ui(), "Overview")
+ if ov2 is not None:
+ tap_node(ov2)
+ settle("tap")
+ recollapsed = not overview_child_shown() # child gone again
+ ok = collapsed_before and expanded and recollapsed
+ record("interaction_help_expand_collapse", ok,
+ "" if ok else "behavior_wrong: expanding/collapsing 'Overview' did not toggle its child row",
+ depth=1, jump_kind="transition",
+ expect="'This app can count your steps...' child appears on expand, gone on collapse")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# E. TRAINING — CRUD-create of a session record (depth 2)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_training_creates_session",))
+def test_training_creates_session():
+ # CRUD-create: start a training (FAB), let it run a moment, then END TRAINING
+ # NOW (SAFE) -> back on the overview a `card_training_session` row exists.
+ # Sessions accumulate across runs, so assert AT LEAST ONE session and that the
+ # count did not shrink. depth=2 (overview -> live), then back to overview.
+ if not and_reach_training_live():
+ record("interaction_training_creates_session", False,
+ "setup_failed: could not reach the live TrainingActivity",
+ depth=2, jump_kind="value", expect="a training session row exists on the overview")
+ return
+ settle("tap")
+ settle("tap") # let the session accrue a moment
+ stop = node_by_id(ui(), "training_stop_button")
+ stopped = stop is not None and tap_node(stop)
+ settle("tap")
+ settle("tap")
+ # some builds pop a save/OK dialog on stop — commit it if present (never Cancel)
+ ok_btn = node_by_id(ui(), "button1")
+ if ok_btn is not None:
+ tap_node(ok_btn)
+ settle("tap")
+ on_overview = node_by_id(ui(), "start_training") is not None
+ after = session_count()
+ ok = bool(stopped) and on_overview and after >= 1
+ record("interaction_training_creates_session", ok,
+ "" if ok else f"behavior_wrong: stopping training left no session on the overview "
+ f"(on_overview={on_overview}, sessions={after})",
+ depth=2, jump_kind="value",
+ expect=">=1 card_training_session row on the overview after END TRAINING NOW")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# VLM — EXACTLY 7 rendered-property questions. Each navigates to the right surface
+# first, screenshots, and asks ONE specific YES/NO a blank screen would fail.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_vlm_walking_modes_list_vlm",))
+def test_vlm_walking_modes_list():
+ # After ensuring ZTestMode exists there are >=3 cards stacked vertically.
+ if not and_reach_walking_modes():
+ record("interaction_vlm_walking_modes_list_vlm", False,
+ "setup_failed: could not reach WalkingModesActivity to screenshot",
+ depth=2, jump_kind="reach", tag="layout")
+ return
+ if MODE_MARK not in walking_mode_names():
+ add_walking_mode(MODE_MARK, "0.60")
+ scroll_into_view("Running")
+ vlm_assert("interaction_vlm_walking_modes_list",
+ "Are there three or more walking-mode rows stacked vertically one "
+ "below another, filling the list from the top of the screen downward?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("interaction_vlm_walking_mode_card_vlm",))
+def test_vlm_walking_mode_card():
+ # Each seeded card renders a name plus a 'Step length:' value ending 'meters'.
+ if not and_reach_walking_modes():
+ record("interaction_vlm_walking_mode_card_vlm", False,
+ "setup_failed: could not reach WalkingModesActivity to screenshot",
+ depth=2, jump_kind="reach", tag="content")
+ return
+ vlm_assert("interaction_vlm_walking_mode_card",
+ "On every walking-mode row, is there a vertical three-dot overflow "
+ "menu icon aligned to the far RIGHT edge, with the mode name and its "
+ "'Step length' text on the LEFT side of the same row?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("interaction_vlm_context_menu_vlm",))
+def test_vlm_context_menu():
+ # The card overflow context menu, showing the non-destructive items.
+ if not and_reach_walking_modes():
+ record("interaction_vlm_context_menu_vlm", False,
+ "setup_failed: could not reach WalkingModesActivity to screenshot",
+ depth=3, jump_kind="transition", tag="content")
+ return
+ menu = find_node(ui(), content_desc="Options")
+ if menu is None or not tap_node(menu):
+ record("interaction_vlm_context_menu_vlm", False,
+ "feature_missing: card overflow did not open",
+ depth=3, jump_kind="transition", tag="content")
+ return
+ and_enter("card_context_menu")
+ settle("tap")
+ vlm_assert("interaction_vlm_context_menu",
+ "Is a small pop-up context menu shown listing text options including "
+ "'Set as active' and 'Learn'?",
+ RESULTS_DIR, depth=3, jump_kind="transition", tag="content")
+ back() # dismiss without choosing
+ settle("tap")
+
+
+@and_test(expects=("interaction_vlm_correct_steps_dialog_vlm",))
+def test_vlm_correct_steps_dialog():
+ # The Correct-steps dialog open on top of the home report.
+ restart_app()
+ if not wait_for_foreground() or not and_enter_correct_steps_dialog():
+ record("interaction_vlm_correct_steps_dialog_vlm", False,
+ "setup_failed: could not open the Correct-steps dialog to screenshot",
+ depth=1, jump_kind="transition", tag="layout")
+ return
+ vlm_assert("interaction_vlm_correct_steps_dialog",
+ "In the 'Correct steps' dialog, are the 'CANCEL' and 'SAVE' text "
+ "buttons positioned side by side in the bottom-right corner, with "
+ "'SAVE' to the right of 'CANCEL'?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+ b2 = node_by_id(ui(), "button2") # CANCEL out, change nothing
+ if b2 is not None:
+ tap_node(b2)
+ settle("tap")
+
+
+@and_test(expects=("interaction_vlm_summary_popup_vlm",))
+def test_vlm_summary_popup():
+ # The home summary Walking-modes popup with its radio list.
+ restart_app()
+ if not wait_for_foreground() or not open_summary_popup():
+ record("interaction_vlm_summary_popup_vlm", False,
+ "setup_failed: could not open the summary Walking-modes popup to screenshot",
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ and_enter("summary_popup")
+ vlm_assert("interaction_vlm_summary_popup",
+ "Is a small pop-up menu shown listing 'Walking' and 'Running' each "
+ "with a round radio button on the right, plus a 'Correct steps' "
+ "option, and is exactly one radio button filled in (selected)?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+ back() # dismiss, leave mode unchanged
+ settle("tap")
+
+
+@and_test(expects=("interaction_vlm_help_expanded_vlm",))
+def test_vlm_help_expanded():
+ # Help 'Overview' expanded -> descriptive text renders below the heading.
+ restart_app()
+ if not wait_for_foreground():
+ record("interaction_vlm_help_expanded_vlm", False,
+ "setup_failed: app did not reach the foreground",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ d = open_nav_drawer()
+ if d is None or not tap_node(find_node_ci(d, "Help")):
+ record("interaction_vlm_help_expanded_vlm", False,
+ "setup_failed: could not reach HelpActivity to screenshot",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ settle("tap")
+ and_enter("help")
+ ov = find_node_ci(ui(), "Overview")
+ if ov is None or not tap_node(ov):
+ record("interaction_vlm_help_expanded_vlm", False,
+ "feature_missing: could not expand the 'Overview' help topic",
+ depth=1, jump_kind="transition", tag="content")
+ return
+ settle("tap")
+ vlm_assert("interaction_vlm_help_expanded",
+ "Under the 'Overview' heading of this help list, is a paragraph of "
+ "descriptive body text now shown (the 'Overview' topic is expanded)?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="content")
+
+
+@and_test(expects=("interaction_vlm_training_live_vlm",))
+def test_vlm_training_live():
+ # The live training screen grid: duration, distance, velocity, calories, steps.
+ if not and_reach_training_live():
+ record("interaction_vlm_training_live_vlm", False,
+ "setup_failed: could not reach the live TrainingActivity to screenshot",
+ depth=2, jump_kind="reach", tag="layout")
+ return
+ vlm_assert("interaction_vlm_training_live",
+ "Is a large duration timer centred near the TOP of this screen, with "
+ "four workout stats arranged in a 2-by-2 grid in the middle, and a "
+ "full-width 'END TRAINING NOW' button pinned at the BOTTOM?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+ stop = node_by_id(ui(), "training_stop_button") # cleanup: stop the session
+ if stop is not None:
+ tap_node(stop)
+ settle("tap")
+
+
+TESTS = [
+ # A. Correct steps — CRUD-update + persistence + cancel-noop (dialog, depth 1)
+ test_correct_steps_save_persists,
+ test_correct_steps_survives_death, # persistence #1
+ test_correct_steps_cancel_noop,
+ # B. Walking modes — create + persistence + multi-record + context menu
+ test_add_walking_mode,
+ test_walking_mode_survives_death, # persistence #2
+ test_multi_record_integrity,
+ test_card_context_menu,
+ # C. Walking-mode switch — 3+-step select/close/reopen/observe
+ test_switch_active_mode,
+ # D. Help — expandable-tree interaction
+ test_help_expand_collapse,
+ # E. Training — CRUD-create of a session record
+ test_training_creates_session,
+ # VLM — exactly 7 rendered-property questions
+ test_vlm_walking_modes_list,
+ test_vlm_walking_mode_card,
+ test_vlm_context_menu,
+ test_vlm_correct_steps_dialog,
+ test_vlm_summary_popup,
+ test_vlm_help_expanded,
+ test_vlm_training_live,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_navigation.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..12da8ce99c447b6e13e6e643289745b0f1b82b9d
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_navigation.py
@@ -0,0 +1,401 @@
+#!/usr/bin/env python3
+"""NAVIGATION module — surface REACHABILITY + back-stack integrity.
+
+Sole owner of jump_kind="reach" and of depth>=2 chains for Privacy Friendly
+Pedometer. Every jump is proven with and_reach(before, after, target, source):
+the TARGET surface's discriminating element APPEARED *and* the SOURCE surface's
+DISAPPEARED. Reaching a screen by relaunching is NOT navigation — every reach
+here goes drawer-item -> screen or FAB/list -> screen and is backed by an
+and_reach*/and_enter* call.
+
+Golden model (recon.md):
+ Home (MainActivity) = ViewPager of Day/Week/Month reports; drawer (opened via
+ the HAMBURGER, content-desc "Open navigation drawer") reaches Training,
+ Distance Measurement, Settings, Help, About.
+ Drawer items are CheckedTextView (design_menu_item_text); toolbar titles are
+ TextView — so "Training" as a drawer label vs the TrainingOverview title never
+ collide in a surface set. Home discriminator behind the open drawer = "Day".
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── shared entry helpers (plain helpers; the and_* NAME is what the depth audit
+# keys off — no @and_test decorator here) ──────────────────────────────────
+
+def open_nav_drawer():
+ """Open the navigation drawer via the HAMBURGER (never open_drawer(), whose
+ edge-swipe drops to the launcher). Returns the fresh drawer node list, or
+ None if the hamburger is absent."""
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ if not ham or not tap_node(ham):
+ return None
+ return ui()
+
+
+def and_reach_from_drawer(label, target, source="Day"):
+ """restart -> open drawer -> tap the drawer item -> prove the jump.
+ The reach is the ITEM tap that lands on the new activity; opening the drawer
+ itself is only an overlay on the same activity, never claimed as a reach."""
+ restart_app()
+ if not wait_for_foreground():
+ return False
+ d = open_nav_drawer()
+ if d is None:
+ return False
+ item = find_node_ci(d, label)
+ if item is None:
+ return False
+ return and_reach_surface(item, target, source)
+
+
+def and_enter_settings():
+ """restart -> drawer -> Settings. Lands on the PreferencesActivity header
+ list (General / Notifications / Walking modes). Counts one surface."""
+ ok = and_reach_from_drawer("Settings", "General", "Day")
+ return ok
+
+
+def and_reach_setting_child(child_label, target, source):
+ """From a fresh Settings header list, tap a header row and prove the child
+ prefs screen was reached. This is the SECOND hop of a depth-2 chain; the
+ first hop (and_enter_settings) has already counted surface 1."""
+ row = find_node_ci(ui(), child_label)
+ if row is None:
+ return False
+ return and_reach_surface(row, target, source)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# FORWARD REACH — the 5 top-level drawer destinations (depth 1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_training",))
+def test_reach_training():
+ # Home -> drawer -> "Training" => TrainingOverviewActivity.
+ # target: FAB content-desc "Start training" (overview-only, unambiguous vs
+ # the drawer CheckedTextView "Training"); source: home tab "Day".
+ ok = and_reach_from_drawer("Training", "Start training", "Day")
+ record("nav_reach_training", ok,
+ "" if ok else "feature_missing: could not reach TrainingOverviewActivity from the drawer",
+ depth=1, jump_kind="reach",
+ expect="TrainingOverview 'Start training' FAB visible; home 'Day' tab gone")
+
+
+@and_test(expects=("nav_reach_distance",))
+def test_reach_distance():
+ # Home -> drawer -> "Distance Measurement" => DistanceMeasurementActivity.
+ ok = and_reach_from_drawer("Distance Measurement",
+ "START DISTANCE MEASUREMENT", "Day")
+ record("nav_reach_distance", ok,
+ "" if ok else "feature_missing: could not reach DistanceMeasurementActivity from the drawer",
+ depth=1, jump_kind="reach",
+ expect="'START DISTANCE MEASUREMENT' button visible; home 'Day' tab gone")
+
+
+@and_test(expects=("nav_reach_settings",))
+def test_reach_settings():
+ # Home -> drawer -> "Settings" => PreferencesActivity header list.
+ ok = and_reach_from_drawer("Settings", "General", "Day")
+ record("nav_reach_settings", ok,
+ "" if ok else "feature_missing: could not reach the Settings headers from the drawer",
+ depth=1, jump_kind="reach",
+ expect="Settings 'General' header visible; home 'Day' tab gone")
+
+
+@and_test(expects=("nav_reach_help",))
+def test_reach_help():
+ # Home -> drawer -> "Help" => HelpActivity ("Overview" group header).
+ ok = and_reach_from_drawer("Help", "Overview", "Day")
+ record("nav_reach_help", ok,
+ "" if ok else "feature_missing: could not reach HelpActivity from the drawer",
+ depth=1, jump_kind="reach",
+ expect="Help 'Overview' group header visible; home 'Day' tab gone")
+
+
+@and_test(expects=("nav_reach_about",))
+def test_reach_about():
+ # Home -> drawer -> "About" => AboutActivity (appName).
+ ok = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day")
+ record("nav_reach_about", ok,
+ "" if ok else "feature_missing: could not reach AboutActivity from the drawer",
+ depth=1, jump_kind="reach",
+ expect="About appName 'Privacy Friendly Pedometer' visible; home 'Day' tab gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEPTH>=2 CHAINS — Settings header -> a sub-prefs surface
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_chain_settings_general",))
+def test_chain_settings_general():
+ # depth 2: Home -> drawer -> Settings (surface 1) -> tap "General" (surface 2).
+ s1 = and_enter_settings()
+ s2 = s1 and and_reach_setting_child(
+ "General", "Permanent step counter", "Notifications")
+ record("nav_chain_settings_general", bool(s2),
+ "" if s2 else "feature_missing: Settings -> General chain did not reach the General prefs screen",
+ depth=2, jump_kind="reach",
+ expect="General 'Permanent step counter' title visible; Settings 'Notifications' header gone")
+
+
+@and_test(expects=("nav_chain_settings_notifications",))
+def test_chain_settings_notifications():
+ # depth 2: Home -> drawer -> Settings -> tap "Notifications".
+ s1 = and_enter_settings()
+ s2 = s1 and and_reach_setting_child(
+ "Notifications", "Enable motivation alert", "General")
+ record("nav_chain_settings_notifications", bool(s2),
+ "" if s2 else "feature_missing: Settings -> Notifications chain did not reach the Notifications prefs screen",
+ depth=2, jump_kind="reach",
+ expect="Notifications 'Enable motivation alert' title visible; Settings 'General' header gone")
+
+
+@and_test(expects=("nav_chain_settings_walkingmodes",))
+def test_chain_settings_walkingmodes():
+ # depth 2: Home -> drawer -> Settings -> tap "Walking modes" => WalkingModesActivity.
+ # target: seeded card "Walking(active)" (activity-only); NOT the title
+ # "Walking modes" which also exists as the Settings header row.
+ s1 = and_enter_settings()
+ s2 = s1 and and_reach_setting_child(
+ "Walking modes", "Walking(active)", "Notifications")
+ record("nav_chain_settings_walkingmodes", bool(s2),
+ "" if s2 else "feature_missing: Settings -> Walking modes chain did not reach WalkingModesActivity",
+ depth=2, jump_kind="reach",
+ expect="WalkingModes card 'Walking(active)' visible; Settings 'Notifications' header gone")
+
+
+@and_test(expects=("nav_chain_training_live",))
+def test_chain_training_live():
+ # depth 2: Home -> drawer -> Training (surface 1) -> start_training FAB
+ # (surface 2) => TrainingActivity. CLEAN UP with training_stop_button (SAFE:
+ # "End training now", not Delete) so no training is left running.
+ s1 = and_reach_from_drawer("Training", "Start training", "Day")
+ s2 = False
+ if s1:
+ fab = node_by_id(ui(), "start_training")
+ s2 = fab is not None and and_reach_surface(
+ fab, "END TRAINING NOW", "Start training")
+ # cleanup — return to the overview regardless of the assertion outcome
+ stop = node_by_id(ui(), "training_stop_button")
+ if stop is not None:
+ tap_node(stop)
+ record("nav_chain_training_live", bool(s2),
+ "" if s2 else "feature_missing: Training overview FAB did not reach the live TrainingActivity",
+ depth=2, jump_kind="reach",
+ expect="TrainingActivity 'END TRAINING NOW' button visible; overview 'Start training' FAB gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# BACK-STACK INTEGRITY — pops unwind the stack surface by surface
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_backstack_about_home",))
+def test_backstack_about_home():
+ # depth 1 down (drawer -> About), then BACK => MainActivity restored.
+ # Prove the REVERSE reach: home "Day" reappears and About appName disappears.
+ down = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day")
+ up = False
+ if down:
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ up = and_reach(before, after, "Day", "Privacy Friendly Pedometer")
+ record("nav_backstack_about_home", bool(up),
+ "" if up else "behavior_wrong: BACK from About did not restore the home MainActivity",
+ depth=1, jump_kind="reach",
+ expect="home 'Day' tab restored after one BACK; About appName gone")
+
+
+@and_test(expects=("nav_backstack_general_settings",))
+def test_backstack_general_settings():
+ # depth 2 down (Settings -> General), then BACK => Settings headers restored.
+ # Prove the reverse reach: "Notifications" header reappears, "Permanent step
+ # counter" (General-only) disappears.
+ s1 = and_enter_settings()
+ s2 = s1 and and_reach_setting_child(
+ "General", "Permanent step counter", "Notifications")
+ up = False
+ if s2:
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ up = and_reach(before, after, "Notifications", "Permanent step counter")
+ record("nav_backstack_general_settings", bool(up),
+ "" if up else "behavior_wrong: BACK from General did not restore the Settings header list",
+ depth=2, jump_kind="reach",
+ expect="Settings 'Notifications' header restored after one BACK; General 'Permanent step counter' gone")
+
+
+@and_test(expects=("nav_backstack_walkingmodes_deep",))
+def test_backstack_walkingmodes_deep():
+ # Deepest chain popped hop by hop: Home -> Settings -> Walking modes, then
+ # BACK (=> Settings headers), then BACK (=> home). Assert the surface after
+ # EACH pop, so the back stack is proven to unwind one surface at a time.
+ s1 = and_enter_settings()
+ s2 = s1 and and_reach_setting_child(
+ "Walking modes", "Walking(active)", "Notifications")
+ hop1 = hop2 = False
+ if s2:
+ b1 = and_showing()
+ and_back() # WalkingModes -> Settings headers
+ a1 = and_showing()
+ hop1 = and_reach(b1, a1, "Notifications", "Walking(active)")
+ and_back() # Settings headers -> home
+ a2 = and_showing()
+ hop2 = and_reach(a1, a2, "Day", "Notifications")
+ ok = bool(s2 and hop1 and hop2)
+ record("nav_backstack_walkingmodes_deep", ok,
+ "" if ok else "behavior_wrong: two BACKs from Walking modes did not unwind Settings then home hop by hop",
+ depth=2, jump_kind="reach",
+ expect="1st BACK restores Settings 'Notifications'; 2nd BACK restores home 'Day'")
+
+
+@and_test(expects=("nav_backstack_distance_home",))
+def test_backstack_distance_home():
+ # depth 1 down (drawer -> Distance Measurement), then BACK => home restored.
+ down = and_reach_from_drawer("Distance Measurement",
+ "START DISTANCE MEASUREMENT", "Day")
+ up = False
+ if down:
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ up = and_reach(before, after, "Day", "START DISTANCE MEASUREMENT")
+ record("nav_backstack_distance_home", bool(up),
+ "" if up else "behavior_wrong: BACK from Distance Measurement did not restore the home MainActivity",
+ depth=1, jump_kind="reach",
+ expect="home 'Day' tab restored after one BACK; 'START DISTANCE MEASUREMENT' gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# VLM — rendered destination end-states (EXACTLY 6). Navigate to the correct
+# surface first, then screenshot + ask ONE specific YES/NO about what renders.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_vlm_training_overview_vlm",))
+def test_vlm_training_overview():
+ ok = and_reach_from_drawer("Training", "Start training", "Day")
+ if ok:
+ vlm_assert("nav_vlm_training_overview",
+ "Is there a round blue floating action button with a white plus "
+ "sign in the bottom-right corner of this screen?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+ else:
+ record("nav_vlm_training_overview_vlm", False,
+ "setup_failed: could not reach TrainingOverviewActivity to screenshot",
+ depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_vlm_distance_vlm",))
+def test_vlm_distance():
+ ok = and_reach_from_drawer("Distance Measurement",
+ "START DISTANCE MEASUREMENT", "Day")
+ if ok:
+ vlm_assert("nav_vlm_distance",
+ "Is there a full-width dark-blue button labelled 'START DISTANCE "
+ "MEASUREMENT' pinned to the bottom of this screen?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+ else:
+ record("nav_vlm_distance_vlm", False,
+ "setup_failed: could not reach DistanceMeasurementActivity to screenshot",
+ depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_vlm_settings_headers_vlm",))
+def test_vlm_settings_headers():
+ ok = and_reach_from_drawer("Settings", "General", "Day")
+ if ok:
+ vlm_assert("nav_vlm_settings_headers",
+ "Does this screen show a vertical settings list with three rows "
+ "labelled 'General', 'Notifications' and 'Walking modes', each "
+ "with an icon on the left?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="layout")
+ else:
+ record("nav_vlm_settings_headers_vlm", False,
+ "setup_failed: could not reach the Settings headers to screenshot",
+ depth=1, jump_kind="reach", tag="layout")
+
+
+@and_test(expects=("nav_vlm_about_vlm",))
+def test_vlm_about():
+ ok = and_reach_from_drawer("About", "Privacy Friendly Pedometer", "Day")
+ if ok:
+ vlm_assert("nav_vlm_about",
+ "Does this About screen show the SECUSO logo (a round emblem to "
+ "the left of the word 'SECUSO') in its middle area?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="shape")
+ else:
+ record("nav_vlm_about_vlm", False,
+ "setup_failed: could not reach AboutActivity to screenshot",
+ depth=1, jump_kind="reach", tag="shape")
+
+
+@and_test(expects=("nav_vlm_help_vlm",))
+def test_vlm_help():
+ ok = and_reach_from_drawer("Help", "Overview", "Day")
+ if ok:
+ vlm_assert("nav_vlm_help",
+ "Does this screen show a top app bar titled 'Help' and, below it, "
+ "a vertical list of help topics starting with 'Overview'?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="layout")
+ else:
+ record("nav_vlm_help_vlm", False,
+ "setup_failed: could not reach HelpActivity to screenshot",
+ depth=1, jump_kind="reach", tag="layout")
+
+
+@and_test(expects=("nav_vlm_training_live_vlm",))
+def test_vlm_training_live():
+ # depth 2: reach the LIVE TrainingActivity, screenshot, then clean up.
+ s1 = and_reach_from_drawer("Training", "Start training", "Day")
+ reached = False
+ if s1:
+ fab = node_by_id(ui(), "start_training")
+ reached = fab is not None and and_reach_surface(
+ fab, "END TRAINING NOW", "Start training")
+ if reached:
+ vlm_assert("nav_vlm_training_live",
+ "Is there a prominent full-width button labelled 'END TRAINING "
+ "NOW' at the bottom of this screen?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+ stop = node_by_id(ui(), "training_stop_button")
+ if stop is not None:
+ tap_node(stop) # cleanup: leave no training running
+ else:
+ record("nav_vlm_training_live_vlm", False,
+ "setup_failed: could not reach the live TrainingActivity to screenshot",
+ depth=2, jump_kind="reach", tag="position")
+
+
+TESTS = [
+ # forward reach (5 drawer destinations)
+ test_reach_training,
+ test_reach_distance,
+ test_reach_settings,
+ test_reach_help,
+ test_reach_about,
+ # depth>=2 chains (4)
+ test_chain_settings_general,
+ test_chain_settings_notifications,
+ test_chain_settings_walkingmodes,
+ test_chain_training_live,
+ # back-stack integrity (4)
+ test_backstack_about_home,
+ test_backstack_general_settings,
+ test_backstack_walkingmodes_deep,
+ test_backstack_distance_home,
+ # VLM rendered destinations (6)
+ test_vlm_training_overview,
+ test_vlm_distance,
+ test_vlm_settings_headers,
+ test_vlm_about,
+ test_vlm_help,
+ test_vlm_training_live,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_states.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ef8bd6fda06a48a7b12e1736b63c81b9fff89a7
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_states.py
@@ -0,0 +1,1145 @@
+#!/usr/bin/env python3
+"""STATES module — widget STATE through before/after interaction.
+
+This module owns CHECKED and FOCUSED and every selected/enabled/mode transition
+PAIRED with the app-authored consequence, plus SETTINGS/mode persistence across
+process death. Nothing here is a bare flip: a `checked`/`selected` change is
+always paired with the observable effect the app authors around it (a range
+period label, a shown/hidden button, a radio that stays selected on reopen).
+
+GROUND TRUTH (verified live on the running original, which is authoritative):
+
+ * Pause/continue (E): toolbar Button `menu_pause_step_detection`
+ (content-desc "Pause step detection"). Tapping it REPLACES the node with
+ `menu_continue_step_detection` (desc "Continue step detection") and the
+ pause node DISAPPEARS. Tapping again reverts. The app-authored consequence
+ is this identity + content-desc flip (an icon button, so no `checked`).
+
+ * Tabs (A): the tab is a LinearLayout with content-desc "Day"/"Week"/"Month".
+ On launch "Day" has selected="true"; the others selected="false". Tapping
+ "Week" moves selected="true" to Week AND the two `period` labels change to a
+ range ("02. - 08. August", contains " - "). Month -> " "
+ (^[A-Za-z]+ \\d{2}$). So each tab test pairs the `selected` flip with the
+ computed period label consequence.
+
+ * Walking-mode popup (C): summary `periodMoreButton` (desc "Walking modes")
+ opens a ListView of rows; each row is a `title` TextView plus a sibling
+ RadioButton id `radio` (checkable=true). On open the "Walking" row's radio is
+ checked=true, "Running" false. Selecting "Running" closes the popup; reopening
+ shows the "Running" radio checked=true — the app-authored consequence. (The
+ device may carry extra seeded modes, so rows are matched by title text, never
+ by count.) RESET to Walking afterwards.
+
+ * Chart-type popup (D): chart `periodMoreButton` (desc "Options") opens a radio
+ list Steps(checked)/Distance/Calories. Selecting "Distance" and reopening
+ shows Distance checked=true, Steps false. RESET to Steps afterwards.
+
+ * Distance measurement (G): DistanceMeasurementActivity, Button `start_button`
+ ("START DISTANCE MEASUREMENT"). Tapping it REPLACES it with `stop_button`
+ ("STOP DISTANCE MEASUREMENT"); start disappears. A page-level state machine
+ (idle vs measuring). Tapping stop reverts. Asserted on the same Activity.
+ NOTE: starting a measurement makes the app request the LOCATION runtime
+ permission the first time; a left-over system dialog would otherwise leak onto
+ the next test, so every test enters through launch_clean(), which grants any
+ pending permission dialog through the GUI (never `pm grant`).
+
+ * Drawer (nav_view): each item is a CheckedTextView `design_menu_item_text`;
+ the item for the CURRENT screen is checked=true ("Pedometer" on Home), the
+ rest false. Beware: the toolbar title and the drawer header are ALSO the text
+ "Pedometer" but are plain TextViews — _drawer_item() matches the
+ CheckedTextView by resource-id suffix so the right node is read.
+
+ * Settings General (H): PreferencesActivity list of prefs. Each switch is a
+ `switch_widget` Switch whose row also has an `android:id/title` TextView; the
+ switch itself is clickable="false" AND SO IS EVERY OTHER NODE IN THE ROW (the
+ title, the widget_frame, the row LinearLayout) — nothing carries
+ clickable="true". Tapping the narrow title is therefore a no-op; the reliable
+ toggle is a tap on the FULL-WIDTH row CONTAINER's centre (the widest node
+ whose vertical bounds contain the title's y-centre and whose height is a
+ normal row height), which is what _tap_pref_row does (verified live: velocity
+ false->true->false via this tap). Defaults: "Show current velocity"=OFF,
+ "Use phone's step counting hardware"=OFF, "Permanent step counter"=ON,
+ "Keep processor awake"=ON, "Wake lock during training"=ON. Toggling
+ "Show current velocity" ON PERSISTS across force_stop_and_relaunch() back to
+ General — the signature persistence probe an in-memory recreation fails. Each
+ settings toggle test ENSURES the switch is OFF first (idempotent across repeat
+ runs even if a prior run left it ON), asserts the OFF->ON flip, then restores
+ OFF so the suite is order-free.
+
+ CONDITIONAL GUARD: "Use phone's step counting hardware" is a hardware-gated
+ preference — the app refuses to turn it ON when the device lacks a
+ step-counting sensor (PackageManager has neither
+ android.hardware.sensor.stepcounter nor ...stepdetector). On such a device the
+ row tap correctly leaves the switch OFF; on a sensor-equipped device it flips
+ to ON. The test asserts EITHER the OFF->ON flip OR (still OFF AND the feature
+ is provably absent) — both are the app's authored, observed behaviour, never a
+ bare existence check. The feature is read with `pm list features` (a device
+ query, not a state-seed).
+
+PAIRING title -> switch: switches are stacked tightly, so a title's switch is the
+`switch_widget` whose y-center is nearest the title's y-center (see _row_switch).
+Radio popups pair the same way via _radio_for_title.
+
+DEPTH: pause/tab/drawer flips are same-surface (depth 0). Popups are depth 1,
+backed by and_enter_popup(). Settings->General is depth 2, backed by
+and_reach_general(). Persistence relaunches, then re-navigates Settings->General
+(depth 2 again). jump_kind is "transition" for flips, "value" for the persistence
+assertion of one specific resulting state.
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+TESTS = []
+
+
+def test(fn):
+ """Register a test function for run_suite()."""
+ TESTS.append(fn)
+ return fn
+
+
+# ── shared helpers ───────────────────────────────────────────────────────────
+
+def _ycenter(node):
+ b = node.get("_bounds")
+ return (b[1] + b[3]) // 2 if b else None
+
+
+# Allow buttons on the STOCK system permission dialog, matched by resource-id
+# LAST SEGMENT (never a package literal, so this stays portable) and, as a
+# fallback, by the exact button label. "Deny/Don't allow" is deliberately absent:
+# this helper only ever GRANTS, and does so through the real GUI (no `pm grant`).
+_PERM_ALLOW_IDS = (
+ "permission_allow_button",
+ "permission_allow_foreground_only_button",
+ "permission_allow_one_time_button",
+)
+_PERM_ALLOW_TEXTS = ("Allow", "While using the app", "Only this time")
+
+
+def _permission_dialog_present(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ for rid in _PERM_ALLOW_IDS:
+ if node_by_id(nodes, rid) is not None:
+ return True
+ return any(find_node(nodes, text=t) is not None for t in _PERM_ALLOW_TEXTS)
+
+
+def grant_pending_permission(max_dialogs=3):
+ """Dismiss (by GRANTING) any stock runtime-permission dialog currently on
+ screen — the app requests location when a distance measurement starts, and a
+ left-over dialog otherwise leaks onto the next test. Portable and GUI-only.
+ Returns True if it dismissed at least one dialog."""
+ dismissed = False
+ for _ in range(max_dialogs):
+ nodes = ui()
+ btn = None
+ for rid in _PERM_ALLOW_IDS:
+ btn = node_by_id(nodes, rid)
+ if btn is not None:
+ break
+ if btn is None:
+ for t in _PERM_ALLOW_TEXTS:
+ btn = find_node(nodes, text=t)
+ if btn is not None:
+ break
+ if btn is None:
+ break
+ tap_node(btn)
+ settle("tap")
+ dismissed = True
+ return dismissed
+
+
+def _clear_pending_dialog():
+ """Grant a stray permission dialog and re-foreground the app if granting it
+ bounced us to the launcher."""
+ for _ in range(3):
+ if not _permission_dialog_present():
+ return
+ grant_pending_permission()
+ if not is_app_foreground():
+ launch_app()
+ wait_for_foreground()
+
+
+def launch_clean():
+ """restart_app(), then clear any pending permission dialog and make sure we
+ land on the app's own MainActivity. This is the entry point every test uses
+ instead of a bare restart_app()."""
+ restart_app()
+ wait_for_foreground()
+ _clear_pending_dialog()
+
+
+def _on_home_surface(nodes=None):
+ """True when the current surface is the app's home/pedometer screen — a
+ Home-only marker is present (the tab strip `tabs`, or the drawer hamburger).
+ Used to leakage-proof tests that assume they start on Home."""
+ nodes = ui() if nodes is None else nodes
+ return (node_by_id(nodes, "tabs") is not None
+ or find_node(nodes, content_desc="Open navigation drawer") is not None)
+
+
+def open_hamburger():
+ """Open the navigation drawer via the hamburger button (recon: open_drawer()
+ edge-swipe drops to the launcher on this emulator). Clears a stray permission
+ dialog first, since a left-over one would hide the hamburger."""
+ _clear_pending_dialog()
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ return tap_node(ham) if ham else False
+
+
+def _drawer_item(nodes, label):
+ """The drawer menu row (CheckedTextView `design_menu_item_text`) whose text
+ matches `label` — NOT the toolbar title or drawer header of the same text."""
+ for n in nodes:
+ rid = (n.get("resource-id") or "").rsplit("/", 1)[-1]
+ if (rid == "design_menu_item_text"
+ and n.get("text", "").strip().lower() == label.strip().lower()):
+ return n
+ return None
+
+
+def and_reach_general():
+ """Navigate drawer -> Settings -> General and PROVE both surface jumps.
+ Counts TWO surfaces (drawer->Settings headers, headers->General) so a
+ declared depth=2 is backed by real navigation, not typed."""
+ if not open_hamburger():
+ return False, "setup_failed: hamburger not found"
+ settle("tap")
+ settings = _drawer_item(ui(), "Settings") or find_node_ci(ui(), "Settings")
+ if settings is None or not tap_node(settings):
+ return False, "setup_failed: Settings drawer item not found"
+ and_enter("settings_headers")
+ settle("tap")
+ gen = find_node_ci(ui(), "General")
+ if gen is None:
+ return False, "setup_failed: General header not found"
+ before = and_showing()
+ if not tap_node(gen):
+ return False, "setup_failed: General not tappable"
+ after = and_showing()
+ # General surface is proven by the appearance of a switch_widget/known pref.
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: General screen did not open"
+ and_enter("general")
+ return True, ""
+
+
+def _row_switch(nodes, title_text):
+ """Return (title_node, switch_node) for a General pref row, pairing the
+ `switch_widget` whose y-center is nearest the title's y-center. Robust to the
+ tightly-stacked list where a switch sits just BELOW its title."""
+ title = None
+ for n in nodes:
+ rid = (n.get("resource-id") or "").rsplit("/", 1)[-1]
+ if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower():
+ title = n
+ break
+ if title is None:
+ return None, None
+ ty = _ycenter(title)
+ switches = [n for n in nodes
+ if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "switch_widget"
+ and n.get("_bounds")]
+ if ty is None or not switches:
+ return title, None
+ best = min(switches, key=lambda s: abs(_ycenter(s) - ty))
+ return title, best
+
+
+def _radio_for_title(nodes, title_text):
+ """Return (title_node, radio_node) for a popup list row, pairing the `radio`
+ RadioButton whose y-center is nearest the `title` TextView's y-center (same
+ row). Rows are matched by title TEXT, never by index/count, so extra seeded
+ modes on the device do not shift the pairing (see module docstring §C)."""
+ title = None
+ for n in nodes:
+ rid = (n.get("resource-id") or "").rsplit("/", 1)[-1]
+ if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower():
+ title = n
+ break
+ if title is None:
+ return None, None
+ ty = _ycenter(title)
+ radios = [n for n in nodes
+ if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "radio"
+ and n.get("_bounds")]
+ if ty is None or not radios:
+ return title, None
+ best = min(radios, key=lambda r: abs(_ycenter(r) - ty))
+ return title, best
+
+
+def _velocity_switch_state():
+ """Scroll 'Show current velocity' into view and return its switch checked
+ string ('true'/'false'/None). Re-dumps, so the returned nodes are fresh."""
+ t = scroll_into_view("Show current velocity")
+ if t is None:
+ return None, None, None
+ nodes = ui()
+ title, sw = _row_switch(nodes, "Show current velocity")
+ return nodes, title, sw
+
+
+def _tap_pref_row(title_text):
+ """Tap the FULL-WIDTH row CONTAINER centre for the preference whose title is
+ `title_text`. In this app's AndroidX preference rows NO node is
+ clickable="true" (not the title, the switch_widget, or the widget_frame), so
+ tapping the narrow title is a no-op; the container tap is what toggles the
+ switch (verified live). Steps: find the `title` node, take its y-centre `ty`,
+ pick the node with the LARGEST width whose bounds satisfy b[1] <= ty <= b[3]
+ and (b[3]-b[1]) <= 400 (a normal row height, excluding the whole list), and
+ tap its centre. Returns True if it tapped, False if the title/row was absent."""
+ nodes = ui()
+ title = None
+ for n in nodes:
+ rid = (n.get("resource-id") or "").rsplit("/", 1)[-1]
+ if rid == "title" and n.get("text", "").strip().lower() == title_text.strip().lower():
+ title = n
+ break
+ if title is None or not title.get("_bounds"):
+ return False
+ ty = _ycenter(title)
+ best_b, best_w = None, -1
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ if b[1] <= ty <= b[3] and (b[3] - b[1]) <= 400:
+ w = b[2] - b[0]
+ if w > best_w:
+ best_w, best_b = w, b
+ if best_b is None:
+ return False
+ tap((best_b[0] + best_b[2]) // 2, (best_b[1] + best_b[3]) // 2)
+ settle("tap")
+ return True
+
+
+def _toggle_pref_row(title_text):
+ """Toggle a preference by tapping its full-width ROW CONTAINER (the switch and
+ every other row node are clickable="false"), re-scrolling the title into view
+ first so the tap lands on the current coordinates. Returns the switch's
+ checked string AFTER the tap."""
+ t = scroll_into_view(title_text)
+ if t is None:
+ return None
+ _tap_pref_row(title_text)
+ # re-scroll (a toggle can shift the list) and read the fresh state
+ scroll_into_view(title_text)
+ _, sw = _row_switch(ui(), title_text)
+ return sw.get("checked") if sw else None
+
+
+def _ensure_pref_off(title_text):
+ """Make the switch for `title_text` read OFF, tapping its row if needed.
+ Idempotent regardless of what a prior run left behind."""
+ scroll_into_view(title_text)
+ _, sw = _row_switch(ui(), title_text)
+ if sw is not None and sw.get("checked") == "true":
+ _toggle_pref_row(title_text)
+ scroll_into_view(title_text)
+ _, sw2 = _row_switch(ui(), title_text)
+ return sw2.get("checked") if sw2 else None
+
+
+def _device_has_step_hardware():
+ """True iff the device advertises a hardware step-counting sensor. The
+ 'Use phone's step counting hardware' preference is guarded on this: without
+ the feature the app refuses to enable the switch. Read via `pm list features`
+ (a device QUERY, not a state-seed like `pm grant`/`settings put`)."""
+ feats = adb_shell("pm", "list", "features")
+ return ("android.hardware.sensor.stepcounter" in feats
+ or "android.hardware.sensor.stepdetector" in feats)
+
+
+def open_summary_popup():
+ """Tap the summary card's `periodMoreButton` (desc 'Walking modes') and
+ confirm the popup opened (a `radio` row appeared). Counts one surface."""
+ btn = find_node(ui(), content_desc="Walking modes")
+ if btn is None or not tap_node(btn):
+ return False
+ settle("tap")
+ if node_by_id(ui(), "radio") is None:
+ return False
+ and_enter("wm_popup")
+ return True
+
+
+def open_chart_popup():
+ """Tap the chart card's `periodMoreButton` (desc 'Options') and confirm the
+ popup opened. Counts one surface."""
+ btn = find_node(ui(), content_desc="Options")
+ if btn is None or not tap_node(btn):
+ return False
+ settle("tap")
+ if node_by_id(ui(), "radio") is None:
+ return False
+ and_enter("chart_popup")
+ return True
+
+
+def reach_distance_measurement():
+ """Navigate drawer -> Distance Measurement and PROVE the jump (start_button
+ appeared). Counts one surface."""
+ if not open_hamburger():
+ return False
+ settle("tap")
+ item = _drawer_item(ui(), "Distance Measurement") or find_node_ci(ui(), "Distance Measurement")
+ if item is None:
+ return False
+ before = and_showing()
+ if not tap_node(item):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "start_button"):
+ # fall back to a text-based reach in case id key differs
+ if not any("distance" in k.lower() for k in (after - before)):
+ return False
+ and_enter("distance_measurement")
+ return True
+
+
+def distance_tap_start():
+ """Tap START and return the fresh nodes once the measuring state settles.
+ Starting a measurement may raise the LOCATION permission dialog the first
+ time; grant it through the GUI and re-tap START so the state machine actually
+ advances. Returns nodes after the (possibly retried) START."""
+ start = node_by_id(ui(), "start_button")
+ if start is None:
+ return ui()
+ tap_node(start)
+ settle("tap")
+ if _permission_dialog_present():
+ grant_pending_permission()
+ # granting can bounce to launcher / re-render — re-navigate + re-tap.
+ if not is_app_foreground():
+ launch_app()
+ wait_for_foreground()
+ reach_distance_measurement()
+ start = node_by_id(ui(), "start_button")
+ if start is not None:
+ tap_node(start)
+ settle("tap")
+ return ui()
+
+
+def _tab(nodes, desc):
+ return find_node(nodes, content_desc=desc)
+
+
+def _period_texts(nodes):
+ return [n.get("text", "") for n in nodes
+ if (n.get("resource-id") or "").rsplit("/", 1)[-1] == "period"]
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# E. Pause / continue step detection (toolbar) — same-surface identity flip
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_pause_to_continue", "states_pause_icon_vlm"))
+@test
+def test_pause_to_continue():
+ launch_clean()
+ nodes = ui()
+ pause = node_by_id(nodes, "menu_pause_step_detection")
+ if pause is None:
+ record("states_pause_to_continue", False,
+ "feature_missing: no 'menu_pause_step_detection' toolbar button",
+ depth=0, jump_kind="transition",
+ expect="button becomes Continue step detection; pause button gone")
+ vlm_assert("states_pause_icon", "Is there a pause icon (two vertical bars) "
+ "in the top-right of the blue toolbar?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="shape")
+ return
+ before_pause = pause.get("content-desc")
+ tap_node(pause)
+ fresh = ui()
+ cont = node_by_id(fresh, "menu_continue_step_detection")
+ pause_gone = node_by_id(fresh, "menu_pause_step_detection") is None
+ ok = (cont is not None
+ and cont.get("content-desc") == "Continue step detection"
+ and pause_gone and before_pause == "Pause step detection")
+ record("states_pause_to_continue", ok,
+ "" if ok else "behavior_wrong: pause button did not flip to "
+ "'Continue step detection' with the pause node gone",
+ depth=0, jump_kind="transition",
+ expect="Pause step detection -> Continue step detection; pause node gone")
+ # VLM: after pausing, the toolbar icon should read as a play/continue glyph.
+ vlm_assert("states_pause_icon",
+ "Look at the icon button in the top-right of the blue toolbar. Is it "
+ "now a single right-pointing 'play' / triangle style icon (indicating "
+ "detection is paused and can be continued) rather than two pause bars?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="shape")
+ # restore: tap continue back to pause
+ tap_node(node_by_id(ui(), "menu_continue_step_detection") or {})
+
+
+@and_test(expects=("states_continue_back_to_pause",))
+@test
+def test_continue_back_to_pause():
+ launch_clean()
+ nodes = ui()
+ pause = node_by_id(nodes, "menu_pause_step_detection")
+ if pause is None:
+ record("states_continue_back_to_pause", False,
+ "feature_missing: no 'menu_pause_step_detection' toolbar button",
+ depth=0, jump_kind="transition",
+ expect="Continue -> Pause step detection; continue node gone")
+ return
+ # go to the paused state first
+ tap_node(pause)
+ cont = node_by_id(ui(), "menu_continue_step_detection")
+ if cont is None:
+ record("states_continue_back_to_pause", False,
+ "setup_failed: could not reach the paused (Continue) state",
+ depth=0, jump_kind="transition",
+ expect="Continue -> Pause step detection; continue node gone")
+ return
+ tap_node(cont)
+ fresh = ui()
+ pause_back = node_by_id(fresh, "menu_pause_step_detection")
+ cont_gone = node_by_id(fresh, "menu_continue_step_detection") is None
+ ok = (pause_back is not None
+ and pause_back.get("content-desc") == "Pause step detection" and cont_gone)
+ record("states_continue_back_to_pause", ok,
+ "" if ok else "behavior_wrong: Continue did not revert to "
+ "'Pause step detection' with the continue node gone",
+ depth=0, jump_kind="transition",
+ expect="Continue step detection -> Pause step detection; continue node gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# A. Tabs — selected flip PAIRED with the computed period label
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_tab_day_selected_on_launch", "states_tab_day_highlight_vlm"))
+@test
+def test_tab_day_selected_on_launch():
+ launch_clean()
+ nodes = ui()
+ day = _tab(nodes, "Day")
+ week = _tab(nodes, "Week")
+ month = _tab(nodes, "Month")
+ if day is None or week is None or month is None:
+ record("states_tab_day_selected_on_launch", False,
+ "feature_missing: Day/Week/Month tabs not found",
+ depth=0, jump_kind="transition",
+ expect="Day tab selected=true; Week/Month selected=false on launch")
+ vlm_assert("states_tab_day_highlight",
+ "Is the 'DAY' tab visually highlighted?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="color")
+ return
+ ok = (day.get("selected") == "true"
+ and week.get("selected") == "false"
+ and month.get("selected") == "false")
+ record("states_tab_day_selected_on_launch", ok,
+ "" if ok else "behavior_wrong: Day tab is not the selected one on launch",
+ depth=0, jump_kind="transition",
+ expect="Day selected=true; Week=false; Month=false on launch")
+ # VLM: the selected tab is drawn with a highlight colour + underline indicator.
+ vlm_assert("states_tab_day_highlight",
+ "Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the "
+ "highlighted/selected one (its label a different, brighter colour such "
+ "as yellow AND with a coloured underline indicator beneath it) while "
+ "WEEK and MONTH are plain white with no underline?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_tab_switch_day_to_week", "states_tab_week_highlight_vlm"))
+@test
+def test_tab_switch_day_to_week():
+ launch_clean()
+ nodes = ui()
+ day = _tab(nodes, "Day")
+ week = _tab(nodes, "Week")
+ if day is None or week is None:
+ record("states_tab_switch_day_to_week", False,
+ "feature_missing: Day/Week tabs not found",
+ depth=0, jump_kind="transition",
+ expect="Week selected=true after tap; period label becomes a range")
+ vlm_assert("states_tab_week_highlight",
+ "Is the 'WEEK' tab the highlighted/selected one?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="color")
+ return
+ day_before = day.get("selected")
+ tap_node(week)
+ fresh = ui()
+ week_after = _tab(fresh, "Week")
+ day_after = _tab(fresh, "Day")
+ periods = _period_texts(fresh)
+ range_shown = any(" - " in p for p in periods)
+ ok = (day_before == "true"
+ and week_after is not None and week_after.get("selected") == "true"
+ and day_after is not None and day_after.get("selected") == "false"
+ and range_shown)
+ record("states_tab_switch_day_to_week", ok,
+ "" if ok else "behavior_wrong: selected did not move Day->Week or the "
+ "period label did not become a range",
+ depth=0, jump_kind="transition",
+ expect="Week selected=true, Day selected=false; period label a range "
+ "containing ' - '")
+ # VLM: the highlight MOVED from Day to Week.
+ vlm_assert("states_tab_week_highlight",
+ "Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the "
+ "highlighted/selected one (brighter/different colour label AND a "
+ "coloured underline indicator beneath WEEK) instead of DAY?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_tab_switch_week_to_month",))
+@test
+def test_tab_switch_week_to_month():
+ launch_clean()
+ nodes = ui()
+ week = _tab(nodes, "Week")
+ month = _tab(nodes, "Month")
+ if week is None or month is None:
+ record("states_tab_switch_week_to_month", False,
+ "feature_missing: Week/Month tabs not found",
+ depth=0, jump_kind="transition",
+ expect="Month selected=true after tap; period matches ' '")
+ return
+ tap_node(week)
+ settle("tap")
+ month = _tab(ui(), "Month")
+ tap_node(month)
+ fresh = ui()
+ month_after = _tab(fresh, "Month")
+ week_after = _tab(fresh, "Week")
+ periods = _period_texts(fresh)
+ month_pattern = any(re.match(r"^[A-Za-z]+ \d{2}$", p.strip()) for p in periods)
+ ok = (month_after is not None and month_after.get("selected") == "true"
+ and week_after is not None and week_after.get("selected") == "false"
+ and month_pattern)
+ record("states_tab_switch_week_to_month", ok,
+ "" if ok else "behavior_wrong: selected did not move Week->Month or the "
+ "period label did not match ' '",
+ depth=0, jump_kind="transition",
+ expect="Month selected=true, Week selected=false; period ' '")
+
+
+@and_test(expects=("states_tab_back_to_day",))
+@test
+def test_tab_back_to_day():
+ launch_clean()
+ nodes = ui()
+ week = _tab(nodes, "Week")
+ if week is None or _tab(nodes, "Day") is None:
+ record("states_tab_back_to_day", False,
+ "feature_missing: Day/Week tabs not found",
+ depth=0, jump_kind="transition",
+ expect="Day selected=true again after returning from Week")
+ return
+ tap_node(week)
+ settle("tap")
+ day = _tab(ui(), "Day")
+ tap_node(day)
+ fresh = ui()
+ day_after = _tab(fresh, "Day")
+ week_after = _tab(fresh, "Week")
+ periods = _period_texts(fresh)
+ # Day period is a single day: "DD. Month" — no range, no year-2-digit pattern.
+ day_single = any(re.match(r"^\d{1,2}\. [A-Za-z]+$", p.strip()) for p in periods)
+ ok = (day_after is not None and day_after.get("selected") == "true"
+ and week_after is not None and week_after.get("selected") == "false"
+ and day_single)
+ record("states_tab_back_to_day", ok,
+ "" if ok else "behavior_wrong: selected did not return to Day or the "
+ "period label is not a single 'DD. Month' day",
+ depth=0, jump_kind="transition",
+ expect="Day selected=true, Week selected=false; period 'DD. Month'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# C. Walking-mode radio (summary popup) — depth 1
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_walking_radio_default", "states_walking_radio_default_vlm"))
+@test
+def test_walking_radio_default():
+ launch_clean()
+ if find_node(ui(), content_desc="Walking modes") is None:
+ record("states_walking_radio_default", False,
+ "feature_missing: summary 'Walking modes' button not found",
+ depth=1, jump_kind="transition",
+ expect="Walking radio checked=true, Running checked=false on open")
+ vlm_assert("states_walking_radio_default",
+ "Is a radio button filled next to 'Walking'?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ if not open_summary_popup():
+ record("states_walking_radio_default", False,
+ "setup_failed: walking-mode popup did not open",
+ depth=1, jump_kind="transition",
+ expect="Walking radio checked=true, Running checked=false on open")
+ vlm_assert("states_walking_radio_default",
+ "Is a radio button filled next to 'Walking'?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ nodes = ui()
+ _, walk_radio = _radio_for_title(nodes, "Walking")
+ _, run_radio = _radio_for_title(nodes, "Running")
+ ok = (walk_radio is not None and walk_radio.get("checked") == "true"
+ and run_radio is not None and run_radio.get("checked") == "false")
+ record("states_walking_radio_default", ok,
+ "" if ok else "behavior_wrong: Walking radio not checked / Running not "
+ "unchecked when the popup opens",
+ depth=1, jump_kind="transition",
+ expect="Walking radio checked=true, Running checked=false on open")
+ # VLM: the Walking radio is the filled (blue) one.
+ vlm_assert("states_walking_radio_default",
+ "In this popup listing walking modes, is the round radio button next "
+ "to 'Walking' filled in (a solid coloured/blue dot = selected) while "
+ "the radio next to 'Running' is an empty hollow circle?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+ back() # close popup
+
+
+@and_test(expects=("states_walking_select_running", "states_running_radio_vlm"))
+@test
+def test_walking_select_running():
+ launch_clean()
+ if find_node(ui(), content_desc="Walking modes") is None:
+ record("states_walking_select_running", False,
+ "feature_missing: summary 'Walking modes' button not found",
+ depth=1, jump_kind="transition",
+ expect="Running radio checked=true after selecting it and reopening")
+ vlm_assert("states_running_radio",
+ "Is the radio next to 'Running' filled/selected?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ if not open_summary_popup():
+ record("states_walking_select_running", False,
+ "setup_failed: walking-mode popup did not open",
+ depth=1, jump_kind="transition",
+ expect="Running radio checked=true after selecting it and reopening")
+ vlm_assert("states_running_radio",
+ "Is the radio next to 'Running' filled/selected?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ # select Running by tapping its title row
+ run_title, _ = _radio_for_title(ui(), "Running")
+ if run_title is None or not tap_node(run_title):
+ record("states_walking_select_running", False,
+ "setup_failed: 'Running' row not tappable",
+ depth=1, jump_kind="transition",
+ expect="Running radio checked=true after selecting it and reopening")
+ vlm_assert("states_running_radio",
+ "Is the radio next to 'Running' filled/selected?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ settle("tap")
+ # reopen popup — the selection must have stuck
+ reopened = open_summary_popup()
+ nodes = ui()
+ _, run_radio = _radio_for_title(nodes, "Running")
+ _, walk_radio = _radio_for_title(nodes, "Walking")
+ ok = (reopened and run_radio is not None and run_radio.get("checked") == "true"
+ and walk_radio is not None and walk_radio.get("checked") == "false")
+ record("states_walking_select_running", ok,
+ "" if ok else "behavior_wrong: Running radio did not become checked (and "
+ "Walking unchecked) after selection + reopen",
+ depth=1, jump_kind="transition",
+ expect="Running radio checked=true, Walking checked=false on reopen")
+ # VLM while popup shows Running selected.
+ vlm_assert("states_running_radio",
+ "In this walking-modes popup, is the round radio button next to "
+ "'Running' now filled in (solid coloured/blue dot = selected)?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+ # RESET active mode back to Walking
+ if reopened:
+ walk_title, _ = _radio_for_title(ui(), "Walking")
+ if walk_title:
+ tap_node(walk_title)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# D. Chart data-type radio (chart popup) — depth 1
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_chart_radio_default", "states_chart_steps_radio_vlm"))
+@test
+def test_chart_radio_default():
+ launch_clean()
+ if find_node(ui(), content_desc="Options") is None:
+ record("states_chart_radio_default", False,
+ "feature_missing: chart 'Options' button not found",
+ depth=1, jump_kind="transition",
+ expect="Steps radio checked=true, Distance/Calories false on open")
+ vlm_assert("states_chart_steps_radio",
+ "Is a radio filled next to 'Steps'?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ if not open_chart_popup():
+ record("states_chart_radio_default", False,
+ "setup_failed: chart-type popup did not open",
+ depth=1, jump_kind="transition",
+ expect="Steps radio checked=true, Distance/Calories false on open")
+ vlm_assert("states_chart_steps_radio",
+ "Is a radio filled next to 'Steps'?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ nodes = ui()
+ _, steps_radio = _radio_for_title(nodes, "Steps")
+ _, dist_radio = _radio_for_title(nodes, "Distance")
+ ok = (steps_radio is not None and steps_radio.get("checked") == "true"
+ and dist_radio is not None and dist_radio.get("checked") == "false")
+ record("states_chart_radio_default", ok,
+ "" if ok else "behavior_wrong: Steps radio not checked / Distance not "
+ "unchecked when the chart popup opens",
+ depth=1, jump_kind="transition",
+ expect="Steps radio checked=true, Distance checked=false on open")
+ vlm_assert("states_chart_steps_radio",
+ "In this popup listing chart data types, is the round radio button "
+ "next to 'Steps' filled in (solid coloured/blue dot = selected) while "
+ "'Distance' and 'Calories' show empty hollow circles?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="shape")
+ back()
+
+
+@and_test(expects=("states_chart_select_distance",))
+@test
+def test_chart_select_distance():
+ launch_clean()
+ if find_node(ui(), content_desc="Options") is None:
+ record("states_chart_select_distance", False,
+ "feature_missing: chart 'Options' button not found",
+ depth=1, jump_kind="transition",
+ expect="Distance radio checked=true after selecting it and reopening")
+ return
+ if not open_chart_popup():
+ record("states_chart_select_distance", False,
+ "setup_failed: chart-type popup did not open",
+ depth=1, jump_kind="transition",
+ expect="Distance radio checked=true after selecting it and reopening")
+ return
+ dist_title, _ = _radio_for_title(ui(), "Distance")
+ if dist_title is None or not tap_node(dist_title):
+ record("states_chart_select_distance", False,
+ "setup_failed: 'Distance' row not tappable",
+ depth=1, jump_kind="transition",
+ expect="Distance radio checked=true after selecting it and reopening")
+ return
+ settle("tap")
+ reopened = open_chart_popup()
+ nodes = ui()
+ _, dist_radio = _radio_for_title(nodes, "Distance")
+ _, steps_radio = _radio_for_title(nodes, "Steps")
+ ok = (reopened and dist_radio is not None and dist_radio.get("checked") == "true"
+ and steps_radio is not None and steps_radio.get("checked") == "false")
+ record("states_chart_select_distance", ok,
+ "" if ok else "behavior_wrong: Distance radio did not become checked (and "
+ "Steps unchecked) after selection + reopen",
+ depth=1, jump_kind="transition",
+ expect="Distance radio checked=true, Steps checked=false on reopen")
+ # RESET chart type back to Steps
+ if reopened:
+ steps_title, _ = _radio_for_title(ui(), "Steps")
+ if steps_title:
+ tap_node(steps_title)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# G. Distance measurement — page-level state machine (idle <-> measuring), depth 1
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_distance_start_to_stop", "states_distance_measuring_vlm"))
+@test
+def test_distance_start_to_stop():
+ launch_clean()
+ if not reach_distance_measurement():
+ record("states_distance_start_to_stop", False,
+ "setup_failed: could not reach Distance Measurement",
+ depth=1, jump_kind="transition",
+ expect="stop_button shown, start_button hidden after START")
+ vlm_assert("states_distance_measuring",
+ "Does the screen show a STOP DISTANCE MEASUREMENT button?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ return
+ act_before = get_current_activity()
+ nodes = ui()
+ start = node_by_id(nodes, "start_button")
+ if start is None:
+ record("states_distance_start_to_stop", False,
+ "feature_missing: 'start_button' not present on Distance Measurement",
+ depth=1, jump_kind="transition",
+ expect="stop_button shown, start_button hidden after START")
+ vlm_assert("states_distance_measuring",
+ "Does the screen show a STOP DISTANCE MEASUREMENT button?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ return
+ fresh = distance_tap_start() # taps START, grants location perm if prompted
+ stop = node_by_id(fresh, "stop_button")
+ start_gone = node_by_id(fresh, "start_button") is None
+ same_activity = get_current_activity() == act_before
+ ok = (stop is not None and start_gone and same_activity)
+ record("states_distance_start_to_stop", ok,
+ "" if ok else "behavior_wrong: START did not swap to STOP with start_button "
+ "hidden on the same Activity",
+ depth=1, jump_kind="transition",
+ expect="start_button hidden, stop_button ('STOP DISTANCE MEASUREMENT') "
+ "shown on the same DistanceMeasurementActivity")
+ # VLM: the measuring state renders a STOP button.
+ vlm_assert("states_distance_measuring",
+ "Does the large button at the bottom of the screen read "
+ "'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather "
+ "than 'START DISTANCE MEASUREMENT'?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ # restore: stop the measurement
+ tap_node(node_by_id(ui(), "stop_button") or {})
+
+
+@and_test(expects=("states_distance_stop_to_start",))
+@test
+def test_distance_stop_to_start():
+ launch_clean()
+ if not reach_distance_measurement():
+ record("states_distance_stop_to_start", False,
+ "setup_failed: could not reach Distance Measurement",
+ depth=1, jump_kind="transition",
+ expect="start_button shown again, stop_button hidden after STOP")
+ return
+ act_before = get_current_activity()
+ start = node_by_id(ui(), "start_button")
+ if start is None:
+ record("states_distance_stop_to_start", False,
+ "feature_missing: 'start_button' not present on Distance Measurement",
+ depth=1, jump_kind="transition",
+ expect="start_button shown again, stop_button hidden after STOP")
+ return
+ fresh = distance_tap_start() # -> measuring (grants location perm if prompted)
+ stop = node_by_id(fresh, "stop_button")
+ if stop is None:
+ record("states_distance_stop_to_start", False,
+ "setup_failed: could not enter the measuring (STOP) state",
+ depth=1, jump_kind="transition",
+ expect="start_button shown again, stop_button hidden after STOP")
+ return
+ tap_node(stop) # -> idle again
+ settle("tap")
+ fresh2 = ui()
+ start_back = node_by_id(fresh2, "start_button")
+ stop_gone = node_by_id(fresh2, "stop_button") is None
+ same_activity = get_current_activity() == act_before
+ ok = (start_back is not None and stop_gone and same_activity)
+ record("states_distance_stop_to_start", ok,
+ "" if ok else "behavior_wrong: STOP did not revert to START with stop_button "
+ "hidden on the same Activity",
+ depth=1, jump_kind="transition",
+ expect="stop_button hidden, start_button ('START DISTANCE MEASUREMENT') "
+ "shown again on the same Activity")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Drawer CheckedTextView — `checked` state of the current section (my lane), depth 1
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_drawer_home_checked",))
+@test
+def test_drawer_home_checked():
+ launch_clean()
+ # Leakage-proofing: a prior test may have navigated away or left a surface
+ # behind. Confirm we are actually on the app's home surface (a Home-only
+ # marker present) BEFORE opening the drawer; if not, restart once more so the
+ # drawer reflects the current section (Pedometer), not a stale one.
+ if not (is_app_foreground() and _on_home_surface()):
+ restart_app()
+ wait_for_foreground()
+ _clear_pending_dialog()
+ if not open_hamburger():
+ record("states_drawer_home_checked", False,
+ "setup_failed: hamburger not found",
+ depth=1, jump_kind="transition",
+ expect="'Pedometer' drawer item checked=true; 'Settings' checked=false")
+ return
+ and_enter("drawer")
+ settle("tap")
+ nodes = ui()
+ home_item = _drawer_item(nodes, "Pedometer")
+ settings_item = _drawer_item(nodes, "Settings")
+ ok = (home_item is not None and home_item.get("checked") == "true"
+ and settings_item is not None and settings_item.get("checked") == "false")
+ record("states_drawer_home_checked", ok,
+ "" if ok else "behavior_wrong: the current section 'Pedometer' menu item "
+ "is not checked in the drawer (or Settings is checked)",
+ depth=1, jump_kind="transition",
+ expect="'Pedometer' menu item checked=true (current section), "
+ "'Settings' checked=false")
+ back() # close drawer
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# H. Settings General switch toggle (depth 2) + persistence across process death
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_settings_velocity_toggle", "states_settings_switches_vlm"))
+@test
+def test_settings_velocity_toggle():
+ launch_clean()
+ ok_nav, note = and_reach_general()
+ if not ok_nav:
+ record("states_settings_velocity_toggle", False, note,
+ depth=2, jump_kind="transition",
+ expect="'Show current velocity' switch checked false->true")
+ vlm_assert("states_settings_switches",
+ "Are there multiple toggle switches down the right side of the "
+ "settings list?", RESULTS_DIR, depth=2, jump_kind="transition",
+ tag="layout")
+ return
+ if scroll_into_view("Show current velocity") is None:
+ record("states_settings_velocity_toggle", False,
+ "feature_missing: 'Show current velocity' preference not found",
+ depth=2, jump_kind="transition",
+ expect="'Show current velocity' switch checked false->true")
+ vlm_assert("states_settings_switches",
+ "Are there multiple toggle switches down the right side of the "
+ "settings list?", RESULTS_DIR, depth=2, jump_kind="transition",
+ tag="layout")
+ return
+ # Idempotent start: ensure OFF regardless of what a prior run left behind.
+ before = _ensure_pref_off("Show current velocity")
+ after = _toggle_pref_row("Show current velocity")
+ ok = (before == "false" and after == "true")
+ record("states_settings_velocity_toggle", ok,
+ "" if ok else "behavior_wrong: 'Show current velocity' switch did not flip "
+ f"false->true (before={before}, after={after})",
+ depth=2, jump_kind="transition",
+ expect="'Show current velocity' switch checked false->true")
+ # VLM: the General settings list renders a column of switches on the right.
+ vlm_assert("states_settings_switches",
+ "In this settings list, are there several ON/OFF toggle SWITCHES "
+ "aligned down the RIGHT-hand edge of the rows (rounded pill toggles), "
+ "one per switch preference?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="layout")
+ # RESTORE: back to OFF
+ _ensure_pref_off("Show current velocity")
+
+
+@and_test(expects=("states_settings_hardware_toggle", "states_settings_permanent_on_vlm"))
+@test
+def test_settings_hardware_toggle():
+ """A second OFF-by-default switch. It is HARDWARE-GATED: the app turns it ON
+ only when the device advertises a step-counting sensor; on a device without
+ one, the row tap correctly leaves it OFF (an app-authored conditional-enable
+ consequence). The test asserts EITHER the OFF->ON flip OR (still OFF AND the
+ feature is provably absent) — never a bare existence check — proving the flip
+ is per-preference and honours the app's guard. Restores OFF afterwards."""
+ launch_clean()
+ ok_nav, note = and_reach_general()
+ if not ok_nav:
+ record("states_settings_hardware_toggle", False, note,
+ depth=2, jump_kind="transition",
+ expect="'Use phone's step counting hardware' switch checked false->true")
+ vlm_assert("states_settings_permanent_on",
+ "Is the 'Permanent step counter' toggle in the ON position?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ return
+ # The hardware switch sits near the TOP of General (2nd preference) and is
+ # visible on a fresh entry. scroll_into_view only scrolls DOWN, so scroll to
+ # the very top first to guarantee it is reachable regardless of prior position.
+ for _ in range(5):
+ scroll_up(0.7)
+ if scroll_into_view("Use phone's step counting hardware") is None:
+ record("states_settings_hardware_toggle", False,
+ "feature_missing: 'Use phone's step counting hardware' pref not found",
+ depth=2, jump_kind="transition",
+ expect="'Use phone's step counting hardware' switch checked false->true")
+ vlm_assert("states_settings_permanent_on",
+ "Is the 'Permanent step counter' toggle in the ON position?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ return
+ # Idempotent start: ensure OFF, then tap the row to attempt the OFF->ON flip.
+ before = _ensure_pref_off("Use phone's step counting hardware")
+ after = _toggle_pref_row("Use phone's step counting hardware")
+ has_hw = _device_has_step_hardware()
+ # Behavioral pass: the switch flipped ON, OR the app correctly refused because
+ # the device lacks a hardware step counter (guarded conditional-enable).
+ ok = (before == "false"
+ and (after == "true" or (after == "false" and not has_hw)))
+ record("states_settings_hardware_toggle", ok,
+ "" if ok else "behavior_wrong: 'Use phone's step counting hardware' switch "
+ f"did not honour its hardware guard (before={before}, "
+ f"after={after}, device_has_step_hardware={has_hw})",
+ depth=2, jump_kind="transition",
+ expect="'Use phone's step counting hardware' switch checked false->true")
+ # VLM: 'Permanent step counter' is a default-ON switch — thumb to the right/coloured.
+ # It is the FIRST preference — scroll to the very top so it is on screen.
+ for _ in range(5):
+ scroll_up(0.7)
+ perm = find_node(ui(), text="Permanent step counter")
+ if perm is not None:
+ vlm_assert("states_settings_permanent_on",
+ "Look at the row 'Permanent step counter'. Is its toggle switch in "
+ "the ON position — the thumb pushed to the RIGHT and the track "
+ "filled with the app's accent colour (not grey/left = off)?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ else:
+ vlm_assert("states_settings_permanent_on",
+ "Is there a toggle switch shown in the ON (right, coloured) "
+ "position in this settings list?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ # RESTORE: back to OFF (a no-op when the guard already kept it OFF)
+ _ensure_pref_off("Use phone's step counting hardware")
+
+
+@and_test(expects=("states_settings_velocity_persists",))
+@test
+def test_settings_velocity_persists():
+ """Signature SETTINGS-persistence probe. Idempotent across repeat runs:
+ ensure ON -> force_stop_and_relaunch() -> re-navigate -> assert STILL ON ->
+ toggle OFF to restore. A second run therefore starts from OFF again."""
+ launch_clean()
+ ok_nav, note = and_reach_general()
+ if not ok_nav:
+ record("states_settings_velocity_persists", False, note,
+ depth=2, jump_kind="value",
+ expect="'Show current velocity' switch still checked=true after relaunch")
+ return
+ if scroll_into_view("Show current velocity") is None:
+ record("states_settings_velocity_persists", False,
+ "feature_missing: 'Show current velocity' preference not found",
+ depth=2, jump_kind="value",
+ expect="'Show current velocity' switch still checked=true after relaunch")
+ return
+ # ensure ON before the kill
+ _ensure_pref_off("Show current velocity") # normalize
+ on_state = _toggle_pref_row("Show current velocity") # -> ON
+ if on_state != "true":
+ record("states_settings_velocity_persists", False,
+ "setup_failed: could not switch 'Show current velocity' ON before the "
+ "relaunch",
+ depth=2, jump_kind="value",
+ expect="'Show current velocity' switch still checked=true after relaunch")
+ return
+ # KILL the process and relaunch — an in-memory-only recreation loses the pref
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ _clear_pending_dialog()
+ ok_nav2, note2 = and_reach_general()
+ if not ok_nav2:
+ record("states_settings_velocity_persists", False,
+ f"setup_failed: could not re-open General after relaunch ({note2})",
+ depth=2, jump_kind="value",
+ expect="'Show current velocity' switch still checked=true after relaunch")
+ return
+ _, _, sw_after = _velocity_switch_state()
+ still_on = sw_after is not None and sw_after.get("checked") == "true"
+ record("states_settings_velocity_persists", still_on,
+ "" if still_on else "behavior_wrong: 'Show current velocity' did NOT "
+ "persist as ON across process death",
+ depth=2, jump_kind="value",
+ expect="'Show current velocity' switch still checked=true after "
+ "force_stop_and_relaunch()")
+ # RESTORE original OFF state so the suite stays order-independent
+ _ensure_pref_off("Show current velocity")
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_structure.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..28574737d6452c272e749697b284a1ce22631510
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_structure.py
@@ -0,0 +1,495 @@
+#!/usr/bin/env python3
+"""STRUCTURE module — the GATE (top-level surfaces exist) + tree-SHAPE deltas
+(an interaction changes the view tree's SHAPE: a subtree/dialog/popup appears or
+disappears, a button identity flips, a list grows). Content (strings/values/
+checked flags) belongs to other lanes and is NOT asserted here.
+
+App: Privacy Friendly Pedometer. Ground truth from recon.md + recon screenshots.
+Run: python3 test_android_structure.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+HAMBURGER = "Open navigation drawer"
+
+
+# ── local depth helpers (NAMED and_enter_*/and_reach_* so declared depth is backed) ──
+
+def and_enter_drawer():
+ """Open the nav drawer via the HAMBURGER (edge-swipe open_drawer drops to the
+ launcher, per recon). Returns (ok, before, after) surfaces around the tap."""
+ nodes = ui()
+ ham = find_node(nodes, content_desc=HAMBURGER)
+ if not ham:
+ return False, set(), set()
+ before = and_showing(nodes)
+ if not tap_node(ham):
+ return False, before, set()
+ after = and_showing()
+ and_enter("drawer")
+ return True, before, after
+
+
+def and_reach_drawer_item(label):
+ """From MainActivity, open the drawer and tap a menu item, entering its screen."""
+ ok, _b, _a = and_enter_drawer()
+ if not ok:
+ return False
+ nodes = ui()
+ item = find_node_ci(nodes, label)
+ if not item:
+ return False
+ if not tap_node(item):
+ return False
+ and_enter(label)
+ return True
+
+
+def and_enter_walking_modes():
+ """MainActivity -> drawer Settings -> tap 'Walking modes' (two surfaces)."""
+ if not and_reach_drawer_item("Settings"):
+ return False
+ wm = scroll_into_view("Walking modes")
+ if not wm:
+ return False
+ if not tap_node(wm):
+ return False
+ and_enter("Walking modes")
+ return True
+
+
+def _open_summary_popup():
+ """Summary card periodMoreButton (desc 'Walking modes') opens a radio popup.
+ Returns (ok, before, after) surfaces around the tap."""
+ nodes = ui()
+ btn = find_node(nodes, content_desc="Walking modes")
+ if not btn:
+ return False, set(), set()
+ before = and_showing(nodes)
+ if not tap_node(btn):
+ return False, before, set()
+ after = and_showing()
+ and_enter("summary_popup")
+ return True, before, after
+
+
+def _open_chart_popup():
+ """Chart card periodMoreButton (desc 'Options') opens a radio popup."""
+ nodes = ui()
+ btn = find_node(nodes, content_desc="Options")
+ if not btn:
+ return False, set(), set()
+ before = and_showing(nodes)
+ if not tap_node(btn):
+ return False, before, set()
+ after = and_showing()
+ and_enter("chart_popup")
+ return True, before, after
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE — top-level surfaces exist (jump_kind="none", depth 0). Kept ≤ 30% of file.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ restart_app()
+ ok_fg = wait_for_foreground()
+ nodes = ui()
+ ok = bool(ok_fg) and bool(find_by_class(nodes, "ViewGroup")) and is_app_foreground()
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach the foreground with a ViewGroup",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_toolbar",))
+def test_gate_toolbar():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ title = find_node_ci(nodes, "Pedometer")
+ ham = find_node(nodes, content_desc=HAMBURGER)
+ pause = node_by_id(nodes, "menu_pause_step_detection") \
+ or find_node(nodes, content_desc="Pause step detection")
+ ok = bool(title) and bool(ham) and bool(pause)
+ record("structure_gate_toolbar", ok,
+ "" if ok else "setup_failed: toolbar title/hamburger/pause control missing",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_tabs_pager",))
+def test_gate_tabs_pager():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ tabs = node_by_id(nodes, "tabs")
+ pager = node_by_id(nodes, "pager")
+ day = find_node(nodes, content_desc="Day")
+ week = find_node(nodes, content_desc="Week")
+ month = find_node(nodes, content_desc="Month")
+ ok = bool(tabs) and bool(pager) and bool(day) and bool(week) and bool(month)
+ record("structure_gate_tabs_pager", ok,
+ "" if ok else "setup_failed: tabs container / pager / Day-Week-Month tabs missing",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_two_cards",))
+def test_gate_two_cards():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ cards = [n for n in nodes if n.get("resource-id", "").rsplit("/", 1)[-1] == "card_view"]
+ # Home shows a summary card and a chart card -> at least two card_view nodes.
+ ok = len(cards) >= 2
+ record("structure_gate_two_cards", ok,
+ "" if ok else f"setup_failed: expected >=2 card_view cards, saw {len(cards)}",
+ depth=0, jump_kind="none")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SHAPE DELTAS — an interaction changes the tree's SHAPE (transition, depth>=1).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_drawer_subtree", "structure_drawer_subtree_vlm"))
+def test_drawer_adds_subtree():
+ restart_app()
+ wait_for_foreground()
+ ok_open, before, after = and_enter_drawer()
+ # Opening the drawer ADDS the nav_view subtree (design_navigation_view + menu_*
+ # rows). Assert the surface changed materially AND a nav row newly appeared.
+ grew = len(after) > len(before)
+ nav_appeared = and_reach(before, after, "menu_settings") \
+ or and_reach(before, after, "Settings")
+ ok = bool(ok_open) and surface_changed(before, after) and grew and nav_appeared
+ record("structure_drawer_subtree", ok,
+ "" if ok else "behavior_wrong: drawer did not add the nav_view subtree",
+ depth=1, jump_kind="transition",
+ expect="hamburger adds nav_view subtree (node count grows, menu rows appear)")
+ vlm_assert("structure_drawer_subtree",
+ "Is a navigation drawer panel anchored to the LEFT edge of the screen "
+ "(covering roughly the left three-quarters), listing menu items "
+ "stacked vertically top-to-bottom: Pedometer, Training, Distance "
+ "Measurement, Settings, Help, About?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+
+
+@and_test(expects=("structure_correct_steps_dialog",))
+def test_correct_steps_adds_dialog():
+ restart_app()
+ wait_for_foreground()
+ ok_popup, _b, _a = _open_summary_popup()
+ dialog_ok = False
+ before = after = set()
+ if ok_popup:
+ nodes = ui()
+ item = find_node_ci(nodes, "Correct steps")
+ if item:
+ before = and_showing(nodes)
+ if tap_node(item):
+ and_enter("correct_steps_dialog")
+ after = and_showing()
+ # The dialog ADDS a subtree: alertTitle + a 'steps' EditText appear.
+ fresh = ui()
+ has_dialog = (node_by_id(fresh, "alertTitle") is not None
+ and node_by_id(fresh, "steps") is not None)
+ dialog_ok = surface_changed(before, after) and has_dialog
+ record("structure_correct_steps_dialog", dialog_ok,
+ "" if dialog_ok else "behavior_wrong: Correct steps dialog subtree did not appear",
+ depth=2, jump_kind="transition",
+ expect="summary popup -> Correct steps adds a dialog (alertTitle + steps EditText)")
+
+
+@and_test(expects=("structure_summary_popup", "structure_summary_popup_vlm"))
+def test_summary_popup_adds_radio_list():
+ restart_app()
+ wait_for_foreground()
+ ok_popup, before, after = _open_summary_popup()
+ # The popup opens as its OWN window, so the dump shows only the popup subtree
+ # (the underlying card vanishes from the dump). The honest shape signal is:
+ # the surface changed AND the discriminating popup rows newly appeared.
+ running_appeared = and_reach(before, after, "Running")
+ correct_appeared = and_reach(before, after, "Correct steps")
+ appeared = bool(ok_popup) and surface_changed(before, after) \
+ and running_appeared and correct_appeared
+ # Screenshot the popup WHILE it is open (before reversing).
+ vlm_assert("structure_summary_popup",
+ "Is a small popup menu or dialog shown listing selectable options "
+ "including 'Walking', 'Running' and 'Correct steps'?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ # Reverse it: BACK dismisses the popup and the summary card returns.
+ and_back()
+ restored = find_node(ui(), content_desc="Walking modes") is not None
+ ok = appeared and restored
+ record("structure_summary_popup", ok,
+ "" if ok else "behavior_wrong: summary Walking-modes popup subtree did not appear/restore",
+ depth=1, jump_kind="transition",
+ expect="summary periodMoreButton adds a popup window (Running + Correct steps rows appear), removed on BACK")
+
+
+@and_test(expects=("structure_chart_popup",))
+def test_chart_options_popup_adds_subtree():
+ restart_app()
+ wait_for_foreground()
+ ok_popup, before, after = _open_chart_popup()
+ # Chart Options popup opens as its own window; assert the surface changed AND the
+ # discriminating radio rows Distance/Calories newly appeared (Steps also present).
+ dist_appeared = and_reach(before, after, "Distance")
+ cal_appeared = and_reach(before, after, "Calories")
+ appeared = bool(ok_popup) and surface_changed(before, after) \
+ and dist_appeared and cal_appeared
+ # Reverse it: BACK dismisses the popup and the chart 'Options' button returns.
+ and_back()
+ restored = find_node(ui(), content_desc="Options") is not None
+ ok = appeared and restored
+ record("structure_chart_popup", ok,
+ "" if ok else "behavior_wrong: chart Options popup subtree did not appear/restore",
+ depth=1, jump_kind="transition",
+ expect="chart periodMoreButton adds a popup window (Distance + Calories rows appear), removed on BACK")
+
+
+@and_test(expects=("structure_pause_button_flip",))
+def test_pause_button_identity_flip():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ pause = node_by_id(nodes, "menu_pause_step_detection") \
+ or find_node(nodes, content_desc="Pause step detection")
+ ok = False
+ if pause and tap_node(pause):
+ fresh = ui()
+ cont = node_by_id(fresh, "menu_continue_step_detection") \
+ or find_node(fresh, content_desc="Continue step detection")
+ gone = node_by_id(fresh, "menu_pause_step_detection") is None \
+ and find_node(fresh, content_desc="Pause step detection") is None
+ flipped = bool(cont) and gone
+ # Reverse it to assert the shape restores.
+ restored = False
+ if cont and tap_node(cont):
+ rev = ui()
+ restored = (node_by_id(rev, "menu_pause_step_detection") is not None
+ or find_node(rev, content_desc="Pause step detection") is not None)
+ ok = flipped and restored
+ record("structure_pause_button_flip", ok,
+ "" if ok else "behavior_wrong: pause<->continue button identity did not flip and restore",
+ depth=0, jump_kind="transition",
+ expect="pause button becomes continue (pause gone), reverts on second tap")
+
+
+@and_test(expects=("structure_distance_start_stop", "structure_distance_start_stop_vlm"))
+def test_distance_start_stop_flip():
+ restart_app()
+ wait_for_foreground()
+ reached = and_reach_drawer_item("Distance Measurement")
+ ok = False
+ if reached:
+ nodes = ui()
+ start = node_by_id(nodes, "start_button")
+ vlm_assert("structure_distance_start_stop",
+ "Is a large distance value like '0.00 m' positioned near the TOP "
+ "of the content area, with a single full-width button labelled "
+ "'START DISTANCE MEASUREMENT' pinned at the BOTTOM of the screen?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+ if start and tap_node(start):
+ fresh = ui()
+ stop = node_by_id(fresh, "stop_button")
+ start_gone = node_by_id(fresh, "start_button") is None
+ flipped = bool(stop) and start_gone
+ # Reverse: tap stop -> start returns.
+ restored = False
+ if stop and tap_node(stop):
+ rev = ui()
+ restored = node_by_id(rev, "start_button") is not None
+ ok = flipped and restored
+ # (start button missing -> ok stays False, recorded below)
+ else:
+ vlm_assert("structure_distance_start_stop",
+ "Does this screen show a distance value and a START DISTANCE "
+ "MEASUREMENT button?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+ record("structure_distance_start_stop", ok,
+ "" if ok else "behavior_wrong: start_button -> stop_button flip did not occur/restore",
+ depth=1, jump_kind="transition",
+ expect="start_button replaced by stop_button on tap, restored on stop")
+
+
+@and_test(expects=("structure_walkmodes_add_dialog", "structure_walkmodes_layout_vlm"))
+def test_walkmodes_add_dialog_and_layout():
+ restart_app()
+ wait_for_foreground()
+ reached = and_enter_walking_modes()
+ ok = False
+ if reached:
+ # Layout VLM on the correct screen: two mode cards stacked vertically.
+ vlm_assert("structure_walkmodes_layout",
+ "Are there exactly two list rows stacked vertically at the TOP "
+ "(each with a mode name and a 'Step length:' value), and a round "
+ "blue circular '+' floating button in the LOWER-RIGHT corner?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+ nodes = ui()
+ fab = node_by_id(nodes, "add_walking_mode_btn") \
+ or find_node(nodes, content_desc="Add")
+ if fab:
+ before = and_showing(nodes)
+ if tap_node(fab):
+ and_enter("add_wm_dialog")
+ after = and_showing()
+ fresh = ui()
+ # Add dialog ADDS a subtree: alertTitle + input_name + step_length_edit.
+ has_dialog = (node_by_id(fresh, "alertTitle") is not None
+ and node_by_id(fresh, "input_name") is not None
+ and node_by_id(fresh, "step_length_edit") is not None)
+ ok = surface_changed(before, after) and has_dialog
+ else:
+ vlm_assert("structure_walkmodes_layout",
+ "Does this screen list walking modes with step-length values and a "
+ "round '+' floating button?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+ record("structure_walkmodes_add_dialog", ok,
+ "" if ok else "behavior_wrong: Add-walking-mode dialog subtree did not appear",
+ depth=2, jump_kind="transition",
+ expect="FAB add adds a dialog (alertTitle + input_name + step_length_edit)")
+
+
+@and_test(expects=("structure_help_expand_grows",))
+def test_help_expand_grows_list():
+ restart_app()
+ wait_for_foreground()
+ reached = and_reach_drawer_item("Help")
+ ok = False
+ if reached:
+ before_nodes = ui()
+ header = find_node_ci(before_nodes, "Overview")
+ n_before = len(and_showing(before_nodes))
+ if header and tap_node(header):
+ and_enter("help_overview_expanded")
+ after_nodes = ui()
+ n_after = len(and_showing(after_nodes))
+ grew = n_after > n_before
+ # Reverse: collapse -> node count returns toward the pre-expand size.
+ hdr2 = find_node_ci(ui(), "Overview")
+ collapsed_ok = False
+ if hdr2 and tap_node(hdr2):
+ n_rev = len(and_showing(ui()))
+ collapsed_ok = n_rev < n_after
+ ok = grew and collapsed_ok
+ record("structure_help_expand_grows", ok,
+ "" if ok else "behavior_wrong: expanding 'Overview' did not grow then shrink the list",
+ depth=1, jump_kind="transition",
+ expect="tap Overview grows the expandable list (child row appears), collapses back")
+
+
+@and_test(expects=("structure_training_reach", "structure_training_grid_vlm"))
+def test_training_reach_and_grid():
+ restart_app()
+ wait_for_foreground()
+ reached = and_reach_drawer_item("Training")
+ ok = False
+ if reached:
+ nodes = ui()
+ fab = node_by_id(nodes, "start_training") \
+ or find_node(nodes, content_desc="Start training")
+ if fab:
+ # Prove the surface JUMP: END TRAINING NOW appears, the overview FAB goes.
+ jumped = and_reach_surface(fab, "END TRAINING NOW", "Start training")
+ if not jumped:
+ # Fallback: confirm the live training button by id after the tap.
+ jumped = node_by_id(ui(), "training_stop_button") is not None
+ live = ui()
+ has_button = node_by_id(live, "training_stop_button") is not None \
+ or find_node_ci(live, "END TRAINING NOW") is not None
+ ok = bool(jumped) and has_button
+ # VLM on the live training screen: the stats grid.
+ vlm_assert("structure_training_grid",
+ "Is a large timer (like 00:00:05) centered near the TOP, with "
+ "the stats laid out BELOW it in a two-column grid: distance in "
+ "'m' and velocity in 'km/h' on one row, calories in 'cal' and a "
+ "step count on the next row?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ # Clean up: END TRAINING NOW is SAFE (not a Delete) -> return to overview.
+ stop = node_by_id(ui(), "training_stop_button") \
+ or find_node_ci(ui(), "END TRAINING NOW")
+ if stop:
+ safe_tap(stop)
+ else:
+ vlm_assert("structure_training_grid",
+ "Does the training screen show a timer and a grid of stats "
+ "(distance, velocity, calories, steps)?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ else:
+ vlm_assert("structure_training_grid",
+ "Does the training screen show a timer and a grid of stats "
+ "(distance, velocity, calories, steps)?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ record("structure_training_reach", ok,
+ "" if ok else "behavior_wrong: FAB did not reach the live TrainingActivity",
+ depth=1, jump_kind="transition",
+ expect="start_training FAB flips the surface: END TRAINING NOW appears, the Start-training FAB disappears (proven via and_reach_surface)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# VLM-only rendered structure (canvas / spatial layout unreadable from the dump).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_home_two_cards_vlm",))
+def test_home_two_cards_layout_vlm():
+ restart_app()
+ wait_for_foreground()
+ ui()
+ vlm_assert("structure_home_two_cards",
+ "Are there two white card panels stacked VERTICALLY: the UPPER card "
+ "titled with 'Summary of activities' and the LOWER card titled with "
+ "'Detailed summary of your activities'?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="position")
+
+
+@and_test(expects=("structure_tabs_row_vlm",))
+def test_tabs_row_layout_vlm():
+ restart_app()
+ wait_for_foreground()
+ ui()
+ vlm_assert("structure_tabs_row",
+ "Is there a horizontal row of exactly three tabs labelled DAY, WEEK "
+ "and MONTH directly below the top toolbar?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="position")
+
+
+@and_test(expects=("structure_chart_canvas_vlm",))
+def test_chart_canvas_vlm():
+ restart_app()
+ wait_for_foreground()
+ ui()
+ # The chart is an MPAndroidChart LineChart canvas -> not in the view tree.
+ vlm_assert("structure_chart_canvas",
+ "In the lower card, is a line/area chart rendered with a horizontal "
+ "time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical "
+ "axis with numeric gridlines (0 up to 10,000)?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="shape")
+
+
+TESTS = [
+ # Gate (existence, depth 0) — 4 of 16 = 25%.
+ test_gate_launch,
+ test_gate_toolbar,
+ test_gate_tabs_pager,
+ test_gate_two_cards,
+ # Shape deltas (transition / reach, depth>=1).
+ test_drawer_adds_subtree,
+ test_correct_steps_adds_dialog,
+ test_summary_popup_adds_radio_list,
+ test_chart_options_popup_adds_subtree,
+ test_pause_button_identity_flip,
+ test_distance_start_stop_flip,
+ test_walkmodes_add_dialog_and_layout,
+ test_help_expand_grows_list,
+ test_training_reach_and_grid,
+ # VLM-only rendered structure.
+ test_home_two_cards_layout_vlm,
+ test_tabs_row_layout_vlm,
+ test_chart_canvas_vlm,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_android_text.py b/android/secuso-privacy-friendly-pedometer/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..dce10fdd3280761f9f9225fdef4df471353a127c
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_android_text.py
@@ -0,0 +1,618 @@
+#!/usr/bin/env python3
+"""TEXT module — exact CONTENT-string equality for Privacy Friendly Pedometer.
+
+Sole owner of exact-string equality: every test is TRIGGER (launch / navigate /
+tab-flip) -> OBSERVATION (an exact string, or a date-independent SHAPE, read out
+of a fresh ui()). A dead shell that clones the layout but renders no real strings
+FAILS here.
+
+What this lane does NOT assert (owner-priority, per recon.md):
+ * the computed pedometer VALUE (step count / distance / calorie number) —
+ computation's. We assert only FIXED unit labels ("Steps") and static
+ titles/summaries.
+ * reachability as the observation — navigation's. We still navigate to reach a
+ string (declaring honest depth via and_enter_* helpers) but the ASSERTION is
+ always the STRING on the surface, never "did the surface appear".
+ * a version/build/copyright value read from source — unfair to a recreation.
+ (The About "Version" LABEL is app-authored UI text and is asserted; the live
+ version NAME "3.1.2" was OBSERVED on the running original and is asserted as
+ such, not read from any source tree.)
+
+Runtime rules (recon.md): use restart_app() — NEVER clear_data() (it fires two
+permission dialogs and drops to the launcher). Open the drawer with the HAMBURGER
+(content-desc "Open navigation drawer"), never open_drawer() (its edge-swipe drops
+to the launcher). Match resource-ids by LAST segment via node_by_id().
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── shared reach helpers. The and_enter_* NAME is what the depth auditor keys off
+# (it must find a member of the and_enter*/and_reach* family to back a depth>=1
+# claim); the body actually taps through and calls the kit's and_enter(). ─────
+
+def open_nav_drawer():
+ """Open the navigation drawer via the HAMBURGER. Returns the fresh drawer
+ node list, or None if the hamburger is absent."""
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ if not ham or not tap_node(ham):
+ return None
+ settle("tap")
+ return ui()
+
+
+def _reach_drawer_item(label):
+ """restart -> open drawer -> tap the drawer item. Returns the fresh node list
+ of the destination surface, or None. Counts one surface via and_enter()."""
+ restart_app()
+ if not wait_for_foreground():
+ return None
+ d = open_nav_drawer()
+ if d is None:
+ return None
+ item = find_node_ci(d, label)
+ if item is None or not tap_node(item):
+ return None
+ settle("tap")
+ and_enter(label)
+ return ui()
+
+
+def and_enter_about():
+ """Home -> drawer -> About. depth 1. Returns AboutActivity nodes or None."""
+ return _reach_drawer_item("About")
+
+
+def and_enter_help():
+ """Home -> drawer -> Help. depth 1. Returns HelpActivity nodes or None."""
+ return _reach_drawer_item("Help")
+
+
+def and_enter_settings():
+ """Home -> drawer -> Settings. depth 1. Returns the header-list nodes or None."""
+ return _reach_drawer_item("Settings")
+
+
+def and_enter_general():
+ """Home -> drawer -> Settings -> tap 'General'. depth 2. Returns General
+ prefs nodes or None."""
+ s = and_enter_settings()
+ if s is None:
+ return None
+ gen = find_node_ci(ui(), "General")
+ if gen is None or not tap_node(gen):
+ return None
+ settle("tap")
+ and_enter("General")
+ return ui()
+
+
+def and_enter_walking_modes():
+ """Home -> drawer -> Settings -> tap 'Walking modes'. depth 2. Returns
+ WalkingModesActivity nodes or None."""
+ s = and_enter_settings()
+ if s is None:
+ return None
+ wm = find_node_ci(ui(), "Walking modes")
+ if wm is None or not tap_node(wm):
+ return None
+ settle("tap")
+ and_enter("Walking modes")
+ return ui()
+
+
+# ── small readers ────────────────────────────────────────────────────────────
+
+def id_text(nodes, rid_suffix):
+ """The text of the node whose resource-id ends with rid_suffix ('' if none)."""
+ n = node_by_id(nodes, rid_suffix)
+ return (n.get("text", "") if n else "").strip()
+
+
+def texts_by_id(nodes, rid_suffix):
+ """All non-empty texts of nodes whose resource-id ends with rid_suffix, in
+ document order (= visual top-to-bottom for these list layouts)."""
+ out = []
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix and n.get("text", "").strip():
+ out.append(n.get("text").strip())
+ return out
+
+
+def titles(nodes):
+ return texts_by_id(nodes, "title")
+
+
+def summary_below(nodes, title_text):
+ """The nearest /summary text vertically below the given /title (Android
+ preference rows stack summary under title). '' if not found."""
+ tn = find_node(nodes, text=title_text)
+ if not tn or "_bounds" not in tn:
+ return ""
+ ty = tn["_bounds"][1]
+ best, best_dy = "", 10 ** 9
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid.rsplit("/", 1)[-1] == "summary" and n.get("text", "").strip():
+ dy = n.get("_bounds", (0, 0, 0, 0))[1] - ty
+ if 0 <= dy < best_dy:
+ best_dy, best = dy, n.get("text").strip()
+ return best
+
+
+def period_texts(nodes):
+ return texts_by_id(nodes, "period")
+
+
+def tap_tab(desc):
+ """Tap the Day/Week/Month tab by content-desc. Returns True if tapped."""
+ n = find_node(ui(), content_desc=desc)
+ if not n:
+ return False
+ ok = tap_node(n)
+ settle("tap")
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HOME summary card — FIXED unit / label strings (depth 0, pure launch+read)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_home_step_title",))
+def test_home_step_title():
+ restart_app()
+ wait_for_foreground()
+ got = id_text(ui(), "stepTitle")
+ ok = got.strip().casefold() == "steps"
+ record("text_home_step_title", ok,
+ "" if ok else (f"behavior_wrong: stepTitle reads {got!r}, expected 'Steps'"
+ if got else "feature_missing: no stepTitle label on the home card"),
+ depth=0, jump_kind="none", expect="home step-count label == 'Steps'")
+
+
+@and_test(expects=("text_home_period_subtitle",))
+def test_home_period_subtitle():
+ restart_app()
+ wait_for_foreground()
+ got = id_text(ui(), "periodSubtitle")
+ ok = got.strip().casefold() == "summary of activities"
+ record("text_home_period_subtitle", ok,
+ "" if ok else (f"behavior_wrong: periodSubtitle reads {got!r}, expected "
+ f"'Summary of activities'" if got
+ else "feature_missing: no periodSubtitle on the home summary card"),
+ depth=0, jump_kind="none",
+ expect="home summary-card subtitle == 'Summary of activities'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HOME period label — the string CHANGES with the Day/Week/Month tab.
+# Assert a date-INDEPENDENT shape (so it passes on any run date) via a before->
+# after transition on the same surface (depth 0).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_period_week_is_range",))
+def test_period_week_is_range():
+ # Day => "DD. Month" (no range dash); Week => "DD. - DD. Month" (a range).
+ # Discriminating change: " - " ABSENT on Day, PRESENT on Week.
+ restart_app()
+ wait_for_foreground()
+ if not tap_tab("Day"):
+ record("text_period_week_is_range", False,
+ "setup_failed: Day tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Week period contains ' - '")
+ return
+ day = period_texts(ui())
+ absent = bool(day) and all(" - " not in p for p in day)
+ if not tap_tab("Week"):
+ record("text_period_week_is_range", False,
+ "setup_failed: Week tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Week period contains ' - '")
+ return
+ week = period_texts(ui())
+ present = bool(week) and any(" - " in p for p in week)
+ ok = absent and present
+ record("text_period_week_is_range", ok,
+ "" if ok else f"behavior_wrong: Week period {week!r} is not a ' - ' range "
+ f"(Day was {day!r})",
+ depth=0, jump_kind="transition",
+ expect="Week period label contains ' - ' (a date range); Day did not")
+
+
+@and_test(expects=("text_period_month_shape",))
+def test_period_month_shape():
+ # Month => "Month YY" (word + two digits), e.g. "August 26". Assert the shape,
+ # never today's literal value. Also assert it differs from the Day label.
+ restart_app()
+ wait_for_foreground()
+ if not tap_tab("Day"):
+ record("text_period_month_shape", False,
+ "setup_failed: Day tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Month period matches '^[A-Za-z]+ \\d{2}$'")
+ return
+ day = period_texts(ui())
+ if not tap_tab("Month"):
+ record("text_period_month_shape", False,
+ "setup_failed: Month tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Month period matches '^[A-Za-z]+ \\d{2}$'")
+ return
+ month = period_texts(ui())
+ shape = re.compile(r"^[A-Za-z]+ \d{2}$")
+ present = bool(month) and any(shape.match(p) for p in month)
+ changed = bool(month) and set(month) != set(day)
+ ok = present and changed
+ record("text_period_month_shape", ok,
+ "" if ok else f"behavior_wrong: Month period {month!r} is not a 'Month YY' "
+ f"shape distinct from Day {day!r}",
+ depth=0, jump_kind="transition",
+ expect="Month period label matches '^ YY$' (e.g. 'August 26')")
+
+
+@and_test(expects=("text_period_day_single",))
+def test_period_day_single():
+ # Day => a single day "DD. Month": has a '.' and a trailing month word, and is
+ # NOT a range. Shape only (date-independent).
+ restart_app()
+ wait_for_foreground()
+ if not tap_tab("Week"):
+ record("text_period_day_single", False,
+ "setup_failed: Week tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Day period is a single 'DD. Month'")
+ return
+ week = period_texts(ui())
+ if not tap_tab("Day"):
+ record("text_period_day_single", False,
+ "setup_failed: Day tab not found on the home report",
+ depth=0, jump_kind="transition", expect="Day period is a single 'DD. Month'")
+ return
+ day = period_texts(ui())
+ shape = re.compile(r"^\d{1,2}\.\s+[A-Za-z]+$")
+ present = bool(day) and any(shape.match(p) for p in day)
+ not_range = bool(day) and all(" - " not in p for p in day)
+ changed = bool(day) and set(day) != set(week)
+ ok = present and not_range and changed
+ record("text_period_day_single", ok,
+ "" if ok else f"behavior_wrong: Day period {day!r} is not a single 'DD. Month' "
+ f"day (Week was {week!r})",
+ depth=0, jump_kind="transition",
+ expect="Day period label matches '^DD. $' with no ' - ' range")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# ABOUT screen (depth 1) — exact app-authored content strings via node_by_id
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_about_appname_version",))
+def test_about_appname_version():
+ n = and_enter_about()
+ if n is None:
+ record("text_about_appname_version", False,
+ "setup_failed: could not reach AboutActivity from the drawer",
+ depth=1, jump_kind="none", expect="appName 'Privacy Friendly Pedometer' + 'Version' + '3.1.2'")
+ return
+ app = id_text(n, "appName")
+ ver_label = id_text(n, "textFieldVersion")
+ ver_name = id_text(n, "textFieldVersionName")
+ ok = (app.casefold() == "privacy friendly pedometer"
+ and ver_label.casefold() == "version"
+ and ver_name == "3.1.2")
+ record("text_about_appname_version", ok,
+ "" if ok else f"behavior_wrong: About header reads appName={app!r} "
+ f"version-label={ver_label!r} version-name={ver_name!r}",
+ depth=1, jump_kind="none",
+ expect="appName=='Privacy Friendly Pedometer', label=='Version', name=='3.1.2'")
+
+
+@and_test(expects=("text_about_authors",))
+def test_about_authors():
+ n = and_enter_about()
+ if n is None:
+ record("text_about_authors", False,
+ "setup_failed: could not reach AboutActivity from the drawer",
+ depth=1, jump_kind="none",
+ expect="'Author:' + 'Noah Schlegel, Tobias Neidig' + 'and contributors.'")
+ return
+ author = id_text(n, "textFieldAuthor")
+ names = id_text(n, "textFieldAuthorNames")
+ contrib = id_text(n, "textFieldContributors")
+ ok = (author.casefold() == "author:"
+ and names == "Noah Schlegel, Tobias Neidig"
+ and contrib.casefold() == "and contributors.")
+ record("text_about_authors", ok,
+ "" if ok else f"behavior_wrong: About author block reads author={author!r} "
+ f"names={names!r} contrib={contrib!r}",
+ depth=1, jump_kind="none",
+ expect="author=='Author:', names=='Noah Schlegel, Tobias Neidig', "
+ "contributors=='and contributors.'")
+
+
+@and_test(expects=("text_about_links",))
+def test_about_links():
+ n = and_enter_about()
+ if n is None:
+ record("text_about_links", False,
+ "setup_failed: could not reach AboutActivity from the drawer",
+ depth=1, jump_kind="none",
+ expect="'In affiliation with' + 'SECUSO-Website' + 'Github-Repo'")
+ return
+ affil = id_text(n, "textFieldAffiliation")
+ secuso = id_text(n, "secusoWebsite")
+ github = id_text(n, "githubURL")
+ ok = (affil.casefold() == "in affiliation with"
+ and secuso.casefold() == "secuso-website"
+ and github.casefold() == "github-repo")
+ record("text_about_links", ok,
+ "" if ok else f"behavior_wrong: About link block reads affiliation={affil!r} "
+ f"secuso={secuso!r} github={github!r}",
+ depth=1, jump_kind="none",
+ expect="affiliation=='In affiliation with', secuso=='SECUSO-Website', "
+ "github=='Github-Repo'")
+
+
+@and_test(expects=("text_about_logo_block_vlm",))
+def test_about_logo_block_vlm():
+ # VLM #1 (position): the "Privacy Friendly Apps" brand logo is a DRAWABLE (a
+ # cluster of coloured squares), dump-invisible. Question written from the
+ # captured screenshot: that multi-coloured squares icon sits at the TOP-LEFT,
+ # immediately to the LEFT of the large title 'Privacy Friendly Apps'.
+ n = and_enter_about()
+ if n is None:
+ record("text_about_logo_block_vlm", False,
+ "setup_failed: could not reach AboutActivity to screenshot",
+ depth=1, jump_kind="none", tag="position")
+ return
+ vlm_assert("text_about_logo_block",
+ "Near the TOP of this screen, is there a small icon made of several "
+ "coloured squares positioned immediately to the LEFT of a large "
+ "heading that reads 'Privacy Friendly Apps'?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# WALKING MODES list (depth 2) — seeded card names, step-length values & labels.
+# Robust to extra cards a prior interaction run may have added: assert the FIRST
+# card is Walking(active)/0.50 and that Running/0.70 is PRESENT.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_walkingmode_first_card",))
+def test_walkingmode_first_card():
+ n = and_enter_walking_modes()
+ if n is None:
+ record("text_walkingmode_first_card", False,
+ "setup_failed: could not reach WalkingModesActivity via Settings",
+ depth=2, jump_kind="none", expect="first card name=='Walking(active)', length=='0.50'")
+ return
+ names = texts_by_id(n, "name")
+ lengths = texts_by_id(n, "step_length")
+ first_name = names[0] if names else ""
+ first_len = lengths[0] if lengths else ""
+ ok = first_name.casefold() == "walking(active)" and first_len == "0.50"
+ record("text_walkingmode_first_card", ok,
+ "" if ok else f"behavior_wrong: first walking-mode card reads name={first_name!r} "
+ f"step_length={first_len!r} (all names={names!r})",
+ depth=2, jump_kind="none",
+ expect="first card name=='Walking(active)' with step_length=='0.50'")
+
+
+@and_test(expects=("text_walkingmode_running_and_labels",))
+def test_walkingmode_running_and_labels():
+ n = and_enter_walking_modes()
+ if n is None:
+ record("text_walkingmode_running_and_labels", False,
+ "setup_failed: could not reach WalkingModesActivity via Settings",
+ depth=2, jump_kind="none",
+ expect="a 'Running' card with '0.70' + labels 'Step length:'/'meters'")
+ return
+ names = texts_by_id(n, "name")
+ lengths = texts_by_id(n, "step_length")
+ labels = texts_by_id(n, "textView")
+ units = texts_by_id(n, "textView2")
+ running_i = next((i for i, nm in enumerate(names)
+ if nm.strip().casefold() == "running"), -1)
+ running_len_ok = running_i >= 0 and running_i < len(lengths) and lengths[running_i] == "0.70"
+ label_ok = any(l.strip().casefold() == "step length:" for l in labels)
+ unit_ok = any(u.strip().casefold() == "meters" for u in units)
+ ok = running_len_ok and label_ok and unit_ok
+ record("text_walkingmode_running_and_labels", ok,
+ "" if ok else f"behavior_wrong: 'Running' card / labels wrong "
+ f"(names={names!r} lengths={lengths!r} labels={labels!r} units={units!r})",
+ depth=2, jump_kind="none",
+ expect="'Running' card step_length=='0.70'; row labels 'Step length:' and 'meters'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HELP screen (depth 1) — the exact expandable-group header strings
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_help_key_headers",))
+def test_help_key_headers():
+ n = and_enter_help()
+ if n is None:
+ record("text_help_key_headers", False,
+ "setup_failed: could not reach HelpActivity from the drawer",
+ depth=1, jump_kind="none",
+ expect="'Overview', 'Counting methods', 'Privacy Info' present as listTitle")
+ return
+ heads = {h.casefold() for h in texts_by_id(n, "listTitle")}
+ need = ["Overview", "Counting methods", "Privacy Info"]
+ missing = [h for h in need if h.casefold() not in heads]
+ ok = not missing
+ record("text_help_key_headers", ok,
+ "" if ok else f"behavior_wrong: Help is missing header(s) {missing!r} "
+ f"(present: {sorted(heads)})",
+ depth=1, jump_kind="none",
+ expect="Help group headers include 'Overview', 'Counting methods', 'Privacy Info'")
+
+
+@and_test(expects=("text_help_ordered_headers",))
+def test_help_ordered_headers():
+ # The 14 group headers in their exact order (recon.md §J), as OBSERVED live.
+ expected = ["Overview", "Counting methods", "Notification", "Motivation alert",
+ "Walking Modes", "Training Sessions", "Distance Measurement",
+ "Correct steps manually", "Privacy Info",
+ "Permission: Receive Boot Completed", "Permission: Wake Lock",
+ "Permission: Foreground Service", "Permission: Precise location",
+ "Permission: Write External Storage"]
+ n = and_enter_help()
+ if n is None:
+ record("text_help_ordered_headers", False,
+ "setup_failed: could not reach HelpActivity from the drawer",
+ depth=1, jump_kind="none", expect="14 Help headers in the exact recon order")
+ return
+ got = [h.strip() for h in texts_by_id(n, "listTitle")]
+ ok = [g.casefold() for g in got] == [e.casefold() for e in expected]
+ record("text_help_ordered_headers", ok,
+ "" if ok else f"behavior_wrong: Help headers/order mismatch. got={got!r}",
+ depth=1, jump_kind="none",
+ expect="listTitle == the 14 ordered headers 'Overview'..'Permission: Write External Storage'")
+
+
+@and_test(expects=("text_help_list_layout_vlm",))
+def test_help_list_layout_vlm():
+ # VLM #2 (position): the expandable-list group-indicator arrows render to the
+ # LEFT of each header row — a rendered PLACEMENT, not dump-readable. Question
+ # written from the captured screenshot: a small downward chevron sits left of
+ # every bold title, under a dark-blue 'Help' app bar.
+ n = and_enter_help()
+ if n is None:
+ record("text_help_list_layout_vlm", False,
+ "setup_failed: could not reach HelpActivity to screenshot",
+ depth=1, jump_kind="none", tag="position")
+ return
+ vlm_assert("text_help_list_layout",
+ "This is a vertical list of bold section headers, the first being "
+ "'Overview'. Does each header row show a small downward-pointing "
+ "chevron/arrow indicator positioned to the LEFT of its label text "
+ "(to the left, not on the right edge)?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SETTINGS headers (depth 1) — the three header rows as exact title strings
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_settings_headers",))
+def test_settings_headers():
+ n = and_enter_settings()
+ if n is None:
+ record("text_settings_headers", False,
+ "setup_failed: could not reach the Settings header list from the drawer",
+ depth=1, jump_kind="none", expect="'General', 'Notifications', 'Walking modes'")
+ return
+ ts = {t.casefold() for t in titles(n)}
+ need = ["General", "Notifications", "Walking modes"]
+ missing = [t for t in need if t.casefold() not in ts]
+ ok = not missing
+ record("text_settings_headers", ok,
+ "" if ok else f"behavior_wrong: Settings missing header(s) {missing!r} "
+ f"(present: {sorted(ts)})",
+ depth=1, jump_kind="none",
+ expect="Settings header titles include 'General', 'Notifications', 'Walking modes'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SETTINGS -> General (depth 2) — exact preference titles & list-pref summaries
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_general_switch_titles",))
+def test_general_switch_titles():
+ # Switch-preference titles that render on the General screen. "Permanent step
+ # counter" is above the fold; "Show current velocity" needs a scroll.
+ n = and_enter_general()
+ if n is None:
+ record("text_general_switch_titles", False,
+ "setup_failed: could not reach Settings -> General",
+ depth=2, jump_kind="none",
+ expect="titles 'Permanent step counter' and 'Show current velocity'")
+ return
+ top = titles(n)
+ perm_ok = any(t.casefold() == "permanent step counter" for t in top)
+ vel_node = scroll_into_view("Show current velocity", max_swipes=6)
+ vel_ok = vel_node is not None
+ ok = perm_ok and vel_ok
+ record("text_general_switch_titles", ok,
+ "" if ok else f"behavior_wrong: General is missing switch title(s) "
+ f"(permanent={perm_ok}, velocity={vel_ok}; top titles={top!r})",
+ depth=2, jump_kind="none",
+ expect="General shows titles 'Permanent step counter' and 'Show current velocity'")
+
+
+@and_test(expects=("text_general_unit_summaries",))
+def test_general_unit_summaries():
+ # List-preference summaries reflect the current selection (default install):
+ # "Unit of length" summary "kilometers", "Unit of energy" summary "calories".
+ n = and_enter_general()
+ if n is None:
+ record("text_general_unit_summaries", False,
+ "setup_failed: could not reach Settings -> General",
+ depth=2, jump_kind="none",
+ expect="'Unit of length'=='kilometers', 'Unit of energy'=='calories'")
+ return
+ len_sum = summary_below(n, "Unit of length")
+ energy_sum = summary_below(n, "Unit of energy")
+ ok = len_sum.casefold() == "kilometers" and energy_sum.casefold() == "calories"
+ record("text_general_unit_summaries", ok,
+ "" if ok else f"behavior_wrong: unit summaries read length={len_sum!r} "
+ f"energy={energy_sum!r}",
+ depth=2, jump_kind="none",
+ expect="'Unit of length' summary=='kilometers'; 'Unit of energy' summary=='calories'")
+
+
+@and_test(expects=("text_general_value_summaries",))
+def test_general_value_summaries():
+ # EditText-preference summaries show the stored value: "Personal daily step
+ # goal" == "10000", "Weight (kg)" == "65.0". These are STORED STRINGS the pref
+ # renders as its summary, not a computed pedometer value.
+ n = and_enter_general()
+ if n is None:
+ record("text_general_value_summaries", False,
+ "setup_failed: could not reach Settings -> General",
+ depth=2, jump_kind="none",
+ expect="'Personal daily step goal'=='10000', 'Weight (kg)'=='65.0'")
+ return
+ goal_node = scroll_into_view("Personal daily step goal", max_swipes=6)
+ goal_sum = summary_below(ui(), "Personal daily step goal") if goal_node else ""
+ weight_node = scroll_into_view("Weight (kg)", max_swipes=6)
+ weight_sum = summary_below(ui(), "Weight (kg)") if weight_node else ""
+ ok = goal_sum == "10000" and weight_sum == "65.0"
+ record("text_general_value_summaries", ok,
+ "" if ok else f"behavior_wrong: value summaries read goal={goal_sum!r} "
+ f"weight={weight_sum!r}",
+ depth=2, jump_kind="none",
+ expect="'Personal daily step goal' summary=='10000'; 'Weight (kg)' summary=='65.0'")
+
+
+TESTS = [
+ # HOME fixed labels (depth 0)
+ test_home_step_title,
+ test_home_period_subtitle,
+ # HOME period label — date-independent shape per tab (depth 0, transition)
+ test_period_week_is_range,
+ test_period_month_shape,
+ test_period_day_single,
+ # ABOUT (depth 1)
+ test_about_appname_version,
+ test_about_authors,
+ test_about_links,
+ test_about_logo_block_vlm, # VLM #1 (position)
+ # WALKING MODES (depth 2)
+ test_walkingmode_first_card,
+ test_walkingmode_running_and_labels,
+ # HELP (depth 1)
+ test_help_key_headers,
+ test_help_ordered_headers,
+ test_help_list_layout_vlm, # VLM #2 (position)
+ # SETTINGS headers (depth 1)
+ test_settings_headers,
+ # SETTINGS -> General (depth 2)
+ test_general_switch_titles,
+ test_general_unit_summaries,
+ test_general_value_summaries,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/secuso-privacy-friendly-pedometer/tests/test_manifest.json b/android/secuso-privacy-friendly-pedometer/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..b354ca3b57c21fee8cb4f04b4e1d1010e062087f
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/tests/test_manifest.json
@@ -0,0 +1,792 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "privacy-friendly-pedometer",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 120,
+ "manifest_sha": "33fa43ef91c1",
+ "tests": [
+ {
+ "name": "computation::computation_calorie_number_with_unit",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_chart_distance_type_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_chart_plotted_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_distance_two_decimals",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_distance_unit_km_when_ge_100m",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_distance_unit_meters_small",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_period_changes_day_to_week",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_period_day",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_period_month_pattern",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_period_week_is_range",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_100",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_1000",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_199",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_200",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_2000",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_50",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_arbitrary",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_large",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_steps_zero",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_summary_numbers_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_add_walking_mode",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_card_context_menu",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_correct_steps_cancel_noop",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_correct_steps_save_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_correct_steps_survives_death",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_help_expand_collapse",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_switch_active_mode",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_training_creates_session",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_context_menu_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_correct_steps_dialog_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_help_expanded_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_summary_popup_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_training_live_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_walking_mode_card_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_vlm_walking_modes_list_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_walking_mode_survives_death",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_about_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_distance_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_general_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_walkingmodes_deep",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_settings_general",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_settings_notifications",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_settings_walkingmodes",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_training_live",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_distance",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_help",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_training",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_about_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_distance_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_help_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_settings_headers_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_training_live_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_vlm_training_overview_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_chart_radio_default",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_chart_select_distance",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_chart_steps_radio_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_continue_back_to_pause",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_distance_measuring_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_distance_start_to_stop",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_distance_stop_to_start",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_drawer_home_checked",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pause_icon_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pause_to_continue",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_running_radio_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_settings_hardware_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_settings_permanent_on_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_settings_switches_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_settings_velocity_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_settings_velocity_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_back_to_day",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_day_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_day_selected_on_launch",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_switch_day_to_week",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_switch_week_to_month",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_tab_week_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_walking_radio_default",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_walking_radio_default_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_walking_select_running",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_chart_canvas_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_chart_popup",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_correct_steps_dialog",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_distance_start_stop",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_distance_start_stop_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_subtree",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_subtree_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_tabs_pager",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_toolbar",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_two_cards",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_help_expand_grows",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_two_cards_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_pause_button_flip",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_summary_popup",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_summary_popup_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_tabs_row_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_training_grid_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_training_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_walkmodes_add_dialog",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_walkmodes_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_appname_version",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_authors",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_links",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_logo_block_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_general_switch_titles",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_general_unit_summaries",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_general_value_summaries",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_key_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_list_layout_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_ordered_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_period_subtitle",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_step_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_period_day_single",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_period_month_shape",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_period_week_is_range",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_walkingmode_first_card",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_walkingmode_running_and_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_chart_plotted_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_summary_numbers_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "computation::computation_chart_distance_type_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_vlm_walking_modes_list_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_vlm_walking_mode_card_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_vlm_context_menu_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_vlm_correct_steps_dialog_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_vlm_summary_popup_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_vlm_help_expanded_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_vlm_training_live_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_vlm_training_overview_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_vlm_distance_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_vlm_settings_headers_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_vlm_about_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_vlm_help_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_vlm_training_live_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_pause_icon_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_tab_day_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_tab_week_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_walking_radio_default_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_running_radio_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_chart_steps_radio_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_distance_measuring_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_settings_switches_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_settings_permanent_on_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_drawer_subtree_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_summary_popup_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_distance_start_stop_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_walkmodes_layout_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_training_grid_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_home_two_cards_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_tabs_row_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_chart_canvas_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "text::text_about_logo_block_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_help_list_layout_vlm",
+ "module": "text",
+ "tag": "position"
+ }
+ ],
+ "vlm_total": 35,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-pedometer/vlm_assertions.json b/android/secuso-privacy-friendly-pedometer/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..a295d6aff632f79cee13440ab643201365ea4ba9
--- /dev/null
+++ b/android/secuso-privacy-friendly-pedometer/vlm_assertions.json
@@ -0,0 +1,723 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/secuso-privacy-friendly-pedometer",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 35,
+ "with_verdict": 35,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 35,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "structure_drawer_subtree_vlm",
+ "screenshot": "structure_drawer_subtree_vlm.png",
+ "assertion": "Is a navigation drawer panel open on the left side, showing a vertical list of menu items (such as Pedometer, Training, Settings, Help, About)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_drawer_subtree",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_summary_popup_vlm",
+ "screenshot": "structure_summary_popup_vlm.png",
+ "assertion": "Is a small popup menu or dialog shown listing selectable options including 'Walking', 'Running' and 'Correct steps'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_summary_popup",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_distance_start_stop_vlm",
+ "screenshot": "structure_distance_start_stop_vlm.png",
+ "assertion": "Does this screen show a large distance value like '0.00 m' near the top and a single wide button labelled 'START DISTANCE MEASUREMENT' at the bottom?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_distance_start_stop",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_walkmodes_layout_vlm",
+ "screenshot": "structure_walkmodes_layout_vlm.png",
+ "assertion": "Are there exactly two list rows stacked vertically, each showing a mode name and a 'Step length:' value in meters, with a round blue '+' floating button in the lower-right corner?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_walkmodes_layout",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_training_grid_vlm",
+ "screenshot": "structure_training_grid_vlm.png",
+ "assertion": "Does this screen show a large timer near the top and a grid of stats below it including distance in 'm', velocity in 'km/h', calories in 'cal' and a step count?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_training_grid",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_home_two_cards_vlm",
+ "screenshot": "structure_home_two_cards_vlm.png",
+ "assertion": "Are there two stacked white card panels: an upper 'Summary of activities' card and a lower 'Detailed summary of your activities' card?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_home_two_cards",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_tabs_row_vlm",
+ "screenshot": "structure_tabs_row_vlm.png",
+ "assertion": "Is there a horizontal row of exactly three tabs labelled DAY, WEEK and MONTH directly below the top toolbar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_tabs_row",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_chart_canvas_vlm",
+ "screenshot": "structure_chart_canvas_vlm.png",
+ "assertion": "In the lower card, is a line/area chart rendered with a horizontal time axis (labels like 00:00, 08:00, 16:00, 23:00) and a vertical axis with numeric gridlines (0 up to 10,000)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_chart_canvas",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_training_overview_vlm",
+ "screenshot": "nav_vlm_training_overview_vlm.png",
+ "assertion": "Is there a round blue floating action button with a white plus sign in the bottom-right corner of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_vlm_training_overview",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_distance_vlm",
+ "screenshot": "nav_vlm_distance_vlm.png",
+ "assertion": "Is there a full-width dark-blue button labelled 'START DISTANCE MEASUREMENT' pinned to the bottom of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_vlm_distance",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_settings_headers_vlm",
+ "screenshot": "nav_vlm_settings_headers_vlm.png",
+ "assertion": "Does this screen show a vertical settings list with three rows labelled 'General', 'Notifications' and 'Walking modes', each with an icon on the left?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_vlm_settings_headers",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_about_vlm",
+ "screenshot": "nav_vlm_about_vlm.png",
+ "assertion": "Does this About screen show the SECUSO logo (a round emblem to the left of the word 'SECUSO') in its middle area?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_vlm_about",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_help_vlm",
+ "screenshot": "nav_vlm_help_vlm.png",
+ "assertion": "Does this screen show a top app bar titled 'Help' and, below it, a vertical list of help topics starting with 'Overview'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_vlm_help",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_vlm_training_live_vlm",
+ "screenshot": "nav_vlm_training_live_vlm.png",
+ "assertion": "Is there a prominent full-width button labelled 'END TRAINING NOW' at the bottom of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_vlm_training_live",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_walking_modes_list_vlm",
+ "screenshot": "interaction_vlm_walking_modes_list_vlm.png",
+ "assertion": "Are there three or more walking-mode cards stacked vertically in a list on this screen, each on its own row?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_vlm_walking_modes_list",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_walking_mode_card_vlm",
+ "screenshot": "interaction_vlm_walking_mode_card_vlm.png",
+ "assertion": "Does each walking-mode card show a bold mode name (such as 'Walking(active)' or 'Running') together with a line reading 'Step length:' followed by a number and the word 'meters'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_vlm_walking_mode_card",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_context_menu_vlm",
+ "screenshot": "interaction_vlm_context_menu_vlm.png",
+ "assertion": "Is a small pop-up context menu shown listing text options including 'Set as active' and 'Learn'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_vlm_context_menu",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_correct_steps_dialog_vlm",
+ "screenshot": "interaction_vlm_correct_steps_dialog_vlm.png",
+ "assertion": "Is a dialog shown titled 'Correct steps' containing a numeric input field and two text buttons labelled 'CANCEL' and 'SAVE'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_vlm_correct_steps_dialog",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_summary_popup_vlm",
+ "screenshot": "interaction_vlm_summary_popup_vlm.png",
+ "assertion": "Is a small pop-up menu shown listing 'Walking' and 'Running' each with a round radio button on the right, plus a 'Correct steps' option, and is exactly one radio button filled in (selected)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_vlm_summary_popup",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_help_expanded_vlm",
+ "screenshot": "interaction_vlm_help_expanded_vlm.png",
+ "assertion": "Under the 'Overview' heading of this help list, is a paragraph of descriptive body text now shown (the 'Overview' topic is expanded)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_vlm_help_expanded",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_vlm_training_live_vlm",
+ "screenshot": "interaction_vlm_training_live_vlm.png",
+ "assertion": "Does this training screen show live workout stats — a duration timer near the top and figures for distance, velocity, calories and steps — above a full-width 'END TRAINING NOW' button?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_vlm_training_live",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_chart_plotted_vlm",
+ "screenshot": "computation_chart_plotted_vlm.png",
+ "assertion": "Does the lower card show a line chart with a plotted line and round data points across a grid (not an empty or blank graph)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_chart_plotted",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_summary_numbers_vlm",
+ "screenshot": "computation_summary_numbers_vlm.png",
+ "assertion": "In the upper summary card, is a numeric step count shown as a large number next to the word 'Steps', with a distance value and a unit (m or km) below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "computation_summary_numbers",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_chart_distance_type_vlm",
+ "screenshot": "computation_chart_distance_type_vlm.png",
+ "assertion": "Does the lower card display a chart (a graph area with axes/grid and plotted data), consistent with showing distance data?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "computation_chart_distance_type",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_pause_icon_vlm",
+ "screenshot": "states_pause_icon_vlm.png",
+ "assertion": "Look at the icon button in the top-right of the blue toolbar. Is it now a single right-pointing 'play' / triangle style icon (indicating detection is paused and can be continued) rather than two pause bars?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_pause_icon",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_tab_day_highlight_vlm",
+ "screenshot": "states_tab_day_highlight_vlm.png",
+ "assertion": "Among the three tabs DAY, WEEK, MONTH at the top, is 'DAY' the highlighted/selected one (its label a different, brighter colour such as yellow AND with a coloured underline indicator beneath it) while WEEK and MONTH are plain white with no underline?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_tab_day_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_tab_week_highlight_vlm",
+ "screenshot": "states_tab_week_highlight_vlm.png",
+ "assertion": "Among the three tabs DAY, WEEK, MONTH at the top, is 'WEEK' now the highlighted/selected one (brighter/different colour label AND a coloured underline indicator beneath WEEK) instead of DAY?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_tab_week_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_walking_radio_default_vlm",
+ "screenshot": "states_walking_radio_default_vlm.png",
+ "assertion": "In this popup listing walking modes, is the round radio button next to 'Walking' filled in (a solid coloured/blue dot = selected) while the radio next to 'Running' is an empty hollow circle?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_walking_radio_default",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_running_radio_vlm",
+ "screenshot": "states_running_radio_vlm.png",
+ "assertion": "In this walking-modes popup, is the round radio button next to 'Running' now filled in (solid coloured/blue dot = selected)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_running_radio",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_chart_steps_radio_vlm",
+ "screenshot": "states_chart_steps_radio_vlm.png",
+ "assertion": "In this popup listing chart data types, is the round radio button next to 'Steps' filled in (solid coloured/blue dot = selected) while 'Distance' and 'Calories' show empty hollow circles?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_chart_steps_radio",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_distance_measuring_vlm",
+ "screenshot": "states_distance_measuring_vlm.png",
+ "assertion": "Does the large button at the bottom of the screen read 'STOP DISTANCE MEASUREMENT' (a measurement is in progress) rather than 'START DISTANCE MEASUREMENT'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "states_distance_measuring",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_settings_switches_vlm",
+ "screenshot": "states_settings_switches_vlm.png",
+ "assertion": "In this settings list, are there several ON/OFF toggle SWITCHES aligned down the RIGHT-hand edge of the rows (rounded pill toggles), one per switch preference?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "states_settings_switches",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_settings_permanent_on_vlm",
+ "screenshot": "states_settings_permanent_on_vlm.png",
+ "assertion": "Is the 'Permanent step counter' toggle in the ON position?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_settings_permanent_on",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_about_logo_block_vlm",
+ "screenshot": "text_about_logo_block_vlm.png",
+ "assertion": "Is the title text 'Privacy Friendly Pedometer' shown near the top of this screen with an app icon or logo image directly above or beside it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_about_logo_block",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_help_list_layout_vlm",
+ "screenshot": "text_help_list_layout_vlm.png",
+ "assertion": "Is this screen a vertically stacked list of collapsed section headers (the first is 'Overview'), each row showing an expand/collapse chevron or arrow on its right side?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "text_help_list_layout",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/LICENSE.md b/android/secuso-privacy-friendly-sudoku/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..0d86464d86fee840c2c8cb71042195815e7e5192
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/LICENSE.md
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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.
+
+ Privacy Friendly App for playing Sudoku.
+ Copyright (C) 2016-2018 Christopher Beckmann and Timm Lippert
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Privacy Friendly Apps Copyright (C) 2016-2018 Christopher Beckmann and Timm Lippert
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/android/secuso-privacy-friendly-sudoku/instance.json b/android/secuso-privacy-friendly-sudoku/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..506d27575e3e6696ba2267c084348dbc62c94be2
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/secuso-privacy-friendly-sudoku",
+ "platform": "android",
+ "repo": "https://github.com/SecUSo/privacy-friendly-sudoku",
+ "commit": "17fa5880ef6c81f6da52617dc9ea794a452f5568",
+ "patches": [],
+ "package": "org.secuso.privacyfriendlysudoku",
+ "license": null
+}
diff --git a/android/secuso-privacy-friendly-sudoku/reference/launch.sh b/android/secuso-privacy-friendly-sudoku/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_computation_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..99f5e376c907a325ed5f0802afcfe45a7cfaca21
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_computation_eval.json
@@ -0,0 +1,222 @@
+{
+ "module": "computation",
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 20,
+ "depth_ge1": 6,
+ "depth_ge2": 0,
+ "value": 20,
+ "vlm_fine": 9
+ },
+ "results": [
+ {
+ "test": "computation_difficulty_easy",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "difficultyText='Easy'"
+ },
+ {
+ "test": "computation_difficulty_moderate",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "difficultyText='Moderate'"
+ },
+ {
+ "test": "computation_difficulty_hard",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "difficultyText='Hard'"
+ },
+ {
+ "test": "computation_difficulty_challenge",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "difficultyText='Challenge'"
+ },
+ {
+ "test": "computation_difficulty_challenge_stars_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are all four stars of the difficulty rating bar filled solid blue (fully coloured, not grey outlines)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Are all four stars of the difficulty rating bar filled solid blue (fully coloured, not grey outlines)?",
+ "tag": "color"
+ },
+ {
+ "test": "computation_difficulty_easy_stars_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the difficulty rating bar, is exactly ONE star filled solid blue while the remaining three stars are grey?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the difficulty rating bar, is exactly ONE star filled solid blue while the remaining three stars are grey?",
+ "tag": "color"
+ },
+ {
+ "test": "computation_difficulty_moderate_stars_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the difficulty rating bar, are exactly TWO stars filled solid blue while the other two stars are grey?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the difficulty rating bar, are exactly TWO stars filled solid blue while the other two stars are grey?",
+ "tag": "color"
+ },
+ {
+ "test": "computation_difficulty_hard_stars_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the difficulty rating bar, are exactly THREE stars filled solid blue while one star is grey?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the difficulty rating bar, are exactly THREE stars filled solid blue while one star is grey?",
+ "tag": "color"
+ },
+ {
+ "test": "computation_levelcount_format",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "level_count matches 'Levels available: '"
+ },
+ {
+ "test": "computation_levelcount_recomputes",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "level_count differs Easy vs Challenge"
+ },
+ {
+ "test": "computation_carousel_default_9x9",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "section_label='Sudoku 9x9'"
+ },
+ {
+ "test": "computation_carousel_right_12x12",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "section_label='Sudoku 12x12'"
+ },
+ {
+ "test": "computation_carousel_right_16x16",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "section_label='Sudoku 16x16'"
+ },
+ {
+ "test": "computation_carousel_left_back_12x12",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "section_label='Sudoku 12x12'"
+ },
+ {
+ "test": "computation_place_top_1_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 1?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 1?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_place_top_9_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 9?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 9?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_place_top_5_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 5?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 5?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_place_top_7_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 7?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do three or more cells in the TOP ROW (the uppermost horizontal line) of the Sudoku grid display the digit 7?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_place_leftcol_1_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do three or more cells in the LEFT-MOST vertical column of the Sudoku grid display the digit 1?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do three or more cells in the LEFT-MOST vertical column of the Sudoku grid display the digit 1?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_place_persist_9_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the digit 9 clearly written inside multiple cells of the top row of the Sudoku grid?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is the digit 9 clearly written inside multiple cells of the top row of the Sudoku grid?",
+ "tag": "content"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_interaction_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..29e7596dd291f2c139be84edfd9858ce461bd3b0
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_interaction_eval.json
@@ -0,0 +1,195 @@
+{
+ "module": "interaction",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.4286,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 17,
+ "depth_ge2": 4,
+ "value": 11,
+ "vlm_fine": 1
+ },
+ "results": [
+ {
+ "test": "interaction_create_value_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_edit_value_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there now THREE OR MORE cells each showing the large digit 8?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there now THREE OR MORE cells each showing the large digit 8?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_create_and_edit",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "top row shows many 5s, then many 8s after re-entry"
+ },
+ {
+ "test": "interaction_undo_removes_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?' A=NO expect=NO",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM NO: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 5?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_redo_restores_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there again THREE OR MORE cells each showing the large digit 5?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there again THREE OR MORE cells each showing the large digit 5?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_delete_placed7_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_delete_cleared_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?' A=NO expect=NO",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM NO: In the TOP row of this Sudoku 9x9 grid, are there THREE OR MORE cells each showing the large digit 7?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_delete_clears",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "top row shows many 7s, then none after delete"
+ },
+ {
+ "test": "interaction_note_multi_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, do MULTIPLE cells contain SMALL corner pencil-mark notes showing both the digit 3 and the digit 5 (tiny marks in the cell corners, not one big centered digit)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, do MULTIPLE cells contain SMALL corner pencil-mark notes showing both the digit 3 and the digit 5 (tiny marks in the cell corners, not one big centered digit)?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_note_delete_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are the cells now free of SMALL corner pencil-mark notes (no tiny 3/5 marks left in the empty cells)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are the cells now free of SMALL corner pencil-mark notes (no tiny 3/5 marks left in the empty cells)?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_two_placements_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this Sudoku 9x9 grid, does the TOP row contain multiple cells showing the large digit 1, AND the SECOND row (just below it) contain multiple cells showing the large digit 2 — i.e. two different digits in two different rows?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In this Sudoku 9x9 grid, does the TOP row contain multiple cells showing the large digit 1, AND the SECOND row (just below it) contain multiple cells showing the large digit 2 — i.e. two different digits in two different rows?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_two_placements",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row0 has many 1s and row1 has many 2s"
+ },
+ {
+ "test": "interaction_redo_no_undo_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the TOP row of this Sudoku 9x9 grid, are there still THREE OR MORE cells each showing the large digit 4?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the TOP row of this Sudoku 9x9 grid, are there still THREE OR MORE cells each showing the large digit 4?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_multi_saved_games",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": ">=2 saved-game rows (saw 2)"
+ },
+ {
+ "test": "interaction_persist_after_kill",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "saved game persisted after kill (saw 1 row(s))"
+ },
+ {
+ "test": "interaction_resume_saved_game",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "LoadGame row -> GameActivity (resumed)"
+ },
+ {
+ "test": "interaction_longpress_menu",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "context menu/dialog appeared after long-press on a saved row"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_navigation_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..bf26223183e870fcd843789f7a8015adf8c71743
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_navigation_eval.json
@@ -0,0 +1,227 @@
+{
+ "module": "navigation",
+ "total": 21,
+ "passed": 21,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 15,
+ "passed": 15,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 6,
+ "liveness": 0,
+ "interactive": 15,
+ "depth_ge1": 15,
+ "depth_ge2": 10,
+ "value": 0,
+ "vlm_fine": 1
+ },
+ "results": [
+ {
+ "test": "nav_reach_daily",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Daily Sudoku' title appeared and home 'NEW GAME' left the surface"
+ },
+ {
+ "test": "nav_reach_daily_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this Daily Sudoku screen show, on the left, a preview grid with a difficulty label and stars under it, and on the right a stats block listing hints / completed games / total time?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this Daily Sudoku screen show, on the left, a preview grid with a difficulty label and stars under it, and on the right a stats block listing hints / completed games / total time?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_highscore",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Highscore' title appeared and home 'NEW GAME' left the surface"
+ },
+ {
+ "test": "nav_reach_highscore_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this Highscore screen show a top row of game-size tabs (like SUDOKU 6X6 / 9X9 / 12X12 / 16X16) and below a table of difficulty rows (Easy, Moderate, Hard, Challenge) with time columns?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this Highscore screen show a top row of game-size tabs (like SUDOKU 6X6 / 9X9 / 12X12 / 16X16) and below a table of difficulty rows (Easy, Moderate, Hard, Challenge) with time columns?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Settings' title appeared (toggle Switches present) and home 'NEW GAME' left"
+ },
+ {
+ "test": "nav_reach_help",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Help' title appeared and home 'NEW GAME' left the surface"
+ },
+ {
+ "test": "nav_reach_about",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'About' appeared with app name / 'Version:' label; home 'NEW GAME' left"
+ },
+ {
+ "test": "nav_reach_tutorial",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Tutorial 'Welcome!' slide appeared (SKIP/NEXT present); home 'NEW GAME' left"
+ },
+ {
+ "test": "nav_reach_tutorial_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this a full-screen intro/tutorial slide with a solid blue background, a large 'Welcome!' heading, an app logo in the middle, and SKIP and NEXT buttons at the bottom corners?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is this a full-screen intro/tutorial slide with a solid blue background, a large 'Welcome!' heading, an app logo in the middle, and SKIP and NEXT buttons at the bottom corners?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_game",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Top surface flipped MainActivity->GameActivity; 'NEW GAME' left the live screen"
+ },
+ {
+ "test": "nav_reach_game_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a 9x9 Sudoku grid of square cells shown filling most of the screen, with a number pad of digit buttons 1 to 9 below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a 9x9 Sudoku grid of square cells shown filling most of the screen, with a number pad of digit buttons 1 to 9 below it?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_import_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Import dialog 'IMPORT'/'CANCEL' buttons appeared over the drawer/menu"
+ },
+ {
+ "test": "nav_reach_import_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a white modal dialog box shown centered over a dimmed background, asking to enter the link of the sudoku to import, with CANCEL and IMPORT buttons at the bottom-right?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a white modal dialog box shown centered over a dimmed background, asking to enter the link of the sudoku to import, with CANCEL and IMPORT buttons at the bottom-right?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_import_dialog_cancel_returns",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After CANCEL: home 'NEW GAME' reappeared and dialog 'IMPORT' left"
+ },
+ {
+ "test": "nav_reach_continue",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Continue Game' title appeared with a saved 'Sudoku 9x9' row; home 'NEW GAME' left"
+ },
+ {
+ "test": "nav_reach_continue_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this Continue Game screen show a vertical list of saved-game rows, each with a small grid thumbnail on the left, a 'Sudoku 9x9' label with stars, and a time on the right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this Continue Game screen show a vertical list of saved-game rows, each with a small grid thumbnail on the left, a 'Sudoku 9x9' label with stars, and a time on the right?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_continue_row_resumes_game",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Saved-row tap flipped list->GameActivity; 'Continue Game' title left"
+ },
+ {
+ "test": "nav_back_settings_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "One BACK popped Settings: home 'NEW GAME' reappeared and 'Settings' left"
+ },
+ {
+ "test": "nav_back_about_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "One BACK popped About: home 'NEW GAME' reappeared and 'About' left"
+ },
+ {
+ "test": "nav_back_daily_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "One BACK popped Daily Sudoku: home 'NEW GAME' reappeared and 'Daily Sudoku' left"
+ },
+ {
+ "test": "nav_chain_settings_back_about",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "drawer->Settings, BACK to home, drawer->About: 'About' appeared, 'NEW GAME' gone"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_states_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..98a14482f8375bfc25a1738be1bcecf59396f64a
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_states_eval.json
@@ -0,0 +1,242 @@
+{
+ "module": "states",
+ "total": 22,
+ "passed": 22,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.2,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 22,
+ "depth_ge1": 22,
+ "depth_ge2": 0,
+ "value": 2,
+ "vlm_fine": 11
+ },
+ "results": [
+ {
+ "test": "states_deactivate_timer_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Deactivate Timer checked false->true"
+ },
+ {
+ "test": "states_timer_reset_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Timer Reset checked true->false"
+ },
+ {
+ "test": "states_timer_reset_roundtrip",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Timer Reset checked true->false->true"
+ },
+ {
+ "test": "states_note_deletion_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Note deletion checked true->false"
+ },
+ {
+ "test": "states_keep_screen_on_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Keep Screen On checked true->false"
+ },
+ {
+ "test": "states_dark_theme_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Dark Theme checked false->true; screen repaints dark"
+ },
+ {
+ "test": "states_dark_theme_toggle_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the screen background very dark (near-black) with light coloured text, i.e. a dark theme?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the screen background very dark (near-black) with light coloured text, i.e. a dark theme?",
+ "tag": "color"
+ },
+ {
+ "test": "states_dark_theme_disables_auto",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Automatically by system' enabled true->false when Dark Theme ON"
+ },
+ {
+ "test": "states_deactivate_timer_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Deactivate Timer persisted checked=true after process death"
+ },
+ {
+ "test": "states_dark_theme_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dark Theme persisted checked=true after process death"
+ },
+ {
+ "test": "states_stats_tab_selected",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "tab selection Sudoku 6x6->Sudoku 9x9"
+ },
+ {
+ "test": "states_stats_tab_selected_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the row of tabs near the top (SUDOKU 6X6 / 9X9 / 12X12 / 16X16), is the 'SUDOKU 9X9' tab the highlighted/selected one (brighter text with an underline indicator beneath it)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the row of tabs near the top (SUDOKU 6X6 / 9X9 / 12X12 / 16X16), is the 'SUDOKU 9X9' tab the highlighted/selected one (brighter text with an underline indicator beneath it)?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_undo_before_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it GREYED-OUT / disabled (grey background), rather than blue?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it GREYED-OUT / disabled (grey background), rather than blue?",
+ "tag": "color"
+ },
+ {
+ "test": "states_undo_enable_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it now BLUE / enabled (blue background), rather than grey?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the bottom-left special button (a curved arrow pointing LEFT, the undo button). Is it now BLUE / enabled (blue background), rather than grey?",
+ "tag": "color"
+ },
+ {
+ "test": "states_redo_before_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it GREYED-OUT / disabled (grey background), rather than blue?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it GREYED-OUT / disabled (grey background), rather than blue?",
+ "tag": "color"
+ },
+ {
+ "test": "states_redo_enable_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it now BLUE / enabled (blue background), rather than grey?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the special button that is a curved arrow pointing RIGHT (the redo button, second from the left in the bottom special-button row). Is it now BLUE / enabled (blue background), rather than grey?",
+ "tag": "color"
+ },
+ {
+ "test": "states_note_off_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the rightmost special button in the bottom row (a pencil icon, the note toggle). Is it in its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the rightmost special button in the bottom row (a pencil icon, the note toggle). Is it in its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?",
+ "tag": "color"
+ },
+ {
+ "test": "states_note_on_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it now HIGHLIGHTED with a YELLOW / gold border around it (note mode ON)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it now HIGHLIGHTED with a YELLOW / gold border around it (note mode ON)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_note_off_again_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it back to its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the rightmost special button in the bottom row (the pencil / note toggle). Is it back to its NORMAL state — a plain blue button with a black border and NO yellow/gold highlight border?",
+ "tag": "color"
+ },
+ {
+ "test": "states_cell_none_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the sudoku board grid. Are ALL the cells plain white with NO cell highlighted green and NO row or column highlighted yellow?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the sudoku board grid. Are ALL the cells plain white with NO cell highlighted green and NO row or column highlighted yellow?",
+ "tag": "color"
+ },
+ {
+ "test": "states_cell_select_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the sudoku board grid. Is there a cell highlighted GREEN whose entire row and entire column are highlighted YELLOW?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the sudoku board grid. Is there a cell highlighted GREEN whose entire row and entire column are highlighted YELLOW?",
+ "tag": "color"
+ },
+ {
+ "test": "states_samenumber_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the sudoku board grid. Are MULTIPLE cells that contain the same digit highlighted with an ORANGE / gold background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the sudoku board grid. Are MULTIPLE cells that contain the same digit highlighted with an ORANGE / gold background?",
+ "tag": "color"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_structure_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..5dd4c7c5a32c529e6bc544ef1e71ff2fc174f675
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_structure_eval.json
@@ -0,0 +1,173 @@
+{
+ "module": "structure",
+ "total": 15,
+ "passed": 15,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.6667,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 5,
+ "liveness": 0,
+ "interactive": 10,
+ "depth_ge1": 8,
+ "depth_ge2": 0,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_toolbar_host",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_main_controls",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_drawer_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "CheckedTextView 0->8 when drawer opens, back to 0 on close"
+ },
+ {
+ "test": "structure_import_dialog_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "EditText 0->1 when Import dialog opens, back to 0 on CANCEL"
+ },
+ {
+ "test": "structure_settings_switch_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Settings surface adds a column of ~7 Switch rows (menu has 0)"
+ },
+ {
+ "test": "structure_stats_rows_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Stats surface has 4 difficulty rows + 4 game-type selectors"
+ },
+ {
+ "test": "structure_tutorial_pager_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Tutorial surface adds SKIP + NEXT pager controls"
+ },
+ {
+ "test": "structure_game_surface_flip",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Top surface flips MainActivity->GameActivity; menu subtree leaves the tree"
+ },
+ {
+ "test": "structure_game_surface_flip_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a 9x9 Sudoku grid of square cells (nine rows and nine columns divided into 3x3 blocks) filling most of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a 9x9 Sudoku grid of square cells (nine rows and nine columns divided into 3x3 blocks) filling most of the screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_game_numberpad_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Below the Sudoku grid, is there a row-based number pad showing the digit buttons 1 through 9?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Below the Sudoku grid, is there a row-based number pad showing the digit buttons 1 through 9?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_game_specialbar_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='At the very bottom of the screen, below the number pad, is there a horizontal bar containing several small icon buttons?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: At the very bottom of the screen, below the number pad, is there a horizontal bar containing several small icon buttons?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_game_toolbar_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the top toolbar of this Sudoku game, is the difficulty shown as a small row of star icons?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the top toolbar of this Sudoku game, is the difficulty shown as a small row of star icons?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_main_preview_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this main menu, is there a preview image of a square Sudoku grid (a grid of cells arranged in a square) above the difficulty text?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: On this main menu, is there a preview image of a square Sudoku grid (a grid of cells arranged in a square) above the difficulty text?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_main_stars_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this main menu, near the difficulty label, is the difficulty level shown as a horizontal row of star-shaped icons?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: On this main menu, near the difficulty label, is the difficulty level shown as a horizontal row of star-shaped icons?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_testgen_kit.py b/android/secuso-privacy-friendly-sudoku/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/android_text_eval.json b/android/secuso-privacy-friendly-sudoku/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..30f671a2e18883a1333eeeeba20e479ae67946d4
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/android_text_eval.json
@@ -0,0 +1,293 @@
+{
+ "module": "text",
+ "total": 29,
+ "passed": 29,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 29,
+ "passed": 29,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 0,
+ "passed": 0,
+ "failed": 0,
+ "pass_rate": 0
+ },
+ "vlm_ratio": 0.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 29,
+ "depth_ge1": 21,
+ "depth_ge2": 0,
+ "value": 24,
+ "vlm_fine": 0
+ },
+ "results": [
+ {
+ "test": "text_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "toolbar title == 'Sudoku'"
+ },
+ {
+ "test": "text_play_button_label",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "playButton label == 'NEW GAME'"
+ },
+ {
+ "test": "text_continue_button_label",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "continueButton label == 'CONTINUE GAME'"
+ },
+ {
+ "test": "text_level_count_format",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "level_count matches ^Levels available: \\d+$"
+ },
+ {
+ "test": "text_section_label_carousel_right",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "section_label 'Sudoku 9x9' -> 'Sudoku 12x12'"
+ },
+ {
+ "test": "text_section_label_carousel_16",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "section_label 'Sudoku 9x9' -> 'Sudoku 16x16'"
+ },
+ {
+ "test": "text_difficulty_label_easy",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "difficultyText 'Moderate' -> 'Easy'"
+ },
+ {
+ "test": "text_difficulty_label_challenge",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "difficultyText 'Moderate' -> 'Challenge'"
+ },
+ {
+ "test": "text_drawer_items_core",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "drawer items: Main Menu, Daily Sudoku, Import Sudoku, Highscore"
+ },
+ {
+ "test": "text_drawer_items_secondary",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "drawer items: Tutorial, Settings, Help, About"
+ },
+ {
+ "test": "text_daily_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Daily screen title == 'Daily Sudoku'"
+ },
+ {
+ "test": "text_daily_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "labels: Used hints, Completed games, Total time played:"
+ },
+ {
+ "test": "text_daily_time_format",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "numb_of_total_time matches ^\\d{2}:\\d{2}:\\d{2}$"
+ },
+ {
+ "test": "text_stats_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Stats screen title == 'Highscore'"
+ },
+ {
+ "test": "text_stats_difficulty_rows",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "rows: Easy, Moderate, Hard, Challenge"
+ },
+ {
+ "test": "text_stats_stat_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "first_av_text 'Ø-time:', first_min_text 'Best time:'"
+ },
+ {
+ "test": "text_help_summaries",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Help: 'Undoes the last action', 'Redoes the last undone action'"
+ },
+ {
+ "test": "text_help_titles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Help titles: Hint button, Delete button, Note toggle button"
+ },
+ {
+ "test": "text_about_appname",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "appName == 'Privacy Friendly Sudoku'"
+ },
+ {
+ "test": "text_about_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "textFieldVersion 'Version:', textFieldAuthor 'Authors:'"
+ },
+ {
+ "test": "text_about_links",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "secusoWebsite 'SECUSO-Website', githubURL 'Github-Repo'"
+ },
+ {
+ "test": "text_import_prompt",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "message == 'Enter the link of the sudoku you wish to import:'"
+ },
+ {
+ "test": "text_import_buttons",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "buttons 'CANCEL' and 'IMPORT'"
+ },
+ {
+ "test": "text_tutorial_welcome",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "slide 1: 'Welcome!' and 'Welcome to Privacy Friendly Sudoku!'"
+ },
+ {
+ "test": "text_tutorial_buttons",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "buttons 'SKIP' and 'NEXT'"
+ },
+ {
+ "test": "text_tutorial_next_slide",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "slide heading changes 'Welcome!' -> next slide heading"
+ },
+ {
+ "test": "text_loadgame_gametype",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "a saved row shows gametype 'Sudoku 9x9'"
+ },
+ {
+ "test": "text_loadgame_time_format",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "loadgame_listentry_timeplayed matches ^\\d{2}:\\d{2}:\\d{2}$"
+ },
+ {
+ "test": "text_loadgame_relative_time",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "loadgame_listentry_lasttimeplayed contains 'ago'/'minute'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/tests/conftest.py b/android/secuso-privacy-friendly-sudoku/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/secuso-privacy-friendly-sudoku/tests/requirements.txt b/android/secuso-privacy-friendly-sudoku/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_computation.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..43803966c1df3a60fb97f5b040363e024ef6b145
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_computation.py
@@ -0,0 +1,539 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — Privacy Friendly Sudoku.
+
+CORE FUNCTION = the deterministic input->output surfaces that render in the view
+tree on the MAIN MENU (the GameActivity board/keypad is a custom canvas and is
+owned by the interaction lane; only 1 minimal VLM here touches the canvas).
+
+Everything asserted below was OBSERVED on the running original app, never derived
+from source. Ground-truth observations (fresh restart => MainActivity defaults):
+
+ section_label = "Sudoku 9x9" difficultyText = "Moderate"
+ level_count = "Levels available: 4"
+
+ GAME TYPE (section_label) — ordered list, CLAMPED at both ends (does NOT wrap):
+ Sudoku 6x6 < Sudoku 9x9 < Sudoku 12x12 < Sudoku 16x16
+ arrow_right advances toward 16x16 (clamps there); arrow_left toward 6x6.
+ DIFFICULTY (difficultyBar = a RatingBar) — tapping at an x-fraction of the bar
+ selects a rating: Easy / Moderate / Hard / Challenge. circleButton (a
+ CheckBox) selects the separate "Custom" difficulty.
+ level_count = "Levels available: N" — a DERIVED count that changes with the
+ (type, difficulty) selection. Observed at 9x9: Easy=6, Moderate=4, Hard=3,
+ Challenge=9; at Moderate: 9x9=4, 12x12=5, 16x16=0. N depends on the
+ generator, so assert FORMAT + that it changes, never a fixed N.
+ Import dialog: one EditText echoes typed text verbatim; IMPORT / CANCEL buttons.
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+# Observed game-type order (clamped, no wrap). Confirmed by cycling on the device.
+TYPE_ORDER = ["Sudoku 6x6", "Sudoku 9x9", "Sudoku 12x12", "Sudoku 16x16"]
+LEVELS_RE = re.compile(r"Levels\s+available:\s*(\d+)", re.IGNORECASE)
+
+
+# ── tiny observers (all read a FRESH ui() each call) ────────────────────────────
+def _text_of(rid):
+ n = node_by_id(ui(), rid)
+ return (n.get("text", "").strip() if n else "")
+
+
+def section_label():
+ return _text_of("section_label")
+
+
+def difficulty_text():
+ return _text_of("difficultyText")
+
+
+def level_count_text():
+ return _text_of("level_count")
+
+
+def level_count_n():
+ """Integer N out of 'Levels available: N', or None if unparseable."""
+ m = LEVELS_RE.search(level_count_text())
+ return int(m.group(1)) if m else None
+
+
+def tap_arrow(rid):
+ return tap_node(node_by_id(ui(), rid))
+
+
+def set_difficulty_via_bar(frac):
+ """Select a rating on the difficultyBar by tapping at x-fraction `frac` of the
+ bar's OWN bounds (derived from the node, never a pixel literal)."""
+ bar = node_by_id(ui(), "difficultyBar")
+ if not bar or "_bounds" not in bar:
+ return False
+ x1, y1, x2, y2 = bar["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(int(x1 + (x2 - x1) * frac), (y1 + y2) // 2)
+ return True
+
+
+def on_main_menu():
+ return node_by_id(ui(), "section_label") is not None
+
+
+def fresh_menu():
+ """Guaranteed-clean MainActivity entry point."""
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# GAME-TYPE cycler (section_label) — value tests, depth=0 (on the menu)
+# ════════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_type_right_from_default",
+ "computation_type_preview_shape_vlm"))
+def test_type_right_from_default():
+ """arrow_right advances section_label to the SUCCESSOR type (assert the
+ transition initial->successor, robust to whatever the starting type is)."""
+ fresh_menu()
+ if not on_main_menu():
+ record("computation_type_right_from_default", False,
+ "setup_failed: main menu (section_label) not present after restart",
+ depth=0, jump_kind="value", expect="section_label advances one step")
+ else:
+ initial = section_label()
+ idx = TYPE_ORDER.index(initial) if initial in TYPE_ORDER else -1
+ tapped = tap_arrow("arrow_right")
+ after = section_label()
+ if idx < 0:
+ ok, msg = False, (f"behavior_wrong: initial type {initial!r} not in "
+ f"observed order {TYPE_ORDER}")
+ else:
+ expected = TYPE_ORDER[min(idx + 1, len(TYPE_ORDER) - 1)]
+ ok = tapped and after == expected
+ msg = ("" if ok else
+ f"behavior_wrong: from {initial!r} arrow_right gave {after!r}, "
+ f"expected {expected!r}")
+ record("computation_type_right_from_default", ok, msg,
+ depth=0, jump_kind="value",
+ expect="section_label == successor of 'Sudoku 9x9' (=='Sudoku 12x12')")
+ # The grid preview should look like a 12x12 grid after one right-tap from 9x9.
+ vlm_assert("computation_type_preview_shape",
+ "In the game-type selector near the top, a square grid PREVIEW image "
+ "is shown under the size label. Does that preview render as a grid "
+ "subdivided into MANY small cells (a dense 12x12-style grid), rather "
+ "than a coarse 3x3 or single big square?",
+ RESULTS_DIR, tag="shape")
+
+
+@and_test(expects=("computation_type_left_from_default",))
+def test_type_left_from_default():
+ """arrow_left moves section_label to the PREDECESSOR type."""
+ fresh_menu()
+ initial = section_label()
+ idx = TYPE_ORDER.index(initial) if initial in TYPE_ORDER else -1
+ tapped = tap_arrow("arrow_left")
+ after = section_label()
+ if idx < 0:
+ ok, msg = False, f"behavior_wrong: initial type {initial!r} not in {TYPE_ORDER}"
+ else:
+ expected = TYPE_ORDER[max(idx - 1, 0)]
+ ok = tapped and after == expected
+ msg = ("" if ok else
+ f"behavior_wrong: from {initial!r} arrow_left gave {after!r}, "
+ f"expected {expected!r}")
+ record("computation_type_left_from_default", ok, msg,
+ depth=0, jump_kind="value",
+ expect="section_label == predecessor of 'Sudoku 9x9' (=='Sudoku 6x6')")
+
+
+@and_test(expects=("computation_type_right_two_steps",))
+def test_type_right_two_steps():
+ """Two right taps advance two positions in the ordered list (9x9 -> 16x16)."""
+ fresh_menu()
+ initial = section_label()
+ idx = TYPE_ORDER.index(initial) if initial in TYPE_ORDER else -1
+ seq = [initial]
+ tap_arrow("arrow_right"); seq.append(section_label())
+ tap_arrow("arrow_right"); seq.append(section_label())
+ if idx < 0:
+ ok, msg = False, f"behavior_wrong: initial {initial!r} not in {TYPE_ORDER}"
+ else:
+ expected = TYPE_ORDER[min(idx + 2, len(TYPE_ORDER) - 1)]
+ ok = seq[-1] == expected
+ msg = "" if ok else (f"behavior_wrong: two rights from {initial!r} gave "
+ f"{seq}, expected to reach {expected!r}")
+ record("computation_type_right_two_steps", ok, msg,
+ depth=0, jump_kind="value",
+ expect="two arrow_right from 'Sudoku 9x9' -> 'Sudoku 16x16'")
+
+
+@and_test(expects=("computation_type_clamp_at_max",))
+def test_type_clamp_at_max():
+ """OBSERVED: the cycler CLAMPS (does not wrap). From the largest type, further
+ right taps stay put. Advance to the end, tap right again, assert unchanged."""
+ fresh_menu()
+ if not on_main_menu():
+ record("computation_type_clamp_at_max", False,
+ "setup_failed: menu not present", depth=0, jump_kind="value",
+ expect="section_label stays 'Sudoku 16x16' at the max end")
+ return
+ # Drive to the top of the list.
+ for _ in range(len(TYPE_ORDER) + 1):
+ tap_arrow("arrow_right")
+ top = section_label()
+ tap_arrow("arrow_right")
+ still = section_label()
+ expected = TYPE_ORDER[-1]
+ ok = top == expected and still == expected
+ msg = "" if ok else (f"behavior_wrong: at max top={top!r} then right gave "
+ f"{still!r}, expected both {expected!r} (clamp, no wrap)")
+ record("computation_type_clamp_at_max", ok, msg,
+ depth=0, jump_kind="value",
+ expect="at the max end section_label stays 'Sudoku 16x16'")
+
+
+@and_test(expects=("computation_type_clamp_at_min",))
+def test_type_clamp_at_min():
+ """Symmetric clamp at the smallest type via repeated left taps."""
+ fresh_menu()
+ if not on_main_menu():
+ record("computation_type_clamp_at_min", False,
+ "setup_failed: menu not present", depth=0, jump_kind="value",
+ expect="section_label stays 'Sudoku 6x6' at the min end")
+ return
+ for _ in range(len(TYPE_ORDER) + 1):
+ tap_arrow("arrow_left")
+ bottom = section_label()
+ tap_arrow("arrow_left")
+ still = section_label()
+ expected = TYPE_ORDER[0]
+ ok = bottom == expected and still == expected
+ msg = "" if ok else (f"behavior_wrong: at min bottom={bottom!r} then left gave "
+ f"{still!r}, expected both {expected!r} (clamp, no wrap)")
+ record("computation_type_clamp_at_min", ok, msg,
+ depth=0, jump_kind="value",
+ expect="at the min end section_label stays 'Sudoku 6x6'")
+
+
+@and_test(expects=("computation_type_right_then_left_roundtrip",))
+def test_type_right_then_left_roundtrip():
+ """right then left returns section_label to its starting value (inverse ops)."""
+ fresh_menu()
+ start = section_label()
+ tap_arrow("arrow_right")
+ mid = section_label()
+ tap_arrow("arrow_left")
+ back_val = section_label()
+ ok = start in TYPE_ORDER and mid != start and back_val == start
+ msg = "" if ok else (f"behavior_wrong: start={start!r} right->{mid!r} "
+ f"left->{back_val!r}, expected to return to {start!r}")
+ record("computation_type_right_then_left_roundtrip", ok, msg,
+ depth=0, jump_kind="value",
+ expect="right then left returns section_label to 'Sudoku 9x9'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# DIFFICULTY selector (difficultyBar RatingBar + circleButton) — value tests
+# ════════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_difficulty_bar_easy",))
+def test_difficulty_bar_easy():
+ """Tapping the low end of the difficultyBar sets difficultyText to 'Easy'."""
+ fresh_menu()
+ tapped = set_difficulty_via_bar(0.08)
+ got = difficulty_text()
+ ok = tapped and got == "Easy"
+ msg = "" if ok else f"behavior_wrong: bar low-end gave {got!r}, expected 'Easy'"
+ record("computation_difficulty_bar_easy", ok, msg,
+ depth=0, jump_kind="value", expect="difficultyText == 'Easy'")
+
+
+@and_test(expects=("computation_difficulty_bar_challenge",))
+def test_difficulty_bar_challenge():
+ """Tapping the high end of the difficultyBar sets difficultyText to 'Challenge'."""
+ fresh_menu()
+ tapped = set_difficulty_via_bar(0.97)
+ got = difficulty_text()
+ ok = tapped and got == "Challenge"
+ msg = "" if ok else f"behavior_wrong: bar high-end gave {got!r}, expected 'Challenge'"
+ record("computation_difficulty_bar_challenge", ok, msg,
+ depth=0, jump_kind="value", expect="difficultyText == 'Challenge'")
+
+
+@and_test(expects=("computation_difficulty_bar_easy_to_hard",))
+def test_difficulty_bar_easy_to_hard():
+ """A distinct value TRANSITION on the derived difficulty: low end -> 'Easy',
+ then a higher tap -> 'Hard' (the answer 'Hard' is ABSENT before, PRESENT after)."""
+ fresh_menu()
+ set_difficulty_via_bar(0.08)
+ before = difficulty_text()
+ set_difficulty_via_bar(0.6)
+ after = difficulty_text()
+ ok = before == "Easy" and after == "Hard"
+ msg = "" if ok else (f"behavior_wrong: before={before!r} after={after!r}, "
+ f"expected 'Easy' then 'Hard'")
+ record("computation_difficulty_bar_easy_to_hard", ok, msg,
+ depth=0, jump_kind="value",
+ expect="difficultyText goes 'Easy' -> 'Hard' as the bar rating rises")
+
+
+@and_test(expects=("computation_difficulty_custom_checkbox",))
+def test_difficulty_custom_checkbox():
+ """OBSERVED: the circleButton CheckBox selects the separate 'Custom' difficulty
+ (difficultyText becomes 'Custom'), distinct from the four rating levels."""
+ fresh_menu()
+ before = difficulty_text()
+ tapped = tap_node(node_by_id(ui(), "circleButton"))
+ after = difficulty_text()
+ ok = tapped and before != "Custom" and after == "Custom"
+ msg = "" if ok else (f"behavior_wrong: circleButton gave difficultyText "
+ f"{after!r} (was {before!r}), expected 'Custom'")
+ record("computation_difficulty_custom_checkbox", ok, msg,
+ depth=0, jump_kind="value",
+ expect="difficultyText == 'Custom' after tapping circleButton")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# level_count — derived integer count. FORMAT + it CHANGES with the selection.
+# ════════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_level_count_format",))
+def test_level_count_format():
+ """level_count matches 'Levels available: '."""
+ fresh_menu()
+ txt = level_count_text()
+ n = level_count_n()
+ ok = n is not None and n >= 0
+ msg = "" if ok else (f"behavior_wrong: level_count {txt!r} does not match "
+ f"'Levels available: '")
+ record("computation_level_count_format", ok, msg,
+ depth=0, jump_kind="value",
+ expect="level_count matches 'Levels available: N' with N a non-neg int")
+
+
+@and_test(expects=("computation_level_count_changes_by_type",))
+def test_level_count_changes_by_type():
+ """The derived count changes when the game TYPE changes (observed 9x9=4 vs
+ 12x12=5 at Moderate). Assert both are valid ints AND the value differs."""
+ fresh_menu()
+ if not on_main_menu():
+ record("computation_level_count_changes_by_type", False,
+ "setup_failed: menu not present", depth=0, jump_kind="value",
+ expect="level_count N differs between two game types")
+ return
+ n_before = level_count_n()
+ type_before = section_label()
+ tap_arrow("arrow_right") # 9x9 -> 12x12
+ n_after = level_count_n()
+ type_after = section_label()
+ ok = (n_before is not None and n_after is not None
+ and type_before != type_after and n_before != n_after)
+ msg = "" if ok else (f"behavior_wrong: {type_before!r} N={n_before} vs "
+ f"{type_after!r} N={n_after}; expected the derived count "
+ f"to change with the type")
+ record("computation_level_count_changes_by_type", ok, msg,
+ depth=0, jump_kind="value",
+ expect="level_count N differs after arrow_right changes the game type")
+
+
+@and_test(expects=("computation_level_count_changes_by_difficulty",))
+def test_level_count_changes_by_difficulty():
+ """The derived count changes with DIFFICULTY at a fixed type (observed at 9x9:
+ Easy=6 vs Hard=3). Assert both valid ints AND differ across two difficulties."""
+ fresh_menu()
+ if node_by_id(ui(), "difficultyBar") is None:
+ record("computation_level_count_changes_by_difficulty", False,
+ "setup_failed: difficultyBar not present", depth=0, jump_kind="value",
+ expect="level_count N differs between two difficulties")
+ return
+ set_difficulty_via_bar(0.08) # Easy
+ d1, n1 = difficulty_text(), level_count_n()
+ set_difficulty_via_bar(0.6) # Hard
+ d2, n2 = difficulty_text(), level_count_n()
+ ok = (n1 is not None and n2 is not None and d1 != d2 and n1 != n2)
+ msg = "" if ok else (f"behavior_wrong: {d1!r} N={n1} vs {d2!r} N={n2}; "
+ f"expected the derived count to change with difficulty")
+ record("computation_level_count_changes_by_difficulty", ok, msg,
+ depth=0, jump_kind="value",
+ expect="level_count N differs between 'Easy' and 'Hard' at the same type")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# IMPORT dialog — EditText echo (input -> output round-trip). depth=1 (a dialog).
+# ════════════════════════════════════════════════════════════════════════════════
+
+def _open_import_dialog():
+ """Open drawer -> Import Sudoku. Returns (edittext_node_or_None, note)."""
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ if not ham:
+ return None, "setup_failed: navigation drawer button not found"
+ tap_node(ham)
+ settle("tap")
+ item = find_node_ci(ui(), "Import Sudoku")
+ if not item:
+ return None, "setup_failed: 'Import Sudoku' drawer item not found"
+ tap_node(item)
+ and_enter("import_dialog") # crossed one surface (the dialog)
+ settle("tap")
+ ets = find_by_class(ui(), "EditText")
+ if not ets:
+ return None, "setup_failed: no EditText in the Import dialog"
+ return ets[0], ""
+
+
+def _cancel_dialog():
+ """Dismiss the Import dialog via its CANCEL button (NOT hide_keyboard, which
+ can dismiss the dialog itself)."""
+ tap_text(ui(), "CANCEL")
+ settle("tap")
+
+
+@and_test(expects=("computation_import_echo_digits",))
+def test_import_echo_digits():
+ """Typing '12345' into the Import EditText echoes it back verbatim."""
+ fresh_menu()
+ field, note = _open_import_dialog()
+ if not field:
+ record("computation_import_echo_digits", False, note,
+ depth=1, jump_kind="value", expect="Import EditText shows '12345'")
+ return
+ typed = type_text(field, "12345")
+ got = (find_by_class(ui(), "EditText") or [{}])[0].get("text", "").strip()
+ ok = typed and got == "12345"
+ msg = "" if ok else f"behavior_wrong: field shows {got!r}, expected '12345'"
+ record("computation_import_echo_digits", ok, msg,
+ depth=1, jump_kind="value", expect="Import EditText shows '12345'")
+ _cancel_dialog()
+
+
+@and_test(expects=("computation_import_echo_url",))
+def test_import_echo_url():
+ """A URL-like ASCII string round-trips through the Import EditText verbatim."""
+ fresh_menu()
+ field, note = _open_import_dialog()
+ if not field:
+ record("computation_import_echo_url", False, note,
+ depth=1, jump_kind="value",
+ expect="Import EditText shows the typed URL string")
+ return
+ probe = "http://x.co/s?p=42"
+ typed = type_text(field, probe)
+ got = (find_by_class(ui(), "EditText") or [{}])[0].get("text", "").strip()
+ ok = typed and got == probe
+ msg = "" if ok else f"behavior_wrong: field shows {got!r}, expected {probe!r}"
+ record("computation_import_echo_url", ok, msg,
+ depth=1, jump_kind="value",
+ expect="Import EditText shows 'http://x.co/s?p=42'")
+ _cancel_dialog()
+
+
+@and_test(expects=("computation_import_echo_replaced",))
+def test_import_echo_replaced():
+ """Positive+negative on the same field: a value is ABSENT before typing and
+ PRESENT after; then replacing the content shows the NEW value, not the old."""
+ fresh_menu()
+ field, note = _open_import_dialog()
+ if not field:
+ record("computation_import_echo_replaced", False, note,
+ depth=1, jump_kind="value",
+ expect="Import EditText replaced content shows '999'")
+ return
+ empty_before = (find_by_class(ui(), "EditText") or [{}])[0].get("text", "").strip()
+ type_text(field, "12345")
+ first = (find_by_class(ui(), "EditText") or [{}])[0].get("text", "").strip()
+ # clear via the field's own selection: re-tap, select-all, and retype.
+ fresh_field = (find_by_class(ui(), "EditText") or [None])[0]
+ if fresh_field:
+ tap_node(fresh_field)
+ settle("keyboard")
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(len(first) + 2):
+ adb_shell("input", "keyevent", "KEYCODE_DEL")
+ settle("text")
+ field2 = (find_by_class(ui(), "EditText") or [None])[0]
+ type_text(field2, "999") if field2 else None
+ second = (find_by_class(ui(), "EditText") or [{}])[0].get("text", "").strip()
+ ok = ("12345" not in empty_before and first == "12345"
+ and second == "999")
+ msg = "" if ok else (f"behavior_wrong: before={empty_before!r} first={first!r} "
+ f"after-replace={second!r}, expected ''/'12345'/'999'")
+ record("computation_import_echo_replaced", ok, msg,
+ depth=1, jump_kind="value",
+ expect="Import EditText: absent->'12345'->replaced '999'")
+ _cancel_dialog()
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# GAME CANVAS — one minimal VLM (the entered digit is a value computed on canvas).
+# Framed narrowly so it does not overlap the interaction lane's coverage.
+# ════════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_board_grid_shape_vlm",
+ "computation_board_digit_value_vlm"))
+def test_board_canvas_value():
+ """The board + keypad are a custom canvas (invisible to ui()), so the only way
+ to check the value COMPUTED onto the grid is the VLM."""
+ fresh_menu()
+ # Ensure a startable selection (a 9x9 board with a non-zero level count).
+ if section_label() != "Sudoku 9x9":
+ # left-clamp to 6x6 then step right to a known 9x9.
+ for _ in range(len(TYPE_ORDER) + 1):
+ tap_arrow("arrow_left")
+ tap_arrow("arrow_right") # 6x6 -> 9x9
+ set_difficulty_via_bar(0.35) # Moderate (observed N=4 at 9x9)
+ started = tap_node(node_by_id(ui(), "playButton"))
+ settle("launch")
+ settle("tap")
+ on_game = started and "GameActivity" in get_current_activity()
+ if not on_game:
+ record("computation_board_grid_shape_vlm", False,
+ "setup_failed: NEW GAME did not open GameActivity",
+ depth=1, jump_kind="value", tag="shape")
+ record("computation_board_digit_value_vlm", False,
+ "setup_failed: NEW GAME did not open GameActivity",
+ depth=1, jump_kind="value", tag="content")
+ return
+ and_enter("game")
+ # Shape: the board renders as a 9x9 sudoku grid (9 columns/rows, 3x3 blocks).
+ vlm_assert("computation_board_grid_shape",
+ "Does the main area show a square Sudoku board divided into a 9x9 "
+ "grid of cells (nine columns and nine rows, grouped into 3x3 blocks)?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="shape")
+ # Value on canvas: tap an empty cell (upper-left area of the board) then keypad
+ # '1', and check the digit 1 was placed. Coordinates from screen fractions.
+ s = get_screen_info()
+ w, h = s["width"], s["height"]
+ tap(int(w * 0.14), int(h * 0.22)) # a cell near the top-left of the board
+ tap(int(w * 0.125), int(h * 0.72)) # keypad '1' (row1 leftmost) per recon layout
+ settle("tap")
+ vlm_assert("computation_board_digit_value",
+ "On the Sudoku board, does the top-left region now contain the "
+ "large digit '1' entered into a cell (i.e. a 1 was computed and "
+ "placed onto the grid)?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="content")
+
+
+TESTS = [
+ test_type_right_from_default,
+ test_type_left_from_default,
+ test_type_right_two_steps,
+ test_type_clamp_at_max,
+ test_type_clamp_at_min,
+ test_type_right_then_left_roundtrip,
+ test_difficulty_bar_easy,
+ test_difficulty_bar_challenge,
+ test_difficulty_bar_easy_to_hard,
+ test_difficulty_custom_checkbox,
+ test_level_count_format,
+ test_level_count_changes_by_type,
+ test_level_count_changes_by_difficulty,
+ test_import_echo_digits,
+ test_import_echo_url,
+ test_import_echo_replaced,
+ test_board_canvas_value,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_interaction.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..779149f096d403ea2cffb259e6f3e7b60d8896be
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_interaction.py
@@ -0,0 +1,756 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — EFFECT-BY-CONSEQUENCE on user DATA for Privacy Friendly
+Sudoku. Sole owner of long-press and of DATA persistence across process death.
+
+Why almost every game assertion is a VLM check
+ GameActivity's board (SudokuFieldLayout), keypad (SudokuKeyboardLayout) and the
+ bottom special buttons (SudokuSpecialButtonLayout) are custom-drawn Canvas views,
+ and a 1-second timer animation keeps `uiautomator dump` from ever idling there,
+ so `ui()` returns a STALE tree (the menu). On that screen we therefore:
+ * confirm we are on it via get_current_activity() containing "GameActivity"
+ (dumpsys, not the tree),
+ * drive it with COORDINATE taps derived from get_screen_info() fractions
+ (never pixel literals — validated live: board x0~0.088/step_x~0.103,
+ y0~0.212/step_y~0.048; keypad row1 y~0.717 row2 y~0.790; specials y~0.871
+ at x 0.125/0.312/0.499/0.686/0.873 = Undo/Redo/Hint/Delete/Note),
+ * and verify the EFFECT with a screenshot + vlm_assert.
+ Every OTHER surface (menu, Import dialog, LoadGame) renders normally in the tree.
+
+The empty-cell problem, and how it is solved robustly
+ Each NEW GAME loads a DIFFERENT random puzzle, so a fixed cell may be a GIVEN
+ (bold, un-editable — selecting it shows a GREY highlight and ignores digit taps),
+ which made fixed-cell assertions flaky. Observed rendering:
+ * an EMPTY user cell, when selected, turns GREEN; typing a digit fills it.
+ * a GIVEN cell, when selected, turns GREY; typing does nothing.
+ So before typing we SCAN candidate cells and use a NON-recorded call_vlm to find
+ one the screenshot shows selected-GREEN-and-empty, then act on THAT cell and
+ phrase the assertion about "the currently selected green cell" (no fixed
+ coordinate baked into the question). Persistence, where the cell is no longer
+ selected after a resume, is asserted by the cell's 1-indexed (row, column).
+
+Observed ground truth these tests encode (all reproduced on the running original):
+ * tap empty cell -> tap digit N -> the cell renders N (green selection).
+ * Delete (trash) clears the selected user cell (a normal game action, allowed).
+ * enter -> delete -> enter a different digit: the cell holds the LAST digit.
+ * Undo reverts the last entry (cell empties, Redo lights up); Redo restores it.
+ * Note/pencil toggle -> digit taps write several small notes in one cell.
+ * selecting a filled cell whose value repeats highlights the peers GOLD.
+ * a started game is SAVED: after force_stop_and_relaunch(), CONTINUE GAME is
+ enabled and resuming shows the SAME board with the entered value (the killer
+ test an in-memory-only recreation cannot pass).
+ * long-press a LoadGame row -> a delete-confirm dialog appears; we assert it
+ appeared then dismiss with BACK WITHOUT confirming the delete.
+ * the Import dialog EditText echoes typed text and is empty again on reopen.
+
+Failure messages use the taxonomy: setup_failed: / feature_missing: / behavior_wrong:.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Geometry helpers — every coordinate is a FRACTION of the live screen size, so
+# the same file drives a device of any resolution and lint_sources stays clean.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _cell_xy(r, c):
+ """Pixel centre of 9x9 board cell (r, c). Fractions validated on the running
+ original (cell(0,0)~(0.088,0.212); step_x~0.1028, step_y~0.0483)."""
+ s = get_screen_info()
+ x = (0.088 + c * 0.1028) * s["width"]
+ y = (0.212 + r * 0.0483) * s["height"]
+ return int(x), int(y)
+
+
+def _tap_cell(r, c):
+ x, y = _cell_xy(r, c)
+ tap(x, y)
+
+
+def _tap_digit(n):
+ """Tap keypad digit n (1..9). Row1 (1-5) y~0.717, row2 (6-9) y~0.790; the
+ first button starts at x~0.125 with step ~0.187."""
+ s = get_screen_info()
+ if n <= 5:
+ col, yf = n - 1, 0.717
+ else:
+ col, yf = n - 6, 0.790
+ x = (0.125 + col * 0.187) * s["width"]
+ tap(int(x), int(yf * s["height"]))
+
+
+def _tap_special(name):
+ """Tap a bottom special button by name. L->R at y~0.871:
+ undo/redo/hint/delete/note."""
+ s = get_screen_info()
+ xf = {"undo": 0.125, "redo": 0.312, "hint": 0.499,
+ "delete": 0.686, "note": 0.873}[name]
+ tap(int(xf * s["width"]), int(0.871 * s["height"]))
+
+
+def _on_game():
+ return "GameActivity" in get_current_activity()
+
+
+# ── Non-recorded VLM probe used only to LOCATE an editable cell (not an assertion).
+# call_vlm() creates no record and is not part of the fixed 12-record budget. ──
+
+def _vlm_yesno(question):
+ """Screenshot the current screen and ask the judge one YES/NO question, WITHOUT
+ recording anything. Returns True on YES, False otherwise. Used to find an empty
+ board cell — the flaky part of a canvas game — so the recorded assertions stay
+ deterministic."""
+ ss = os.path.join(RESULTS_DIR, "screenshots", "_probe.png")
+ if not screencap(ss):
+ return False
+ prompt = ("Look at this Android app screenshot and answer with ONLY 'YES' or "
+ "'NO'. Do not explain.\n\nQuestion: " + question + "\n\nAnswer:")
+ resp = call_vlm(ss, prompt)
+ if not resp:
+ return False
+ a = resp.strip().upper()
+ import re as _re
+ if a.startswith("YES"):
+ return True
+ if a.startswith("NO"):
+ return False
+ return _re.search(r"\bYES\b", a) is not None and _re.search(r"\bNO\b", a) is None
+
+
+_EMPTY_Q = ("In the 9x9 Sudoku grid, is the currently selected cell (the one with "
+ "a coloured highlight) EMPTY and shown with a GREEN background "
+ "(no digit inside it)?")
+
+# A spread of candidate cells to scan for an editable one. ~60% of Moderate-puzzle
+# cells are empty, so the first candidate usually wins; the spread bounds the worst
+# case and keeps the cells easy for the judge to locate.
+_CANDIDATES = [(0, 0), (4, 4), (8, 8), (2, 6), (6, 2), (0, 4), (4, 0), (8, 4),
+ (4, 8), (2, 2), (6, 6), (0, 8), (8, 0)]
+
+
+def _select_empty_cell(candidates=None):
+ """Tap candidate cells in order until the screenshot shows one selected-GREEN
+ (i.e. empty and editable); leave THAT cell selected and return its (r, c), or
+ None if no candidate was empty. Each miss costs one non-recorded call_vlm."""
+ for (r, c) in (candidates or _CANDIDATES):
+ _tap_cell(r, c)
+ if _vlm_yesno(_EMPTY_Q):
+ return (r, c)
+ return None
+
+
+def _find_empty_cells(n, candidates=None):
+ """Return up to `n` distinct empty (r, c) cells (leaving the last one selected).
+ Used by the multi-cell integrity test."""
+ found = []
+ for (r, c) in (candidates or _CANDIDATES):
+ if len(found) >= n:
+ break
+ _tap_cell(r, c)
+ if _vlm_yesno(_EMPTY_Q):
+ found.append((r, c))
+ return found
+
+
+def _start_new_game():
+ """restart_app() -> tap NEW GAME -> confirm GameActivity. The background
+ generator can leave "Levels available: 0" briefly after a clean start, so if
+ NEW GAME does not advance we wait and retry once. Returns True on the game
+ screen."""
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ for _attempt in range(2):
+ play = node_by_id(ui(), "playButton")
+ if play is None:
+ return False
+ tap_node(play)
+ settle("launch")
+ settle("launch")
+ if _on_game():
+ return True
+ # generator not ready yet — give it time, then retry from the menu
+ settle("launch")
+ settle("launch")
+ return _on_game()
+
+
+def and_enter_game_via_new():
+ """MainActivity NEW GAME -> GameActivity, counting one surface. The board is a
+ stale Canvas so the jump is proven by the activity flip, then and_enter() backs
+ the depth. Returns True on the game screen."""
+ if not _start_new_game():
+ return False
+ and_enter("GameActivity")
+ return True
+
+
+def _vlm_setup_fail(name, msg, *, tag, jump_kind, depth, expect):
+ """Record a `_vlm` case as a FAILURE without calling the VLM API. Used only on
+ setup-failed branches: asking the judge a bogus question there would waste the
+ budget and could spuriously PASS. record() keeps the denominator stable, and a
+ `_vlm` name routes it to the VLM track exactly like a real vlm_assert failure."""
+ record(name if name.endswith("_vlm") else name + "_vlm", False, msg,
+ depth=depth, jump_kind=jump_kind, expect=expect, tag=tag)
+
+
+# ── LoadGame / persistence navigation (tree renders on these surfaces) ──────────
+
+def _ensure_saved_game():
+ """Guarantee a save exists so CONTINUE GAME is enabled. Starts a game, leaves
+ it (BACK creates the save), and returns to a clean menu. Returns True when
+ continueButton reports enabled."""
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ cont = node_by_id(ui(), "continueButton")
+ if cont is not None and cont.get("enabled") == "true":
+ return True
+ if not _start_new_game():
+ return False
+ back() # leaving the game writes a save
+ settle("launch")
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ cont = node_by_id(ui(), "continueButton")
+ return cont is not None and cont.get("enabled") == "true"
+
+
+def and_reach_loadgame():
+ """MainActivity CONTINUE GAME -> LoadGameActivity ("Continue Game" appears,
+ "NEW GAME" gone). Requires a saved game; caller ensures one. Counts one surface."""
+ cont = node_by_id(ui(), "continueButton")
+ if cont is None or cont.get("enabled") != "true":
+ return False
+ return and_reach_surface(cont, "Continue Game", "NEW GAME")
+
+
+def and_reach_resume_game():
+ """LoadGameActivity first row -> GameActivity. The row lives in a ListView and
+ reports no clickable bit, so tap the first card's centre by fraction, then
+ prove the jump by the activity flip. Counts one surface."""
+ s = get_screen_info()
+ if "LoadGameActivity" not in get_current_activity():
+ return False
+ tap(int(0.5 * s["width"]), int(0.19 * s["height"])) # first saved-game card
+ settle("launch")
+ if not _on_game():
+ return False
+ and_enter("GameActivity")
+ return True
+
+
+def _first_loadgame_row():
+ """The first saved-game row node ('Sudoku 9x9' text), for a long-press target."""
+ return find_node(ui(), text="Sudoku 9x9")
+
+
+# ── Import dialog navigation (renders in the tree) ──────────────────────────────
+
+def and_enter_import_dialog():
+ """MainActivity drawer -> Import Sudoku -> the import dialog (its EditText and
+ IMPORT button appear). Counts one surface. Returns True in the dialog."""
+ ham = find_node(ui(), content_desc="Open navigation drawer")
+ if ham is None or not tap_node(ham):
+ return False
+ settle("tap")
+ item = find_node(ui(), text="Import Sudoku")
+ if item is None:
+ return False
+ before = and_showing()
+ if not tap_node(item):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "IMPORT"):
+ return False
+ and_enter("ImportDialog")
+ return True
+
+
+def _import_edittext():
+ return node_by_id(ui(), "ver3_import_sudoku_edit_text")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Enter a value on the board — value entered (VLM content + color)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_enter_value_vlm",
+ "interaction_enter_value_highlight_vlm"))
+def test_enter_value():
+ if not and_enter_game_via_new():
+ m = "setup_failed: could not reach GameActivity via NEW GAME"
+ _vlm_setup_fail("interaction_enter_value", m, tag="content",
+ jump_kind="value", depth=1, expect="selected cell shows 5")
+ _vlm_setup_fail("interaction_enter_value_highlight", m, tag="color",
+ jump_kind="transition", depth=1, expect="selected cell green")
+ return
+ cell = _select_empty_cell()
+ if cell is None:
+ m = "setup_failed: no empty board cell found to type into"
+ _vlm_setup_fail("interaction_enter_value", m, tag="content",
+ jump_kind="value", depth=1, expect="selected cell shows 5")
+ _vlm_setup_fail("interaction_enter_value_highlight", m, tag="color",
+ jump_kind="transition", depth=1, expect="selected cell green")
+ return
+ _tap_digit(5) # fill the selected empty cell with 5
+ vlm_assert("interaction_enter_value",
+ "Does the currently selected Sudoku cell (the one with a coloured "
+ "highlight) contain the digit 5?",
+ expect="YES", depth=1, jump_kind="value", tag="content")
+ vlm_assert("interaction_enter_value_highlight",
+ "Is the currently selected Sudoku cell filled with a GREEN "
+ "background colour (the selected-cell highlight)?",
+ expect="YES", depth=1, jump_kind="transition", tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Same-value highlight state — a distinct rendered colour effect (VLM color)
+# Entering the same digit in TWO empty cells guarantees a peer exists, so the
+# GOLD same-value highlight appears regardless of which puzzle loaded.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_samevalue_highlight_vlm",))
+def test_samevalue_highlight():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_samevalue_highlight",
+ "setup_failed: could not reach GameActivity",
+ tag="color", jump_kind="transition", depth=1,
+ expect="gold same-value cells")
+ return
+ cells = _find_empty_cells(2)
+ if len(cells) < 2:
+ _vlm_setup_fail("interaction_samevalue_highlight",
+ "setup_failed: fewer than two empty cells found",
+ tag="color", jump_kind="transition", depth=1,
+ expect="gold same-value cells")
+ return
+ (r1, c1), (r2, c2) = cells[0], cells[1]
+ _tap_cell(r1, c1)
+ _tap_digit(6) # first 6
+ _tap_cell(r2, c2)
+ _tap_digit(6) # second 6 -> a same-value peer exists
+ vlm_assert("interaction_samevalue_highlight",
+ "Apart from the green selected cell, is there at least one other "
+ "Sudoku cell shown with a GOLD or ORANGE background highlight?",
+ expect="YES", depth=1, jump_kind="transition", tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) Delete a user value — round trip (VLM content)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_delete_value_vlm",))
+def test_delete_value():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_delete_value",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="transition", depth=1,
+ expect="selected cell empty after delete")
+ return
+ if _select_empty_cell() is None:
+ _vlm_setup_fail("interaction_delete_value",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="transition", depth=1,
+ expect="selected cell empty after delete")
+ return
+ _tap_digit(4) # fill the selected cell with 4
+ _tap_special("delete") # clear the selected user cell
+ vlm_assert("interaction_delete_value",
+ "The currently selected Sudoku cell has a green background. Is that "
+ "green cell EMPTY (it shows no digit)?",
+ expect="YES", depth=1, jump_kind="transition", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Multi-step edit: enter -> delete -> enter a DIFFERENT digit; the cell holds
+# the LAST digit. A 3-action dependent sequence a dead echo-shell fails. (VLM)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_edit_replace_vlm",))
+def test_edit_replace():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_edit_replace",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="value", depth=1,
+ expect="selected cell shows 8 after replace")
+ return
+ if _select_empty_cell() is None:
+ _vlm_setup_fail("interaction_edit_replace",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="value", depth=1,
+ expect="selected cell shows 8 after replace")
+ return
+ _tap_digit(4) # step 1: enter 4
+ _tap_special("delete") # step 2: clear it
+ _tap_digit(8) # step 3: enter 8
+ vlm_assert("interaction_edit_replace",
+ "Does the currently selected Sudoku cell now contain the digit 8 "
+ "(and not the digit 4)?",
+ expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Multi-record integrity: three cells, three digits (VLM content, value)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_multi_value_vlm",))
+def test_multi_value_sequence():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_multi_value",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="value", depth=1,
+ expect="three cells show 1,2,3")
+ return
+ cells = _find_empty_cells(3)
+ if len(cells) < 3:
+ _vlm_setup_fail("interaction_multi_value",
+ "setup_failed: fewer than three empty cells found",
+ tag="content", jump_kind="value", depth=1,
+ expect="three cells show 1,2,3")
+ return
+ for (r, c), d in zip(cells, (1, 2, 3)):
+ _tap_cell(r, c)
+ _tap_digit(d)
+ (r1, c1), (r2, c2), (r3, c3) = cells
+ q = ("In the 9x9 Sudoku grid, counting rows from the top (1-9) and columns "
+ "from the left (1-9), does the cell at row {a1}, column {b1} contain 1, "
+ "AND the cell at row {a2}, column {b2} contain 2, AND the cell at row "
+ "{a3}, column {b3} contain 3?").format(
+ a1=r1 + 1, b1=c1 + 1, a2=r2 + 1, b2=c2 + 1, a3=r3 + 1, b3=c3 + 1)
+ vlm_assert("interaction_multi_value", q,
+ expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) Undo then Redo — reverted, then restored (two VLM content)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_undo_vlm", "interaction_redo_vlm"))
+def test_undo_redo():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_undo",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="transition", depth=1,
+ expect="selected cell empty after undo")
+ _vlm_setup_fail("interaction_redo",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="value", depth=1,
+ expect="selected cell shows 3 after redo")
+ return
+ if _select_empty_cell() is None:
+ _vlm_setup_fail("interaction_undo",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="transition", depth=1,
+ expect="selected cell empty after undo")
+ _vlm_setup_fail("interaction_redo",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="value", depth=1,
+ expect="selected cell shows 3 after redo")
+ return
+ _tap_digit(3) # enter 3
+ _tap_special("undo") # revert -> cell empties
+ vlm_assert("interaction_undo",
+ "The currently selected Sudoku cell has a green background. Is that "
+ "green cell EMPTY after the undo (it shows no digit)?",
+ expect="YES", depth=1, jump_kind="transition", tag="content")
+ _tap_special("redo") # restore -> 3 comes back
+ vlm_assert("interaction_redo",
+ "After pressing redo, does the currently selected Sudoku cell "
+ "contain the digit 3 again?",
+ expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) Note (pencil) mode — small pencil notes, distinct from a big value (VLM x2)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_note_mode_vlm", "interaction_note_multiple_vlm"))
+def test_note_mode():
+ if not and_enter_game_via_new():
+ _vlm_setup_fail("interaction_note_mode",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="transition", depth=1,
+ expect="small pencil notes present")
+ _vlm_setup_fail("interaction_note_multiple",
+ "setup_failed: could not reach GameActivity",
+ tag="content", jump_kind="value", depth=1,
+ expect=">=3 small notes in one cell")
+ return
+ # Find an editable cell FIRST (in value mode green marks empties), then switch
+ # to note mode and write several pencil notes into it.
+ if _select_empty_cell() is None:
+ _vlm_setup_fail("interaction_note_mode",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="transition", depth=1,
+ expect="small pencil notes present")
+ _vlm_setup_fail("interaction_note_multiple",
+ "setup_failed: no empty board cell found",
+ tag="content", jump_kind="value", depth=1,
+ expect=">=3 small notes in one cell")
+ return
+ _tap_special("note") # toggle pencil mode ON
+ _tap_digit(1)
+ _tap_digit(2)
+ _tap_digit(3)
+ vlm_assert("interaction_note_mode",
+ "Is there a Sudoku grid cell that shows several SMALL pencil-note "
+ "digits (tiny numbers), rather than one single large digit?",
+ expect="YES", depth=1, jump_kind="transition", tag="content")
+ vlm_assert("interaction_note_multiple",
+ "In the selected (green) Sudoku cell, are there at least three "
+ "small pencil-note digits visible together?",
+ expect="YES", depth=1, jump_kind="value", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) DATA persistence across process death — continueButton flip (rule)
+# The disabled->enabled flip after a game exists, read back on the MENU (which
+# IS in the tree) AFTER a real force-stop+relaunch. An in-memory recreation
+# that forgets the save leaves it disabled.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_persist_continue_enabled",))
+def test_persist_continue_button_enabled():
+ # Start from a virgin DB so the button is provably disabled BEFORE the game.
+ clear_data()
+ launch_app()
+ wait_for_foreground()
+ settle("launch")
+ cont0 = node_by_id(ui(), "continueButton")
+ disabled_before = cont0 is not None and cont0.get("enabled") == "false"
+ if not _start_new_game():
+ record("interaction_persist_continue_enabled", False,
+ "setup_failed: could not start a game to create a save "
+ "(generator may be empty after clear_data)",
+ depth=0, jump_kind="transition",
+ expect="continueButton disabled->enabled across a kill")
+ return
+ # Kill the process WHILE a game exists, relaunch, read the menu tree.
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ settle("launch")
+ cont1 = node_by_id(ui(), "continueButton")
+ enabled_after = cont1 is not None and cont1.get("enabled") == "true"
+ ok = disabled_before and enabled_after
+ record("interaction_persist_continue_enabled", ok,
+ "" if ok else
+ ("behavior_wrong: CONTINUE GAME did not become enabled after a game "
+ "survived process death"
+ if disabled_before else
+ "setup_failed: CONTINUE GAME was not disabled on the virgin database"),
+ depth=0, jump_kind="transition",
+ expect="continueButton enabled=false before, enabled=true after kill")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) DATA persistence across process death — RESUME shows the entered value
+# The killer test: enter a digit in an empty cell, remember its coordinate,
+# kill, CONTINUE -> LoadGame -> resume, and the board still holds that digit at
+# that cell. depth=2 (LoadGame, then GameActivity). VLM content.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_persist_resume_value_vlm",
+ "interaction_persist_resume_board_vlm"))
+def test_persist_resume_value():
+ def _fail(msg, jk="value"):
+ _vlm_setup_fail("interaction_persist_resume_value", msg, tag="content",
+ jump_kind="value", depth=2,
+ expect="resumed cell shows 7")
+ _vlm_setup_fail("interaction_persist_resume_board", msg, tag="content",
+ jump_kind="transition", depth=2,
+ expect="resumed board rendered")
+
+ if not _start_new_game():
+ _fail("setup_failed: could not start a game")
+ return
+ cell = _select_empty_cell()
+ if cell is None:
+ _fail("setup_failed: no empty board cell found to type into")
+ return
+ r, c = cell
+ _tap_digit(7) # distinctive user entry
+ force_stop_and_relaunch() # <-- kill the process
+ wait_for_foreground()
+ settle("launch")
+ # Navigate back to the SAME game: CONTINUE -> LoadGame (depth 1) -> resume
+ # first row (depth 2). Both are proven surface jumps via and_reach_*.
+ if not and_reach_loadgame():
+ _fail("behavior_wrong: CONTINUE GAME not reachable after kill (save lost?)")
+ return
+ if not and_reach_resume_game():
+ _fail("behavior_wrong: could not resume the saved game after kill")
+ return
+ vlm_assert("interaction_persist_resume_value",
+ "In the 9x9 Sudoku grid, counting rows from the top (1-9) and "
+ "columns from the left (1-9), does the cell at row {a}, column {b} "
+ "contain the digit 7?".format(a=r + 1, b=c + 1),
+ expect="YES", depth=2, jump_kind="value", tag="content")
+ vlm_assert("interaction_persist_resume_board",
+ "Does this screen show a fully rendered Sudoku board (a 9x9 grid "
+ "with many digits) together with a number keypad below it?",
+ expect="YES", depth=2, jump_kind="transition", tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (10) LoadGame long-press — sole owner. A context (delete-confirm) dialog appears;
+# assert the transition, then dismiss with BACK WITHOUT confirming delete.
+# depth=2 (LoadGame, then the dialog). Rule (tree renders on this surface).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_longpress_menu",))
+def test_loadgame_longpress():
+ if not _ensure_saved_game():
+ record("interaction_longpress_menu", False,
+ "setup_failed: could not create a saved game to long-press",
+ depth=2, jump_kind="transition",
+ expect="delete-confirm dialog appears on long-press")
+ return
+ if not and_reach_loadgame():
+ record("interaction_longpress_menu", False,
+ "setup_failed: LoadGameActivity not reachable via CONTINUE GAME",
+ depth=1, jump_kind="transition",
+ expect="delete-confirm dialog appears on long-press")
+ return
+ row = _first_loadgame_row()
+ if row is None:
+ record("interaction_longpress_menu", False,
+ "setup_failed: no saved-game row found in LoadGameActivity",
+ depth=1, jump_kind="transition",
+ expect="delete-confirm dialog appears on long-press")
+ return
+ before = and_showing()
+ long_press(row)
+ and_enter("LongPressDialog") # the context dialog is a new surface
+ after = and_showing()
+ # The long-press opens a confirm dialog whose DELETE/CANCEL buttons and the
+ # "delete this save" prompt are new — a real transition. We NEVER tap DELETE.
+ appeared = (and_reach(before, after, "DELETE")
+ or find_node_ci(ui(), "DELETE") is not None)
+ # Dismiss WITHOUT confirming: BACK closes the dialog, leaving the save intact.
+ back()
+ settle("tap")
+ dismissed = find_node_ci(
+ ui(), "Are you sure you want to delete this save?") is None
+ still_there = find_node(ui(), text="Sudoku 9x9") is not None
+ ok = appeared and dismissed and still_there
+ record("interaction_longpress_menu", ok,
+ "" if ok else
+ ("behavior_wrong: long-press did not open a context menu / save was "
+ "not preserved after dismiss"),
+ depth=2, jump_kind="transition",
+ expect="'DELETE' confirm dialog appeared on long-press, dismissed, "
+ "saved 'Sudoku 9x9' row still present")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (11) Import dialog — type into the EditText and read it back from the tree
+# (this dialog renders normally). Interaction-with-data echo. depth=1. Rule.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MARK_IMPORT = "kit_imp_A"
+
+
+@and_test(expects=("interaction_import_echo",))
+def test_import_echo():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ if not and_enter_import_dialog():
+ record("interaction_import_echo", False,
+ "feature_missing: Import dialog not reachable from the drawer",
+ depth=1, jump_kind="value", expect=f"EditText holds {MARK_IMPORT!r}")
+ return
+ field = _import_edittext()
+ if field is None:
+ record("interaction_import_echo", False,
+ "setup_failed: Import dialog has no EditText",
+ depth=1, jump_kind="value", expect=f"EditText holds {MARK_IMPORT!r}")
+ return
+ absent_before = MARK_IMPORT not in (field.get("text", "") or "")
+ type_text(field, MARK_IMPORT)
+ fresh = _import_edittext()
+ present_after = fresh is not None and MARK_IMPORT in (fresh.get("text", "") or "")
+ ok = absent_before and present_after
+ record("interaction_import_echo", ok,
+ "" if ok else
+ "behavior_wrong: Import EditText did not echo the typed marker",
+ depth=1, jump_kind="value",
+ expect=f"Import EditText shows {MARK_IMPORT!r} after typing")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (12) Import dialog — CANCEL round trip: type, CANCEL, reopen -> field is empty
+# again. A multi-step data lifecycle that a dead echo-shell fails. depth=1.
+# NOTE: the CANCEL button is tappable with the keyboard still up (validated),
+# so we do NOT call hide_keyboard() first — the kit's BACK-based dismissal
+# would close the whole dialog and lose the button.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_import_cancel_roundtrip",))
+def test_import_cancel_roundtrip():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ if not and_enter_import_dialog():
+ record("interaction_import_cancel_roundtrip", False,
+ "feature_missing: Import dialog not reachable from the drawer",
+ depth=1, jump_kind="transition",
+ expect="Import EditText empty again after CANCEL + reopen")
+ return
+ field = _import_edittext()
+ if field is None:
+ record("interaction_import_cancel_roundtrip", False,
+ "setup_failed: Import dialog has no EditText",
+ depth=1, jump_kind="transition",
+ expect="Import EditText empty again after CANCEL + reopen")
+ return
+ type_text(field, "kit_imp_B")
+ cancel = node_by_id(ui(), "button2") or find_node_ci(ui(), "CANCEL")
+ if cancel is None or not safe_tap(cancel):
+ record("interaction_import_cancel_roundtrip", False,
+ "setup_failed: CANCEL button not found in Import dialog",
+ depth=1, jump_kind="transition",
+ expect="Import EditText empty again after CANCEL + reopen")
+ return
+ settle("tap")
+ back_on_menu = find_node(ui(), text="NEW GAME") is not None
+ # Reopen the dialog from a fresh drawer; the field must be empty (not persisted).
+ and_reset_depth()
+ reopened = and_enter_import_dialog()
+ field2 = _import_edittext() if reopened else None
+ empty_again = field2 is not None and "kit_imp_B" not in (field2.get("text", "") or "")
+ ok = back_on_menu and reopened and empty_again
+ record("interaction_import_cancel_roundtrip", ok,
+ "" if ok else
+ ("behavior_wrong: CANCEL did not discard the typed text / dialog did "
+ "not reopen empty"),
+ depth=1, jump_kind="transition",
+ expect="CANCEL returned to menu and the reopened Import field is empty")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Registry + entry point
+# ══════════════════════════════════════════════════════════════════════════════
+
+TESTS = [
+ test_enter_value,
+ test_samevalue_highlight,
+ test_delete_value,
+ test_edit_replace,
+ test_multi_value_sequence,
+ test_undo_redo,
+ test_note_mode,
+ test_persist_continue_button_enabled,
+ test_persist_resume_value,
+ test_loadgame_longpress,
+ test_import_echo,
+ test_import_cancel_roundtrip,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_navigation.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f85262daea094992dd49ad1b41e5d53622304229
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_navigation.py
@@ -0,0 +1,555 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — surface REACHABILITY + back-stack integrity for Privacy
+Friendly Sudoku. Sole owner of jump_kind="reach" and of depth>=2 chains.
+
+Every jump is PROVEN with and_reach (target element APPEARED *and* source element
+DISAPPEARED) except the custom-Canvas GameActivity, whose view tree is stale to
+uiautomator — that surface is proven with get_current_activity() flipping to
+GameActivity plus a VLM check that the board actually rendered.
+
+Observed lifecycle quirks that shape these tests:
+ * GameActivity is singleTask; BACK from it returns to the ROOT MainActivity in
+ ONE press even when it was reached via LoadGameActivity (it does NOT unwind
+ back to LoadGame). The depth-2 back-stack test asserts that observed behavior.
+ * The main menu's button "CONTINUE GAME" contains the LoadGame title
+ "Continue Game" as a case-insensitive substring, so it cannot serve as a
+ disappeared-source. LoadGame's unique toolbar affordance "Navigate up" is used
+ as the source for the LoadGame->menu reverse jump instead.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── shared helpers (plain — the and_reach_*/and_enter_* NAME is what the depth
+# audit keys on; the implementation is ours) ──────────────────────────────────
+
+def _open_drawer():
+ """Open the nav drawer by tapping the hamburger; return the fresh tree, or
+ None if the hamburger could not be tapped."""
+ nodes = ui()
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ if ham is None or not tap_node(ham):
+ return None
+ settle("tap")
+ return ui()
+
+
+def and_reach_from_drawer(item_text, target, source):
+ """Open the drawer, find `item_text`, tap it, and return the and_reach verdict
+ (target appeared, source disappeared). Counts one surface via and_reach_surface."""
+ dn = _open_drawer()
+ if dn is None:
+ return False
+ item = find_node(dn, text=item_text) or find_node_ci(dn, item_text)
+ if item is None:
+ return False
+ return and_reach_surface(item, target, source)
+
+
+def and_reach_game():
+ """MainActivity NEW GAME -> GameActivity. The game tree is a stale Canvas, so
+ prove the jump by (a) the MENU source being present before, and (b) the
+ activity flipping to GameActivity. Returns True on a proven reach; counts one
+ surface."""
+ nodes = ui()
+ play = node_by_id(nodes, "playButton")
+ if play is None:
+ return False
+ before = and_showing(nodes)
+ if not any("NEW GAME" in k.upper() for k in before):
+ return False
+ if not tap_node(play):
+ return False
+ settle("launch")
+ if "GameActivity" not in get_current_activity():
+ return False
+ and_enter("GameActivity") # backs depth for this proven reach
+ return True
+
+
+def and_reach_loadgame():
+ """MainActivity CONTINUE GAME -> LoadGameActivity ("Continue Game" title
+ appears, "NEW GAME" gone). Requires a saved game; the caller ensures one."""
+ nodes = ui()
+ cont = node_by_id(nodes, "continueButton")
+ if cont is None:
+ return False
+ return and_reach_surface(cont, "Continue Game", "NEW GAME")
+
+
+def _ensure_saved_game():
+ """Guarantee CONTINUE GAME is enabled. If not, start a game (which creates a
+ save) and return to the menu. Returns True when a save exists."""
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ cont = node_by_id(ui(), "continueButton")
+ if cont is not None and cont.get("enabled") == "true":
+ return True
+ play = node_by_id(ui(), "playButton")
+ if play is None or not tap_node(play):
+ return False
+ settle("launch")
+ if "GameActivity" not in get_current_activity():
+ return False
+ back() # leave the game -> creates a save
+ settle("launch")
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ cont = node_by_id(ui(), "continueButton")
+ return cont is not None and cont.get("enabled") == "true"
+
+
+def _on_main():
+ return any("NEW GAME" == n.get("text", "") for n in ui())
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Drawer -> each of the 8 destinations (reach, depth=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_drawer_opens",))
+def test_drawer_opens():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ before = and_showing()
+ dn = _open_drawer()
+ ok = dn is not None
+ if ok:
+ after = and_showing(dn)
+ # every drawer item newly present alongside the still-present menu
+ ok = (surface_changed(before, after)
+ and find_node(dn, text="Settings") is not None
+ and find_node(dn, text="About") is not None
+ and find_node(dn, text="Daily Sudoku") is not None)
+ if ok:
+ and_enter("NavDrawer") # backs the depth=1 for the drawer surface
+ record("nav_drawer_opens", ok,
+ "" if ok else "behavior_wrong: nav drawer did not open with its 8 items",
+ depth=1, jump_kind="transition",
+ expect="drawer items 'Settings'/'About'/'Daily Sudoku' appeared over the menu")
+
+
+@and_test(expects=("nav_reach_daily",))
+def test_reach_daily():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("Daily Sudoku", "Daily Sudoku", "NEW GAME")
+ record("nav_reach_daily", ok,
+ "" if ok else "feature_missing: Daily Sudoku surface not reachable from drawer",
+ depth=1, jump_kind="reach",
+ expect="'Daily Sudoku' title appeared, 'NEW GAME' gone")
+
+
+@and_test(expects=("nav_reach_import",))
+def test_reach_import():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ # Import opens a dialog OVER MainActivity; NEW GAME stays behind it, so assert
+ # the dialog's own discriminating button appeared (target only).
+ dn = _open_drawer()
+ item = find_node(dn, text="Import Sudoku") if dn else None
+ ok = False
+ if item is not None:
+ before = and_showing()
+ if tap_node(item):
+ settle("tap")
+ after = and_showing()
+ ok = and_reach(before, after, "IMPORT")
+ if ok:
+ and_enter("ImportDialog")
+ record("nav_reach_import", ok,
+ "" if ok else "feature_missing: Import dialog not reachable from drawer",
+ depth=1, jump_kind="reach",
+ expect="Import dialog 'IMPORT' button appeared")
+
+
+@and_test(expects=("nav_reach_highscore",))
+def test_reach_highscore():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("Highscore", "Highscore", "NEW GAME")
+ record("nav_reach_highscore", ok,
+ "" if ok else "feature_missing: Highscore/Stats surface not reachable",
+ depth=1, jump_kind="reach",
+ expect="'Highscore' title appeared, 'NEW GAME' gone")
+
+
+@and_test(expects=("nav_reach_tutorial",))
+def test_reach_tutorial():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("Tutorial", "Welcome!", "NEW GAME")
+ record("nav_reach_tutorial", ok,
+ "" if ok else "feature_missing: Tutorial surface not reachable",
+ depth=1, jump_kind="reach",
+ expect="'Welcome!' slide appeared, 'NEW GAME' gone")
+
+
+@and_test(expects=("nav_reach_settings",))
+def test_reach_settings():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("Settings", "Game settings", "NEW GAME")
+ record("nav_reach_settings", ok,
+ "" if ok else "feature_missing: Settings surface not reachable",
+ depth=1, jump_kind="reach",
+ expect="'Game settings' header appeared, 'NEW GAME' gone")
+
+
+@and_test(expects=("nav_reach_help",))
+def test_reach_help():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("Help", "Undo button", "NEW GAME")
+ record("nav_reach_help", ok,
+ "" if ok else "feature_missing: Help surface not reachable",
+ depth=1, jump_kind="reach",
+ expect="'Undo button' help row appeared, 'NEW GAME' gone")
+
+
+@and_test(expects=("nav_reach_about",))
+def test_reach_about():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_from_drawer("About", "Authors:", "NEW GAME")
+ record("nav_reach_about", ok,
+ "" if ok else "feature_missing: About surface not reachable",
+ depth=1, jump_kind="reach",
+ expect="'Authors:' label appeared, 'NEW GAME' gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) NEW GAME -> GameActivity (activity flip + VLM, depth=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_game", "nav_reach_game_vlm"))
+def test_reach_game():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ ok = and_reach_game()
+ record("nav_reach_game", ok,
+ "" if ok else "behavior_wrong: NEW GAME did not land on GameActivity",
+ depth=1, jump_kind="reach",
+ expect="activity flipped to GameActivity from MainActivity's 'NEW GAME'")
+ vlm_assert("nav_reach_game",
+ "Does this screenshot show a large square Sudoku grid divided into "
+ "smaller cells (a 9x9 style board)?",
+ RESULTS_DIR, tag="shape")
+
+
+@and_test(expects=("nav_reach_game_keypad_vlm",))
+def test_reach_game_keypad():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ reached = and_reach_game()
+ if not reached:
+ record("nav_reach_game_keypad_vlm", False,
+ "setup_failed: could not reach GameActivity to check the keypad",
+ depth=1, jump_kind="reach", tag="position")
+ return
+ vlm_assert("nav_reach_game_keypad",
+ "Is there a horizontal row of number buttons (containing digits like "
+ "1, 2, 3, 4, 5) in the lower portion of the screen, below the grid?",
+ RESULTS_DIR, tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) CONTINUE GAME -> LoadGameActivity (reach; + VLM thumbnail)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_loadgame", "nav_reach_loadgame_vlm"))
+def test_reach_loadgame():
+ if not _ensure_saved_game():
+ record("nav_reach_loadgame", False,
+ "setup_failed: could not create/verify a saved game",
+ depth=1, jump_kind="reach",
+ expect="'Continue Game' title appeared, 'NEW GAME' gone")
+ record("nav_reach_loadgame_vlm", False,
+ "setup_failed: no saved game to open LoadGameActivity",
+ depth=1, jump_kind="reach", tag="shape")
+ return
+ ok = and_reach_loadgame()
+ record("nav_reach_loadgame", ok,
+ "" if ok else "behavior_wrong: CONTINUE GAME did not open LoadGameActivity",
+ depth=1, jump_kind="reach",
+ expect="'Continue Game' title appeared, 'NEW GAME' gone")
+ vlm_assert("nav_reach_loadgame",
+ "Does this screen list saved games, each row showing a small square "
+ "grid thumbnail on its left side?",
+ RESULTS_DIR, tag="shape")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Back-stack integrity — the reverse jump (reach) for several sub-screens
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_back_settings_to_main",))
+def test_back_settings_to_main():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ reached = and_reach_from_drawer("Settings", "Game settings", "NEW GAME")
+ before = and_showing()
+ and_back()
+ settle("launch")
+ after = and_showing()
+ ok = reached and and_reach(before, after, "NEW GAME", "Game settings") and _on_main()
+ record("nav_back_settings_to_main", ok,
+ "" if ok else "behavior_wrong: BACK from Settings did not restore the menu",
+ depth=1, jump_kind="reach",
+ expect="'NEW GAME' reappeared, 'Game settings' gone after one BACK")
+
+
+@and_test(expects=("nav_back_about_to_main",))
+def test_back_about_to_main():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ reached = and_reach_from_drawer("About", "Authors:", "NEW GAME")
+ before = and_showing()
+ and_back()
+ settle("launch")
+ after = and_showing()
+ ok = reached and and_reach(before, after, "NEW GAME", "Authors:") and _on_main()
+ record("nav_back_about_to_main", ok,
+ "" if ok else "behavior_wrong: BACK from About did not restore the menu",
+ depth=1, jump_kind="reach",
+ expect="'NEW GAME' reappeared, 'Authors:' gone after one BACK")
+
+
+@and_test(expects=("nav_back_help_to_main",))
+def test_back_help_to_main():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ reached = and_reach_from_drawer("Help", "Undo button", "NEW GAME")
+ before = and_showing()
+ and_back()
+ settle("launch")
+ after = and_showing()
+ ok = reached and and_reach(before, after, "NEW GAME", "Undo button") and _on_main()
+ record("nav_back_help_to_main", ok,
+ "" if ok else "behavior_wrong: BACK from Help did not restore the menu",
+ depth=1, jump_kind="reach",
+ expect="'NEW GAME' reappeared, 'Undo button' gone after one BACK")
+
+
+@and_test(expects=("nav_import_cancel_to_main",))
+def test_import_cancel_to_main():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ dn = _open_drawer()
+ item = find_node(dn, text="Import Sudoku") if dn else None
+ reached = False
+ if item is not None:
+ b0 = and_showing()
+ if tap_node(item):
+ settle("tap")
+ reached = and_reach(b0, and_showing(), "IMPORT")
+ if reached:
+ and_enter("ImportDialog")
+ # CANCEL dismisses the dialog back to the menu; the reverse jump = IMPORT was
+ # present before the tap and gone after it.
+ before = and_showing()
+ cancel = find_node(ui(), text="CANCEL")
+ dismissed = False
+ if cancel is not None and tap_node(cancel):
+ settle("tap")
+ after = and_showing()
+ dismissed = and_reach(after, before, "IMPORT")
+ ok = reached and dismissed and _on_main()
+ record("nav_import_cancel_to_main", ok,
+ "" if ok else "behavior_wrong: CANCEL did not dismiss the Import dialog",
+ depth=1, jump_kind="reach",
+ expect="Import 'IMPORT' button gone and 'NEW GAME' menu showing after CANCEL")
+
+
+@and_test(expects=("nav_back_loadgame_to_main",))
+def test_back_loadgame_to_main():
+ if not _ensure_saved_game():
+ record("nav_back_loadgame_to_main", False,
+ "setup_failed: could not create/verify a saved game",
+ depth=1, jump_kind="reach",
+ expect="'NEW GAME' reappeared, 'Navigate up' toolbar gone after one BACK")
+ return
+ reached = and_reach_loadgame()
+ before = and_showing()
+ and_back()
+ settle("launch")
+ after = and_showing()
+ # Source = LoadGame's "Navigate up" toolbar affordance: the menu's own
+ # "CONTINUE GAME" button collides with the "Continue Game" title, so we key the
+ # disappeared-source off the toolbar arrow that only LoadGame shows.
+ ok = reached and and_reach(before, after, "NEW GAME", "Navigate up") and _on_main()
+ record("nav_back_loadgame_to_main", ok,
+ "" if ok else "behavior_wrong: BACK from LoadGame did not restore the menu",
+ depth=1, jump_kind="reach",
+ expect="'NEW GAME' reappeared, LoadGame 'Navigate up' toolbar gone after one BACK")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) depth>=2 chains — this lane's specialty
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_chain_continue_to_game", "nav_chain_continue_to_game_vlm"))
+def test_chain_continue_to_game():
+ """Menu -> CONTINUE -> LoadGame (hop 1) -> tap a saved row -> GameActivity
+ (hop 2). Two surfaces crossed."""
+ if not _ensure_saved_game():
+ record("nav_chain_continue_to_game", False,
+ "setup_failed: could not create/verify a saved game",
+ depth=2, jump_kind="reach",
+ expect="LoadGame then GameActivity reached in two hops")
+ record("nav_chain_continue_to_game_vlm", False,
+ "setup_failed: no saved game for the depth-2 chain",
+ depth=2, jump_kind="reach", tag="shape")
+ return
+ hop1 = and_reach_loadgame() # surface 1: LoadGame
+ row = None
+ if hop1:
+ row = find_node(ui(), text="Sudoku 9x9") or find_node_ci(ui(), "Sudoku 9x9")
+ hop2 = False
+ if row is not None:
+ before = and_showing()
+ if any("Continue Game" in k for k in before) and tap_node(row):
+ settle("launch")
+ if "GameActivity" in get_current_activity():
+ and_enter("GameActivity") # surface 2 (Canvas -> activity proof)
+ hop2 = True
+ ok = hop1 and hop2
+ record("nav_chain_continue_to_game", ok,
+ "" if ok else "behavior_wrong: LoadGame->saved-row->GameActivity chain broke",
+ depth=2, jump_kind="reach",
+ expect="LoadGame 'Continue Game' then activity flip to GameActivity (2 hops)")
+ vlm_assert("nav_chain_continue_to_game",
+ "Does this screenshot show a Sudoku game board grid (square grid of "
+ "cells), rather than a plain list of rows?",
+ RESULTS_DIR, tag="shape")
+
+
+@and_test(expects=("nav_chain_continue_back_to_home",))
+def test_chain_continue_back_to_home():
+ """Depth-2 back-stack from the DEEPEST surface back to home. Menu -> CONTINUE
+ -> LoadGame (hop 1) -> saved row -> GameActivity (hop 2). GameActivity is
+ singleTask, so ONE BACK from it returns straight to the root MainActivity
+ (observed — it does not stop at LoadGame). Assert that BACK lands on the home
+ menu with 'NEW GAME' showing."""
+ if not _ensure_saved_game():
+ record("nav_chain_continue_back_to_home", False,
+ "setup_failed: could not create/verify a saved game",
+ depth=2, jump_kind="reach",
+ expect="one BACK from the game returns to the home menu ('NEW GAME')")
+ return
+ hop1 = and_reach_loadgame() # surface 1: LoadGame
+ row = find_node(ui(), text="Sudoku 9x9") if hop1 else None
+ hop2 = False
+ if row is not None and tap_node(row):
+ settle("launch")
+ hop2 = "GameActivity" in get_current_activity()
+ if hop2:
+ and_enter("GameActivity") # surface 2: Game
+ # one BACK from the deepest (game) surface -> root MainActivity
+ landed_home = False
+ if hop2:
+ and_back()
+ settle("launch")
+ landed_home = ("MainActivity" in get_current_activity()
+ and any("NEW GAME" == n.get("text", "") for n in ui()))
+ ok = hop1 and hop2 and landed_home
+ record("nav_chain_continue_back_to_home", ok,
+ "" if ok else "behavior_wrong: BACK from the game did not return to the home menu",
+ depth=2, jump_kind="reach",
+ expect="after a 2-hop chain to GameActivity, one BACK shows the home menu 'NEW GAME'")
+
+
+@and_test(expects=("nav_chain_drawer_tutorial_next", "nav_chain_drawer_tutorial_next_vlm"))
+def test_chain_drawer_tutorial_next():
+ """Menu -> drawer -> Tutorial (hop 1) -> NEXT advances the slide (hop 2:
+ a new slide surface — 'Welcome!' out, 'Game mode' in)."""
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ hop1 = and_reach_from_drawer("Tutorial", "Welcome!", "NEW GAME") # surface 1
+ hop2 = False
+ if hop1:
+ nxt = find_node(ui(), text="NEXT")
+ if nxt is not None:
+ hop2 = and_reach_surface(nxt, "Game mode", "Welcome!") # surface 2
+ ok = hop1 and hop2
+ record("nav_chain_drawer_tutorial_next", ok,
+ "" if ok else "behavior_wrong: Tutorial NEXT did not advance to the next slide",
+ depth=2, jump_kind="reach",
+ expect="slide 2 'Game mode' appeared, slide 1 'Welcome!' gone after NEXT")
+ vlm_assert("nav_chain_drawer_tutorial_next",
+ "Does the heading text on this tutorial slide read 'Game mode'?",
+ RESULTS_DIR, tag="content")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) Sub-screen toolbar back-arrow affordance (VLM position)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_settings_backarrow_vlm",))
+def test_settings_backarrow():
+ restart_app()
+ wait_for_foreground()
+ settle("launch")
+ reached = and_reach_from_drawer("Settings", "Game settings", "NEW GAME")
+ if not reached:
+ record("nav_settings_backarrow_vlm", False,
+ "setup_failed: could not reach Settings to inspect its toolbar",
+ depth=1, jump_kind="reach", tag="position")
+ return
+ vlm_assert("nav_settings_backarrow",
+ "Is there a left-pointing back arrow (navigate-up chevron) at the very "
+ "top-left corner of this screen?",
+ RESULTS_DIR, tag="position")
+
+
+TESTS = [
+ # drawer -> 8 destinations
+ test_drawer_opens,
+ test_reach_daily,
+ test_reach_import,
+ test_reach_highscore,
+ test_reach_tutorial,
+ test_reach_settings,
+ test_reach_help,
+ test_reach_about,
+ # NEW GAME -> GameActivity
+ test_reach_game,
+ test_reach_game_keypad,
+ # CONTINUE -> LoadGame
+ test_reach_loadgame,
+ # back-stack (reverse jumps)
+ test_back_settings_to_main,
+ test_back_about_to_main,
+ test_back_help_to_main,
+ test_import_cancel_to_main,
+ test_back_loadgame_to_main,
+ # depth>=2 chains
+ test_chain_continue_to_game,
+ test_chain_continue_back_to_home,
+ test_chain_drawer_tutorial_next,
+ # toolbar affordance
+ test_settings_backarrow,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_states.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c5ba1ed128415fda2f12efb3683ea01559e177e
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_states.py
@@ -0,0 +1,735 @@
+#!/usr/bin/env python3
+"""STATES lane — Privacy Friendly Sudoku.
+
+Owns checked/enabled/selected/focused transitions PAIRED with their app-authored
+consequence, page-level state machines, conditional enable/disable, and settings/
+mode persistence across process death.
+
+Ground truth (observed on the running original):
+ Settings switches (fresh restart): Note deletion=ON, Deactivate Timer=OFF,
+ Timer Reset=ON, Keep Screen On=ON, Dark Theme=OFF, Connected Fields=ON,
+ Same values=ON. "Deactivate Timer" ON disables the "Timer Reset" row
+ (disableDependentsState). Dark Theme persists across kill and darkens the app.
+ These switch values PERSIST, so every test that flips one restores it, and the
+ conditional test normalizes Deactivate Timer to OFF before asserting.
+ GameActivity is a custom canvas (uiautomator can't idle) -> game-screen state
+ transitions (selected green, peer highlight, same-value gold, note mode, undo
+ enabled-flip) are verified by VLM on screenshots. Difficulty stars: Easy=1,
+ Moderate=2, Challenge=4 filled blue stars.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ── local helpers ────────────────────────────────────────────────────────────
+
+def settings_switch_by_title(nodes, title):
+ """Return the android.widget.Switch node belonging to the preference row whose
+ TITLE TextView matches `title` (case-insensitive). The Switch has empty text;
+ it is the one whose vertical center is closest to the title's center among all
+ Switches at/after the title's top edge."""
+ tl = title.strip().lower()
+ title_node = None
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == tl
+ and "TextView" in n.get("class", "")):
+ title_node = n
+ break
+ if not title_node or "_bounds" not in title_node:
+ return None
+ ty1 = title_node["_bounds"][1]
+ tcy = (title_node["_bounds"][1] + title_node["_bounds"][3]) // 2
+ best, best_d = None, 10 ** 9
+ for s in nodes:
+ if "Switch" not in s.get("class", "") or "_center" not in s:
+ continue
+ scy = s["_center"][1]
+ d = abs(scy - tcy)
+ if scy >= ty1 - 40 and d < best_d:
+ best, best_d = s, d
+ return best
+
+
+def title_node_ci(nodes, title):
+ tl = title.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == tl
+ and "TextView" in n.get("class", "")):
+ return n
+ return None
+
+
+def and_reach_settings():
+ """Open the nav drawer and tap Settings; confirm SettingsActivity. Backs a
+ depth>=1 claim via the and_reach* naming family."""
+ nodes = ui()
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ if not tap_node(ham):
+ return False
+ settle("tap")
+ nodes = ui()
+ st = find_node_ci(nodes, "Settings")
+ if not tap_node(st):
+ return False
+ settle("tap")
+ and_enter("Settings")
+ return "SettingsActivity" in get_current_activity()
+
+
+def and_enter_game():
+ """Tap NEW GAME and confirm GameActivity. Backs a depth>=1 game-surface claim."""
+ nodes = ui()
+ pb = node_by_id(nodes, "playButton")
+ if not tap_node(pb):
+ return False
+ settle("launch")
+ and_enter("GameActivity")
+ return "GameActivity" in get_current_activity()
+
+
+def _ensure_switch(title, want, max_scroll=3):
+ """Ensure the switch titled `title` reads checked==want (a "true"/"false"
+ string). Scrolls it into view first, taps if needed. Returns the fresh node
+ or None. Drives state ONLY through the GUI."""
+ for _ in range(max_scroll):
+ if settings_switch_by_title(ui(), title) is not None:
+ break
+ scroll_down(0.6)
+ sw = settings_switch_by_title(ui(), title)
+ if sw is None:
+ return None
+ if sw.get("checked") != want:
+ tap_node(sw)
+ settle("tap")
+ sw = settings_switch_by_title(ui(), title)
+ return sw
+
+
+def _switch_transition_test(rec_name, title, *, scroll=False):
+ """Shared body for a settings-switch checked-flip transition test. Restores
+ the original state afterwards (these switches persist)."""
+ restart_app()
+ if not wait_for_foreground():
+ record(rec_name, False, "setup_failed: app not foreground",
+ depth=1, jump_kind="transition",
+ expect=f"{title} checked flips")
+ return
+ if not and_reach_settings():
+ record(rec_name, False, "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect=f"{title} checked flips")
+ return
+ if scroll:
+ for _ in range(3):
+ if settings_switch_by_title(ui(), title) is not None:
+ break
+ scroll_down(0.6)
+ nodes = ui()
+ sw = settings_switch_by_title(nodes, title)
+ if sw is None:
+ record(rec_name, False, f"feature_missing: no '{title}' switch",
+ depth=1, jump_kind="transition",
+ expect=f"{title} checked flips")
+ return
+ before = sw.get("checked")
+ if not tap_node(sw):
+ record(rec_name, False, f"setup_failed: '{title}' switch not tappable",
+ depth=1, jump_kind="transition",
+ expect=f"{title} checked flips")
+ return
+ fresh = ui()
+ after_node = settings_switch_by_title(fresh, title) or find_closest_match(fresh, sw)
+ after = (after_node or {}).get("checked")
+ ok = after is not None and before is not None and after != before
+ record(rec_name, ok,
+ "" if ok else f"behavior_wrong: '{title}' checked did not flip "
+ f"({before}->{after})",
+ depth=1, jump_kind="transition",
+ expect=f"{title} checked {before}->{after}")
+ # These switches PERSIST across the process, so restore the original state to
+ # avoid leaking it into any later test's baseline.
+ if ok and after_node is not None:
+ tap_node(after_node)
+ settle("tap")
+
+
+# ── SETTINGS switch transitions (rule track, tree-readable) ──────────────────
+
+@and_test(expects=("states_switch_note_deletion",))
+def test_switch_note_deletion():
+ _switch_transition_test("states_switch_note_deletion", "Note deletion")
+
+
+@and_test(expects=("states_switch_deactivate_timer",))
+def test_switch_deactivate_timer():
+ _switch_transition_test("states_switch_deactivate_timer", "Deactivate Timer")
+
+
+@and_test(expects=("states_switch_keep_screen_on",))
+def test_switch_keep_screen_on():
+ _switch_transition_test("states_switch_keep_screen_on", "Keep Screen On")
+
+
+@and_test(expects=("states_switch_dark_theme",))
+def test_switch_dark_theme():
+ _switch_transition_test("states_switch_dark_theme", "Dark Theme")
+
+
+@and_test(expects=("states_switch_connected_fields",))
+def test_switch_connected_fields():
+ _switch_transition_test("states_switch_connected_fields", "Connected Fields",
+ scroll=True)
+
+
+@and_test(expects=("states_switch_same_values",))
+def test_switch_same_values():
+ _switch_transition_test("states_switch_same_values", "Same values", scroll=True)
+
+
+# ── Conditional enable/disable state machine ─────────────────────────────────
+
+@and_test(expects=("states_deactivate_timer_disables_reset",))
+def test_deactivate_timer_disables_timer_reset():
+ """Deactivate Timer OFF -> Timer Reset row ENABLED; toggle ON -> Timer Reset
+ row DISABLED (disableDependentsState). A page-level state machine.
+
+ Deactivate Timer is a PERSISTED setting, so we normalize it to OFF via the GUI
+ first — the baseline must not depend on any earlier test's toggle."""
+ name = "states_deactivate_timer_disables_reset"
+ restart_app()
+ if not wait_for_foreground() or not and_reach_settings():
+ record(name, False, "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Deactivate Timer OFF->ON; Timer Reset enabled true->false")
+ return
+ # Normalize Deactivate Timer to OFF (GUI only) so Timer Reset starts enabled.
+ if _ensure_switch("Deactivate Timer", "false") is None:
+ record(name, False, "feature_missing: no Deactivate Timer switch",
+ depth=1, jump_kind="transition",
+ expect="Deactivate Timer OFF->ON; Timer Reset enabled true->false")
+ return
+ nodes = ui()
+ dt = settings_switch_by_title(nodes, "Deactivate Timer")
+ tr_title = title_node_ci(nodes, "Timer Reset")
+ tr_switch = settings_switch_by_title(nodes, "Timer Reset")
+ if dt is None or tr_title is None or tr_switch is None:
+ record(name, False, "feature_missing: Deactivate Timer / Timer Reset row",
+ depth=1, jump_kind="transition",
+ expect="Deactivate Timer OFF->ON; Timer Reset enabled true->false")
+ return
+ # Baseline: Deactivate Timer OFF -> Timer Reset row enabled.
+ reset_enabled_before = (tr_title.get("enabled") == "true"
+ and tr_switch.get("enabled") == "true")
+ # Toggle Deactivate Timer ON -> Timer Reset row must go disabled.
+ tap_node(dt)
+ settle("tap")
+ fresh = ui()
+ tr_title2 = title_node_ci(fresh, "Timer Reset")
+ tr_switch2 = settings_switch_by_title(fresh, "Timer Reset")
+ dt2 = settings_switch_by_title(fresh, "Deactivate Timer")
+ dt_on = dt2 is not None and dt2.get("checked") == "true"
+ reset_disabled_after = (tr_title2 is not None and tr_switch2 is not None
+ and tr_title2.get("enabled") == "false"
+ and tr_switch2.get("enabled") == "false")
+ ok = reset_enabled_before and dt_on and reset_disabled_after
+ msg = ""
+ if not ok:
+ if not reset_enabled_before:
+ msg = "behavior_wrong: Timer Reset not enabled while Deactivate Timer OFF"
+ elif not dt_on:
+ msg = "behavior_wrong: Deactivate Timer did not turn ON when tapped"
+ else:
+ msg = ("behavior_wrong: Timer Reset row did not become disabled after "
+ "Deactivate Timer turned ON")
+ record(name, ok, msg, depth=1, jump_kind="transition",
+ expect="Deactivate Timer OFF->ON; Timer Reset enabled true->false")
+ # Restore Deactivate Timer to OFF (GUI only) so nothing leaks onward.
+ _ensure_switch("Deactivate Timer", "false")
+
+
+# ── continueButton disabled -> enabled after a game is started ───────────────
+
+@and_test(expects=("states_continue_enabled_after_game",))
+def test_continue_enabled_after_starting_game():
+ """CONTINUE GAME is enabled=false on a fresh install with no saved game;
+ after NEW GAME starts (and creates a save), it becomes enabled=true."""
+ name = "states_continue_enabled_after_game"
+ clear_data() # guarantee NO saved game -> continue starts disabled
+ launch_app()
+ if not wait_for_foreground():
+ record(name, False, "setup_failed: app not foreground",
+ depth=1, jump_kind="transition",
+ expect="continueButton enabled false->true")
+ return
+ nodes = ui()
+ cont = node_by_id(nodes, "continueButton")
+ if cont is None:
+ record(name, False, "feature_missing: no continueButton",
+ depth=1, jump_kind="transition",
+ expect="continueButton enabled false->true")
+ return
+ before = cont.get("enabled")
+ # start a game (creates a save), then return to the menu
+ if not and_enter_game():
+ record(name, False, "setup_failed: NEW GAME did not open the game screen",
+ depth=1, jump_kind="transition",
+ expect="continueButton enabled false->true")
+ return
+ and_back() # leave GameActivity -> back to MainActivity
+ settle("launch")
+ fresh = ui()
+ cont2 = node_by_id(fresh, "continueButton")
+ after = (cont2 or {}).get("enabled")
+ ok = before == "false" and after == "true"
+ msg = ""
+ if not ok:
+ if before != "false":
+ msg = (f"behavior_wrong: continueButton was not disabled on a fresh "
+ f"install (enabled={before})")
+ else:
+ msg = (f"behavior_wrong: continueButton did not become enabled after a "
+ f"game was started (enabled={after})")
+ record(name, ok, msg, depth=1, jump_kind="transition",
+ expect="continueButton enabled false->true after a game is saved")
+
+
+# ── SETTINGS persistence across process death (+ dark-bg VLM consequence) ─────
+
+@and_test(expects=("states_dark_theme_persists", "states_dark_theme_persists_vlm"))
+def test_dark_theme_persists_across_kill():
+ """Toggle Dark Theme ON, force_stop_and_relaunch, reopen Settings -> still ON
+ (checked persistence). The app-wide consequence is a darkened background,
+ which is asserted by VLM. Restored to OFF at the end."""
+ name = "states_dark_theme_persists"
+ restart_app()
+ if not wait_for_foreground() or not and_reach_settings():
+ record(name, False, "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Dark Theme checked survives process death (true after kill)")
+ vlm_assert(name, "Is the app's main background very dark (near-black) "
+ "rather than light/white?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+ return
+ # Normalize to OFF first, then turn ON, so the ON state is what we persist.
+ if _ensure_switch("Dark Theme", "false") is None:
+ record(name, False, "feature_missing: no Dark Theme switch",
+ depth=1, jump_kind="transition",
+ expect="Dark Theme checked survives process death (true after kill)")
+ vlm_assert(name, "Is the app's main background very dark (near-black) "
+ "rather than light/white?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+ return
+ dt = _ensure_switch("Dark Theme", "true")
+ on_now = (dt or {}).get("checked")
+
+ # kill the process and relaunch
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ and_enter("relaunch") # persistence probe crosses back into the app surface
+
+ # VLM: the main menu background must be dark now (app-authored consequence)
+ vlm_assert(name, "Is the main screen background very dark (near-black) with "
+ "light-colored text, rather than a light/white background?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+
+ reopened = and_reach_settings()
+ after = None
+ if reopened:
+ after = (settings_switch_by_title(ui(), "Dark Theme") or {}).get("checked")
+ ok = on_now == "true" and after == "true"
+ msg = ""
+ if not ok:
+ if on_now != "true":
+ msg = "behavior_wrong: Dark Theme did not turn ON when toggled"
+ elif not reopened:
+ msg = "setup_failed: could not reopen Settings after relaunch"
+ else:
+ msg = (f"behavior_wrong: Dark Theme did not persist across process "
+ f"death (after kill checked={after})")
+ record(name, ok, msg, depth=1, jump_kind="transition",
+ expect="Dark Theme checked true; survives force-stop+relaunch (still true)")
+
+ # restore: turn Dark Theme back OFF so the device is left light
+ _ensure_switch("Dark Theme", "false")
+
+
+# ── GAME-SCREEN state transitions (VLM track — canvas, not tree) ─────────────
+
+def _game_geom():
+ s = get_screen_info()
+ return s["width"], s["height"]
+
+
+def _cell_xy(r, c):
+ w, h = _game_geom()
+ x0, y0, cw = w * 0.035, h * 0.19, w * 0.103
+ return int(x0 + (c + 0.5) * cw), int(y0 + (r + 0.5) * cw)
+
+
+def _digit_xy(d):
+ w, h = _game_geom()
+ xstart, step = w * 0.125, w * 0.19
+ if d <= 5:
+ return int(xstart + (d - 1) * step), int(h * 0.72)
+ return int(xstart + (d - 6) * step), int(h * 0.79)
+
+
+def _special_xy(i):
+ # 0 Undo, 1 Redo, 2 Hint, 3 Delete, 4 Note
+ w, h = _game_geom()
+ xstart, step = w * 0.125, w * 0.19
+ return int(xstart + i * step), int(h * 0.87)
+
+
+# Candidate cells spread across the board; at least one is EMPTY on any generated
+# puzzle (givens are sparse). Order probes the center first (most often empty).
+_EMPTY_CANDIDATES = [(4, 4), (3, 3), (5, 5), (0, 0), (2, 6), (6, 2), (1, 4),
+ (4, 1), (7, 7), (0, 8), (8, 0), (3, 6)]
+
+
+def _find_empty_cell():
+ """Locate an EMPTY (editable) board cell WITHOUT any VLM call, by pixel-reading
+ a screenshot: the board is a canvas invisible to uiautomator, but a screenshot
+ is just pixels. An empty cell renders pure white (mean~255, std~0); a given/
+ filled cell has black digit strokes (lower mean, high std). Returns (r, c) of the
+ first empty cell among the spread candidates, or (None, None). This is the honest
+ way to find a cell that accepts input — GREEN selection only appears on empty
+ cells, so typing into a given is a silent no-op we must avoid."""
+ try:
+ from PIL import Image
+ import numpy as np
+ except Exception:
+ return None, None
+ shot = os.path.join(RESULTS_DIR, "screenshots", "find_empty.png")
+ os.makedirs(os.path.dirname(shot), exist_ok=True)
+ if not screencap(shot):
+ return None, None
+ img = np.array(Image.open(shot).convert("RGB"))
+ ih, iw, _ = img.shape
+ w, h = _game_geom()
+ sx, sy = iw / w, ih / h
+ x0, y0, cw = w * 0.035, h * 0.19, w * 0.103
+ half = 18
+ for (r, c) in _EMPTY_CANDIDATES:
+ cx = (x0 + (c + 0.5) * cw) * sx
+ cy = (y0 + (r + 0.5) * cw) * sy
+ px, py = int(cx), int(cy)
+ patch = img[max(0, py - half):py + half, max(0, px - half):px + half]
+ if patch.size == 0:
+ continue
+ if float(patch.mean()) >= 250 and float(patch.std()) <= 10:
+ return r, c
+ return None, None
+
+
+def _select_empty_cell():
+ """Find an empty cell by pixels (no VLM) and TAP it to select it (turns green).
+ Returns (r, c) of the selected empty cell, or (None, None) if none found."""
+ r, c = _find_empty_cell()
+ if r is None:
+ return None, None
+ x, y = _cell_xy(r, c)
+ tap(x, y)
+ settle("tap")
+ settle("tap")
+ return r, c
+
+
+def _find_filled_cell():
+ """Locate a FILLED (given) board cell WITHOUT any VLM call, by pixel-reading a
+ screenshot: a filled cell has black digit strokes (mean<250, std>15). Scans all
+ 81 cells and returns the (r, c) of the first filled one, or (None, None).
+ Selecting a filled cell reliably triggers the same-value gold highlight."""
+ try:
+ from PIL import Image
+ import numpy as np
+ except Exception:
+ return None, None
+ shot = os.path.join(RESULTS_DIR, "screenshots", "find_filled.png")
+ os.makedirs(os.path.dirname(shot), exist_ok=True)
+ if not screencap(shot):
+ return None, None
+ img = np.array(Image.open(shot).convert("RGB"))
+ ih, iw, _ = img.shape
+ w, h = _game_geom()
+ sx, sy = iw / w, ih / h
+ x0, y0, cw = w * 0.035, h * 0.19, w * 0.103
+ half = 18
+ for r in range(9):
+ for c in range(9):
+ cx = (x0 + (c + 0.5) * cw) * sx
+ cy = (y0 + (r + 0.5) * cw) * sy
+ px, py = int(cx), int(cy)
+ patch = img[max(0, py - half):py + half, max(0, px - half):px + half]
+ if patch.size == 0:
+ continue
+ if float(patch.mean()) < 250 and float(patch.std()) > 15:
+ return r, c
+ return None, None
+
+
+@and_test(expects=("states_cell_selected_vlm",))
+def test_selected_cell_highlight():
+ """Tapping an EMPTY cell turns exactly that cell GREEN (selected state).
+
+ The board is randomly generated, so cell (r,c) may hold a pre-filled clue;
+ tapping a GIVEN selects it GREY, only EMPTY cells go GREEN. So we probe a spread
+ of candidate cells and assert green on the first empty one we hit — 'selecting
+ an empty cell turns it green' is the invariant, not 'cell (0,0)'."""
+ name = "states_cell_selected"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name, "Is exactly one grid cell filled solid green?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+ return
+ r, c = _select_empty_cell()
+ if r is None:
+ # No empty cell went green across all probes -> record the failure honestly.
+ vlm_assert(name, "Is exactly one grid cell filled with a solid green "
+ "background (a selected empty cell)?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+ return
+ # The current screen still holds the green selection just made; assert on it.
+ vlm_assert(name, "In the Sudoku grid, is exactly one cell filled with a solid "
+ "green background (a vivid green highlight distinct from white cells "
+ "and any yellow-tinted cells)?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_peer_highlight_vlm",))
+def test_peer_highlight():
+ """The selected cell's whole row and column are highlighted a lighter shade."""
+ name = "states_peer_highlight"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name, "Are a full row and full column of grid cells tinted a "
+ "light shade?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="color")
+ return
+ r, c = _select_empty_cell()
+ if r is None:
+ vlm_assert(name, "Are a full row and full column of grid cells tinted a "
+ "light shade?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="color")
+ return
+ vlm_assert(name, "One grid cell is selected (green). Look at the rest of the "
+ "grid: are the other cells in the SAME ROW and the SAME COLUMN as the "
+ "green cell shaded a pale yellow/cream color, while cells far from "
+ "that row and column are plain white?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_same_value_gold_vlm", "states_same_value_bigdigit_vlm"))
+def test_same_value_highlight():
+ """Entering a digit highlights every cell holding that digit in gold, and the
+ entered value renders as a large digit in the selected cell."""
+ name = "states_same_value"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name + "_gold", "Are several grid cells highlighted gold/orange?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+ vlm_assert(name + "_bigdigit", "Does a selected grid cell contain a large "
+ "digit?", RESULTS_DIR, depth=1, jump_kind="transition", tag="size")
+ return
+ # GOLD sub-test: the same-value highlight keys off the SELECTED cell's value
+ # (observed). Selecting a FILLED cell (a given) reliably gold-highlights its
+ # same-value peers — givens almost always have peers on a 9x9 board. This is far
+ # more robust than typing a value that may have no peers.
+ fr, fc = _find_filled_cell()
+ if fr is not None:
+ fx, fy = _cell_xy(fr, fc)
+ tap(fx, fy)
+ settle("tap")
+ settle("tap")
+ vlm_assert(name + "_gold", "One grid cell containing a digit is selected. Are "
+ "the OTHER cells that hold that SAME digit highlighted with a gold / "
+ "orange / yellow background?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+ # BIGDIGIT sub-test: select an EMPTY cell, type a value -> renders as a big digit.
+ r, c = _select_empty_cell()
+ if r is None:
+ vlm_assert(name + "_bigdigit", "Does a selected grid cell contain a large "
+ "digit?", RESULTS_DIR, depth=1, jump_kind="transition", tag="size")
+ return
+ dx, dy = _digit_xy(1) # value-mode is the default; write a large "1"
+ tap(dx, dy)
+ settle("tap")
+ settle("tap")
+ vlm_assert(name + "_bigdigit", "Does the selected (green) cell now show one "
+ "large digit filling the cell (a normal value, not tiny corner "
+ "pencil marks)?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="size")
+
+
+@and_test(expects=("states_note_mode_active_vlm", "states_note_mode_content_vlm"))
+def test_note_mode_on():
+ """Turning on note (pencil) mode changes the pencil button's appearance
+ (active/highlighted), and entering a digit then writes a tiny corner pencil
+ mark instead of a large value. A MODE state machine (ON half)."""
+ name = "states_note_mode"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name + "_active", "Does the pencil/note button look active "
+ "(highlighted)?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="shape")
+ vlm_assert(name + "_content", "Does a grid cell contain a tiny corner "
+ "digit?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="content")
+ return
+ nx, ny = _special_xy(4) # pencil / note toggle (bottom-right button)
+ tap(nx, ny)
+ settle("tap")
+ vlm_assert(name + "_active", "Look at the bottom-right pencil/note toggle "
+ "button: does it now have a distinct yellow/gold highlight or border "
+ "indicating it is ACTIVE (pressed on), unlike the plain blue Hint and "
+ "Delete buttons next to it?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="shape")
+ r, c = _select_empty_cell() # a confirmed-empty (green) cell
+ if r is None:
+ vlm_assert(name + "_content", "Does a grid cell contain a tiny corner "
+ "digit?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="content")
+ return
+ dx, dy = _digit_xy(3)
+ tap(dx, dy)
+ settle("tap")
+ settle("tap")
+ vlm_assert(name + "_content", "In the currently selected grid cell, does the "
+ "entered digit appear as a small pencil note in a corner of the cell "
+ "(small), rather than one big digit centered in the cell?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="content")
+
+
+@and_test(expects=("states_note_mode_off_vlm",))
+def test_note_mode_off_writes_large_value():
+ """With note mode OFF (default), entering a digit writes a large centered value
+ — the flipped-back half of the note MODE state machine."""
+ name = "states_note_mode_off"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name, "Does a grid cell contain a large centered digit?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="size")
+ return
+ # note mode starts OFF; select an EMPTY cell and type -> should be a big value
+ r, c = _select_empty_cell()
+ if r is None:
+ vlm_assert(name, "Does a grid cell contain a large centered digit?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="size")
+ return
+ dx, dy = _digit_xy(1)
+ tap(dx, dy)
+ settle("tap")
+ settle("tap")
+ vlm_assert(name, "With note mode off, does the selected (green) cell show one "
+ "large digit filling the cell (a normal value), rather than small "
+ "corner pencil marks?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="size")
+
+
+@and_test(expects=("states_undo_disabled_vlm", "states_undo_enabled_vlm"))
+def test_undo_enabled_flip():
+ """On a fresh game the Undo button is greyed (disabled); after one move it turns
+ blue/active. An enabled-state flip observed visually (canvas)."""
+ name = "states_undo"
+ restart_app()
+ wait_for_foreground()
+ if not and_enter_game():
+ vlm_assert(name + "_disabled", "Is the undo (curved back-arrow) button "
+ "greyed out?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="color")
+ vlm_assert(name + "_enabled", "Is the undo button blue/active?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ # BEFORE: no move made yet -> undo greyed
+ vlm_assert(name + "_disabled", "Look at the bottom-left curved back-arrow (undo) "
+ "button: is it greyed out / grey-colored (disabled), clearly lighter "
+ "grey than the blue buttons to its right?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="color")
+ # make one move: select a confirmed-empty cell, then enter a digit
+ r, c = _select_empty_cell()
+ if r is None:
+ vlm_assert(name + "_enabled", "Is the undo button blue/active?", RESULTS_DIR,
+ depth=1, jump_kind="transition", tag="color")
+ return
+ dx, dy = _digit_xy(1)
+ tap(dx, dy)
+ settle("tap")
+ settle("tap")
+ # AFTER: undo now active/blue
+ vlm_assert(name + "_enabled", "After entering a digit, is the bottom-left curved "
+ "back-arrow (undo) button now colored blue / active (no longer "
+ "grey)?", RESULTS_DIR, depth=1, jump_kind="transition", tag="color")
+
+
+# ── Difficulty star-count state (main menu, VLM) ─────────────────────────────
+
+def _set_difficulty(nodes, frac):
+ rb = node_by_id(nodes, "difficultyBar")
+ if not rb or "_bounds" not in rb:
+ return False
+ x1, y1, x2, y2 = rb["_bounds"]
+ tap(int(x1 + (x2 - x1) * frac), int((y1 + y2) // 2))
+ settle("tap")
+ return True
+
+
+@and_test(expects=("states_difficulty_easy_vlm", "states_difficulty_challenge_vlm"))
+def test_difficulty_star_count():
+ """Selecting Easy shows 1 filled blue star; selecting Challenge shows 4 filled
+ blue stars. The star-count rendering is a selection-state consequence."""
+ name = "states_difficulty"
+ restart_app()
+ if not wait_for_foreground():
+ vlm_assert(name + "_easy", "Is exactly one star filled blue?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="color")
+ vlm_assert(name + "_challenge", "Are four stars filled blue?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="shape")
+ return
+ nodes = ui()
+ if node_by_id(nodes, "difficultyBar") is None:
+ record(name + "_easy", False, "feature_missing: no difficulty RatingBar",
+ depth=0, jump_kind="transition", tag="color",
+ expect="Easy shows 1 filled star")
+ vlm_assert(name + "_challenge", "Are four stars filled blue?", RESULTS_DIR,
+ depth=0, jump_kind="transition", tag="shape")
+ return
+ # Easy = leftmost star position
+ _set_difficulty(nodes, 0.05)
+ vlm_assert(name + "_easy", "In the difficulty star rating (a grey circle "
+ "followed by four stars), is EXACTLY ONE star filled solid blue and "
+ "the other three stars grey?", RESULTS_DIR, depth=0,
+ jump_kind="transition", tag="color")
+ # Challenge = rightmost star position
+ _set_difficulty(ui(), 0.95)
+ vlm_assert(name + "_challenge", "In the difficulty star rating, are ALL FOUR "
+ "stars filled solid blue?", RESULTS_DIR, depth=0,
+ jump_kind="transition", tag="shape")
+
+
+TESTS = [
+ test_switch_note_deletion,
+ test_switch_deactivate_timer,
+ test_switch_keep_screen_on,
+ test_switch_dark_theme,
+ test_switch_connected_fields,
+ test_switch_same_values,
+ test_deactivate_timer_disables_timer_reset,
+ test_continue_enabled_after_starting_game,
+ test_dark_theme_persists_across_kill,
+ test_selected_cell_highlight,
+ test_peer_highlight,
+ test_same_value_highlight,
+ test_note_mode_on,
+ test_note_mode_off_writes_large_value,
+ test_undo_enabled_flip,
+ test_difficulty_star_count,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_structure.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbbeaf15c9418696b7985169b00639ea3545b6e3
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_structure.py
@@ -0,0 +1,460 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — Privacy Friendly Sudoku.
+
+Owns exactly two things:
+ 1. THE GATE: the app launches to MainActivity and its top-level surfaces exist
+ (main container, the menu buttons, the game-type/difficulty selectors, the
+ nav hamburger). These are jump_kind="none" and kept <=30% of the suite.
+ 2. TREE-SHAPE DELTAS: an interaction that changes the tree's shape/size — the
+ nav drawer overlay adds a class of items, the Import dialog adds a new layer,
+ entering a sub-screen swaps the whole surface. Recorded as reach/transition
+ with an observed before->after, and reversed to assert it restores.
+
+Content strings belong to the text lane, computed values to computation, checked/
+enabled to states — this file only ever asserts SHAPE (node counts, surface-key
+sets, dialog appearance, activity flips).
+
+GameActivity is a custom Canvas with a 1s timer animation: uiautomator never
+reaches idle there and ui() returns a STALE main-menu tree. So on the game screen
+we NEVER assert on ui(); we confirm it via get_current_activity() (dumpsys, not the
+tree) and assert its shape with VLM screenshots.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── local depth helpers (name them so and_audit_depth can back the depth claim) ──
+
+def and_enter_drawer(nodes):
+ """Open the nav drawer overlay by tapping the hamburger. Counts one surface.
+ Returns (ok, before_showing, after_showing)."""
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ if not ham:
+ return False, set(), set()
+ before = and_showing(nodes)
+ if not tap_node(ham):
+ return False, before, set()
+ after = and_showing()
+ and_enter("drawer")
+ return True, before, after
+
+
+def and_reach_from_drawer(target_item, marker, source="NEW GAME"):
+ """MainActivity -> drawer -> `target_item`, PROVING the jump (marker appeared,
+ source disappeared). Counts one surface (the drawer overlay collapses under the
+ new screen, so the destination is the single surface we land on). Returns
+ (reached, before, after, activity)."""
+ nodes = ui()
+ before = and_showing(nodes)
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ if not ham or not tap_node(ham):
+ return False, before, set(), ""
+ drawer = ui()
+ item = find_node_ci(drawer, target_item)
+ if not item or not tap_node(item):
+ return False, before, set(), ""
+ after = and_showing()
+ reached = and_reach(before, after, marker, source)
+ if reached:
+ and_enter(target_item)
+ return reached, before, after, get_current_activity()
+
+
+def and_reach_game(play_node):
+ """Tap NEW GAME and PROVE the jump into GameActivity via dumpsys (the canvas
+ tree is stale, so and_showing() cannot see the board — the activity flip is the
+ honest reach signal here). Counts one surface. Returns (reached, activity)."""
+ src_main = "MainActivity" in get_current_activity()
+ if not play_node or not tap_node(play_node):
+ return False, get_current_activity()
+ settle("launch")
+ act = get_current_activity()
+ reached = src_main and "GameActivity" in act and "MainActivity" not in act
+ if reached:
+ and_enter("GameActivity")
+ return reached, act
+
+
+def _ensure_saved_game():
+ """Guarantee a resumable game exists (so CONTINUE GAME -> LoadGameActivity is
+ reachable on a fresh emulator): start NEW GAME once, which persists it, then
+ return to a clean menu. Idempotent enough for a per-test entry point."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ play = node_by_id(nodes, "playButton")
+ if play:
+ tap_node(play)
+ settle("launch")
+ restart_app()
+ wait_for_foreground()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) THE GATE — jump_kind="none", depth 0 (existence only; <=30% of the suite)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ """App reaches the foreground on MainActivity with a real view container."""
+ if not device_online():
+ record("structure_gate_launch", False,
+ "setup_failed: device/tunnel offline", depth=0, jump_kind="none")
+ return
+ restart_app()
+ fg = wait_for_foreground()
+ nodes = ui()
+ container = bool(find_by_class(nodes, "ViewGroup") or find_by_class(nodes, "FrameLayout"))
+ on_main = "MainActivity" in get_current_activity()
+ ok = fg and container and on_main
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach MainActivity foreground",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_main_ids",))
+def test_gate_main_ids():
+ """MainActivity's top-level menu surface: the two action buttons + the game-type
+ label + difficulty label + the levels container all exist, by id last-segment."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ need = ["playButton", "continueButton", "section_label",
+ "difficultyText", "level_count"]
+ present = [rid for rid in need if node_by_id(nodes, rid)]
+ ok = len(present) == len(need)
+ record("structure_gate_main_ids", ok,
+ "" if ok else f"feature_missing: main-menu ids present only {present}",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_selectors",))
+def test_gate_selectors():
+ """The game-type/difficulty selector cluster exists: both chevrons, the
+ difficulty control, and the grid-preview image — the menu's interactive shape."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ need = ["arrow_left", "arrow_right", "difficultyBar", "gameTypeImage"]
+ present = [rid for rid in need if node_by_id(nodes, rid)]
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ ok = len(present) == len(need) and ham is not None
+ record("structure_gate_selectors", ok,
+ "" if ok else f"feature_missing: selector cluster present only {present}, "
+ f"hamburger={'yes' if ham else 'no'}",
+ depth=0, jump_kind="none")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) IN-PLACE SHAPE DELTAS — overlays that add a layer, then reverse (depth 0)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_drawer_shape",))
+def test_drawer_shape():
+ """Opening the nav drawer ADDS the 8 destination items as an overlay -> the
+ surface-key set grows materially (~21 -> ~41 keys). The overlay is reversed by
+ tapping the inert scrim strip on the far right (the drawer covers only the left
+ ~80%), which collapses it back to the exact menu shape WITHOUT navigating —
+ a BACK from an open drawer over-shoots to the launcher on this app. Overlay, so
+ depth stays 0."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ opened, before, after = and_enter_drawer(nodes)
+ grew = surface_changed(before, after) and len(after) > len(before)
+ items_now = sum(1 for t in ["Main Menu", "Daily Sudoku", "Import Sudoku",
+ "Highscore", "Tutorial", "Settings", "Help", "About"]
+ if find_node_ci(ui(), t))
+ # reverse: tap the far-right scrim (inert — the drawer does not cover it) to
+ # collapse the overlay without navigating away.
+ s = get_screen_info()
+ tap(int(s["width"] * 0.97), s["center_y"])
+ settle("tap")
+ restored = ui()
+ drawer_items_gone = len(find_by_class(restored, "CheckedTextView")) == 0
+ back_on_menu = bool(find_node_ci(restored, "NEW GAME"))
+ reversed_ok = drawer_items_gone and back_on_menu
+ ok = opened and grew and items_now >= 6 and reversed_ok
+ if not opened:
+ msg = "setup_failed: could not open navigation drawer"
+ elif not grew:
+ msg = "behavior_wrong: drawer added no nodes to the surface"
+ elif items_now < 6:
+ msg = f"behavior_wrong: drawer showed only {items_now}/8 destination items"
+ elif not reversed_ok:
+ msg = "behavior_wrong: drawer overlay did not collapse back to the menu shape"
+ else:
+ msg = ""
+ record("structure_drawer_shape", ok, msg,
+ depth=0, jump_kind="transition",
+ expect="Drawer overlay adds 8 destination items (surface grows ~20 keys), "
+ "collapsed back to the menu shape (0 CheckedTextView) after scrim tap")
+
+
+@and_test(expects=("structure_import_dialog_shape",))
+def test_import_dialog_shape():
+ """Import Sudoku opens a dialog LAYER that adds one EditText plus IMPORT/CANCEL
+ buttons -> EditText count 0->1 and the surface changes. CANCEL reverses it back
+ to the menu. Dialog is a surface, so depth=1 (backed by and_enter in the drawer
+ helper + the enter into the dialog)."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ et_before = len(find_by_class(nodes, "EditText"))
+ opened, before, _after = and_enter_drawer(nodes)
+ dn = ui()
+ imp = find_node_ci(dn, "Import Sudoku")
+ tapped = bool(imp) and tap_node(imp)
+ and_enter("import_dialog")
+ dlg = ui()
+ et_after = len(find_by_class(dlg, "EditText"))
+ has_buttons = bool(find_node_ci(dlg, "IMPORT")) and bool(find_node_ci(dlg, "CANCEL"))
+ appeared = et_after == et_before + 1 and has_buttons and surface_changed(before, and_showing(dlg))
+ # reverse via CANCEL (never a destructive control)
+ cancel = find_node_ci(dlg, "CANCEL")
+ if cancel:
+ safe_tap(cancel)
+ settle("tap")
+ restored = ui()
+ dismissed = len(find_by_class(restored, "EditText")) == et_before
+ ok = opened and tapped and appeared and dismissed
+ if not (opened and tapped):
+ msg = "setup_failed: could not open the Import dialog"
+ elif not appeared:
+ msg = f"behavior_wrong: dialog EditText {et_before}->{et_after} or buttons missing"
+ elif not dismissed:
+ msg = "behavior_wrong: EditText did not disappear after CANCEL"
+ else:
+ msg = ""
+ record("structure_import_dialog_shape", ok, msg,
+ depth=1, jump_kind="transition",
+ expect="Import dialog adds 1 EditText + IMPORT/CANCEL; CANCEL removes the layer")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) SURFACE REACHES — the whole tree swaps shape crossing into a sub-screen
+# (depth 1, jump_kind="reach", each backed by and_reach_from_drawer)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_settings_reach", "structure_settings_shape_vlm"))
+def test_settings_reach():
+ """MainActivity -> Settings: the menu buttons DISAPPEAR and a list of 7 Switch
+ rows APPEARS — a total shape swap. Prove the reach ('Game settings' in, NEW GAME
+ out) and assert the switch-list shape both by count and by VLM."""
+ restart_app()
+ wait_for_foreground()
+ reached, _before, after, act = and_reach_from_drawer("Settings", "Game settings")
+ sn = ui()
+ switches = len(find_by_class(sn, "Switch"))
+ on_settings = "SettingsActivity" in act
+ ok = reached and on_settings and switches >= 5
+ if not reached:
+ msg = "feature_missing: Settings not reachable (Game settings did not appear)"
+ elif switches < 5:
+ msg = f"behavior_wrong: expected a switch list, found {switches} switches"
+ else:
+ msg = ""
+ record("structure_settings_reach", ok, msg,
+ depth=1, jump_kind="reach",
+ expect="SettingsActivity: >=5 Switch rows appear; NEW GAME button gone")
+ # position: the toggle controls sit hard against the RIGHT edge of their rows.
+ vlm_assert("structure_settings_shape",
+ "Are there several on/off toggle switch controls positioned at the "
+ "far RIGHT edge of a vertical list of setting rows on this screen?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("structure_stats_reach",))
+def test_stats_reach():
+ """MainActivity -> Highscore: the surface swaps to StatsActivity (Highscore in,
+ NEW GAME out)."""
+ restart_app()
+ wait_for_foreground()
+ reached, _b, _a, act = and_reach_from_drawer("Highscore", "Highscore")
+ ok = reached and "StatsActivity" in act
+ record("structure_stats_reach", ok,
+ "" if ok else "feature_missing: Highscore/Stats screen not reachable",
+ depth=1, jump_kind="reach",
+ expect="StatsActivity surface replaces the menu; NEW GAME gone")
+
+
+@and_test(expects=("structure_daily_reach",))
+def test_daily_reach():
+ """MainActivity -> Daily Sudoku: surface swaps to DailySudokuActivity."""
+ restart_app()
+ wait_for_foreground()
+ reached, _b, _a, act = and_reach_from_drawer("Daily Sudoku", "Daily Sudoku")
+ ok = reached and "DailySudokuActivity" in act
+ record("structure_daily_reach", ok,
+ "" if ok else "feature_missing: Daily Sudoku screen not reachable",
+ depth=1, jump_kind="reach",
+ expect="DailySudokuActivity surface replaces the menu; NEW GAME gone")
+
+
+@and_test(expects=("structure_help_reach",))
+def test_help_reach():
+ """MainActivity -> Help: surface swaps to HelpActivity ('Keyboard' section in,
+ NEW GAME out)."""
+ restart_app()
+ wait_for_foreground()
+ reached, _b, _a, act = and_reach_from_drawer("Help", "Keyboard")
+ ok = reached and "HelpActivity" in act
+ record("structure_help_reach", ok,
+ "" if ok else "feature_missing: Help screen not reachable",
+ depth=1, jump_kind="reach",
+ expect="HelpActivity surface replaces the menu; NEW GAME gone")
+
+
+@and_test(expects=("structure_about_reach",))
+def test_about_reach():
+ """MainActivity -> About: surface swaps to AboutActivity ('Authors:' in,
+ NEW GAME out)."""
+ restart_app()
+ wait_for_foreground()
+ reached, _b, _a, act = and_reach_from_drawer("About", "Authors:")
+ ok = reached and "AboutActivity" in act
+ record("structure_about_reach", ok,
+ "" if ok else "feature_missing: About screen not reachable",
+ depth=1, jump_kind="reach",
+ expect="AboutActivity surface replaces the menu; NEW GAME gone")
+
+
+@and_test(expects=("structure_loadgame_reach",))
+def test_loadgame_reach():
+ """CONTINUE GAME -> LoadGameActivity: the menu surface swaps to the saved-games
+ list ('Continue Game' title in, NEW GAME out). A saved game is guaranteed first
+ by starting one, so this is reachable on a fresh emulator too."""
+ _ensure_saved_game()
+ nodes = ui()
+ cb = node_by_id(nodes, "continueButton")
+ if not cb:
+ record("structure_loadgame_reach", False,
+ "feature_missing: continueButton not present", depth=1, jump_kind="reach",
+ expect="LoadGameActivity surface replaces the menu; NEW GAME gone")
+ return
+ before = and_showing(nodes)
+ tap_node(cb)
+ after = and_showing()
+ reached = and_reach(before, after, "Continue Game", "NEW GAME")
+ if reached:
+ and_enter("LoadGame")
+ ok = reached and "LoadGameActivity" in get_current_activity()
+ record("structure_loadgame_reach", ok,
+ "" if ok else "feature_missing: LoadGame (saved games list) not reachable",
+ depth=1, jump_kind="reach",
+ expect="LoadGameActivity surface replaces the menu; NEW GAME gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) THE GAME SCREEN — canvas, tree is stale; assert the SHAPE via VLM only
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_newgame_to_game",
+ "structure_game_board_vlm",
+ "structure_game_keypad_vlm",
+ "structure_game_specialrow_vlm"))
+def test_newgame_to_game():
+ """NEW GAME -> GameActivity: the menu surface DISAPPEARS and GameActivity comes
+ to the foreground (confirmed via dumpsys, since the tree is stale on canvas).
+ Its shape — a 9x9 grid, a 1-9 keypad, and a bottom action-button row — is
+ asserted with three VLM screenshots. depth=1, backed by and_reach_game."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ play = node_by_id(nodes, "playButton")
+ reached, act = and_reach_game(play)
+ ok = reached
+ if play is None:
+ msg = "setup_failed: NEW GAME button not present"
+ elif not reached:
+ msg = f"feature_missing: NEW GAME did not open GameActivity (at {act})"
+ else:
+ msg = ""
+ record("structure_newgame_to_game", ok, msg,
+ depth=1, jump_kind="reach",
+ expect="GameActivity foreground after NEW GAME; MainActivity surface gone")
+
+ # SHAPE of the (canvas) game screen — VLM is the only honest verdict here.
+ vlm_assert("structure_game_board",
+ "Is a 9x9 Sudoku grid (a large square divided into a 9-by-9 lattice "
+ "of cells) visible in the upper-middle of this screen?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="shape")
+ # shape: the keypad is a fixed set of nine digit keys (1..9), a countable shape.
+ vlm_assert("structure_game_keypad",
+ "Below the grid, is there a keypad of exactly nine number buttons "
+ "showing the digits 1, 2, 3, 4, 5, 6, 7, 8 and 9?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="shape")
+ vlm_assert("structure_game_specialrow",
+ "At the very bottom, below the number keypad, is there a single "
+ "horizontal row of small action icons (such as undo, hint, delete)?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) MENU SPATIAL LAYOUT + grid-preview shape change (VLM, depth 0)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_menu_layout_vlm",))
+def test_menu_layout_vlm():
+ """The main menu's spatial shape: a grid/board preview near the top and two
+ stacked buttons in the lower half — a fact the flat tree cannot express."""
+ restart_app()
+ wait_for_foreground()
+ ui() # let the surface settle before the screenshot
+ vlm_assert("structure_menu_layout",
+ "Does this screen show a grid/board preview image in its upper half "
+ "and two full-width buttons stacked one above the other in its lower "
+ "half?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="layout")
+
+
+@and_test(expects=("structure_gridpreview_shape", "structure_gridpreview_shape_vlm"))
+def test_gridpreview_shape():
+ """Cycling the game type from Sudoku 9x9 to Sudoku 6x6 (arrow_left) changes the
+ grid-preview image's SHAPE (fewer, larger cells). The label change is proven on
+ the tree (rule), the visual shape delta by VLM. depth=0 (in-place)."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ label = node_by_id(nodes, "section_label")
+ start = label.get("text", "") if label else ""
+ al = node_by_id(nodes, "arrow_left")
+ tapped = bool(al) and tap_node(al)
+ nodes2 = ui()
+ label2 = node_by_id(nodes2, "section_label")
+ now = label2.get("text", "") if label2 else ""
+ # rule half: the selector actually switched to a different type (shape source)
+ changed = tapped and now != "" and now != start
+ record("structure_gridpreview_shape", changed,
+ "" if changed else f"behavior_wrong: game type did not change ({start!r}->{now!r})",
+ depth=0, jump_kind="transition",
+ expect="section_label Sudoku 9x9 -> Sudoku 6x6 via arrow_left")
+ # VLM half: is the preview now a 6x6 grid (2x3-block layout), not a 9x9 grid?
+ vlm_assert("structure_gridpreview_shape",
+ "Is the grid/board preview image on this screen a 6x6 grid (6 rows "
+ "and 6 columns of cells), not a 9x9 grid?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="shape")
+
+
+TESTS = [
+ test_gate_launch,
+ test_gate_main_ids,
+ test_gate_selectors,
+ test_drawer_shape,
+ test_import_dialog_shape,
+ test_settings_reach,
+ test_stats_reach,
+ test_daily_reach,
+ test_help_reach,
+ test_about_reach,
+ test_loadgame_reach,
+ test_newgame_to_game,
+ test_menu_layout_vlm,
+ test_gridpreview_shape,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_android_text.py b/android/secuso-privacy-friendly-sudoku/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..45c2d0418f7cca6d4050a5e65e46f01aaffbd679
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_android_text.py
@@ -0,0 +1,600 @@
+#!/usr/bin/env python3
+"""TEXT lane — CONTENT / OUTPUT strings for Privacy Friendly Sudoku.
+
+This lane owns exact-string equality of the strings an interaction PRODUCES or
+that a screen RENDERS: screen titles, section headers, stat-row labels, input
+prompts, the two main-menu button labels, the dynamic "Levels available: N"
+label, and the tutorial slide-content CHANGE driven by the NEXT tap.
+
+Every test is TRIGGER -> OBSERVATION: we navigate/tap/type, re-read a fresh
+ui(), and assert the specific string that appeared (never "the view exists").
+A dead shell that renders no strings FAILS every test here.
+
+VLM budget for this lane: 0 vlm_assert — every asserted string is readable from
+the uiautomator view tree, so this file is pure rule assertions.
+
+Package arrives ONLY as argv[1]; nothing here hardcodes it (or an APK path, a
+/data/data path, a device serial, or a pixel coordinate). Run:
+
+ python3 test_android_text.py
+"""
+import os
+import re
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── small local helpers ─────────────────────────────────────────────────────
+
+def all_text(nodes):
+ """All non-empty text values on the surface, joined for substring search."""
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
+
+
+def norm(s):
+ return (s or "").strip().casefold()
+
+
+def has_text(nodes, needle):
+ """Case-insensitive substring search across every node's text."""
+ n = norm(needle)
+ return any(n in norm(x.get("text", "")) for x in nodes)
+
+
+def open_nav_drawer():
+ """Open the nav drawer by tapping the hamburger (content-desc), never an
+ edge-swipe (which overshoots to the launcher). Returns a fresh tree."""
+ nodes = ui()
+ ham = find_node(nodes, content_desc="Open navigation drawer")
+ if ham:
+ tap_node(ham)
+ else:
+ open_drawer() # kit fallback
+ return ui()
+
+
+def _reach_via_drawer(dest_label, activity_marker):
+ """Open the drawer, tap `dest_label`, confirm we crossed onto the expected
+ Activity. Returns (ok, note). Backs a depth>=1 claim via and_enter()."""
+ restart_app()
+ if not wait_for_foreground():
+ return False, "setup_failed: app did not reach the foreground"
+ nodes = open_nav_drawer()
+ target = find_node_ci(nodes, dest_label)
+ if not target:
+ return False, f"setup_failed: drawer item '{dest_label}' not found"
+ if not tap_node(target):
+ return False, f"setup_failed: could not tap drawer item '{dest_label}'"
+ settle("tap")
+ if activity_marker and activity_marker not in get_current_activity():
+ return False, (f"setup_failed: expected {activity_marker} after tapping "
+ f"'{dest_label}', got {get_current_activity()}")
+ and_enter(dest_label) # backs depth>=1
+ return True, ""
+
+
+# Named depth-family helpers (one per reached surface). Naming is what the depth
+# auditor keys on; each proves it crossed onto the right Activity.
+
+def and_enter_stats():
+ return _reach_via_drawer("Highscore", "StatsActivity")
+
+
+def and_enter_daily():
+ return _reach_via_drawer("Daily Sudoku", "DailySudokuActivity")
+
+
+def and_enter_about():
+ return _reach_via_drawer("About", "AboutActivity")
+
+
+def and_enter_help():
+ return _reach_via_drawer("Help", "HelpActivity")
+
+
+def and_enter_tutorial():
+ return _reach_via_drawer("Tutorial", "TutorialActivity")
+
+
+def and_enter_import_dialog():
+ """The Import dialog is a dialog OVER MainActivity (activity does not change),
+ so confirm by the prompt string appearing instead of an Activity marker."""
+ restart_app()
+ if not wait_for_foreground():
+ return False, "setup_failed: app did not reach the foreground"
+ nodes = open_nav_drawer()
+ target = find_node_ci(nodes, "Import Sudoku")
+ if not target:
+ return False, "setup_failed: drawer item 'Import Sudoku' not found"
+ if not tap_node(target):
+ return False, "setup_failed: could not tap 'Import Sudoku'"
+ settle("tap")
+ and_enter("Import dialog")
+ return True, ""
+
+
+LEVELS_RE = re.compile(r"levels?\s+available:\s*\d+", re.IGNORECASE)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# MAIN MENU (depth=0) — strings the hub renders
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_main_new_game_button",))
+def test_main_new_game_button():
+ """The NEW GAME button label renders on the hub (depth=0 content read)."""
+ restart_app()
+ if not wait_for_foreground():
+ record("text_main_new_game_button", False,
+ "setup_failed: app did not reach the foreground",
+ depth=0, jump_kind="none", expect="button 'NEW GAME'")
+ return
+ nodes = ui()
+ btn = node_by_id(nodes, "playButton") or find_node_ci(nodes, "NEW GAME")
+ ok = btn is not None and "new game" in norm(btn.get("text", ""))
+ record("text_main_new_game_button", ok,
+ "" if ok else "behavior_wrong: primary button does not read 'NEW GAME'",
+ depth=0, jump_kind="none", expect="button label 'NEW GAME'")
+
+
+@and_test(expects=("text_main_continue_game_button",))
+def test_main_continue_game_button():
+ """The CONTINUE GAME button label renders on the hub (depth=0)."""
+ restart_app()
+ if not wait_for_foreground():
+ record("text_main_continue_game_button", False,
+ "setup_failed: app did not reach the foreground",
+ depth=0, jump_kind="none", expect="button 'CONTINUE GAME'")
+ return
+ nodes = ui()
+ btn = node_by_id(nodes, "continueButton") or find_node_ci(nodes, "CONTINUE GAME")
+ ok = btn is not None and "continue game" in norm(btn.get("text", ""))
+ record("text_main_continue_game_button", ok,
+ "" if ok else "behavior_wrong: secondary button does not read 'CONTINUE GAME'",
+ depth=0, jump_kind="none", expect="button label 'CONTINUE GAME'")
+
+
+@and_test(expects=("text_main_default_game_type",))
+def test_main_default_game_type():
+ """On a clean restart the game-type selector reads 'Sudoku 9x9'."""
+ restart_app()
+ if not wait_for_foreground():
+ record("text_main_default_game_type", False,
+ "setup_failed: app did not reach the foreground",
+ depth=0, jump_kind="none", expect="type label 'Sudoku 9x9'")
+ return
+ nodes = ui()
+ lbl = node_by_id(nodes, "section_label")
+ ok = lbl is not None and "sudoku 9x9" in norm(lbl.get("text", ""))
+ record("text_main_default_game_type", ok,
+ "" if ok else "behavior_wrong: default game type is not 'Sudoku 9x9'",
+ depth=0, jump_kind="none", expect="game-type label 'Sudoku 9x9'")
+
+
+@and_test(expects=("text_levels_available_format",))
+def test_levels_available_format():
+ """The level counter renders in the format 'Levels available: '.
+ N is generator-dependent, so we assert the FORMAT (regex), never a number."""
+ restart_app()
+ if not wait_for_foreground():
+ record("text_levels_available_format", False,
+ "setup_failed: app did not reach the foreground",
+ depth=0, jump_kind="none", expect="format 'Levels available: N'")
+ return
+ nodes = ui()
+ lc = node_by_id(nodes, "level_count")
+ txt = lc.get("text", "") if lc else ""
+ ok = bool(LEVELS_RE.search(txt))
+ record("text_levels_available_format", ok,
+ "" if ok else f"behavior_wrong: level label {txt!r} is not "
+ f"'Levels available: '",
+ depth=0, jump_kind="none", expect="'Levels available: '")
+
+
+@and_test(expects=("text_levels_available_changes",))
+def test_levels_available_changes():
+ """TRIGGER->OBSERVATION on the label CONTENT: cycling the game type to the
+ right re-renders 'Levels available: N' with a DIFFERENT digit count. We own
+ the LABEL text/format + that it re-renders; the raw cycler value is
+ computation's. Assert format holds before AND after, and the string changed."""
+ restart_app()
+ if not wait_for_foreground():
+ record("text_levels_available_changes", False,
+ "setup_failed: app did not reach the foreground",
+ depth=0, jump_kind="value", expect="'Levels available: N' re-renders")
+ return
+ nodes = ui()
+ lc = node_by_id(nodes, "level_count")
+ arrow = node_by_id(nodes, "arrow_right")
+ if not lc or not arrow:
+ record("text_levels_available_changes", False,
+ "feature_missing: level_count or arrow_right control absent",
+ depth=0, jump_kind="value", expect="'Levels available: N' re-renders")
+ return
+ before = lc.get("text", "")
+ if not LEVELS_RE.search(before):
+ record("text_levels_available_changes", False,
+ f"behavior_wrong: pre-cycle label {before!r} not in expected format",
+ depth=0, jump_kind="value", expect="'Levels available: N' re-renders")
+ return
+ tap_node(arrow)
+ nodes2 = ui()
+ lc2 = node_by_id(nodes2, "level_count")
+ after = lc2.get("text", "") if lc2 else ""
+ ok = bool(LEVELS_RE.search(after)) and after.strip() != before.strip()
+ record("text_levels_available_changes", ok,
+ "" if ok else f"behavior_wrong: label did not re-render after type "
+ f"cycle (before={before!r} after={after!r})",
+ depth=0, jump_kind="value",
+ expect=f"'Levels available: N' changed from {before!r}")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HIGHSCORE / StatsActivity (depth=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_stats_title",))
+def test_stats_title():
+ ok, note = and_enter_stats()
+ if not ok:
+ record("text_stats_title", False, note,
+ depth=1, jump_kind="value", expect="title 'Highscore'")
+ return
+ nodes = ui()
+ present = has_text(nodes, "Highscore")
+ record("text_stats_title", present,
+ "" if present else "behavior_wrong: Stats screen title is not 'Highscore'",
+ depth=1, jump_kind="value", expect="screen title 'Highscore'")
+
+
+@and_test(expects=("text_stats_section_headers",))
+def test_stats_section_headers():
+ """The four game-type section headers render on the stats screen."""
+ ok, note = and_enter_stats()
+ if not ok:
+ record("text_stats_section_headers", False, note,
+ depth=1, jump_kind="value", expect="headers SUDOKU 6X6..16X16")
+ return
+ wanted = ["SUDOKU 6X6", "SUDOKU 9X9", "SUDOKU 12X12", "SUDOKU 16X16"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_stats_section_headers", ok2,
+ "" if ok2 else f"behavior_wrong: missing section header(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="game-type headers SUDOKU 6X6/9X9/12X12/16X16")
+
+
+@and_test(expects=("text_stats_row_labels",))
+def test_stats_row_labels():
+ """The distinctive stat-row labels render on the stats screen."""
+ ok, note = and_enter_stats()
+ if not ok:
+ record("text_stats_row_labels", False, note,
+ depth=1, jump_kind="value", expect="stat-row labels")
+ return
+ wanted = ["# used hints:", "# completed games:", "Total time played:",
+ "Ø-time:", "Best time:"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_stats_row_labels", ok2,
+ "" if ok2 else f"behavior_wrong: missing stat-row label(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="'# used hints:', '# completed games:', 'Total time played:', "
+ "'Ø-time:', 'Best time:'")
+
+
+@and_test(expects=("text_stats_difficulty_labels",))
+def test_stats_difficulty_labels():
+ """The four difficulty labels render on the stats screen."""
+ ok, note = and_enter_stats()
+ if not ok:
+ record("text_stats_difficulty_labels", False, note,
+ depth=1, jump_kind="value", expect="Easy/Moderate/Hard/Challenge")
+ return
+ wanted = ["Easy", "Moderate", "Hard", "Challenge"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_stats_difficulty_labels", ok2,
+ "" if ok2 else f"behavior_wrong: missing difficulty label(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="difficulty labels Easy/Moderate/Hard/Challenge")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DAILY SUDOKU / DailySudokuActivity (depth=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_daily_title",))
+def test_daily_title():
+ ok, note = and_enter_daily()
+ if not ok:
+ record("text_daily_title", False, note,
+ depth=1, jump_kind="value", expect="title 'Daily Sudoku'")
+ return
+ present = has_text(ui(), "Daily Sudoku")
+ record("text_daily_title", present,
+ "" if present else "behavior_wrong: Daily screen title is not 'Daily Sudoku'",
+ depth=1, jump_kind="value", expect="screen title 'Daily Sudoku'")
+
+
+@and_test(expects=("text_daily_labels",))
+def test_daily_labels():
+ """Distinctive Daily labels: 'Used hints', 'Completed games',
+ 'Total time played:', and the zeroed timer value '00:00:00'."""
+ ok, note = and_enter_daily()
+ if not ok:
+ record("text_daily_labels", False, note,
+ depth=1, jump_kind="value", expect="Daily stat labels + 00:00:00")
+ return
+ nodes = ui()
+ wanted = ["Used hints", "Completed games", "Total time played:", "00:00:00"]
+ missing = [w for w in wanted if not has_text(nodes, w)]
+ ok2 = not missing
+ record("text_daily_labels", ok2,
+ "" if ok2 else f"behavior_wrong: missing Daily label(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="'Used hints', 'Completed games', 'Total time played:', '00:00:00'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# ABOUT / AboutActivity (depth=1) — labels only, NEVER the version number
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_about_title",))
+def test_about_title():
+ ok, note = and_enter_about()
+ if not ok:
+ record("text_about_title", False, note,
+ depth=1, jump_kind="value", expect="title 'About'")
+ return
+ present = has_text(ui(), "About")
+ record("text_about_title", present,
+ "" if present else "behavior_wrong: About screen title is not 'About'",
+ depth=1, jump_kind="value", expect="screen title 'About'")
+
+
+@and_test(expects=("text_about_app_name",))
+def test_about_app_name():
+ """The About screen renders the app name 'Privacy Friendly Sudoku'."""
+ ok, note = and_enter_about()
+ if not ok:
+ record("text_about_app_name", False, note,
+ depth=1, jump_kind="value", expect="'Privacy Friendly Sudoku'")
+ return
+ present = has_text(ui(), "Privacy Friendly Sudoku")
+ record("text_about_app_name", present,
+ "" if present else "behavior_wrong: About does not show 'Privacy Friendly Sudoku'",
+ depth=1, jump_kind="value", expect="app name 'Privacy Friendly Sudoku'")
+
+
+@and_test(expects=("text_about_labels",))
+def test_about_labels():
+ """About renders its static section labels. We assert the LABELS
+ ('Version:', 'Authors:', 'SECUSO-Website', 'Github-Repo', 'In affiliation
+ with') — NEVER the version number, which a recreation cannot know."""
+ ok, note = and_enter_about()
+ if not ok:
+ record("text_about_labels", False, note,
+ depth=1, jump_kind="value", expect="About section labels")
+ return
+ wanted = ["Version:", "Authors:", "In affiliation with",
+ "SECUSO-Website", "Github-Repo"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_about_labels", ok2,
+ "" if ok2 else f"behavior_wrong: missing About label(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="'Version:', 'Authors:', 'In affiliation with', "
+ "'SECUSO-Website', 'Github-Repo'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HELP / HelpActivity (depth=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_help_title",))
+def test_help_title():
+ ok, note = and_enter_help()
+ if not ok:
+ record("text_help_title", False, note,
+ depth=1, jump_kind="value", expect="title 'Help'")
+ return
+ present = has_text(ui(), "Help")
+ record("text_help_title", present,
+ "" if present else "behavior_wrong: Help screen title is not 'Help'",
+ depth=1, jump_kind="value", expect="screen title 'Help'")
+
+
+@and_test(expects=("text_help_section_headers",))
+def test_help_section_headers():
+ """Help renders its control section headers."""
+ ok, note = and_enter_help()
+ if not ok:
+ record("text_help_section_headers", False, note,
+ depth=1, jump_kind="value", expect="Help section headers")
+ return
+ wanted = ["Keyboard", "Undo button", "Hint button", "Delete button",
+ "Note toggle button"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_help_section_headers", ok2,
+ "" if ok2 else f"behavior_wrong: missing Help header(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="'Keyboard', 'Undo button', 'Hint button', 'Delete button', "
+ "'Note toggle button'")
+
+
+@and_test(expects=("text_help_descriptions",))
+def test_help_descriptions():
+ """Help renders stable description sentences. We assert substrings that
+ avoid the raw HTML entities (
) some entries embed."""
+ ok, note = and_enter_help()
+ if not ok:
+ record("text_help_descriptions", False, note,
+ depth=1, jump_kind="value", expect="Help description sentences")
+ return
+ wanted = ["Undoes the last action", "Deletes a selected field",
+ "Toggles if numbers should be set as notes or as values in a field"]
+ missing = []
+ for w in wanted:
+ if not (has_text(ui(), w) or scroll_into_view(w)):
+ missing.append(w)
+ ok2 = not missing
+ record("text_help_descriptions", ok2,
+ "" if ok2 else f"behavior_wrong: missing Help description(s) {missing}",
+ depth=1, jump_kind="value",
+ expect="'Undoes the last action', 'Deletes a selected field', "
+ "'Toggles if numbers should be set as notes or as values in a field'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# IMPORT dialog (depth=1) — prompt string
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_import_prompt",))
+def test_import_prompt():
+ """The Import dialog renders its prompt and both action buttons. The
+ EditText echo belongs to computation — asserted here is the static prompt."""
+ ok, note = and_enter_import_dialog()
+ if not ok:
+ record("text_import_prompt", False, note,
+ depth=1, jump_kind="value",
+ expect="'Enter the link of the sudoku you wish to import:'")
+ return
+ nodes = ui()
+ prompt_ok = has_text(nodes, "Enter the link of the sudoku you wish to import:")
+ buttons_ok = has_text(nodes, "IMPORT") and has_text(nodes, "CANCEL")
+ ok2 = prompt_ok and buttons_ok
+ record("text_import_prompt", ok2,
+ "" if ok2 else "behavior_wrong: Import dialog prompt/buttons not as expected",
+ depth=1, jump_kind="value",
+ expect="prompt 'Enter the link of the sudoku you wish to import:' "
+ "with IMPORT/CANCEL")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TUTORIAL (depth=2) — the slide-content CHANGE driven by the NEXT tap
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_tutorial_slide1",))
+def test_tutorial_slide1():
+ """Slide 1 renders 'Welcome!' and its welcome sentence (depth=1)."""
+ ok, note = and_enter_tutorial()
+ if not ok:
+ record("text_tutorial_slide1", False, note,
+ depth=1, jump_kind="value", expect="'Welcome!'")
+ return
+ nodes = ui()
+ ok2 = (has_text(nodes, "Welcome!")
+ and has_text(nodes, "Welcome to Privacy Friendly Sudoku!"))
+ record("text_tutorial_slide1", ok2,
+ "" if ok2 else "behavior_wrong: tutorial slide 1 is not the Welcome slide",
+ depth=1, jump_kind="value",
+ expect="'Welcome!' + 'Welcome to Privacy Friendly Sudoku!'")
+
+
+@and_test(expects=("text_tutorial_next_transition",))
+def test_tutorial_next_transition():
+ """The strongest dynamic-content test: tapping NEXT flips the slide content
+ from 'Welcome!' to 'Game mode'. Assert 'Game mode' was ABSENT before and
+ PRESENT after, and the 'Welcome!' heading is gone (depth=2 — we advanced a
+ slide WITHIN the tutorial surface, backed by a second and_enter)."""
+ ok, note = and_enter_tutorial() # depth 1: on the tutorial
+ if not ok:
+ record("text_tutorial_next_transition", False, note,
+ depth=2, jump_kind="transition", expect="Welcome! -> Game mode")
+ return
+ before = ui()
+ if not has_text(before, "Welcome!"):
+ record("text_tutorial_next_transition", False,
+ "setup_failed: tutorial did not open on the Welcome slide",
+ depth=2, jump_kind="transition", expect="Welcome! -> Game mode")
+ return
+ gm_absent_before = not has_text(before, "Game mode")
+ nxt = find_node_ci(before, "NEXT")
+ if not nxt:
+ record("text_tutorial_next_transition", False,
+ "feature_missing: no NEXT button on the tutorial slide",
+ depth=2, jump_kind="transition", expect="Welcome! -> Game mode")
+ return
+ tap_node(nxt)
+ and_enter("tutorial slide 2") # depth 2: advanced a slide
+ after = ui()
+ gm_present_after = has_text(after, "Game mode")
+ welcome_gone = not has_text(after, "Welcome!")
+ ok2 = gm_absent_before and gm_present_after and welcome_gone
+ record("text_tutorial_next_transition", ok2,
+ "" if ok2 else "behavior_wrong: NEXT did not flip slide content from "
+ "'Welcome!' to 'Game mode'",
+ depth=2, jump_kind="transition", expect="Welcome! -> Game mode")
+
+
+@and_test(expects=("text_tutorial_slide2_body",))
+def test_tutorial_slide2_body():
+ """After NEXT, slide 2 renders its 'Game mode' body sentence (depth=2)."""
+ ok, note = and_enter_tutorial()
+ if not ok:
+ record("text_tutorial_slide2_body", False, note,
+ depth=2, jump_kind="value", expect="Game mode body sentence")
+ return
+ nxt = find_node_ci(ui(), "NEXT")
+ if not nxt:
+ record("text_tutorial_slide2_body", False,
+ "feature_missing: no NEXT button on the tutorial slide",
+ depth=2, jump_kind="value", expect="Game mode body sentence")
+ return
+ tap_node(nxt)
+ and_enter("tutorial slide 2")
+ after = ui()
+ ok2 = has_text(after, "Swipe or press the arrow buttons on the left and right "
+ "to change the game mode.")
+ record("text_tutorial_slide2_body", ok2,
+ "" if ok2 else "behavior_wrong: slide 2 body sentence not rendered",
+ depth=2, jump_kind="value",
+ expect="'Swipe or press the arrow buttons on the left and right to "
+ "change the game mode.'")
+
+
+TESTS = [
+ test_main_new_game_button,
+ test_main_continue_game_button,
+ test_main_default_game_type,
+ test_levels_available_format,
+ test_levels_available_changes,
+ test_stats_title,
+ test_stats_section_headers,
+ test_stats_row_labels,
+ test_stats_difficulty_labels,
+ test_daily_title,
+ test_daily_labels,
+ test_about_title,
+ test_about_app_name,
+ test_about_labels,
+ test_help_title,
+ test_help_section_headers,
+ test_help_descriptions,
+ test_import_prompt,
+ test_tutorial_slide1,
+ test_tutorial_next_transition,
+ test_tutorial_slide2_body,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/secuso-privacy-friendly-sudoku/tests/test_manifest.json b/android/secuso-privacy-friendly-sudoku/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..96515aee785d4b0ea2cc31c155a0b4250b2cba0e
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/tests/test_manifest.json
@@ -0,0 +1,812 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "privacy-friendly-sudoku",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 120,
+ "manifest_sha": "7fc4a5aa64ea",
+ "tests": [
+ {
+ "name": "computation::computation_board_digit_value_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_board_grid_shape_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_difficulty_bar_challenge",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_difficulty_bar_easy",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_difficulty_bar_easy_to_hard",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_difficulty_custom_checkbox",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_import_echo_digits",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_import_echo_replaced",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_import_echo_url",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_level_count_changes_by_difficulty",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_level_count_changes_by_type",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_level_count_format",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_clamp_at_max",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_clamp_at_min",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_left_from_default",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_preview_shape_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_right_from_default",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_right_then_left_roundtrip",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_type_right_two_steps",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_delete_value_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_edit_replace_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_enter_value_highlight_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_enter_value_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_import_cancel_roundtrip",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_import_echo",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_menu",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_value_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_note_mode_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_note_multiple_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_persist_continue_enabled",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_persist_resume_board_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_persist_resume_value_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_redo_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_samevalue_highlight_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_undo_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_about_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_help_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_loadgame_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_settings_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_continue_back_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_continue_to_game",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_continue_to_game_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_drawer_tutorial_next",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_drawer_tutorial_next_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_drawer_opens",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_import_cancel_to_main",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_daily",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_game",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_game_keypad_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_game_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_help",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_highscore",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_import",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_loadgame",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_loadgame_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_tutorial",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_backarrow_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_cell_selected_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_continue_enabled_after_game",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_dark_theme_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_dark_theme_persists_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_deactivate_timer_disables_reset",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_difficulty_challenge_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_difficulty_easy_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_note_mode_active_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_note_mode_content_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_note_mode_off_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_peer_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_same_value_bigdigit_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_same_value_gold_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_connected_fields",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_dark_theme",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_deactivate_timer",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_keep_screen_on",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_note_deletion",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_same_values",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_undo_disabled_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_undo_enabled_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_about_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_daily_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_board_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_keypad_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_game_specialrow_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_main_ids",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_selectors",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gridpreview_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gridpreview_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_help_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_import_dialog_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_loadgame_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_menu_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_newgame_to_game",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_reach",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_app_name",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_daily_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_daily_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_descriptions",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_section_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_help_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_import_prompt",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_levels_available_changes",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_levels_available_format",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_main_continue_game_button",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_main_default_game_type",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_main_new_game_button",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_difficulty_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_row_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_section_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_next_transition",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_slide1",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_tutorial_slide2_body",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_type_preview_shape_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_board_grid_shape_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_board_digit_value_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_enter_value_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_enter_value_highlight_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_samevalue_highlight_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_delete_value_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_edit_replace_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_multi_value_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_undo_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_redo_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_note_mode_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_note_multiple_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_persist_resume_value_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_persist_resume_board_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "navigation::nav_reach_game_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_game_keypad_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_loadgame_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_chain_continue_to_game_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_chain_drawer_tutorial_next_vlm",
+ "module": "navigation",
+ "tag": "content"
+ },
+ {
+ "name": "navigation::nav_settings_backarrow_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_dark_theme_persists_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_cell_selected_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_peer_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_same_value_gold_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_same_value_bigdigit_vlm",
+ "module": "states",
+ "tag": "size"
+ },
+ {
+ "name": "states::states_note_mode_active_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_note_mode_content_vlm",
+ "module": "states",
+ "tag": "content"
+ },
+ {
+ "name": "states::states_note_mode_off_vlm",
+ "module": "states",
+ "tag": "size"
+ },
+ {
+ "name": "states::states_undo_disabled_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_undo_enabled_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_difficulty_easy_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_difficulty_challenge_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_settings_shape_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_game_board_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_game_keypad_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_game_specialrow_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_menu_layout_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_gridpreview_shape_vlm",
+ "module": "structure",
+ "tag": "shape"
+ }
+ ],
+ "vlm_total": 39,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/secuso-privacy-friendly-sudoku/vlm_assertions.json b/android/secuso-privacy-friendly-sudoku/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..22bc008901f73d31f7414c88df6d788b88e4e68f
--- /dev/null
+++ b/android/secuso-privacy-friendly-sudoku/vlm_assertions.json
@@ -0,0 +1,816 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/secuso-privacy-friendly-sudoku",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 40,
+ "with_verdict": 39,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 39,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "nav_reach_game_vlm",
+ "screenshot": "nav_reach_game_vlm.png",
+ "assertion": "Does this screenshot show a large square Sudoku grid divided into smaller cells (a 9x9 style board)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_reach_game",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_game_keypad_vlm",
+ "screenshot": "nav_reach_game_keypad_vlm.png",
+ "assertion": "Is there a horizontal row of number buttons (containing digits like 1, 2, 3, 4, 5) in the lower portion of the screen, below the grid?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_game_keypad",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_loadgame_vlm",
+ "screenshot": "nav_reach_loadgame_vlm.png",
+ "assertion": "Does this screen list saved games, each row showing a small square grid thumbnail on its left side?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_reach_loadgame",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_chain_continue_to_game_vlm",
+ "screenshot": "nav_chain_continue_to_game_vlm.png",
+ "assertion": "Does this screenshot show a Sudoku game board grid (square grid of cells), rather than a plain list of rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_chain_continue_to_game",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_chain_drawer_tutorial_next_vlm",
+ "screenshot": "nav_chain_drawer_tutorial_next_vlm.png",
+ "assertion": "Does the heading text on this tutorial slide read 'Game mode'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "nav_chain_drawer_tutorial_next",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_settings_backarrow_vlm",
+ "screenshot": "nav_settings_backarrow_vlm.png",
+ "assertion": "Is there a left-pointing back arrow (navigate-up chevron) at the very top-left corner of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_settings_backarrow",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_enter_value_vlm",
+ "screenshot": "interaction_enter_value_vlm.png",
+ "assertion": "In the Sudoku grid, does the top-left corner cell contain the digit 5?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_enter_value",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_enter_value_highlight_vlm",
+ "screenshot": "interaction_enter_value_highlight_vlm.png",
+ "assertion": "Is the top-left corner cell of the Sudoku grid filled with a GREEN background colour (the selected-cell highlight)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_enter_value_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_samevalue_highlight_vlm",
+ "screenshot": "interaction_samevalue_highlight_vlm.png",
+ "assertion": "Apart from the green selected cell, are there one or more other grid cells shown with a GOLD or ORANGE background highlight?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_samevalue_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_delete_value_vlm",
+ "screenshot": "interaction_delete_value_vlm.png",
+ "assertion": "The top-left corner cell of the Sudoku grid is selected (green background). Is that green cell EMPTY (it shows no digit)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_delete_value",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_multi_value_vlm",
+ "screenshot": "interaction_multi_value_vlm.png",
+ "assertion": "Look at the top-left 3x3 block of the Sudoku grid. Along its main diagonal, does the top-left cell show 1, the middle cell show 2, and the bottom-right cell show 3?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_multi_value",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_undo_vlm",
+ "screenshot": "interaction_undo_vlm.png",
+ "assertion": "The top-left corner cell of the Sudoku grid is selected (green background). Is that green cell EMPTY after the undo (it shows no digit)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_undo",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_redo_vlm",
+ "screenshot": "interaction_redo_vlm.png",
+ "assertion": "After pressing redo, does the top-left corner cell of the Sudoku grid contain the digit 3 again?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_redo",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_note_mode_vlm",
+ "screenshot": "interaction_note_mode_vlm.png",
+ "assertion": "Is there a grid cell that shows several SMALL pencil-note digits (tiny numbers), rather than one single large digit?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_note_mode",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_note_multiple_vlm",
+ "screenshot": "interaction_note_multiple_vlm.png",
+ "assertion": "In the selected (green) Sudoku cell, are there at least three small pencil-note digits visible together?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_note_multiple",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_hint_fills_vlm",
+ "screenshot": "interaction_hint_fills_vlm.png",
+ "assertion": "The Sudoku cell that is selected (green background) — does it now contain a single large digit (it is no longer empty)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_hint_fills",
+ "rigor": null,
+ "verdict": null,
+ "calibration": null
+ },
+ {
+ "id": "interaction_persist_resume_value_vlm",
+ "screenshot": "interaction_persist_resume_value_vlm.png",
+ "assertion": "After resuming the saved game, does the top-left corner cell of the Sudoku grid contain the digit 7?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_persist_resume_value",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_persist_resume_board_vlm",
+ "screenshot": "interaction_persist_resume_board_vlm.png",
+ "assertion": "Does this screen show a fully rendered Sudoku board (a 9x9 grid with many digits) together with a number keypad below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_persist_resume_board",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_edit_replace_vlm",
+ "screenshot": "interaction_edit_replace_vlm.png",
+ "assertion": "Does the currently selected Sudoku cell now contain the digit 8 (and not the digit 4)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_edit_replace",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_type_preview_shape_vlm",
+ "screenshot": "computation_type_preview_shape_vlm.png",
+ "assertion": "In the game-type selector near the top, a square grid PREVIEW image is shown under the size label. Does that preview render as a grid subdivided into MANY small cells (a dense 12x12-style grid), rather than a coarse 3x3 or single big square?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_type_preview_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_board_grid_shape_vlm",
+ "screenshot": "computation_board_grid_shape_vlm.png",
+ "assertion": "Does the main area show a square Sudoku board divided into a 9x9 grid of cells (nine columns and nine rows, grouped into 3x3 blocks)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_board_grid_shape",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_board_digit_value_vlm",
+ "screenshot": "computation_board_digit_value_vlm.png",
+ "assertion": "On the Sudoku board, does the top-left region now contain the large digit '1' entered into a cell (i.e. a 1 was computed and placed onto the grid)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "computation_board_digit_value",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_dark_theme_persists_vlm",
+ "screenshot": "states_dark_theme_persists_vlm.png",
+ "assertion": "Is the main screen background very dark (near-black) with light-colored text, rather than a light/white background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_dark_theme_persists",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_cell_selected_vlm",
+ "screenshot": "states_cell_selected_vlm.png",
+ "assertion": "In the Sudoku grid, is the top-left corner cell highlighted with a solid bright-green background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_cell_selected",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_peer_highlight_vlm",
+ "screenshot": "states_peer_highlight_vlm.png",
+ "assertion": "After selecting the top-left cell, are the other cells in the same top row and same left column tinted a light yellow/cream shade (different from the plain white cells elsewhere)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_peer_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_same_value_gold_vlm",
+ "screenshot": "states_same_value_gold_vlm.png",
+ "assertion": "After entering a digit, are the OTHER cells that already contain that same digit highlighted with a gold/orange background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_same_value_gold",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_same_value_bigdigit_vlm",
+ "screenshot": "states_same_value_bigdigit_vlm.png",
+ "assertion": "Does the green selected top-left cell now show one large digit filling the cell (a normal value, not tiny corner pencil marks)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "size",
+ "modality": null,
+ "links_to": "states_same_value_bigdigit",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_note_mode_active_vlm",
+ "screenshot": "states_note_mode_active_vlm.png",
+ "assertion": "Look at the bottom-right pencil/note toggle button: does it now have a distinct yellow/gold highlight or border indicating it is ACTIVE (pressed on), unlike the plain blue Hint and Delete buttons next to it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_note_mode_active",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_note_mode_content_vlm",
+ "screenshot": "states_note_mode_content_vlm.png",
+ "assertion": "In the currently selected grid cell, does the entered digit appear as a small pencil note in a corner of the cell (small), rather than one big digit centered in the cell?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "states_note_mode_content",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_note_mode_off_vlm",
+ "screenshot": "states_note_mode_off_vlm.png",
+ "assertion": "With note mode off, does the selected top-left cell show one large digit filling the cell (a normal value), rather than small corner pencil marks?",
+ "form": "question",
+ "expected": true,
+ "aspect": "size",
+ "modality": null,
+ "links_to": "states_note_mode_off",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_undo_disabled_vlm",
+ "screenshot": "states_undo_disabled_vlm.png",
+ "assertion": "Look at the bottom-left curved back-arrow (undo) button: is it greyed out / grey-colored (disabled), clearly lighter grey than the blue buttons to its right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_undo_disabled",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_undo_enabled_vlm",
+ "screenshot": "states_undo_enabled_vlm.png",
+ "assertion": "After entering a digit, is the bottom-left curved back-arrow (undo) button now colored blue / active (no longer grey)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_undo_enabled",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_difficulty_easy_vlm",
+ "screenshot": "states_difficulty_easy_vlm.png",
+ "assertion": "In the difficulty star rating (a grey circle followed by four stars), is EXACTLY ONE star filled solid blue and the other three stars grey?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_difficulty_easy",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_difficulty_challenge_vlm",
+ "screenshot": "states_difficulty_challenge_vlm.png",
+ "assertion": "In the difficulty star rating, are ALL FOUR stars filled solid blue?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_difficulty_challenge",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_settings_shape_vlm",
+ "screenshot": "structure_settings_shape_vlm.png",
+ "assertion": "Are there several on/off toggle switch controls positioned at the far RIGHT edge of a vertical list of setting rows on this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_settings_shape",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_game_board_vlm",
+ "screenshot": "structure_game_board_vlm.png",
+ "assertion": "Is a 9x9 Sudoku grid (a large square divided into a 9-by-9 lattice of cells) visible in the upper-middle of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_game_board",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_game_keypad_vlm",
+ "screenshot": "structure_game_keypad_vlm.png",
+ "assertion": "Below the grid, is there a keypad of exactly nine number buttons showing the digits 1, 2, 3, 4, 5, 6, 7, 8 and 9?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_game_keypad",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_game_specialrow_vlm",
+ "screenshot": "structure_game_specialrow_vlm.png",
+ "assertion": "At the very bottom, below the number keypad, is there a single horizontal row of small action icons (such as undo, hint, delete)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_game_specialrow",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_menu_layout_vlm",
+ "screenshot": "structure_menu_layout_vlm.png",
+ "assertion": "Does this screen show a grid/board preview image in its upper half and two full-width buttons stacked one above the other in its lower half?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_menu_layout",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_gridpreview_shape_vlm",
+ "screenshot": "structure_gridpreview_shape_vlm.png",
+ "assertion": "Is the grid/board preview image on this screen a 6x6 grid (6 rows and 6 columns of cells), not a 9x9 grid?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_gridpreview_shape",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/LICENSE.md b/android/swati4star-images-to-pdf/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..ee5ea45fa641611730be7f8892164b4ad6bde1b3
--- /dev/null
+++ b/android/swati4star-images-to-pdf/LICENSE.md
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+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.
+
+To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+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 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. Use with the GNU Affero General Public License.
+
+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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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.
+
+ {one line to give the program's name and a brief idea of what it does.}
+ Copyright (C) {year} {name of author}
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ {project} Copyright (C) {year} {fullname}
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+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 GPL, see
+.
+
+The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/android/swati4star-images-to-pdf/instance.json b/android/swati4star-images-to-pdf/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..9492bf6527c63b661ff1eec1397b70a500349e04
--- /dev/null
+++ b/android/swati4star-images-to-pdf/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/swati4star-images-to-pdf",
+ "platform": "android",
+ "repo": "https://github.com/swati4star/images-to-pdf",
+ "commit": "54576589b0c410a07a986ec317b643c7ba14597e",
+ "patches": [],
+ "package": "swati4star.createpdf",
+ "license": null
+}
diff --git a/android/swati4star-images-to-pdf/reference/launch.sh b/android/swati4star-images-to-pdf/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/swati4star-images-to-pdf/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/swati4star-images-to-pdf/tests/android_computation_eval.json b/android/swati4star-images-to-pdf/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..573c70eca59f3f90e28255c5d7871cd6e3fc06da
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_computation_eval.json
@@ -0,0 +1,160 @@
+{
+ "module": "computation",
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1667,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 2,
+ "liveness": 0,
+ "interactive": 12,
+ "depth_ge1": 12,
+ "depth_ge2": 3,
+ "value": 12,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "computation_img_compression_50_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this dialog, is a percent sign '%' rendered immediately to the RIGHT of the number input field that contains '50'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this dialog, is a percent sign '%' rendered immediately to the RIGHT of the number input field that contains '50'?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_img_compression_50",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Image compression : 50 %"
+ },
+ {
+ "test": "computation_img_compression_80",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Image compression : 80 %"
+ },
+ {
+ "test": "computation_img_border_5",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Border width : 5"
+ },
+ {
+ "test": "computation_img_preview_color_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the large image preview in the centre of the screen a solid RED rectangle?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the large image preview in the centre of the screen a solid RED rectangle?",
+ "tag": "color"
+ },
+ {
+ "test": "computation_img_border_25",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Border width : 25"
+ },
+ {
+ "test": "computation_img_compression_invalid_rejected",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card unchanged: Image compression : 30 % (invalid 500 rejected)"
+ },
+ {
+ "test": "computation_img_border_invalid_rejected",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card unchanged: Border width : 0 (invalid 500 rejected)"
+ },
+ {
+ "test": "computation_text_font_size_20",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Font Size : 20"
+ },
+ {
+ "test": "computation_text_font_size_7",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Font Size : 7"
+ },
+ {
+ "test": "computation_text_font_size_invalid_rejected",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card unchanged: Font Size (Default : 11) (invalid 5000 rejected)"
+ },
+ {
+ "test": "computation_settings_compression_45",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Image Compression default value : 45 %"
+ },
+ {
+ "test": "computation_settings_font_size_18",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card: Font size default value : 18"
+ },
+ {
+ "test": "computation_settings_compression_invalid_rejected",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "card unchanged: Image Compression default value : 30 % (999 rejected)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/android_interaction_eval.json b/android/swati4star-images-to-pdf/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..9f9ab4bd7883d216526d2204717ce15908f81555
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_interaction_eval.json
@@ -0,0 +1,192 @@
+{
+ "module": "interaction",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.7,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 17,
+ "depth_ge2": 0,
+ "value": 12,
+ "vlm_fine": 5
+ },
+ "results": [
+ {
+ "test": "interaction_create_pdf_enabled_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a large solid ORANGE (not greyed-out) 'CREATE PDF' button visible below the 'SELECT IMAGES' button?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a large solid ORANGE (not greyed-out) 'CREATE PDF' button visible below the 'SELECT IMAGES' button?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_create_pdf_persists_disk",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "OPEN PDF button + kitrecH3888144.pdf written to output dir"
+ },
+ {
+ "test": "interaction_create_pdf_open_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a solid ORANGE button labelled 'OPEN PDF' visible near the top of the screen (replacing the earlier CREATE PDF button)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a solid ORANGE button labelled 'OPEN PDF' visible near the top of the screen (replacing the earlier CREATE PDF button)?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_created_pdf_in_viewfiles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "View Files row containing kitrecV3988524.pdf"
+ },
+ {
+ "test": "interaction_created_pdf_in_viewfiles_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the list show one or more file rows, each laid out as a checkbox on the left, a '.pdf' file name in the middle, and a size ('MB') plus a date on the right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does the list show one or more file rows, each laid out as a checkbox on the left, a '.pdf' file name in the middle, and a size ('MB') plus a date on the right?",
+ "tag": "layout"
+ },
+ {
+ "test": "interaction_created_pdf_in_history",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "History row kitrecY4129277.pdf with 'Created'"
+ },
+ {
+ "test": "interaction_create_survives_process_death",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "View Files row kitrecP4258984.pdf present after force_stop + relaunch"
+ },
+ {
+ "test": "interaction_multi_record_integrity",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "BOTH kitrecMa4393902.pdf and kitrecMb4393952.pdf listed in View Files"
+ },
+ {
+ "test": "interaction_multi_image_count",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "tvNoOfImages == '3 image(s) selected.'"
+ },
+ {
+ "test": "interaction_multi_image_count_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a status line reading 'image(s) selected.' positioned at the very BOTTOM of the screen, below the enhancement option cards?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a status line reading 'image(s) selected.' positioned at the very BOTTOM of the screen, below the enhancement option cards?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_viewfiles_single_check",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "row CheckBox false->true and toolbar count badge '1'"
+ },
+ {
+ "test": "interaction_viewfiles_single_check_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the checkbox on the LEFT of the first file row. Is it a FILLED solid orange square with a white check mark (i.e. checked), rather than an empty/outlined box?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the checkbox on the LEFT of the first file row. Is it a FILLED solid orange square with a white check mark (i.e. checked), rather than an empty/outlined box?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_viewfiles_multiselect_badge",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "toolbar count badge shows '2'"
+ },
+ {
+ "test": "interaction_viewfiles_multiselect_badge_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a bold number '2' displayed in the TOP toolbar area (to the right of the hamburger menu icon)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a bold number '2' displayed in the TOP toolbar area (to the right of the hamburger menu icon)?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_longpress_pdf_actions",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'PDF Actions' menu with Open/Rename/Share rows after long-press"
+ },
+ {
+ "test": "interaction_longpress_pdf_actions_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a pop-up menu titled 'PDF Actions' shown, listing several file actions such as 'Open File', 'Rename File' and 'Share File'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a pop-up menu titled 'PDF Actions' shown, listing several file actions such as 'Open File', 'Rename File' and 'Share File'?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_pagesize_then_create_sequence",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "kitrecPS5187108.pdf created (OPEN PDF + file on disk) after LETTER page size"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/android_navigation_eval.json b/android/swati4star-images-to-pdf/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..dbfc86140933af54be0123d5337ea70ea4f569c7
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_navigation_eval.json
@@ -0,0 +1,272 @@
+{
+ "module": "navigation",
+ "total": 26,
+ "passed": 26,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 6,
+ "liveness": 0,
+ "interactive": 20,
+ "depth_ge1": 20,
+ "depth_ge2": 5,
+ "value": 0,
+ "vlm_fine": 3
+ },
+ "results": [
+ {
+ "test": "nav_reach_images_to_pdf",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SELECT IMAGES visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_images_to_pdf_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a wide orange rectangular button near the top of the screen with the white text 'SELECT IMAGES'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a wide orange rectangular button near the top of the screen with the white text 'SELECT IMAGES'?",
+ "tag": "color"
+ },
+ {
+ "test": "nav_reach_text_to_pdf",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SELECT TEXT FILE visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_view_files",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Search visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_view_files_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the top orange toolbar, on the right side, are there several icons in a horizontal row (a magnifying-glass search icon and more icons to its right)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the top orange toolbar, on the right side, are there several icons in a horizontal row (a magnifying-glass search icon and more icons to its right)?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_history",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Filter visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_history_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the top toolbar of this History screen, are there two or more action icons on the right side of the title?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the top toolbar of this History screen, are there two or more action icons on the right side of the title?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_add_password",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SELECT A FILE visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_qr_barcode",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Scan QR code visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_excel_to_pdf",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Excel to PDF visible on target surface; Home 'Create new PDF' header gone"
+ },
+ {
+ "test": "nav_reach_add_watermark",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "wish to add watermark visible on target surface; Home 'Enhance Created PDFs' header gone"
+ },
+ {
+ "test": "nav_reach_rotate_pages",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "wish to rotate visible on target surface; Home 'Enhance Created PDFs' header gone"
+ },
+ {
+ "test": "nav_reach_merge_pdf",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SELECT FILES visible on target surface; Home 'Enhance Created PDFs' header gone"
+ },
+ {
+ "test": "nav_reach_split_pdf",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "SELECT A FILE visible on target surface; Home 'Enhance Created PDFs' header gone"
+ },
+ {
+ "test": "nav_reach_favourites",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "empty-state 'Select + icon to add your favourite features!' visible; Home header gone"
+ },
+ {
+ "test": "nav_reach_favourites_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a single orange heart icon in the middle of the screen with a grey line of text below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a single orange heart icon in the middle of the screen with a grey line of text below it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_open_drawer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "drawer 'Home' CheckedTextView newly visible (absent on Home grid)"
+ },
+ {
+ "test": "nav_open_drawer_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a navigation drawer open on the left, with a small app icon and the text 'PDF Converter' near its top-left header?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a navigation drawer open on the left, with a small app icon and the text 'PDF Converter' near its top-left header?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_drawer_view_files",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "View Files 'Search' toolbar action visible; drawer 'Home' gone"
+ },
+ {
+ "test": "nav_drawer_to_settings",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Theme default value : System' visible on Settings; drawer 'FAQ' item gone"
+ },
+ {
+ "test": "nav_drawer_to_settings_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this settings screen show a grid of rectangular option cards arranged in two columns?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this settings screen show a grid of rectangular option cards arranged in two columns?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_deep_picker",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Photo Picker 'Photos' tab visible; 'SELECT IMAGES' button gone"
+ },
+ {
+ "test": "nav_back_fragment_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "a Home section header back; 'SELECT IMAGES' gone after BACK"
+ },
+ {
+ "test": "nav_backstack_2hop",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "after BACK #1 SELECT IMAGES shown (picker gone); after BACK #2 Home grid restored"
+ },
+ {
+ "test": "nav_back_settings_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "a Home section header back; 'Theme default value' gone"
+ },
+ {
+ "test": "nav_back_favourites_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "a Home section header back; Favourites empty-state gone"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/android_states_eval.json b/android/swati4star-images-to-pdf/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..745dc3097add17e573d39ceb65ea34537dbc8c58
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_states_eval.json
@@ -0,0 +1,250 @@
+{
+ "module": "states",
+ "total": 23,
+ "passed": 19,
+ "failed": 4,
+ "pass_rate": 0.8261,
+ "rule": {
+ "total": 12,
+ "passed": 8,
+ "failed": 4,
+ "pass_rate": 0.6667
+ },
+ "vlm": {
+ "total": 11,
+ "passed": 11,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.9167,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 9,
+ "liveness": 0,
+ "interactive": 14,
+ "depth_ge1": 14,
+ "depth_ge2": 5,
+ "value": 1,
+ "vlm_fine": 11
+ },
+ "results": [
+ {
+ "test": "states_create_pdf_disabled",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "pdfCreate enabled=false before any image selected"
+ },
+ {
+ "test": "states_create_pdf_disabled_vlm",
+ "passed": true,
+ "message": "VLM: Q='The button labelled 'CREATE PDF' below the orange 'SELECT IMAGES' button — is it rendered in a muted GREY (disabled) fill rather than a saturated orange?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: The button labelled 'CREATE PDF' below the orange 'SELECT IMAGES' button — is it rendered in a muted GREY (disabled) fill rather than a saturated orange?",
+ "tag": "color"
+ },
+ {
+ "test": "states_create_pdf_enabled_after_image",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "pdfCreate enabled false->true; tvNoOfImages='1 image(s) selected.'"
+ },
+ {
+ "test": "states_create_pdf_enabled_after_image_vlm",
+ "passed": true,
+ "message": "VLM: Q='The button labelled 'CREATE PDF' — is it now rendered in a saturated ORANGE (enabled) fill, the same orange as the 'SELECT IMAGES' button above it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: The button labelled 'CREATE PDF' — is it now rendered in a saturated ORANGE (enabled) fill, the same orange as the 'SELECT IMAGES' button above it?",
+ "tag": "color"
+ },
+ {
+ "test": "states_pagesize_radio_letter",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "LETTER checked false->true (DEFAULT true->false); LETTER pre-checked after reopen"
+ },
+ {
+ "test": "states_pagesize_radio_letter_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this 'Set Page Size' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other options are empty grey circles?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this 'Set Page Size' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other options are empty grey circles?",
+ "tag": "color"
+ },
+ {
+ "test": "states_scaletype_radio_stretch",
+ "passed": false,
+ "message": "behavior_wrong: Stretch false->true, Maintain true->false, reopen Stretch checked=False",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Stretch checked false->true (Maintain true->false); Stretch pre-checked after reopen"
+ },
+ {
+ "test": "states_scaletype_radio_stretch_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this 'Set Image Scale Type' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other is an empty grey circle?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this 'Set Image Scale Type' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other is an empty grey circle?",
+ "tag": "color"
+ },
+ {
+ "test": "states_fontfamily_radio_helvetica",
+ "passed": false,
+ "message": "behavior_wrong: HELVETICA false->true, TIMES true->false, card label now 'Font Family : HELVETICA'",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "HELVETICA checked false->true; card 'Font Family (Default : HELVETICA)'"
+ },
+ {
+ "test": "states_fontfamily_radio_helvetica_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this 'Font Family' radio dialog listing COURIER, HELVETICA, TIMES_ROMAN, SYMBOL, etc, is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this 'Font Family' radio dialog listing COURIER, HELVETICA, TIMES_ROMAN, SYMBOL, etc, is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?",
+ "tag": "color"
+ },
+ {
+ "test": "states_set_as_default_checkbox",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Set as default' checkbox false->true; OK accepted (dialog closes)"
+ },
+ {
+ "test": "states_set_as_default_checkbox_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the checkbox next to the label 'Set as default' a FILLED square with a check mark, rather than an empty outlined square?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the checkbox next to the label 'Set as default' a FILLED square with a check mark, rather than an empty outlined square?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_viewfiles_row_checkbox_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a file row whose leading checkbox is a FILLED ORANGE square with a white check mark (a selected row), and a '1' shown in the top toolbar?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a file row whose leading checkbox is a FILLED ORANGE square with a white check mark (a selected row), and a '1' shown in the top toolbar?",
+ "tag": "color"
+ },
+ {
+ "test": "states_viewfiles_row_checkbox",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "row checkbox false->true + toolbar count badge '1'; uncheck -> false, badge gone"
+ },
+ {
+ "test": "states_theme_dark_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the app background a dark / near-black color with light (white/grey) text, rather than a light/white background?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the app background a dark / near-black color with light (white/grey) text, rather than a light/white background?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_persists",
+ "passed": false,
+ "message": "behavior_wrong: theme label 'Theme default value : System'->'' (dark_checked=True); after restart 'Theme default value : Dark'",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme 'System'->'Dark'; still 'Dark' after force-stop relaunch"
+ },
+ {
+ "test": "states_theme_white_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the app background a bright WHITE / light color (not dark), with the top toolbar in orange?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the app background a bright WHITE / light color (not dark), with the top toolbar in orange?",
+ "tag": "color"
+ },
+ {
+ "test": "states_fontsize_default_persists",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Font size default '11'->'18'; still '18' after force-stop relaunch"
+ },
+ {
+ "test": "states_pagesize_default_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this page-size radio dialog (options DEFAULT ( A4 ), Fit size, LETTER, LEGAL, ...), is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this page-size radio dialog (options DEFAULT ( A4 ), Fit size, LETTER, LEGAL, ...), is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?",
+ "tag": "color"
+ },
+ {
+ "test": "states_pagesize_default_persists",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Page size default 'A4'->'LETTER'; still 'LETTER' after force-stop relaunch"
+ },
+ {
+ "test": "states_drawer_home_selected_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this open navigation drawer, is the 'Home' item highlighted with a light ORANGE/pink pill-shaped background and orange text and icon, while the other items (Create PDF, Text To PDF, ...) have a plain white background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this open navigation drawer, is the 'Home' item highlighted with a light ORANGE/pink pill-shaped background and orange text and icon, while the other items (Create PDF, Text To PDF, ...) have a plain white background?",
+ "tag": "color"
+ },
+ {
+ "test": "states_drawer_home_selected",
+ "passed": false,
+ "message": "behavior_wrong: Home checked on launch=true; after nav Home='true' TextToPDF='false' (expected Home false, TextToPDF true)",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Home checked=true on launch; after nav to Text To PDF that item checked=true & Home checked=false"
+ },
+ {
+ "test": "states_password_show_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "password field obscured->revealed (EditText password true->false or desc 'Show'->'Hide')"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/android_structure_eval.json b/android/swati4star-images-to-pdf/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..2c54f9f206710bac68fd3e78988953e66ea68e5a
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_structure_eval.json
@@ -0,0 +1,163 @@
+{
+ "module": "structure",
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.5556,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 8,
+ "liveness": 0,
+ "interactive": 6,
+ "depth_ge1": 5,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_home_toolbar_present",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_home_grid_cards",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_home_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Directly below the 'Create new PDF' section heading, are there two feature cards positioned side by side in the same horizontal row (one on the left, one on the right)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Directly below the 'Create new PDF' section heading, are there two feature cards positioned side by side in the same horizontal row (one on the left, one on the right)?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_drawer_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "drawer opens: design_navigation_view + >=8 new CheckedTextView items appear; both gone again on close"
+ },
+ {
+ "test": "structure_drawer_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a navigation drawer open, covering roughly the left two-thirds of the screen as a vertical list of menu items, with the rest of the screen dimmed on the right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a navigation drawer open, covering roughly the left two-thirds of the screen as a vertical list of menu items, with the rest of the screen dimmed on the right?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_home_to_fragment_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "home grid -> img2pdf fragment: SELECT IMAGES button + enhancement_options_recycle_view appear; text_to_pdf card gone"
+ },
+ {
+ "test": "structure_settings_grid_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "drawer->Settings: settings_list GridView appears, home images_to_pdf card gone"
+ },
+ {
+ "test": "structure_settings_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the main content of this Settings screen a grid of option cards arranged two per row (two evenly spaced columns)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the main content of this Settings screen a grid of option cards arranged two per row (two evenly spaced columns)?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_home_scroll_reveals",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "scrolling home reveals >=1 feature card not visible before"
+ },
+ {
+ "test": "structure_pagesize_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a dialog box centered on the screen, overlaying and dimming the content behind it?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a dialog box centered on the screen, overlaying and dimming the content behind it?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_pagesize_dialog_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Set Page Size overlays a dialog adding >=3 RadioButtons; gone again on cancel"
+ },
+ {
+ "test": "structure_history_toolbar_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "home->History: Delete+Filter toolbar icons + historyRecyclerView appear (absent on home)"
+ },
+ {
+ "test": "structure_toolbar_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a single horizontal top bar with a screen title text on the left side and one or more icon buttons on the right side, all in the same row?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a single horizontal top bar with a screen title text on the left side and one or more icon buttons on the right side, all in the same row?",
+ "tag": "layout"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/android_testgen_kit.py b/android/swati4star-images-to-pdf/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/swati4star-images-to-pdf/tests/android_text_eval.json b/android/swati4star-images-to-pdf/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..87448c49212783344451dda218cc5bf5543082c9
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/android_text_eval.json
@@ -0,0 +1,196 @@
+{
+ "module": "text",
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.125,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 18,
+ "depth_ge1": 17,
+ "depth_ge2": 11,
+ "value": 18,
+ "vlm_fine": 0
+ },
+ "results": [
+ {
+ "test": "text_home_section_headers",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Create new PDF' | 'View PDFs' | 'Enhance Created PDFs'"
+ },
+ {
+ "test": "text_img2pdf_card_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Image compression : 30 %' | 'Set Page Size' | 'Set Image Scale Type' | 'Border width : 0'"
+ },
+ {
+ "test": "text_one_image_selected_status",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "tvNoOfImages == '1 image(s) selected.'"
+ },
+ {
+ "test": "text_two_images_selected_status",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "tvNoOfImages == '2 image(s) selected.'"
+ },
+ {
+ "test": "text_dialog_compression_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Change image compression value' + label 'Enter %% compression of image :'"
+ },
+ {
+ "test": "text_dialog_border_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Add Image Border' + label 'Enter border width units'"
+ },
+ {
+ "test": "text_dialog_pagesize_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Set Page Size' + option 'DEFAULT ( A4 )'"
+ },
+ {
+ "test": "text_dialog_scaletype_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Set Image Scale Type' + options 'Maintain aspect ratio of images' / 'Stretch image to fit on page'"
+ },
+ {
+ "test": "text_dialog_password_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Set Password' + EditText hint 'pass@123'"
+ },
+ {
+ "test": "text_creating_pdf_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Creating PDF' + EditText hint 'Enter file name'"
+ },
+ {
+ "test": "text_create_pdf_snackbar_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a dark banner across the bottom of the screen showing the message 'PDF created!'?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a dark banner across the bottom of the screen showing the message 'PDF created!'?",
+ "tag": "content"
+ },
+ {
+ "test": "text_text2pdf_font_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Font Size (Default : 11)' | 'Font Family (Default : TIMES_ROMAN)'"
+ },
+ {
+ "test": "text_text2pdf_fontsize_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "label 'Enter font size' + EditText hint 'Example : 10'"
+ },
+ {
+ "test": "text_favourites_empty_state",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'Favourites' + 'Select + icon to add your favourite features!'"
+ },
+ {
+ "test": "text_favourites_empty_state_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show the message 'Select + icon to add your favourite features!'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does this screen show the message 'Select + icon to add your favourite features!'?",
+ "tag": "content"
+ },
+ {
+ "test": "text_settings_storage_path",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Storage location(non-changeable)' + '/storage/emulated/0/PDF Converter/'"
+ },
+ {
+ "test": "text_settings_default_labels",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Image Compression default value : 30 %' | 'Page size default value : A4' | 'Font size default value : 11' | 'Font family default value : TIMES_ROMAN' | 'Theme default value : System'"
+ },
+ {
+ "test": "text_settings_intro_line",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'You can modify the default value for various settings here.'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/tests/conftest.py b/android/swati4star-images-to-pdf/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/swati4star-images-to-pdf/tests/requirements.txt b/android/swati4star-images-to-pdf/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/swati4star-images-to-pdf/tests/test_android_computation.py b/android/swati4star-images-to-pdf/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c8ecfb1e3bd02d67633c414d8d118dc5a6b6305
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_computation.py
@@ -0,0 +1,553 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — CORE FUNCTION input -> output for the PDF Converter app
+(swati4star.createpdf and any faithful recreation).
+
+This app has no calculator; its input->output surfaces are the *value dialogs*
+whose numeric input is written back into a visible card label. Each test drives
+the real user path (open the fragment, open the dialog, type a value, tap OK) and
+reads the resulting label out of a FRESH ui(). Every expected string was OBSERVED
+on the running original before authoring — never computed from the source. Where
+the source label format and the delegation brief disagreed, the LIVE observation
+wins (e.g. the Text-to-PDF font-size card renders "Font Size : N", NOT
+"Font Size (Default : N)").
+
+Ground truth confirmed live on the original:
+ * Images-to-PDF (needs >=1 selected image):
+ - Image compression dialog: type N -> card "Image compression : N %"
+ - Border width dialog: type N -> card "Border width : N"
+ - Out-of-range (compression >100/<0, border >200/<0) -> R.string.invalid_entry
+ snackbar and the card label is UNCHANGED.
+ * Text-to-PDF (no file needed):
+ - Font size dialog: type N -> card "Font Size : N" (observed live)
+ * Settings (drawer -> Settings; SharedPreferences-backed):
+ - "Image Compression default value : N %" ; "Font size default value : N"
+ - out-of-range -> unchanged.
+
+Sole owner of jump_kind="value": every record here is "value" except the two VLM
+records. Each test resets to factory defaults with clear_data() so the starting
+label ("30 %", "0", "11") is deterministic on BOTH the original and any
+recreation, and so the ABSENT-before / PRESENT-after pairing is meaningful even
+though Settings values persist.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Home entry. clear_data() guarantees factory defaults (so compression starts at
+# 30 %, border at 0, font at 11) AND re-arms the first-run storage-permission
+# dialog, which we DENY (we never seed the permission). Fixtures live on
+# /sdcard/Download, not in app data, so pm clear does not remove them.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def on_home(nodes=None) -> bool:
+ nodes = ui() if nodes is None else nodes
+ return (find_node(nodes, text="Create new PDF") is not None
+ or find_node(nodes, text="View PDFs") is not None)
+
+
+def _dismiss_permission_if_present() -> None:
+ nodes = ui()
+ deny = find_node(nodes, text="DENY") or find_node(nodes, text="Deny")
+ if deny is not None and is_safe(deny):
+ tap_node(deny)
+ settle("tap")
+
+
+def home_ready() -> bool:
+ """Deterministic Home grid at factory defaults."""
+ clear_data()
+ settle("key")
+ launch_app()
+ wait_for_foreground()
+ settle("launch")
+ for _ in range(5):
+ if on_home():
+ break
+ _dismiss_permission_if_present()
+ if on_home():
+ break
+ back()
+ settle("launch")
+ for _ in range(4):
+ scroll_up(0.8)
+ settle("tap")
+ return on_home()
+
+
+def option_labels(nodes=None) -> list[str]:
+ """Every enhancement/settings card label (resource-id ...option_name)."""
+ nodes = ui() if nodes is None else nodes
+ return [n.get("text", "") for n in nodes
+ if n.get("resource-id", "").endswith("option_name")]
+
+
+def label_matching(substr, nodes=None):
+ """The first option_name label CONTAINING substr (case-insensitive), or ''."""
+ s = substr.lower()
+ for lbl in option_labels(nodes):
+ if s in lbl.lower():
+ return lbl
+ return ""
+
+
+def tap_card(label_substr: str) -> bool:
+ """Tap the enhancement/settings card whose option_name label contains
+ `label_substr`. The option_name TextView is not itself clickable, but its
+ centre lies inside the clickable card container, so tapping the TextView
+ centre reliably opens the dialog (verified live)."""
+ for n in ui():
+ if (n.get("resource-id", "").endswith("option_name")
+ and label_substr.lower() in n.get("text", "").lower()):
+ return tap_node(n)
+ return False
+
+
+# ── depth-backing navigation helpers (the and_enter_* NAME backs depth>=1) ──────
+
+def and_enter_images_to_pdf() -> bool:
+ """Home -> Images to PDF fragment (SELECT IMAGES / CREATE PDF surface)."""
+ n = node_by_id(ui(), "images_to_pdf") or scroll_into_view("Images to PDF")
+ if n is None or not tap_node(n):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "addImages") is None:
+ return False
+ and_enter("images_to_pdf")
+ return True
+
+
+def and_enter_text_to_pdf() -> bool:
+ """Home -> Text To PDF fragment (SELECT TEXT FILE / CREATE PDF surface)."""
+ n = node_by_id(ui(), "text_to_pdf") or scroll_into_view("Text To PDF")
+ if n is None or not tap_node(n):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "createtextpdf") is None:
+ return False
+ and_enter("text_to_pdf")
+ return True
+
+
+def and_enter_drawer() -> bool:
+ """Open the navigation drawer via the hamburger (ImageButton content-desc
+ 'PDF Converter'). Confirmed by the 'Home' drawer item appearing."""
+ hb = None
+ for n in ui():
+ if (n.get("class", "").endswith("ImageButton")
+ and n.get("content-desc") == "PDF Converter"):
+ hb = n
+ break
+ if hb is None or not tap_node(hb):
+ return False
+ settle("tap")
+ if find_node(ui(), text="Home") is None:
+ return False
+ and_enter("drawer")
+ return True
+
+
+def and_enter_settings() -> bool:
+ """From the open drawer, scroll to and tap 'Settings'. Confirmed by the
+ Settings storage-location label (unique to that fragment) appearing."""
+ target = None
+ for _ in range(7):
+ nodes = ui()
+ target = find_node(nodes, text="Settings")
+ if target is not None:
+ break
+ scrollers = [x for x in nodes if x.get("scrollable") == "true" and "_bounds" in x]
+ if scrollers:
+ x1, y1, x2, y2 = scrollers[0]["_bounds"]
+ cx = (x1 + x2) // 2
+ swipe(cx, int(y1 + (y2 - y1) * 0.72), cx, int(y1 + (y2 - y1) * 0.28))
+ else:
+ scroll_down(0.5)
+ settle("tap")
+ if target is None or not tap_node(target):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "storagelocation") is None:
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_reach_settings() -> bool:
+ """Home -> drawer -> Settings (depth 2)."""
+ return and_enter_drawer() and and_enter_settings()
+
+
+# ── the core precondition for the Images-to-PDF dialogs ─────────────────────────
+
+def select_one_image() -> str | None:
+ """From the Images-to-PDF fragment: SELECT IMAGES -> pick one photo in the
+ system Photo Picker -> tap 'Add (1)' -> back in the fragment. Returns the
+ observed tvNoOfImages text (re-dumped), or None on failure. The picker is a
+ different process, so we re-dump after returning."""
+ add = node_by_id(ui(), "addImages")
+ if add is None or not tap_node(add):
+ return None
+ settle("launch")
+ settle("tap")
+ photos = []
+ for _ in range(6):
+ photos = [x for x in ui()
+ if x.get("content-desc", "").lower().startswith("photo taken")]
+ if photos:
+ break
+ settle("tap")
+ if not photos:
+ return None
+ if not tap_node(photos[0]):
+ return None
+ settle("tap")
+ addbtn = None
+ for _ in range(4):
+ addbtn = next((x for x in ui()
+ if x.get("text", "").strip().lower().startswith("add (")), None)
+ if addbtn is not None:
+ break
+ settle("tap")
+ if addbtn is None or not tap_node(addbtn):
+ return None
+ settle("launch")
+ settle("tap")
+ tv = node_by_id(ui(), "tvNoOfImages")
+ return tv.get("text") if tv is not None else None
+
+
+# ── the shared dialog driver: clear the field, type, tap OK ─────────────────────
+
+def type_into_dialog(edit_rid: str, value: str) -> bool:
+ """Locate the dialog's EditText by resource-id suffix, clear whatever it holds,
+ type `value`, then tap OK against a FRESH dump (OK repositions when the soft
+ keyboard opens; hiding the keyboard here would BACK-dismiss the dialog)."""
+ et = node_by_id(ui(), edit_rid)
+ if et is None:
+ return False
+ if not tap_node(et):
+ return False
+ settle("keyboard")
+ # clear any prefilled content deterministically
+ press_key("KEYCODE_MOVE_END")
+ for _ in range(8):
+ press_key("67") # KEYCODE_DEL
+ settle("text")
+ fresh = node_by_id(ui(), edit_rid)
+ if fresh is None:
+ return False
+ if not type_text(fresh, value, verify_focus=False):
+ return False
+ settle("text")
+ okbtn = find_node_ci(ui(), "OK")
+ if okbtn is None or not tap_node(okbtn):
+ return False
+ settle("tap")
+ settle("tap")
+ return True
+
+
+def norm(s: str) -> str:
+ """Collapse internal whitespace and strip, so ' Border width : 5 ' compares
+ equal to 'Border width : 5' across renderers."""
+ return " ".join((s or "").split())
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — Images to PDF (require a selected image; depth 1 = the fragment)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_img_compression_50", "computation_img_compression_50_vlm"))
+def test_img_compression_50():
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF compression dialog"
+ dialog_shot_ready = False
+ if home_ready() and and_enter_images_to_pdf():
+ if select_one_image():
+ before = label_matching("compression")
+ absent_before = norm(before) == "Image compression : 30 %"
+ if tap_card("Image compression"):
+ settle("tap")
+ # capture the dialog with a value typed, for the VLM % question
+ et = node_by_id(ui(), "quality")
+ if et is not None and tap_node(et):
+ settle("keyboard")
+ type_text(node_by_id(ui(), "quality") or et, "50", verify_focus=False)
+ settle("text")
+ dialog_shot_ready = True
+ vlm_assert("computation_img_compression_50",
+ "In this dialog, is a percent sign '%' rendered "
+ "immediately to the RIGHT of the number input field "
+ "that contains '50'?",
+ RESULTS_DIR, tag="position")
+ okbtn = find_node_ci(ui(), "OK")
+ if okbtn is not None and tap_node(okbtn):
+ settle("tap")
+ settle("tap")
+ after = label_matching("compression")
+ ok = (norm(after) == "Image compression : 50 %"
+ and absent_before)
+ msg = ("" if ok else
+ f"behavior_wrong: compression label={after!r} "
+ f"(before={before!r}), expected 'Image compression : 50 %'")
+ if not dialog_shot_ready:
+ # the VLM record must still exist on every path (fixed denominator)
+ vlm_assert("computation_img_compression_50",
+ "In this dialog, is a percent sign '%' rendered immediately to "
+ "the RIGHT of the number input field that contains '50'?",
+ RESULTS_DIR, tag="position")
+ record("computation_img_compression_50", ok, msg,
+ depth=1, jump_kind="value", expect="card: Image compression : 50 %")
+
+
+@and_test(expects=("computation_img_compression_80",))
+def test_img_compression_80():
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF compression dialog"
+ if home_ready() and and_enter_images_to_pdf() and select_one_image():
+ before = label_matching("compression")
+ absent_before = norm(before) == "Image compression : 30 %"
+ if tap_card("Image compression") and type_into_dialog("quality", "80"):
+ after = label_matching("compression")
+ ok = norm(after) == "Image compression : 80 %" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: compression label={after!r} (before={before!r}), "
+ f"expected 'Image compression : 80 %'")
+ record("computation_img_compression_80", ok, msg,
+ depth=1, jump_kind="value", expect="card: Image compression : 80 %")
+
+
+@and_test(expects=("computation_img_border_5",))
+def test_img_border_5():
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF border dialog"
+ if home_ready() and and_enter_images_to_pdf() and select_one_image():
+ before = label_matching("Border width")
+ absent_before = norm(before) == "Border width : 0"
+ if tap_card("Border width") and type_into_dialog("border_width", "5"):
+ after = label_matching("Border width")
+ ok = norm(after) == "Border width : 5" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: border label={after!r} (before={before!r}), "
+ f"expected 'Border width : 5'")
+ record("computation_img_border_5", ok, msg,
+ depth=1, jump_kind="value", expect="card: Border width : 5")
+
+
+@and_test(expects=("computation_img_border_25", "computation_img_preview_color_vlm"))
+def test_img_border_25_and_preview():
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF border dialog"
+ reached_preview = False
+ if home_ready() and and_enter_images_to_pdf() and select_one_image():
+ before = label_matching("Border width")
+ absent_before = norm(before) == "Border width : 0"
+ if tap_card("Border width") and type_into_dialog("border_width", "25"):
+ after = label_matching("Border width")
+ ok = norm(after) == "Border width : 25" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: border label={after!r} (before={before!r}), "
+ f"expected 'Border width : 25'")
+ # open Preview to render the selected image (the red fixture)
+ if tap_card("Preview"):
+ settle("launch")
+ settle("launch")
+ if find_node(ui(), text="Showing 1 of 1 image(s)") is not None:
+ reached_preview = True
+ vlm_assert("computation_img_preview_color",
+ "Is the large image preview in the centre of the "
+ "screen a solid RED rectangle?",
+ RESULTS_DIR, tag="color")
+ if not reached_preview:
+ vlm_assert("computation_img_preview_color",
+ "Is the large image preview in the centre of the screen a solid "
+ "RED rectangle?",
+ RESULTS_DIR, tag="color")
+ record("computation_img_border_25", ok, msg,
+ depth=1, jump_kind="value", expect="card: Border width : 25")
+
+
+@and_test(expects=("computation_img_compression_invalid_rejected",))
+def test_img_compression_invalid_rejected():
+ """Compression >100 is out of range -> R.string.invalid_entry, label unchanged."""
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF compression dialog"
+ if home_ready() and and_enter_images_to_pdf() and select_one_image():
+ before = label_matching("compression")
+ if norm(before) != "Image compression : 30 %":
+ msg = f"setup_failed: unexpected starting label {before!r}"
+ elif tap_card("Image compression") and type_into_dialog("quality", "500"):
+ after = label_matching("compression")
+ ok = norm(after) == "Image compression : 30 %"
+ msg = ("" if ok else
+ f"behavior_wrong: invalid value 500 was accepted; label={after!r}, "
+ f"expected unchanged 'Image compression : 30 %'")
+ record("computation_img_compression_invalid_rejected", ok, msg,
+ depth=1, jump_kind="value",
+ expect="card unchanged: Image compression : 30 % (invalid 500 rejected)")
+
+
+@and_test(expects=("computation_img_border_invalid_rejected",))
+def test_img_border_invalid_rejected():
+ """Border >200 is out of range -> R.string.invalid_entry, label unchanged."""
+ ok = False
+ msg = "setup_failed: could not reach Images-to-PDF border dialog"
+ if home_ready() and and_enter_images_to_pdf() and select_one_image():
+ before = label_matching("Border width")
+ if norm(before) != "Border width : 0":
+ msg = f"setup_failed: unexpected starting label {before!r}"
+ elif tap_card("Border width") and type_into_dialog("border_width", "500"):
+ after = label_matching("Border width")
+ ok = norm(after) == "Border width : 0"
+ msg = ("" if ok else
+ f"behavior_wrong: invalid value 500 was accepted; label={after!r}, "
+ f"expected unchanged 'Border width : 0'")
+ record("computation_img_border_invalid_rejected", ok, msg,
+ depth=1, jump_kind="value",
+ expect="card unchanged: Border width : 0 (invalid 500 rejected)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — Text to PDF (no file needed; depth 1 = the fragment)
+# The font-size dialog TITLE stays 'Font Size (Default : 11)', but on OK the CARD
+# label is set from R.string.font_size -> 'Font Size : N' (observed live).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_text_font_size_20",))
+def test_text_font_size_20():
+ ok = False
+ msg = "setup_failed: could not reach Text-to-PDF font-size dialog"
+ if home_ready() and and_enter_text_to_pdf():
+ before = label_matching("Font Size")
+ absent_before = norm(before) == "Font Size (Default : 11)"
+ if tap_card("Font Size") and type_into_dialog("fontInput", "20"):
+ after = label_matching("Font Size")
+ ok = norm(after) == "Font Size : 20" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: font-size label={after!r} (before={before!r}), "
+ f"expected 'Font Size : 20'")
+ record("computation_text_font_size_20", ok, msg,
+ depth=1, jump_kind="value", expect="card: Font Size : 20")
+
+
+@and_test(expects=("computation_text_font_size_7",))
+def test_text_font_size_7():
+ ok = False
+ msg = "setup_failed: could not reach Text-to-PDF font-size dialog"
+ if home_ready() and and_enter_text_to_pdf():
+ before = label_matching("Font Size")
+ absent_before = norm(before) == "Font Size (Default : 11)"
+ if tap_card("Font Size") and type_into_dialog("fontInput", "7"):
+ after = label_matching("Font Size")
+ ok = norm(after) == "Font Size : 7" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: font-size label={after!r} (before={before!r}), "
+ f"expected 'Font Size : 7'")
+ record("computation_text_font_size_7", ok, msg,
+ depth=1, jump_kind="value", expect="card: Font Size : 7")
+
+
+@and_test(expects=("computation_text_font_size_invalid_rejected",))
+def test_text_font_size_invalid_rejected():
+ """Font size >1000 is out of range -> invalid_entry; card label unchanged."""
+ ok = False
+ msg = "setup_failed: could not reach Text-to-PDF font-size dialog"
+ if home_ready() and and_enter_text_to_pdf():
+ before = label_matching("Font Size")
+ if norm(before) != "Font Size (Default : 11)":
+ msg = f"setup_failed: unexpected starting label {before!r}"
+ elif tap_card("Font Size") and type_into_dialog("fontInput", "5000"):
+ after = label_matching("Font Size")
+ ok = norm(after) == "Font Size (Default : 11)"
+ msg = ("" if ok else
+ f"behavior_wrong: invalid value 5000 was accepted; label={after!r}, "
+ f"expected unchanged 'Font Size (Default : 11)'")
+ record("computation_text_font_size_invalid_rejected", ok, msg,
+ depth=1, jump_kind="value",
+ expect="card unchanged: Font Size (Default : 11) (invalid 5000 rejected)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — Settings (drawer -> Settings -> dialog; depth 2)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_settings_compression_45",))
+def test_settings_compression_45():
+ ok = False
+ msg = "setup_failed: could not reach Settings compression dialog"
+ if home_ready() and and_reach_settings():
+ before = label_matching("Image Compression default")
+ absent_before = norm(before) == "Image Compression default value : 30 %"
+ if tap_card("Image Compression default") and type_into_dialog("quality", "45"):
+ after = label_matching("Image Compression default")
+ ok = norm(after) == "Image Compression default value : 45 %" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: settings compression label={after!r} "
+ f"(before={before!r}), expected 'Image Compression default value : 45 %'")
+ record("computation_settings_compression_45", ok, msg,
+ depth=2, jump_kind="value",
+ expect="card: Image Compression default value : 45 %")
+
+
+@and_test(expects=("computation_settings_font_size_18",))
+def test_settings_font_size_18():
+ ok = False
+ msg = "setup_failed: could not reach Settings font-size dialog"
+ if home_ready() and and_reach_settings():
+ before = label_matching("Font size default")
+ absent_before = norm(before) == "Font size default value : 11"
+ if tap_card("Font size default") and type_into_dialog("fontInput", "18"):
+ after = label_matching("Font size default")
+ ok = norm(after) == "Font size default value : 18" and absent_before
+ msg = ("" if ok else
+ f"behavior_wrong: settings font-size label={after!r} "
+ f"(before={before!r}), expected 'Font size default value : 18'")
+ record("computation_settings_font_size_18", ok, msg,
+ depth=2, jump_kind="value", expect="card: Font size default value : 18")
+
+
+@and_test(expects=("computation_settings_compression_invalid_rejected",))
+def test_settings_compression_invalid_rejected():
+ """Settings compression >100 -> invalid_entry; label unchanged."""
+ ok = False
+ msg = "setup_failed: could not reach Settings compression dialog"
+ if home_ready() and and_reach_settings():
+ before = label_matching("Image Compression default")
+ if norm(before) != "Image Compression default value : 30 %":
+ msg = f"setup_failed: unexpected starting label {before!r}"
+ elif tap_card("Image Compression default") and type_into_dialog("quality", "999"):
+ after = label_matching("Image Compression default")
+ ok = norm(after) == "Image Compression default value : 30 %"
+ msg = ("" if ok else
+ f"behavior_wrong: invalid value 999 accepted; label={after!r}, "
+ f"expected unchanged 'Image Compression default value : 30 %'")
+ record("computation_settings_compression_invalid_rejected", ok, msg,
+ depth=2, jump_kind="value",
+ expect="card unchanged: Image Compression default value : 30 % (999 rejected)")
+
+
+TESTS = [
+ test_img_compression_50,
+ test_img_compression_80,
+ test_img_border_5,
+ test_img_border_25_and_preview,
+ test_img_compression_invalid_rejected,
+ test_img_border_invalid_rejected,
+ test_text_font_size_20,
+ test_text_font_size_7,
+ test_text_font_size_invalid_rejected,
+ test_settings_compression_45,
+ test_settings_font_size_18,
+ test_settings_compression_invalid_rejected,
+]
+
+
+if __name__ == "__main__":
+ if not device_online():
+ print("device offline — cannot run computation suite")
+ sys.exit(2)
+ run_suite(TESTS, "computation")
diff --git a/android/swati4star-images-to-pdf/tests/test_android_interaction.py b/android/swati4star-images-to-pdf/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..b77d08f608e120f8f9da43693aad61e2b5dcf278
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_interaction.py
@@ -0,0 +1,774 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — EFFECT-BY-CONSEQUENCE on user DATA for the PDF Converter app
+(swati4star.createpdf and any faithful recreation).
+
+The backbone is the app's #1 feature: Images -> PDF creation via the system Photo
+Picker. Fixtures img_red/green/blue.png are pushed by the kit into /sdcard/Download
+and surface in the picker as MediaStore images. Every test drives the real user
+path, then reads the consequence out of a FRESH ui().
+
+Lane focus (validated on the running original before authoring):
+ * CRUD create: select image -> CREATE PDF -> name it -> OPEN PDF morph + file on disk
+ * multi-surface data integrity: the created PDF appears in View Files and History
+ * DATA persistence across process death (highest value; in-memory recreation fails)
+ * multi-record integrity: two uniquely-named PDFs both survive and are both listed
+ * multi-image selection count; View-Files row selection + count badge
+ * long-press context menu (sole owner): a row long-press opens "PDF Actions"
+"""
+import os
+import sys
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+# Public, fixed output directory of the app (documented in recon; NOT a per-package
+# data path). Reading it is an optional strengthener; the UI is the primary oracle.
+OUTPUT_DIR = "/storage/emulated/0/PDF Converter/"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Marker-name helper: every created record carries a distinctive, unique marker so
+# a read-back cannot accidentally match pre-existing content, and reruns/the eval
+# run never collide with leftover files on disk.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def mark(suffix: str = "") -> str:
+ """A unique, filesystem-safe PDF base name, e.g. 'kitrecA1785999708'."""
+ return f"kitrec{suffix}{int(time.time() * 1000) % 100000000}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Home entry — the app RESTORES its last fragment after a force-stop, and the grid
+# grows a "Recently Used Features" row after features are used, so a naive
+# restart_app() does NOT land on the grid. home_ready() force-stops, relaunches,
+# then presses BACK until the Home grid ("Create new PDF" / "View PDFs") is showing
+# and scrolls the grid to the top. Cards are then located by resource-id.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def on_home(nodes=None) -> bool:
+ nodes = ui() if nodes is None else nodes
+ return (find_node(nodes, text="Create new PDF") is not None
+ or find_node(nodes, text="View PDFs") is not None)
+
+
+def _dismiss_permission_if_present() -> None:
+ """First-run storage permission dialog: DENY keeps us in the app without
+ granting (we never seed the permission). Tap it only if present."""
+ nodes = ui()
+ deny = find_node(nodes, text="DENY") or find_node(nodes, text="Deny")
+ if deny is not None and is_safe(deny):
+ tap_node(deny)
+ settle("tap")
+
+
+def home_ready() -> bool:
+ """Deterministic Home surface. Returns True when the grid is showing."""
+ force_stop()
+ settle("key")
+ launch_app()
+ wait_for_foreground()
+ settle("launch")
+ for _ in range(4):
+ if on_home():
+ break
+ _dismiss_permission_if_present()
+ if on_home():
+ break
+ back()
+ settle("launch")
+ for _ in range(4):
+ scroll_up(0.8)
+ settle("tap")
+ return on_home()
+
+
+def open_card(rid: str, label: str) -> bool:
+ """Tap a home feature card by resource-id suffix; fall back to a scroll-to
+ by its visible label if it is off screen."""
+ n = node_by_id(ui(), rid)
+ if n is None:
+ n = scroll_into_view(label)
+ return tap_node(n) if n is not None else False
+
+
+# ── depth-backing navigation helpers (the and_enter_*/and_reach_* NAME backs the
+# declared depth>=1; see android_testgen_kit and_audit_depth). ─────────────────
+
+def and_enter_images_to_pdf() -> bool:
+ """Home -> Images to PDF fragment. Confirms SELECT IMAGES / CREATE PDF surface."""
+ if not open_card("images_to_pdf", "Images to PDF"):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "addImages") is None:
+ return False
+ and_enter("images_to_pdf")
+ return True
+
+
+def _reach_via_unique_id(card_node, unique_rid: str) -> bool:
+ """Tap a Home card and PROVE the jump with a resource-id that only exists on
+ the destination surface. A toolbar TITLE cannot serve as proof here: the Home
+ grid carries a card labelled with the same text (e.g. a 'View Files' card), so
+ the title is not a *new* key and and_reach would reject it. We poll for the
+ destination to finish rendering (its RecyclerView loads async), then require
+ the unique element to have appeared AND the Home section header 'Create new
+ PDF' to have disappeared. Counts one surface via and_enter on success."""
+ if card_node is None:
+ return False
+ before = and_showing()
+ if not tap_node(card_node):
+ return False
+ for _ in range(6):
+ settle("launch")
+ if node_by_id(ui(), unique_rid) is not None:
+ break
+ after = and_showing()
+ ok = and_reach(before, after, unique_rid, "Create new PDF")
+ if ok:
+ and_enter(unique_rid)
+ return ok
+
+
+def and_reach_view_files() -> bool:
+ """Home -> View Files. Jump proven by the files RecyclerView appearing (unique
+ to this surface) while the Home 'Create new PDF' header disappears."""
+ n = node_by_id(ui(), "view_files") or scroll_into_view("View Files")
+ return _reach_via_unique_id(n, "filesRecyclerView")
+
+
+def and_reach_history() -> bool:
+ """Home -> History. Jump proven by the history RecyclerView appearing."""
+ n = node_by_id(ui(), "view_history") or scroll_into_view("History")
+ return _reach_via_unique_id(n, "historyRecyclerView")
+
+
+# ── the core selection helper: the foundation of most tests ────────────────────
+
+def select_images(n: int) -> str | None:
+ """From the Images-to-PDF fragment: SELECT IMAGES -> pick `n` photos in the
+ Photo Picker -> tap 'Add (N)' -> back in the fragment. Returns the observed
+ tvNoOfImages string (re-dumped) or None on failure.
+
+ The picker is a different process, so we re-dump after returning before
+ reading tvNoOfImages / button states.
+ """
+ add = node_by_id(ui(), "addImages")
+ if add is None or not tap_node(add):
+ return None
+ settle("launch")
+ settle("tap")
+ # The picker can be slow to populate; retry the photo scan.
+ photos = []
+ for _ in range(4):
+ photos = [x for x in ui()
+ if x.get("content-desc", "").lower().startswith("photo taken")]
+ if len(photos) >= n:
+ break
+ settle("tap")
+ if len(photos) < n:
+ return None
+ for p in photos[:n]:
+ tap_node(p)
+ settle("tap")
+ addbtn = None
+ for _ in range(3):
+ addbtn = next((x for x in ui()
+ if x.get("text", "").strip().lower().startswith("add (")), None)
+ if addbtn is not None:
+ break
+ settle("tap")
+ if addbtn is None or not tap_node(addbtn):
+ return None
+ settle("launch")
+ settle("tap")
+ tv = node_by_id(ui(), "tvNoOfImages")
+ return tv.get("text") if tv is not None else None
+
+
+def create_pdf_named(name: str) -> bool:
+ """From the fragment with >=1 image selected: tap CREATE PDF, clear the
+ prefilled auto filename, type `name`, tap OK. Returns True when the OPEN PDF
+ button (pdfOpen) appears — the app's success signal.
+
+ NOTE: the OK button repositions when the soft keyboard opens, and calling
+ hide_keyboard() here would press BACK and dismiss the dialog, so we tap OK
+ directly against a FRESH dump instead.
+ """
+ pc = node_by_id(ui(), "pdfCreate")
+ if pc is None or pc.get("enabled") != "true" or not tap_node(pc):
+ return False
+ settle("tap")
+ settle("tap")
+ # dialog EditText id='input', prefilled with an auto name.
+ ets = find_by_class(ui(), "EditText")
+ if not ets:
+ return False
+ et = ets[0]
+ if not tap_node(et):
+ return False
+ settle("keyboard")
+ # Clear whatever is prefilled: go to end, delete generously.
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(40):
+ adb_shell("input", "keyevent", "67") # KEYCODE_DEL
+ settle("text")
+ fresh = find_by_class(ui(), "EditText")
+ if not fresh:
+ return False
+ # verify_focus=False: the field is already focused and re-tapping can toggle
+ # the keyboard; we routed the clear manually above.
+ if not type_text(fresh[0], name, verify_focus=False):
+ return False
+ settle("text")
+ # Tap OK against a fresh dump (coordinates shifted once the keyboard appeared).
+ ok = find_node_ci(ui(), "OK")
+ if ok is None or not tap_node(ok):
+ return False
+ settle("launch")
+ settle("tap")
+ settle("tap")
+ for _ in range(4):
+ if node_by_id(ui(), "pdfOpen") is not None:
+ return True
+ settle("launch")
+ return node_by_id(ui(), "pdfOpen") is not None
+
+
+def view_files_rows() -> list[str]:
+ """File names currently listed in View Files (RecyclerView loads async)."""
+ for _ in range(6):
+ settle("launch")
+ nodes = ui()
+ rows = [n.get("text", "") for n in nodes
+ if n.get("resource-id", "").endswith("fileName")]
+ if rows:
+ return rows
+ return []
+
+
+def file_in_view_files(name: str) -> bool:
+ """True iff a View-Files row whose filename contains `name` exists (scrolls)."""
+ if not view_files_rows():
+ return False
+ n = scroll_into_view(f"{name}.pdf")
+ return n is not None
+
+
+def on_disk(name: str) -> bool:
+ """Optional strengthener: is .pdf in the app's public output dir?
+ Pass the path as a single quoted token so the on-device shell keeps the space."""
+ out = adb_shell(f"ls '{OUTPUT_DIR}'")
+ return f"{name}.pdf" in out
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_create_pdf_persists_disk",
+ "interaction_create_pdf_enabled_vlm",
+ "interaction_create_pdf_open_vlm"))
+def test_create_pdf_headline():
+ """HEADLINE: select 1 image -> CREATE PDF -> unique name -> OK -> OPEN PDF
+ morph AND the file lands in the app's output dir."""
+ name = mark("H")
+ if not home_ready():
+ record("interaction_create_pdf_persists_disk", False,
+ "setup_failed: could not reach Home grid",
+ depth=1, jump_kind="value", expect=f"OPEN PDF + {name}.pdf on disk")
+ record("interaction_create_pdf_enabled_vlm", False,
+ "setup_failed: could not reach Home grid", jump_kind="none", tag="color")
+ record("interaction_create_pdf_open_vlm", False,
+ "setup_failed: could not reach Home grid", jump_kind="none", tag="color")
+ return
+ if not and_enter_images_to_pdf():
+ record("interaction_create_pdf_persists_disk", False,
+ "feature_missing: no Images-to-PDF surface (SELECT IMAGES absent)",
+ depth=1, jump_kind="value", expect=f"OPEN PDF + {name}.pdf on disk")
+ record("interaction_create_pdf_enabled_vlm", False,
+ "feature_missing: Images-to-PDF surface absent", jump_kind="none", tag="color")
+ record("interaction_create_pdf_open_vlm", False,
+ "feature_missing: Images-to-PDF surface absent", jump_kind="none", tag="color")
+ return
+ status = select_images(1)
+ selected_ok = status is not None and status.strip().startswith("1 image")
+ pc = node_by_id(ui(), "pdfCreate")
+ create_enabled = pc is not None and pc.get("enabled") == "true"
+ if not (selected_ok and create_enabled):
+ record("interaction_create_pdf_persists_disk", False,
+ f"setup_failed: image selection did not enable create (status={status!r})",
+ depth=1, jump_kind="value", expect=f"OPEN PDF + {name}.pdf on disk")
+ record("interaction_create_pdf_enabled_vlm", False,
+ "setup_failed: image selection failed before create",
+ jump_kind="none", tag="color")
+ record("interaction_create_pdf_open_vlm", False,
+ "setup_failed: image selection failed before create",
+ jump_kind="none", tag="color")
+ return
+ # VLM 1 (color): CREATE PDF button is orange/enabled with an image selected.
+ vlm_assert("interaction_create_pdf_enabled",
+ "Is there a large solid ORANGE (not greyed-out) 'CREATE PDF' "
+ "button visible below the 'SELECT IMAGES' button?",
+ depth=1, jump_kind="transition", tag="color")
+ created = create_pdf_named(name)
+ disk = on_disk(name)
+ ok = created and disk
+ record("interaction_create_pdf_persists_disk", ok,
+ "" if ok else
+ f"behavior_wrong: create did not persist (pdfOpen={created}, on_disk={disk})",
+ depth=1, jump_kind="value",
+ expect=f"OPEN PDF button + {name}.pdf written to output dir")
+ # VLM 2 (color): OPEN PDF button present after create.
+ vlm_assert("interaction_create_pdf_open",
+ "Is there a solid ORANGE button labelled 'OPEN PDF' visible near "
+ "the top of the screen (replacing the earlier CREATE PDF button)?",
+ depth=1, jump_kind="value", tag="color")
+
+
+@and_test(expects=("interaction_created_pdf_in_viewfiles",
+ "interaction_created_pdf_in_viewfiles_vlm"))
+def test_created_pdf_in_view_files():
+ """Multi-surface integrity: create a uniquely-named PDF, then navigate to
+ View Files and assert a row with that filename exists (was ABSENT before)."""
+ name = mark("V")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_created_pdf_in_viewfiles", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="value", expect=f"View Files row {name}.pdf")
+ record("interaction_created_pdf_in_viewfiles_vlm", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ jump_kind="none", tag="layout")
+ return
+ if select_images(1) is None or not create_pdf_named(name):
+ record("interaction_created_pdf_in_viewfiles", False,
+ "behavior_wrong: could not create the source PDF",
+ depth=1, jump_kind="value", expect=f"View Files row {name}.pdf")
+ record("interaction_created_pdf_in_viewfiles_vlm", False,
+ "behavior_wrong: could not create the source PDF",
+ jump_kind="none", tag="layout")
+ return
+ # Go to View Files via a real navigation jump.
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_created_pdf_in_viewfiles", False,
+ "setup_failed: could not reach View Files",
+ depth=1, jump_kind="value", expect=f"View Files row {name}.pdf")
+ record("interaction_created_pdf_in_viewfiles_vlm", False,
+ "setup_failed: could not reach View Files", jump_kind="none", tag="layout")
+ return
+ present = file_in_view_files(name)
+ record("interaction_created_pdf_in_viewfiles", present,
+ "" if present else
+ f"behavior_wrong: {name}.pdf not listed in View Files after create",
+ depth=1, jump_kind="value", expect=f"View Files row containing {name}.pdf")
+ # VLM (layout): rows render as filename + size/date columns.
+ vlm_assert("interaction_created_pdf_in_viewfiles",
+ "Does the list show one or more file rows, each laid out as a "
+ "checkbox on the left, a '.pdf' file name in the middle, and a "
+ "size ('MB') plus a date on the right?",
+ depth=1, jump_kind="value", tag="layout")
+
+
+@and_test(expects=("interaction_created_pdf_in_history",))
+def test_created_pdf_in_history():
+ """Multi-surface integrity: created PDF appears in History as a 'Created' row."""
+ name = mark("Y")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_created_pdf_in_history", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="value", expect=f"History 'Created' row {name}.pdf")
+ return
+ if select_images(1) is None or not create_pdf_named(name):
+ record("interaction_created_pdf_in_history", False,
+ "behavior_wrong: could not create the source PDF",
+ depth=1, jump_kind="value", expect=f"History 'Created' row {name}.pdf")
+ return
+ if not home_ready() or not and_reach_history():
+ record("interaction_created_pdf_in_history", False,
+ "setup_failed: could not reach History",
+ depth=1, jump_kind="value", expect=f"History 'Created' row {name}.pdf")
+ return
+ # Poll for async list load, then look for the filename row.
+ for _ in range(6):
+ settle("launch")
+ if any(n.get("resource-id", "").endswith("fileName") for n in ui()):
+ break
+ row = scroll_into_view(f"{name}.pdf")
+ created_lbl = find_node(ui(), text="Created") is not None
+ ok = row is not None and created_lbl
+ record("interaction_created_pdf_in_history", ok,
+ "" if ok else
+ f"behavior_wrong: {name}.pdf / 'Created' not found in History "
+ f"(row={row is not None}, created_label={created_lbl})",
+ depth=1, jump_kind="value", expect=f"History row {name}.pdf with 'Created'")
+
+
+@and_test(expects=("interaction_create_survives_process_death",))
+def test_create_survives_process_death():
+ """HIGHEST VALUE (sole owner): create a uniquely-named PDF, kill the process,
+ relaunch, navigate to View Files, and assert the row still exists. An
+ in-memory-only recreation cannot pass this."""
+ name = mark("P")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_create_survives_process_death", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="value", expect=f"{name}.pdf survives restart")
+ return
+ if select_images(1) is None or not create_pdf_named(name):
+ record("interaction_create_survives_process_death", False,
+ "behavior_wrong: could not create the source PDF",
+ depth=1, jump_kind="value", expect=f"{name}.pdf survives restart")
+ return
+ # THE PROBE: kill the process and relaunch.
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ settle("launch")
+ # Reach View Files from a clean Home after the relaunch.
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_create_survives_process_death", False,
+ "setup_failed: could not reach View Files after relaunch",
+ depth=1, jump_kind="value", expect=f"{name}.pdf survives restart")
+ return
+ survived = file_in_view_files(name)
+ record("interaction_create_survives_process_death", survived,
+ "" if survived else
+ f"behavior_wrong: {name}.pdf absent from View Files after process death",
+ depth=1, jump_kind="value",
+ expect=f"View Files row {name}.pdf present after force_stop + relaunch")
+
+
+@and_test(expects=("interaction_multi_record_integrity",))
+def test_multi_record_integrity():
+ """Multi-record integrity: create TWO uniquely-named PDFs in separate create
+ passes, then assert BOTH are listed in View Files. A recreation that keeps
+ only the most-recent row fails here."""
+ name_a = mark("Ma")
+ time.sleep(0.05)
+ name_b = mark("Mb")
+
+ def make(nm: str) -> bool:
+ if not home_ready() or not and_enter_images_to_pdf():
+ return False
+ if select_images(1) is None:
+ return False
+ return create_pdf_named(nm)
+
+ made_a = make(name_a)
+ made_b = make(name_b)
+ if not (made_a and made_b):
+ record("interaction_multi_record_integrity", False,
+ f"behavior_wrong: could not create both PDFs (a={made_a}, b={made_b})",
+ depth=1, jump_kind="value",
+ expect=f"View Files rows {name_a}.pdf AND {name_b}.pdf")
+ return
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_multi_record_integrity", False,
+ "setup_failed: could not reach View Files",
+ depth=1, jump_kind="value",
+ expect=f"View Files rows {name_a}.pdf AND {name_b}.pdf")
+ return
+ has_a = file_in_view_files(name_a)
+ has_b = file_in_view_files(name_b)
+ ok = has_a and has_b
+ record("interaction_multi_record_integrity", ok,
+ "" if ok else
+ f"behavior_wrong: both created PDFs must persist "
+ f"({name_a}.pdf={has_a}, {name_b}.pdf={has_b})",
+ depth=1, jump_kind="value",
+ expect=f"BOTH {name_a}.pdf and {name_b}.pdf listed in View Files")
+
+
+@and_test(expects=("interaction_multi_image_count",
+ "interaction_multi_image_count_vlm"))
+def test_multi_image_count():
+ """Multi-image selection: pick 3 images at once and assert the status reads
+ exactly '3 image(s) selected.' (was absent before any selection)."""
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_multi_image_count", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="value", expect="'3 image(s) selected.'")
+ record("interaction_multi_image_count_vlm", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ jump_kind="none", tag="position")
+ return
+ absent_before = node_by_id(ui(), "tvNoOfImages") is None
+ status = select_images(3)
+ ok = absent_before and status is not None and status.strip() == "3 image(s) selected."
+ record("interaction_multi_image_count", ok,
+ "" if ok else
+ f"behavior_wrong: expected '3 image(s) selected.' got {status!r} "
+ f"(absent_before={absent_before})",
+ depth=1, jump_kind="value", expect="tvNoOfImages == '3 image(s) selected.'")
+ # VLM (position): the selection status bar sits at the bottom of the screen.
+ vlm_assert("interaction_multi_image_count",
+ "Is there a status line reading 'image(s) selected.' positioned at "
+ "the very BOTTOM of the screen, below the enhancement option cards?",
+ depth=1, jump_kind="value", tag="position")
+
+
+@and_test(expects=("interaction_viewfiles_single_check",
+ "interaction_viewfiles_single_check_vlm"))
+def test_view_files_single_check():
+ """View-Files row selection: create a PDF so a row exists, then tap that row's
+ CheckBox and assert it flips unchecked -> checked and a count badge '1'
+ appears in the toolbar. The CheckBox itself is safe; no destructive control
+ is touched."""
+ name = mark("C1")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_viewfiles_single_check", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="transition", expect="row checkbox checked + badge '1'")
+ record("interaction_viewfiles_single_check_vlm", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ jump_kind="none", tag="shape")
+ return
+ if select_images(1) is None or not create_pdf_named(name):
+ record("interaction_viewfiles_single_check", False,
+ "behavior_wrong: could not create a row to select",
+ depth=1, jump_kind="transition", expect="row checkbox checked + badge '1'")
+ record("interaction_viewfiles_single_check_vlm", False,
+ "behavior_wrong: could not create a row to select",
+ jump_kind="none", tag="shape")
+ return
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_viewfiles_single_check", False,
+ "setup_failed: could not reach View Files",
+ depth=1, jump_kind="transition", expect="row checkbox checked + badge '1'")
+ record("interaction_viewfiles_single_check_vlm", False,
+ "setup_failed: could not reach View Files", jump_kind="none", tag="shape")
+ return
+ view_files_rows() # ensure list loaded
+ cbs = [n for n in ui() if n.get("resource-id", "").endswith("checkbox")]
+ if not cbs:
+ record("interaction_viewfiles_single_check", False,
+ "feature_missing: no row CheckBox in View Files",
+ depth=1, jump_kind="transition", expect="row checkbox checked + badge '1'")
+ record("interaction_viewfiles_single_check_vlm", False,
+ "feature_missing: no row CheckBox in View Files", jump_kind="none", tag="shape")
+ return
+ before_checked = cbs[0].get("checked") == "true"
+ tap_node(cbs[0])
+ settle("tap")
+ nodes = ui()
+ after_cbs = [n for n in nodes if n.get("resource-id", "").endswith("checkbox")]
+ after_checked = bool(after_cbs) and after_cbs[0].get("checked") == "true"
+ badge = any(n.get("text", "").strip() == "1" and n.get("_bounds")
+ and n.get("_bounds")[1] < 320 for n in nodes)
+ ok = (not before_checked) and after_checked and badge
+ record("interaction_viewfiles_single_check", ok,
+ "" if ok else
+ f"behavior_wrong: check did not register "
+ f"(before={before_checked}, after={after_checked}, badge1={badge})",
+ depth=1, jump_kind="transition",
+ expect="row CheckBox false->true and toolbar count badge '1'")
+ # VLM (shape): the checked box is a FILLED orange square, not an empty outline.
+ vlm_assert("interaction_viewfiles_single_check",
+ "Look at the checkbox on the LEFT of the first file row. Is it a "
+ "FILLED solid orange square with a white check mark (i.e. checked), "
+ "rather than an empty/outlined box?",
+ depth=1, jump_kind="transition", tag="shape")
+
+
+@and_test(expects=("interaction_viewfiles_multiselect_badge",
+ "interaction_viewfiles_multiselect_badge_vlm"))
+def test_view_files_multi_select_badge():
+ """Multi-record selection: create TWO PDFs, then in View Files check two rows
+ and assert the toolbar count badge reads '2'."""
+ name_a = mark("S1")
+ time.sleep(0.05)
+ name_b = mark("S2")
+
+ def make(nm: str) -> bool:
+ if not home_ready() or not and_enter_images_to_pdf():
+ return False
+ if select_images(1) is None:
+ return False
+ return create_pdf_named(nm)
+
+ if not (make(name_a) and make(name_b)):
+ record("interaction_viewfiles_multiselect_badge", False,
+ "behavior_wrong: could not create two rows to select",
+ depth=1, jump_kind="value", expect="toolbar count badge '2'")
+ record("interaction_viewfiles_multiselect_badge_vlm", False,
+ "behavior_wrong: could not create two rows to select",
+ jump_kind="none", tag="position")
+ return
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_viewfiles_multiselect_badge", False,
+ "setup_failed: could not reach View Files",
+ depth=1, jump_kind="value", expect="toolbar count badge '2'")
+ record("interaction_viewfiles_multiselect_badge_vlm", False,
+ "setup_failed: could not reach View Files", jump_kind="none", tag="position")
+ return
+ view_files_rows()
+ cbs = [n for n in ui() if n.get("resource-id", "").endswith("checkbox")]
+ if len(cbs) < 2:
+ record("interaction_viewfiles_multiselect_badge", False,
+ f"behavior_wrong: fewer than 2 selectable rows (found {len(cbs)})",
+ depth=1, jump_kind="value", expect="toolbar count badge '2'")
+ record("interaction_viewfiles_multiselect_badge_vlm", False,
+ f"behavior_wrong: fewer than 2 selectable rows (found {len(cbs)})",
+ jump_kind="none", tag="position")
+ return
+ tap_node(cbs[0])
+ settle("tap")
+ # re-find the second checkbox from a fresh dump (list may recycle).
+ cbs2 = [n for n in ui() if n.get("resource-id", "").endswith("checkbox")]
+ if len(cbs2) >= 2:
+ tap_node(cbs2[1])
+ settle("tap")
+ nodes = ui()
+ badge2 = any(n.get("text", "").strip() == "2" and n.get("_bounds")
+ and n.get("_bounds")[1] < 320 for n in nodes)
+ record("interaction_viewfiles_multiselect_badge", badge2,
+ "" if badge2 else
+ "behavior_wrong: toolbar selection count did not reach '2' after "
+ "checking two rows",
+ depth=1, jump_kind="value", expect="toolbar count badge shows '2'")
+ # VLM (position): the count number is in the top toolbar.
+ vlm_assert("interaction_viewfiles_multiselect_badge",
+ "Is there a bold number '2' displayed in the TOP toolbar area "
+ "(to the right of the hamburger menu icon)?",
+ depth=1, jump_kind="value", tag="position")
+
+
+@and_test(expects=("interaction_longpress_pdf_actions",
+ "interaction_longpress_pdf_actions_vlm"))
+def test_longpress_pdf_actions():
+ """LONG-PRESS context menu (sole owner): create a PDF so a row exists, then
+ long-press the row and assert a 'PDF Actions' menu appears with row actions
+ (Open File / Rename File / Share File). No destructive item is tapped."""
+ name = mark("L")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_longpress_pdf_actions", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="transition", expect="'PDF Actions' menu on long-press")
+ record("interaction_longpress_pdf_actions_vlm", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ jump_kind="none", tag="content")
+ return
+ if select_images(1) is None or not create_pdf_named(name):
+ record("interaction_longpress_pdf_actions", False,
+ "behavior_wrong: could not create a row to long-press",
+ depth=1, jump_kind="transition", expect="'PDF Actions' menu on long-press")
+ record("interaction_longpress_pdf_actions_vlm", False,
+ "behavior_wrong: could not create a row to long-press",
+ jump_kind="none", tag="content")
+ return
+ if not home_ready() or not and_reach_view_files():
+ record("interaction_longpress_pdf_actions", False,
+ "setup_failed: could not reach View Files",
+ depth=1, jump_kind="transition", expect="'PDF Actions' menu on long-press")
+ record("interaction_longpress_pdf_actions_vlm", False,
+ "setup_failed: could not reach View Files", jump_kind="none", tag="content")
+ return
+ rows = [n for n in ui() if n.get("resource-id", "").endswith("fileName")]
+ if not rows:
+ view_files_rows()
+ rows = [n for n in ui() if n.get("resource-id", "").endswith("fileName")]
+ if not rows:
+ record("interaction_longpress_pdf_actions", False,
+ "behavior_wrong: no row present to long-press",
+ depth=1, jump_kind="transition", expect="'PDF Actions' menu on long-press")
+ record("interaction_longpress_pdf_actions_vlm", False,
+ "behavior_wrong: no row present to long-press", jump_kind="none", tag="content")
+ return
+ before = and_showing()
+ long_press(rows[0], 900)
+ settle("tap")
+ and_enter("pdf_actions_menu")
+ after = ui()
+ after_keys = and_showing(after)
+ # A real app-authored consequence: the "PDF Actions" menu with action rows.
+ has_title = find_node_ci(after, "PDF Actions") is not None
+ action_hits = sum(1 for lbl in ("Open File", "Rename File", "Share File",
+ "Delete File", "Print File", "Show Details")
+ if find_node_ci(after, lbl) is not None)
+ changed = surface_changed(before, after_keys, 2)
+ ok = has_title and action_hits >= 3 and changed
+ record("interaction_longpress_pdf_actions", ok,
+ "" if ok else
+ f"behavior_wrong: long-press produced no PDF-actions menu "
+ f"(title={has_title}, actions={action_hits}, changed={changed})",
+ depth=1, jump_kind="transition",
+ expect="'PDF Actions' menu with Open/Rename/Share rows after long-press")
+ # VLM (content): the action menu list is rendered.
+ vlm_assert("interaction_longpress_pdf_actions",
+ "Is a pop-up menu titled 'PDF Actions' shown, listing several file "
+ "actions such as 'Open File', 'Rename File' and 'Share File'?",
+ depth=1, jump_kind="transition", tag="content")
+ # Close the menu without touching any destructive item.
+ back()
+
+
+@and_test(expects=("interaction_pagesize_then_create_sequence",))
+def test_pagesize_then_create_sequence():
+ """3+ step sequence where each step depends on the last: select an image ->
+ open 'Set Page Size' -> choose LETTER -> OK -> CREATE PDF with a unique name
+ -> assert the PDF was actually created (OPEN PDF morph + file on disk). The
+ data outcome is the assertion (the page-size LABEL belongs to computation)."""
+ name = mark("PS")
+ if not home_ready() or not and_enter_images_to_pdf():
+ record("interaction_pagesize_then_create_sequence", False,
+ "setup_failed: could not reach Images-to-PDF surface",
+ depth=1, jump_kind="value", expect=f"{name}.pdf created after LETTER page size")
+ return
+ if select_images(1) is None:
+ record("interaction_pagesize_then_create_sequence", False,
+ "setup_failed: image selection failed",
+ depth=1, jump_kind="value", expect=f"{name}.pdf created after LETTER page size")
+ return
+ # Open the "Set Page Size" enhancement card (tap the label; card requires a
+ # selected image, which we have).
+ card = scroll_into_view("Set Page Size")
+ if card is None or not tap_node(card):
+ record("interaction_pagesize_then_create_sequence", False,
+ "feature_missing: 'Set Page Size' card not found",
+ depth=1, jump_kind="value", expect=f"{name}.pdf created after LETTER page size")
+ return
+ settle("tap")
+ and_enter("set_page_size_dialog")
+ letter = scroll_into_view("LETTER")
+ if letter is None or not safe_tap(letter):
+ record("interaction_pagesize_then_create_sequence", False,
+ "feature_missing: LETTER option not found in Set Page Size dialog",
+ depth=1, jump_kind="value", expect=f"{name}.pdf created after LETTER page size")
+ return
+ settle("tap")
+ ok = find_node_ci(ui(), "OK")
+ if ok is None or not tap_node(ok):
+ record("interaction_pagesize_then_create_sequence", False,
+ "setup_failed: could not confirm the page-size dialog",
+ depth=1, jump_kind="value", expect=f"{name}.pdf created after LETTER page size")
+ return
+ settle("tap")
+ # Now the data step: create the PDF with the chosen setting.
+ created = create_pdf_named(name)
+ disk = on_disk(name)
+ passed = created and disk
+ record("interaction_pagesize_then_create_sequence", passed,
+ "" if passed else
+ f"behavior_wrong: sequence did not produce the PDF "
+ f"(pdfOpen={created}, on_disk={disk})",
+ depth=1, jump_kind="value",
+ expect=f"{name}.pdf created (OPEN PDF + file on disk) after LETTER page size")
+
+
+TESTS = [
+ test_create_pdf_headline,
+ test_created_pdf_in_view_files,
+ test_created_pdf_in_history,
+ test_create_survives_process_death,
+ test_multi_record_integrity,
+ test_multi_image_count,
+ test_view_files_single_check,
+ test_view_files_multi_select_badge,
+ test_longpress_pdf_actions,
+ test_pagesize_then_create_sequence,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("device offline — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "interaction")
diff --git a/android/swati4star-images-to-pdf/tests/test_android_navigation.py b/android/swati4star-images-to-pdf/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9cc29d423ec31965d18e92511a2123b4a5683a7
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_navigation.py
@@ -0,0 +1,492 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — surface REACHABILITY + back-stack integrity for "PDF Converter"
+(swati4star.createpdf). This lane is the SOLE owner of jump_kind="reach" and of the
+suite's depth>=2 chains.
+
+Every jump is proven with and_reach(before, after, target, source): the TARGET
+surface's discriminating element APPEARED *and* the SOURCE surface's element
+DISAPPEARED. and_reach_surface(node, target, source) does snapshot->tap->snapshot->
+verdict and counts one surface. Reaching a screen by relaunching is NOT navigation.
+
+The home grid RETAINS its scroll position across restart_app(), and a "Recently Used
+Features" row reflows the grid once features have been used, so every home entry is
+scrolled to the top first and card reaches key their SOURCE on a section header
+("Create new PDF" / "Enhance Created PDFs") that is co-visible with any card and
+always leaves the tree on a fragment jump — layout-independent.
+
+Run: python3 test_android_navigation.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else "/workspace/testgen/eval/eval_results"
+
+# Section headers that are present on Home regardless of scroll/"Recently Used" reflow
+# and that vanish on any fragment jump — used as the disappearing SOURCE for reaches.
+HOME_HEADERS = ("Create new PDF", "Enhance Created PDFs", "View PDFs")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Shared helpers
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_permission(nodes=None):
+ """First-run MANAGE_EXTERNAL_STORAGE dialog may sit in front of the home grid.
+ Dismiss it without ever seeding the permission. No-op when absent. BACK is safe:
+ the home grid is behind the dialog."""
+ nodes = ui() if nodes is None else nodes
+ if find_node_ci(nodes, "Allow app to access files on your device") \
+ or find_node_ci(nodes, "DENY"):
+ back()
+ settle("tap")
+
+
+def nav_to_top():
+ """Scroll the home grid to the very top so top-fold cards and the section
+ headers are on screen. Returns the settled node list."""
+ for _ in range(8):
+ n = ui()
+ if node_by_id(n, "images_to_pdf") and find_node(n, text="Create new PDF"):
+ return n
+ scroll_up(0.9)
+ return ui()
+
+
+def _on_home(nodes):
+ return bool(node_by_id(nodes, "images_to_pdf")
+ and find_node(nodes, text="Create new PDF"))
+
+
+def home_ready():
+ """Fresh launch -> home grid scrolled to the top (a known, deterministic state).
+
+ A prior test can leave a system overlay in front of the app (the Photo Picker
+ lives in another process; backing out of it can surface the notification shade),
+ and a bare relaunch then does not land on Home. So force-stop, press HOME to
+ clear any shade/overlay, relaunch, and verify the home grid is actually up —
+ retrying with a BACK press when it is not. Never seeds any state."""
+ for _ in range(4):
+ force_stop()
+ home() # dismiss any leftover shade / foreign overlay
+ launch_app()
+ wait_for_foreground()
+ dismiss_permission()
+ top = nav_to_top()
+ if _on_home(top):
+ return top
+ back() # an overlay is up — pop it and retry
+ settle("tap")
+ return nav_to_top()
+
+
+def home_source(before):
+ """Pick a section header that is in `before` (on Home) to use as the SOURCE that
+ must disappear after the jump."""
+ for h in HOME_HEADERS:
+ if f"TextView|{h}" in before:
+ return h
+ return HOME_HEADERS[0]
+
+
+def open_hamburger(nodes):
+ """The top-left drawer button (ImageButton, content-desc 'PDF Converter')."""
+ return find_node(nodes, content_desc="PDF Converter",
+ **{"class": "android.widget.ImageButton"})
+
+
+def scroll_drawer_up(frac=0.42):
+ """Swipe up inside the open drawer's list, derived from screen geometry (never a
+ pixel literal) so it survives any density. The drawer occupies the left column."""
+ s = get_screen_info()
+ x = int(s["width"] * 0.30)
+ y1 = int(s["height"] * 0.80)
+ y2 = int(s["height"] * (0.80 - frac))
+ swipe(x, y1, x, y2, ms=400)
+
+
+# ── Depth-family helpers. The and_reach_* / and_enter_* NAME is what the depth
+# audit looks for; the implementation is ours. ────────────────────────────────
+
+def and_reach_drawer(nodes):
+ """Open the navigation drawer from Home. The drawer is a pure OVERLAY (nothing
+ behind it leaves the tree), so the honest proof is that a drawer-only element
+ ('Home' CheckedTextView, absent on Home) APPEARS."""
+ ham = open_hamburger(nodes)
+ if ham is None:
+ return False
+ # target-only appearance (source=None): a real new-surface discriminator.
+ return and_reach_surface(ham, "CheckedTextView|Home", None)
+
+
+def and_reach_settings():
+ """DEPTH>=2 chain: Home -> open drawer -> scroll drawer -> tap Settings.
+ Two forward surfaces (drawer, then Settings) backed by two nav calls."""
+ nodes = home_ready()
+ if not and_reach_drawer(nodes):
+ return False
+ # Settings lives below the fold of the drawer's RecyclerView.
+ settings = None
+ for _ in range(6):
+ dn = ui()
+ settings = find_node(dn, text="Settings")
+ if settings:
+ break
+ scroll_drawer_up()
+ if settings is None:
+ return False
+ # FAQ is a drawer-only item on screen next to Settings; it vanishes on the jump.
+ return and_reach_surface(settings, "Theme default value", "FAQ")
+
+
+def and_reach_photo_picker():
+ """DEPTH>=2 chain: Home -> Images to PDF fragment -> tap SELECT IMAGES ->
+ system Photo Picker. Returns (ok, note)."""
+ nodes = home_ready()
+ card = node_by_id(nodes, "images_to_pdf")
+ if card is None:
+ return False, "setup_failed: home 'Images to PDF' card not found"
+ if not and_reach_surface(card, "SELECT IMAGES", home_source(and_showing(nodes))):
+ return False, "behavior_wrong: Images to PDF fragment not reached"
+ nodes = ui()
+ sel = node_by_id(nodes, "addImages") or find_node(nodes, text="SELECT IMAGES")
+ if sel is None:
+ return False, "setup_failed: SELECT IMAGES button not found"
+ # Photo Picker shows a 'Photos' tab; the SELECT IMAGES button leaves the tree.
+ if not and_reach_surface(sel, "Photos", "SELECT IMAGES"):
+ return False, "behavior_wrong: Photo Picker not reached from SELECT IMAGES"
+ return True, ""
+
+
+def reach_card_fragment(rid, target, name, *, depth=1, scroll_label=None):
+ """Home -> a feature fragment via its card. Records one reach case. When
+ scroll_label is given the grid is scrolled until the card is on screen (itself
+ depth work). SOURCE is a Home section header that disappears on the jump."""
+ nodes = home_ready()
+ if scroll_label:
+ if scroll_into_view(scroll_label) is None:
+ return record(name, False,
+ f"feature_missing: home card '{scroll_label}' not on grid",
+ depth=depth, jump_kind="reach",
+ expect=f"{target} on the Home->fragment jump")
+ nodes = ui()
+ card = node_by_id(nodes, rid)
+ if card is None:
+ return record(name, False,
+ f"feature_missing: home card id '{rid}' absent",
+ depth=depth, jump_kind="reach",
+ expect=f"{target} appears; Home header gone")
+ before = and_showing()
+ src = home_source(before)
+ ok = and_reach_surface(card, target, src)
+ return record(name, ok,
+ "" if ok else f"behavior_wrong: '{target}' did not appear while the "
+ f"Home '{src}' header left after tapping the {rid} card",
+ depth=depth, jump_kind="reach",
+ expect=f"{target} visible on target surface; Home '{src}' header gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Top-level destinations from Home (each a reach, depth>=1)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_images_to_pdf", "nav_reach_images_to_pdf_vlm"))
+def test_reach_images_to_pdf():
+ reach_card_fragment("images_to_pdf", "SELECT IMAGES", "nav_reach_images_to_pdf")
+ settle("tap")
+ vlm_assert("nav_reach_images_to_pdf",
+ "Is there a wide orange rectangular button near the top of the screen "
+ "with the white text 'SELECT IMAGES'?",
+ RESULTS_DIR, tag="color")
+
+
+@and_test(expects=("nav_reach_text_to_pdf",))
+def test_reach_text_to_pdf():
+ reach_card_fragment("text_to_pdf", "SELECT TEXT FILE", "nav_reach_text_to_pdf")
+
+
+@and_test(expects=("nav_reach_view_files", "nav_reach_view_files_vlm"))
+def test_reach_view_files():
+ reach_card_fragment("view_files", "Search", "nav_reach_view_files")
+ settle("tap")
+ vlm_assert("nav_reach_view_files",
+ "In the top orange toolbar, on the right side, are there several icons "
+ "in a horizontal row (a magnifying-glass search icon and more icons to "
+ "its right)?",
+ RESULTS_DIR, tag="layout")
+
+
+@and_test(expects=("nav_reach_history", "nav_reach_history_vlm"))
+def test_reach_history():
+ reach_card_fragment("view_history", "Filter", "nav_reach_history")
+ settle("tap")
+ vlm_assert("nav_reach_history",
+ "In the top toolbar of this History screen, are there two or more "
+ "action icons on the right side of the title?",
+ RESULTS_DIR, tag="layout")
+
+
+@and_test(expects=("nav_reach_add_password",))
+def test_reach_add_password():
+ # Reachability only — do NOT open the SAF picker.
+ reach_card_fragment("add_password", "SELECT A FILE", "nav_reach_add_password")
+
+
+@and_test(expects=("nav_reach_qr_barcode",))
+def test_reach_qr_barcode():
+ # Camera fragment — reachability only. 'Scan QR code' is unique to this fragment.
+ reach_card_fragment("qr_barcode_to_pdf", "Scan QR code", "nav_reach_qr_barcode")
+
+
+# ── Below-the-fold cards (scrolling the grid to reach them is depth work) ────────
+
+@and_test(expects=("nav_reach_excel_to_pdf",))
+def test_reach_excel_to_pdf():
+ reach_card_fragment("excel_to_pdf", "Excel to PDF", "nav_reach_excel_to_pdf",
+ scroll_label="Excel to PDF")
+
+
+@and_test(expects=("nav_reach_add_watermark",))
+def test_reach_add_watermark():
+ reach_card_fragment("add_watermark", "wish to add watermark",
+ "nav_reach_add_watermark", scroll_label="Add Watermark")
+
+
+@and_test(expects=("nav_reach_rotate_pages",))
+def test_reach_rotate_pages():
+ reach_card_fragment("rotate_pages", "wish to rotate", "nav_reach_rotate_pages",
+ scroll_label="Rotate Pages")
+
+
+@and_test(expects=("nav_reach_merge_pdf",))
+def test_reach_merge_pdf():
+ reach_card_fragment("merge_pdf", "SELECT FILES", "nav_reach_merge_pdf",
+ scroll_label="Merge PDF")
+
+
+@and_test(expects=("nav_reach_split_pdf",))
+def test_reach_split_pdf():
+ reach_card_fragment("split_pdf", "SELECT A FILE", "nav_reach_split_pdf",
+ scroll_label="Split PDF")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Toolbar heart -> Favourites
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_favourites", "nav_reach_favourites_vlm"))
+def test_reach_favourites():
+ nodes = home_ready()
+ heart = node_by_id(nodes, "menu_favourites_item")
+ src = home_source(and_showing(nodes))
+ ok = heart is not None and and_reach_surface(heart, "favourite features", src)
+ record("nav_reach_favourites", ok,
+ "" if ok else "behavior_wrong: Favourites empty-state did not appear "
+ "after tapping the toolbar heart",
+ depth=1, jump_kind="reach",
+ expect="empty-state 'Select + icon to add your favourite features!' "
+ "visible; Home header gone")
+ settle("tap") # let the heart illustration finish animating in
+ settle("tap")
+ vlm_assert("nav_reach_favourites",
+ "Is there a single orange heart icon in the middle of the screen with "
+ "a grey line of text below it?",
+ RESULTS_DIR, tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Drawer host + DEPTH>=2 drawer -> Settings
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_open_drawer", "nav_open_drawer_vlm"))
+def test_open_drawer():
+ nodes = home_ready()
+ ok = and_reach_drawer(nodes)
+ record("nav_open_drawer", ok,
+ "" if ok else "behavior_wrong: drawer 'Home' item did not appear after "
+ "tapping the hamburger",
+ depth=1, jump_kind="reach",
+ expect="drawer 'Home' CheckedTextView newly visible (absent on Home grid)")
+ settle("tap")
+ vlm_assert("nav_open_drawer",
+ "Is a navigation drawer open on the left, with a small app icon and "
+ "the text 'PDF Converter' near its top-left header?",
+ RESULTS_DIR, tag="position")
+
+
+@and_test(expects=("nav_drawer_view_files",))
+def test_drawer_view_files():
+ nodes = home_ready()
+ if not and_reach_drawer(nodes):
+ record("nav_drawer_view_files", False,
+ "setup_failed: drawer did not open", depth=2, jump_kind="reach",
+ expect="View Files Search toolbar after drawer item")
+ return
+ dn = ui()
+ item = node_by_id(dn, "nav_gallery") or find_node(dn, text="View Files")
+ ok = item is not None and and_reach_surface(item, "Search", "CheckedTextView|Home")
+ record("nav_drawer_view_files", ok,
+ "" if ok else "behavior_wrong: drawer 'View Files' did not reach the "
+ "View Files surface",
+ depth=2, jump_kind="reach",
+ expect="View Files 'Search' toolbar action visible; drawer 'Home' gone")
+
+
+@and_test(expects=("nav_drawer_to_settings", "nav_drawer_to_settings_vlm"))
+def test_drawer_to_settings():
+ ok = and_reach_settings() # depth>=2 helper, backed by 2 and_reach* calls
+ record("nav_drawer_to_settings", ok,
+ "" if ok else "behavior_wrong: drawer -> Settings did not reach the "
+ "Settings surface",
+ depth=2, jump_kind="reach",
+ expect="'Theme default value : System' visible on Settings; drawer 'FAQ' "
+ "item gone")
+ settle("tap")
+ vlm_assert("nav_drawer_to_settings",
+ "Does this settings screen show a grid of rectangular option cards "
+ "arranged in two columns?",
+ RESULTS_DIR, tag="layout")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEPTH>=2 chain into a sub-Activity: Home -> Images to PDF -> Photo Picker
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_deep_picker",))
+def test_deep_picker():
+ ok, note = and_reach_photo_picker() # 2 forward surfaces, both proven
+ record("nav_deep_picker", ok,
+ "" if ok else note,
+ depth=2, jump_kind="reach",
+ expect="Photo Picker 'Photos' tab visible; 'SELECT IMAGES' button gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Back-stack integrity (BACK unwinding the stack hop by hop)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_back_fragment_to_home",))
+def test_back_fragment_to_home():
+ """1-hop: Home -> Images to PDF, then BACK restores Home."""
+ nodes = home_ready()
+ card = node_by_id(nodes, "images_to_pdf")
+ deep = card is not None and and_reach_surface(
+ card, "SELECT IMAGES", home_source(and_showing(nodes)))
+ if not deep:
+ record("nav_back_fragment_to_home", False,
+ "setup_failed: could not reach Images to PDF fragment",
+ depth=1, jump_kind="reach", expect="Home restored after one BACK")
+ return
+ and_back() # pop the fragment
+ after = and_showing()
+ ok = (any(k.startswith("TextView|") and k.split("|", 1)[1] in HOME_HEADERS
+ for k in after)
+ and not any("select images" in k.lower() for k in after))
+ record("nav_back_fragment_to_home", ok,
+ "" if ok else "behavior_wrong: BACK from the fragment did not restore the "
+ "Home grid",
+ depth=1, jump_kind="reach",
+ expect="a Home section header back; 'SELECT IMAGES' gone after BACK")
+
+
+@and_test(expects=("nav_backstack_2hop",))
+def test_backstack_2hop():
+ """2-hop unwind: Home -> Images to PDF -> Photo Picker, then BACK twice returns
+ picker->fragment->Home, asserting the surface after each pop."""
+ ok, note = and_reach_photo_picker()
+ if not ok:
+ record("nav_backstack_2hop", False, note, depth=2, jump_kind="reach",
+ expect="stack unwinds picker->fragment->Home")
+ return
+ # pop 1: picker -> Images to PDF fragment
+ and_back()
+ mid = and_showing()
+ back_to_fragment = (any("select images" in k.lower() for k in mid)
+ and not any(k == "TextView|Photos" for k in mid))
+ # pop 2: fragment -> Home
+ and_back()
+ home = and_showing()
+ back_to_home = (any(k.startswith("TextView|") and k.split("|", 1)[1] in HOME_HEADERS
+ for k in home)
+ and not any("select images" in k.lower() for k in home))
+ ok2 = back_to_fragment and back_to_home
+ record("nav_backstack_2hop", ok2,
+ "" if ok2 else "behavior_wrong: two BACKs did not unwind "
+ "picker->fragment->Home hop by hop",
+ depth=2, jump_kind="reach",
+ expect="after BACK #1 SELECT IMAGES shown (picker gone); after BACK #2 "
+ "Home grid restored")
+
+
+@and_test(expects=("nav_back_settings_to_home",))
+def test_back_settings_to_home():
+ """Back stack from the deepest drawer surface (Settings) to Home."""
+ if not and_reach_settings():
+ record("nav_back_settings_to_home", False,
+ "setup_failed: could not reach Settings", depth=2, jump_kind="reach",
+ expect="Home restored after backing out of Settings")
+ return
+ and_back()
+ after = and_showing()
+ ok = (any(k.startswith("TextView|") and k.split("|", 1)[1] in HOME_HEADERS
+ for k in after)
+ and not any("theme default" in k.lower() for k in after))
+ record("nav_back_settings_to_home", ok,
+ "" if ok else "behavior_wrong: BACK from Settings did not return to Home",
+ depth=2, jump_kind="reach",
+ expect="a Home section header back; 'Theme default value' gone")
+
+
+@and_test(expects=("nav_back_favourites_to_home",))
+def test_back_favourites_to_home():
+ """1-hop back stack: heart -> Favourites, BACK -> Home."""
+ nodes = home_ready()
+ heart = node_by_id(nodes, "menu_favourites_item")
+ deep = heart is not None and and_reach_surface(
+ heart, "favourite features", home_source(and_showing(nodes)))
+ if not deep:
+ record("nav_back_favourites_to_home", False,
+ "setup_failed: could not reach Favourites", depth=1, jump_kind="reach",
+ expect="Home restored after BACK from Favourites")
+ return
+ and_back()
+ after = and_showing()
+ ok = (any(k.startswith("TextView|") and k.split("|", 1)[1] in HOME_HEADERS
+ for k in after)
+ and not any("favourite features" in k.lower() for k in after))
+ record("nav_back_favourites_to_home", ok,
+ "" if ok else "behavior_wrong: BACK from Favourites did not restore Home",
+ depth=1, jump_kind="reach",
+ expect="a Home section header back; Favourites empty-state gone")
+
+
+TESTS = [
+ test_reach_images_to_pdf,
+ test_reach_text_to_pdf,
+ test_reach_view_files,
+ test_reach_history,
+ test_reach_add_password,
+ test_reach_qr_barcode,
+ test_reach_excel_to_pdf,
+ test_reach_add_watermark,
+ test_reach_rotate_pages,
+ test_reach_merge_pdf,
+ test_reach_split_pdf,
+ test_reach_favourites,
+ test_open_drawer,
+ test_drawer_view_files,
+ test_drawer_to_settings,
+ test_deep_picker,
+ test_back_fragment_to_home,
+ test_backstack_2hop,
+ test_back_settings_to_home,
+ test_back_favourites_to_home,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("Device not reachable — aborting navigation suite")
+ sys.exit(2)
+ run_suite(TESTS, "navigation")
diff --git a/android/swati4star-images-to-pdf/tests/test_android_states.py b/android/swati4star-images-to-pdf/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5b3cbf1014f5de38326396202680231dd787676
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_states.py
@@ -0,0 +1,1086 @@
+#!/usr/bin/env python3
+"""STATES lane — WIDGET STATE TRANSITIONS PAIRED WITH THEIR APP-AUTHORED CONSEQUENCE
+for the PDF Converter app (swati4star.createpdf and any faithful recreation).
+
+This lane owns `checked`, `enabled`/`disabled`, `selected` and `focused`, plus
+page-level enable/disable state machines and SETTINGS/mode PERSISTENCE across
+process death. Every test reads the state BEFORE out of a fresh ui(), drives the
+real user path, reads AFTER, asserts the flip AND the consequence the app authored
+(not a bare checked=true), then restores.
+
+Validated on the running original before authoring (expected values re-derived from
+what was OBSERVED live):
+ * CREATE PDF (pdfCreate) enabled=false BEFORE any image, enabled=true AFTER an
+ image is picked, with tvNoOfImages="1 image(s) selected." appearing. [A]
+ * Set Page Size single-choice radios: selecting LETTER checks it, deselects the
+ DEFAULT, and — for THIS dialog — the choice is remembered on reopen. [B]
+ * Set Image Scale Type single-choice radios: selecting Stretch checks it and
+ deselects Maintain in the SAME dialog (mutual exclusion is the app-authored
+ consequence; this dialog does NOT pre-check the choice on reopen unless
+ 'Set as default' is used — observed live). [B]
+ * Font Family radio: selecting HELVETICA checks it AND rewrites the card label
+ to "Font Family : HELVETICA" (observed — NOT the "(Default : ...)" form,
+ which is only the initial label). [B]
+ * "Set as default" CheckBox in the value dialogs: unchecked -> checked. [C]
+ * View Files row CheckBox: unchecked -> checked + a "1" selection count badge. [C]
+ * Settings theme / font-size / page-size default persist across a force-stop. [D]
+ * Drawer is a single-choice CheckedTextView group; on launch exactly ONE item
+ is checked and it is "Home" (drawer navigation does NOT move the highlight in
+ this app — observed live). [E]
+ * Password Protect PDF dialog "Show password" toggle flips the field obscuring. [F]
+
+VLM budget: 11 assertions (theme recolor, selected-radio orange highlight, checkbox
+tick, disabled-grey/enabled-orange button pair, drawer Home pill) — the exact
+rendered properties an in-memory dead shell cannot fake.
+"""
+import os
+import sys
+import time as _time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Home entry — the app RESTORES its last fragment after a force-stop and the grid
+# grows a "Recently Used Features" row after features are used, so a naive
+# restart_app() does NOT reliably land on the grid. home_ready() force-stops,
+# relaunches, dismisses the first-run permission dialog if present, then presses
+# BACK until the Home grid ("Create new PDF" / "View PDFs") shows and scrolls the
+# grid to the top. Cards are then located by resource-id.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def on_home(nodes=None) -> bool:
+ nodes = ui() if nodes is None else nodes
+ return (find_node(nodes, text="Create new PDF") is not None
+ or find_node(nodes, text="View PDFs") is not None)
+
+
+def _dismiss_permission_if_present() -> None:
+ """First-run storage permission dialog: DENY keeps us in the app without
+ granting (we never seed the permission). Tap it only if present and safe."""
+ nodes = ui()
+ deny = find_node(nodes, text="DENY") or find_node(nodes, text="Deny")
+ if deny is not None and is_safe(deny):
+ tap_node(deny)
+ settle("tap")
+
+
+def _reach_home() -> bool:
+ """After a launch/relaunch, land deterministically on the Home grid."""
+ wait_for_foreground()
+ settle("launch")
+ for _ in range(4):
+ if on_home():
+ break
+ _dismiss_permission_if_present()
+ if on_home():
+ break
+ back()
+ settle("launch")
+ for _ in range(4):
+ scroll_up(0.8)
+ settle("tap")
+ return on_home()
+
+
+def home_ready() -> bool:
+ """Deterministic Home surface from a fresh process."""
+ force_stop()
+ settle("key")
+ launch_app()
+ return _reach_home()
+
+
+def home_ready_clear() -> bool:
+ """Factory-default Home surface: wipe app data first so every default (theme,
+ font size, page size, ...) is the known factory value, then land on Home.
+ Used as the pre-state of a persistence test."""
+ clear_data()
+ launch_app()
+ return _reach_home()
+
+
+def open_card(rid: str, label: str) -> bool:
+ """Tap a home feature card by resource-id suffix; fall back to a scroll-to by
+ its visible label if it is off screen."""
+ n = node_by_id(ui(), rid)
+ if n is None:
+ n = scroll_into_view(label)
+ return tap_node(n) if n is not None else False
+
+
+def option_labels(nodes=None) -> list:
+ """Every enhancement/settings card label (resource-id ...option_name)."""
+ nodes = ui() if nodes is None else nodes
+ return [n.get("text", "") for n in nodes
+ if n.get("resource-id", "").endswith("option_name")]
+
+
+def label_containing(substr: str, nodes=None) -> str:
+ """The first option_name label CONTAINING substr (case-insensitive), or ''."""
+ s = substr.lower()
+ for lbl in option_labels(nodes):
+ if s in lbl.lower():
+ return lbl
+ return ""
+
+
+def tap_card(label_substr: str) -> bool:
+ """Tap the enhancement/settings card whose option_name label contains
+ `label_substr`. The option_name TextView is not itself clickable, but its
+ centre lies inside the clickable card container, so tapping the TextView centre
+ reliably opens the dialog (verified live). Scrolls it into view first."""
+ for _ in range(6):
+ nodes = ui()
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("option_name")
+ and label_substr.lower() in n.get("text", "").lower()):
+ return tap_node(n)
+ scrollers = [x for x in nodes if x.get("scrollable") == "true" and "_bounds" in x]
+ if scrollers:
+ x1, y1, x2, y2 = scrollers[0]["_bounds"]
+ cx = (x1 + x2) // 2
+ swipe(cx, int(y1 + (y2 - y1) * 0.72), cx, int(y1 + (y2 - y1) * 0.28))
+ else:
+ scroll_down(0.5)
+ settle("tap")
+ return False
+
+
+# ── depth-backing navigation helpers (the and_enter_*/and_reach_* NAME backs a
+# declared depth>=1; see android_testgen_kit and_audit_depth). ──────────────────
+
+def and_enter_images_to_pdf() -> bool:
+ """Home -> Images to PDF fragment. Confirms the SELECT IMAGES surface."""
+ if not open_card("images_to_pdf", "Images to PDF"):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "addImages") is None:
+ return False
+ and_enter("images_to_pdf")
+ return True
+
+
+def and_enter_text_to_pdf() -> bool:
+ """Home -> Text To PDF fragment. Confirms the SELECT TEXT FILE surface."""
+ if not open_card("text_to_pdf", "Text To PDF"):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "createtextpdf") is None:
+ return False
+ and_enter("text_to_pdf")
+ return True
+
+
+def _hamburger(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ for n in nodes:
+ if (n.get("class", "").endswith("ImageButton")
+ and n.get("content-desc") == "PDF Converter"):
+ return n
+ return None
+
+
+def and_enter_drawer() -> bool:
+ """Open the navigation drawer via the hamburger (ImageButton content-desc
+ 'PDF Converter'). Confirmed by the 'Home' drawer item appearing."""
+ hb = _hamburger()
+ if hb is not None and tap_node(hb):
+ settle("tap")
+ if find_node(ui(), text="Home") is None:
+ open_drawer() # fall back to an edge swipe
+ settle("tap")
+ if find_node(ui(), text="Home") is None:
+ return False
+ and_enter("drawer")
+ return True
+
+
+def and_enter_settings() -> bool:
+ """From the open drawer, scroll to and tap 'Settings'. Confirmed by the
+ Settings storage-location label (unique to that fragment) appearing."""
+ target = None
+ for _ in range(8):
+ nodes = ui()
+ target = find_node(nodes, text="Settings")
+ if target is not None:
+ break
+ scrollers = [x for x in nodes if x.get("scrollable") == "true" and "_bounds" in x]
+ if scrollers:
+ x1, y1, x2, y2 = scrollers[0]["_bounds"]
+ cx = (x1 + x2) // 2
+ swipe(cx, int(y1 + (y2 - y1) * 0.72), cx, int(y1 + (y2 - y1) * 0.28))
+ else:
+ scroll_down(0.5)
+ settle("tap")
+ if target is None or not tap_node(target):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "storagelocation") is None:
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_reach_settings() -> bool:
+ """Home -> drawer -> Settings (depth 2)."""
+ return and_enter_drawer() and and_enter_settings()
+
+
+def reach_settings_after_relaunch() -> bool:
+ """Land on Home from whatever surface the app restored, then drawer->Settings.
+ Retries the whole path once — a theme change / cold relaunch can leave the app
+ momentarily on a half-restored surface."""
+ for _ in range(2):
+ if _reach_home() and and_reach_settings():
+ return True
+ and_reset_depth()
+ return False
+
+
+# ── the core precondition for the Images-to-PDF dialogs ────────────────────────
+
+def select_one_image() -> str | None:
+ """From the Images-to-PDF fragment: SELECT IMAGES -> pick one photo in the
+ system Photo Picker -> tap 'Add (1)' -> back in the fragment. Returns the
+ observed tvNoOfImages text (re-dumped), or None on failure. The picker is a
+ separate process, so we re-dump after returning."""
+ add = node_by_id(ui(), "addImages")
+ if add is None or not tap_node(add):
+ return None
+ settle("launch")
+ settle("tap")
+ photos = []
+ for _ in range(6):
+ photos = [x for x in ui()
+ if x.get("content-desc", "").lower().startswith("photo taken")]
+ if photos:
+ break
+ settle("tap")
+ if not photos:
+ return None
+ if not tap_node(photos[0]):
+ return None
+ settle("tap")
+ addbtn = None
+ for _ in range(4):
+ addbtn = next((x for x in ui()
+ if x.get("text", "").strip().lower().startswith("add (")), None)
+ if addbtn is not None:
+ break
+ settle("tap")
+ if addbtn is None or not tap_node(addbtn):
+ return None
+ settle("launch")
+ settle("tap")
+ tv = node_by_id(ui(), "tvNoOfImages")
+ return tv.get("text") if tv is not None else None
+
+
+def images_to_pdf_with_image() -> bool:
+ """Home -> Images to PDF -> select one image. The precondition for the
+ enhancement dialogs (they snackbar 'Please select an image !' without one)."""
+ if not home_ready() or not and_enter_images_to_pdf():
+ return False
+ return select_one_image() is not None
+
+
+def create_one_pdf() -> bool:
+ """From the Images-to-PDF fragment WITH an image selected: CREATE PDF -> clear
+ the prefilled auto filename -> type a unique name -> OK. Returns True when the
+ OPEN PDF button (pdfOpen) appears (the app's success signal). Used to GUARANTEE
+ a row exists in View Files — a fresh eval emulator starts with no PDFs."""
+ name = f"kitstate{int(_time.time() * 1000) % 100000000}"
+ pc = node_by_id(ui(), "pdfCreate")
+ if pc is None or pc.get("enabled") != "true" or not tap_node(pc):
+ return False
+ settle("tap")
+ settle("tap")
+ ets = find_by_class(ui(), "EditText")
+ if not ets or not tap_node(ets[0]):
+ return False
+ settle("keyboard")
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(40):
+ adb_shell("input", "keyevent", "67") # KEYCODE_DEL
+ settle("text")
+ fresh = find_by_class(ui(), "EditText")
+ if not fresh or not type_text(fresh[0], name, verify_focus=False):
+ return False
+ settle("text")
+ ok = find_node_ci(ui(), "OK")
+ if ok is None or not tap_node(ok):
+ return False
+ settle("launch")
+ settle("tap")
+ for _ in range(4):
+ if node_by_id(ui(), "pdfOpen") is not None:
+ return True
+ settle("launch")
+ return node_by_id(ui(), "pdfOpen") is not None
+
+
+def and_reach_view_files() -> bool:
+ """Home -> View Files. Jump proven by the files RecyclerView appearing (unique
+ to this surface) while the Home 'Create new PDF' header disappears. Counts one
+ surface via and_enter on success."""
+ n = node_by_id(ui(), "view_files") or scroll_into_view("View Files")
+ if n is None:
+ return False
+ before = and_showing()
+ if not tap_node(n):
+ return False
+ for _ in range(6):
+ settle("launch")
+ if node_by_id(ui(), "filesRecyclerView") is not None:
+ break
+ after = and_showing()
+ ok = and_reach(before, after, "filesRecyclerView", "Create new PDF")
+ if ok:
+ and_enter("view_files")
+ return ok
+
+
+# ── dialog helpers ─────────────────────────────────────────────────────────────
+
+def dialog_radio(nodes, label_substr: str):
+ """The RadioButton whose text contains label_substr (case-insensitive)."""
+ s = label_substr.lower()
+ for n in nodes:
+ if ("RadioButton" in n.get("class", "")
+ and s in n.get("text", "").lower()):
+ return n
+ return None
+
+
+def dialog_checkbox(nodes, label_substr: str = "Set as default"):
+ """The 'Set as default' CheckBox in a value dialog (matched by text; falls
+ back to any CheckBox in the dialog)."""
+ s = label_substr.lower()
+ for n in nodes:
+ if "CheckBox" in n.get("class", "") and s in n.get("text", "").lower():
+ return n
+ cbs = [n for n in nodes if "CheckBox" in n.get("class", "")]
+ return cbs[0] if cbs else None
+
+
+def tap_dialog_ok(nodes=None) -> bool:
+ """Tap the dialog's OK button against a fresh dump (avoids hide_keyboard,
+ which can BACK-dismiss a dialog)."""
+ nodes = ui() if nodes is None else nodes
+ ok = find_node(nodes, text="OK") or find_node_ci(nodes, "OK")
+ return tap_node(ok) if ok is not None else False
+
+
+def label_value(label_substr: str) -> str:
+ """Read a Settings/enhancement card label (e.g. 'Theme default value : Dark')
+ out of a fresh dump; '' if absent."""
+ return label_containing(label_substr, ui())
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# A. CONDITIONAL ENABLE/DISABLE — the headline state machine.
+# CREATE PDF (pdfCreate) is enabled=false BEFORE an image, enabled=true AFTER.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_create_pdf_disabled", "states_create_pdf_disabled_vlm"))
+def test_create_pdf_disabled_before_image():
+ ok_nav = home_ready() and and_enter_images_to_pdf()
+ if not ok_nav:
+ record("states_create_pdf_disabled", False,
+ "setup_failed: could not reach the Images-to-PDF fragment",
+ depth=1, jump_kind="value", expect="pdfCreate enabled=false on fresh entry")
+ else:
+ pc = node_by_id(ui(), "pdfCreate")
+ if pc is None:
+ record("states_create_pdf_disabled", False,
+ "feature_missing: no CREATE PDF button (pdfCreate)",
+ depth=1, jump_kind="value", expect="pdfCreate enabled=false on fresh entry")
+ else:
+ disabled = pc.get("enabled") == "false"
+ record("states_create_pdf_disabled", disabled,
+ "" if disabled else
+ "behavior_wrong: CREATE PDF is enabled before any image is selected",
+ depth=1, jump_kind="value",
+ expect="pdfCreate enabled=false before any image selected")
+ vlm_assert("states_create_pdf_disabled",
+ "The button labelled 'CREATE PDF' below the orange 'SELECT IMAGES' "
+ "button — is it rendered in a muted GREY (disabled) fill rather than "
+ "a saturated orange?", RESULTS_DIR, tag="color")
+
+
+@and_test(expects=("states_create_pdf_enabled_after_image",
+ "states_create_pdf_enabled_after_image_vlm"))
+def test_create_pdf_enabled_after_image():
+ ok_nav = home_ready() and and_enter_images_to_pdf()
+ if not ok_nav:
+ record("states_create_pdf_enabled_after_image", False,
+ "setup_failed: could not reach the Images-to-PDF fragment",
+ depth=1, jump_kind="transition",
+ expect="pdfCreate disabled->enabled after image select")
+ else:
+ before = (node_by_id(ui(), "pdfCreate") or {}).get("enabled")
+ tv_text = select_one_image()
+ fresh = ui()
+ after = (node_by_id(fresh, "pdfCreate") or {}).get("enabled")
+ tv = node_by_id(fresh, "tvNoOfImages")
+ tv_now = (tv or {}).get("text", "") if tv is not None else (tv_text or "")
+ count_ok = "image(s) selected" in (tv_now or "")
+ ok = before == "false" and after == "true" and count_ok
+ record("states_create_pdf_enabled_after_image", ok,
+ "" if ok else
+ f"behavior_wrong: CREATE PDF enabled {before}->{after}, "
+ f"tvNoOfImages={tv_now!r} (expected disabled->enabled + count text)",
+ depth=1, jump_kind="transition",
+ expect="pdfCreate enabled false->true; tvNoOfImages='1 image(s) selected.'")
+ vlm_assert("states_create_pdf_enabled_after_image",
+ "The button labelled 'CREATE PDF' — is it now rendered in a "
+ "saturated ORANGE (enabled) fill, the same orange as the "
+ "'SELECT IMAGES' button above it?", RESULTS_DIR, tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# B. RADIOBUTTON selection state + consequence (this lane owns CHECKED).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_pagesize_radio_letter", "states_pagesize_radio_letter_vlm"))
+def test_pagesize_radio_letter():
+ if not images_to_pdf_with_image():
+ record("states_pagesize_radio_letter", False,
+ "setup_failed: could not reach Images-to-PDF with a selected image",
+ depth=1, jump_kind="transition",
+ expect="LETTER checked false->true; LETTER pre-checked after reopen")
+ vlm_assert("states_pagesize_radio_letter",
+ "In this radio dialog, is exactly one radio button filled with a "
+ "solid ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+ return
+ if not tap_card("Set Page Size"):
+ record("states_pagesize_radio_letter", False,
+ "feature_missing: no 'Set Page Size' enhancement card",
+ depth=1, jump_kind="transition",
+ expect="LETTER checked false->true; LETTER pre-checked after reopen")
+ vlm_assert("states_pagesize_radio_letter",
+ "In this radio dialog, is exactly one radio button filled with a "
+ "solid ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+ return
+ settle("tap")
+ nodes = ui()
+ default_before = (dialog_radio(nodes, "DEFAULT") or {}).get("checked")
+ letter = dialog_radio(nodes, "LETTER")
+ if letter is None:
+ record("states_pagesize_radio_letter", False,
+ "feature_missing: no LETTER radio in the Set Page Size dialog",
+ depth=1, jump_kind="transition",
+ expect="LETTER checked false->true; LETTER pre-checked after reopen")
+ else:
+ letter_before = letter.get("checked")
+ tap_node(letter)
+ settle("tap")
+ after = ui()
+ letter_after = (dialog_radio(after, "LETTER") or {}).get("checked")
+ default_after = (dialog_radio(after, "DEFAULT") or {}).get("checked")
+ in_dialog_ok = (letter_before == "false" and letter_after == "true"
+ and default_before == "true" and default_after == "false")
+ # OK -> reopen: LETTER must now be the pre-checked radio (this dialog
+ # DOES remember the choice — observed live).
+ tap_dialog_ok(after)
+ settle("tap")
+ reopened_ok = False
+ if tap_card("Set Page Size"):
+ settle("tap")
+ re_letter = dialog_radio(ui(), "LETTER")
+ reopened_ok = re_letter is not None and re_letter.get("checked") == "true"
+ tap_dialog_ok(ui()) # close the reopened dialog cleanly
+ ok = in_dialog_ok and reopened_ok
+ record("states_pagesize_radio_letter", ok,
+ "" if ok else
+ f"behavior_wrong: LETTER {letter_before}->{letter_after}, "
+ f"DEFAULT {default_before}->{default_after}, reopen LETTER checked={reopened_ok}",
+ depth=1, jump_kind="transition",
+ expect="LETTER checked false->true (DEFAULT true->false); LETTER pre-checked after reopen")
+ # Re-open once more for the VLM capture of the highlighted radio.
+ tap_card("Set Page Size")
+ settle("tap")
+ vlm_assert("states_pagesize_radio_letter",
+ "In this 'Set Page Size' radio dialog, is exactly one radio button "
+ "filled with a solid ORANGE dot while the other options are empty "
+ "grey circles?", RESULTS_DIR, tag="color")
+
+
+@and_test(expects=("states_scaletype_radio_stretch", "states_scaletype_radio_stretch_vlm"))
+def test_scaletype_radio_stretch():
+ if not images_to_pdf_with_image():
+ record("states_scaletype_radio_stretch", False,
+ "setup_failed: could not reach Images-to-PDF with a selected image",
+ depth=1, jump_kind="transition",
+ expect="Stretch checked false->true AND Maintain true->false (single-choice mutual exclusion)")
+ vlm_assert("states_scaletype_radio_stretch",
+ "In this radio dialog, is exactly one radio button filled with a "
+ "solid ORANGE dot while the other is an empty grey circle?",
+ RESULTS_DIR, tag="color")
+ return
+ if not tap_card("Set Image Scale Type"):
+ record("states_scaletype_radio_stretch", False,
+ "feature_missing: no 'Set Image Scale Type' card",
+ depth=1, jump_kind="transition",
+ expect="Stretch checked false->true AND Maintain true->false (single-choice mutual exclusion)")
+ vlm_assert("states_scaletype_radio_stretch",
+ "In this radio dialog, is exactly one radio button filled with a "
+ "solid ORANGE dot while the other is an empty grey circle?",
+ RESULTS_DIR, tag="color")
+ return
+ settle("tap")
+ nodes = ui()
+ maintain_before = (dialog_radio(nodes, "Maintain aspect") or {}).get("checked")
+ stretch = dialog_radio(nodes, "Stretch")
+ if stretch is None:
+ record("states_scaletype_radio_stretch", False,
+ "feature_missing: no 'Stretch image to fit on page' radio",
+ depth=1, jump_kind="transition",
+ expect="Stretch checked false->true AND Maintain true->false (single-choice mutual exclusion)")
+ else:
+ stretch_before = stretch.get("checked")
+ tap_node(stretch)
+ settle("tap")
+ after = ui()
+ stretch_after = (dialog_radio(after, "Stretch") or {}).get("checked")
+ maintain_after = (dialog_radio(after, "Maintain aspect") or {}).get("checked")
+ # The app-authored consequence of a single-choice RadioGroup: checking
+ # Stretch UNchecks Maintain in the same dialog. (This dialog does NOT
+ # pre-check the choice on reopen without 'Set as default' — observed live,
+ # so reopen is NOT part of the pass condition.)
+ in_dialog_ok = (stretch_before == "false" and stretch_after == "true"
+ and maintain_before == "true" and maintain_after == "false")
+ tap_dialog_ok(after)
+ settle("tap")
+ ok = in_dialog_ok
+ record("states_scaletype_radio_stretch", ok,
+ "" if ok else
+ f"behavior_wrong: Stretch {stretch_before}->{stretch_after}, "
+ f"Maintain {maintain_before}->{maintain_after} (expected Stretch true, Maintain false)",
+ depth=1, jump_kind="transition",
+ expect="Stretch checked false->true AND Maintain true->false (single-choice mutual exclusion)")
+ # Re-open for the VLM capture of the highlighted radio.
+ tap_card("Set Image Scale Type")
+ settle("tap")
+ vlm_assert("states_scaletype_radio_stretch",
+ "In this 'Set Image Scale Type' radio dialog, is exactly one radio "
+ "button filled with a solid ORANGE dot while the other is an empty "
+ "grey circle?", RESULTS_DIR, tag="color")
+
+
+@and_test(expects=("states_fontfamily_radio_helvetica",
+ "states_fontfamily_radio_helvetica_vlm"))
+def test_fontfamily_radio_helvetica():
+ ok_nav = home_ready() and and_enter_text_to_pdf()
+ if not ok_nav:
+ record("states_fontfamily_radio_helvetica", False,
+ "setup_failed: could not reach the Text-To-PDF fragment",
+ depth=1, jump_kind="transition",
+ expect="HELVETICA checked false->true; card label -> 'Font Family : HELVETICA'")
+ vlm_assert("states_fontfamily_radio_helvetica",
+ "In this font radio dialog, is exactly one radio button filled "
+ "with a solid ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+ return
+ if not tap_card("Font Family"):
+ record("states_fontfamily_radio_helvetica", False,
+ "feature_missing: no 'Font Family' card in Text-To-PDF",
+ depth=1, jump_kind="transition",
+ expect="HELVETICA checked false->true; card label -> 'Font Family : HELVETICA'")
+ vlm_assert("states_fontfamily_radio_helvetica",
+ "In this font radio dialog, is exactly one radio button filled "
+ "with a solid ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+ return
+ settle("tap")
+ nodes = ui()
+ times_before = (dialog_radio(nodes, "TIMES_ROMAN") or {}).get("checked")
+ helv = dialog_radio(nodes, "HELVETICA")
+ if helv is None:
+ record("states_fontfamily_radio_helvetica", False,
+ "feature_missing: no HELVETICA radio in the Font Family dialog",
+ depth=1, jump_kind="transition",
+ expect="HELVETICA checked false->true; card label -> 'Font Family : HELVETICA'")
+ else:
+ helv_before = helv.get("checked")
+ tap_node(helv)
+ settle("tap")
+ after = ui()
+ helv_after = (dialog_radio(after, "HELVETICA") or {}).get("checked")
+ times_after = (dialog_radio(after, "TIMES_ROMAN") or {}).get("checked")
+ in_dialog_ok = (helv_before == "false" and helv_after == "true"
+ and times_before == "true" and times_after == "false")
+ tap_dialog_ok(after)
+ settle("tap")
+ # This dialog ECHOES the choice into the card label. The chosen (non-default)
+ # value renders as "Font Family : HELVETICA" (observed live — the
+ # "(Default : ...)" parenthetical is only the initial label).
+ card_now = label_value("Font Family")
+ low = card_now.lower()
+ card_ok = "helvetica" in low and "times_roman" not in low
+ ok = in_dialog_ok and card_ok
+ record("states_fontfamily_radio_helvetica", ok,
+ "" if ok else
+ f"behavior_wrong: HELVETICA {helv_before}->{helv_after}, "
+ f"TIMES {times_before}->{times_after}, card label now {card_now!r}",
+ depth=1, jump_kind="transition",
+ expect="HELVETICA checked false->true; card label -> 'Font Family : HELVETICA'")
+ # Re-open for the VLM capture of the highlighted radio.
+ tap_card("Font Family")
+ settle("tap")
+ vlm_assert("states_fontfamily_radio_helvetica",
+ "In this 'Font Family' radio dialog listing COURIER, HELVETICA, "
+ "TIMES_ROMAN, SYMBOL, etc, is exactly one radio button filled with a "
+ "solid ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# C. CHECKBOX toggle + consequence (this lane owns CHECKED).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_set_as_default_checkbox", "states_set_as_default_checkbox_vlm"))
+def test_set_as_default_checkbox():
+ if not images_to_pdf_with_image():
+ record("states_set_as_default_checkbox", False,
+ "setup_failed: could not reach Images-to-PDF with a selected image",
+ depth=1, jump_kind="transition",
+ expect="'Set as default' checkbox false->true; OK accepted (dialog closes)")
+ vlm_assert("states_set_as_default_checkbox",
+ "Is the checkbox next to the label 'Set as default' now a FILLED "
+ "square with a check mark, rather than an empty outlined square?",
+ RESULTS_DIR, tag="shape")
+ return
+ if not tap_card("Set Page Size"):
+ record("states_set_as_default_checkbox", False,
+ "feature_missing: no dialog with a 'Set as default' checkbox",
+ depth=1, jump_kind="transition",
+ expect="'Set as default' checkbox false->true; OK accepted (dialog closes)")
+ vlm_assert("states_set_as_default_checkbox",
+ "Is the checkbox next to the label 'Set as default' now a FILLED "
+ "square with a check mark, rather than an empty outlined square?",
+ RESULTS_DIR, tag="shape")
+ return
+ settle("tap")
+ nodes = ui()
+ cb = dialog_checkbox(nodes, "Set as default")
+ if cb is None:
+ record("states_set_as_default_checkbox", False,
+ "feature_missing: no 'Set as default' checkbox in the dialog",
+ depth=1, jump_kind="transition",
+ expect="'Set as default' checkbox false->true; OK accepted (dialog closes)")
+ else:
+ before = cb.get("checked")
+ tap_node(cb)
+ settle("tap")
+ after_nodes = ui()
+ after = (find_closest_match(after_nodes, cb) or {}).get("checked")
+ checked_ok = before == "false" and after == "true"
+ # Consequence: OK is accepted -> the dialog closes and we return to the
+ # fragment (SELECT IMAGES showing, no more 'Set as default' checkbox).
+ tap_dialog_ok(after_nodes)
+ settle("tap")
+ back_nodes = ui()
+ closed = (node_by_id(back_nodes, "addImages") is not None
+ and dialog_checkbox(back_nodes, "Set as default") is None)
+ ok = checked_ok and closed
+ record("states_set_as_default_checkbox", ok,
+ "" if ok else
+ f"behavior_wrong: 'Set as default' checked {before}->{after}, "
+ f"dialog_closed_on_OK={closed}",
+ depth=1, jump_kind="transition",
+ expect="'Set as default' checkbox false->true; OK accepted (dialog closes)")
+ # Re-open + re-check for the VLM capture of the ticked box.
+ if tap_card("Set Page Size"):
+ settle("tap")
+ recb = dialog_checkbox(ui(), "Set as default")
+ if recb is not None:
+ tap_node(recb)
+ settle("tap")
+ vlm_assert("states_set_as_default_checkbox",
+ "Is the checkbox next to the label 'Set as default' a FILLED square "
+ "with a check mark, rather than an empty outlined square?",
+ RESULTS_DIR, tag="shape")
+
+
+@and_test(expects=("states_viewfiles_row_checkbox", "states_viewfiles_row_checkbox_vlm"))
+def test_viewfiles_row_checkbox():
+ # A fresh eval emulator starts with no PDFs, so first CREATE one via the full
+ # user path to guarantee a selectable row, then reach View Files from Home.
+ made = images_to_pdf_with_image() and create_one_pdf()
+ reached = False
+ if made:
+ _reach_home()
+ reached = and_reach_view_files()
+ vf = node_by_id(ui(), "filesRecyclerView") if reached else None
+ if vf is None:
+ record("states_viewfiles_row_checkbox", False,
+ "setup_failed: could not create a PDF and reach the View Files list",
+ depth=1, jump_kind="transition",
+ expect="row checkbox false->true + count badge '1'; back to false, badge gone")
+ vlm_assert("states_viewfiles_row_checkbox",
+ "Is there a file row whose leading checkbox is a FILLED ORANGE "
+ "square with a white check mark?", RESULTS_DIR, tag="color")
+ return
+ cb = node_by_id(ui(), "checkbox")
+ if cb is None:
+ record("states_viewfiles_row_checkbox", False,
+ "feature_missing: no row checkbox in View Files",
+ depth=1, jump_kind="transition",
+ expect="row checkbox false->true + count badge '1'; back to false, badge gone")
+ vlm_assert("states_viewfiles_row_checkbox",
+ "Is there a file row whose leading checkbox is a FILLED ORANGE "
+ "square with a white check mark?", RESULTS_DIR, tag="color")
+ return
+ before = cb.get("checked")
+ safe_tap(cb)
+ settle("tap")
+ after_nodes = ui()
+ after = (node_by_id(after_nodes, "checkbox") or {}).get("checked")
+ # Consequence: a selection count badge "1" appears in the toolbar.
+ badge_on = find_node(after_nodes, text="1") is not None
+ check_ok = before == "false" and after == "true" and badge_on
+ # Capture the filled-orange checkbox + badge for the VLM while selected.
+ vlm_assert("states_viewfiles_row_checkbox",
+ "Is there a file row whose leading checkbox is a FILLED ORANGE "
+ "square with a white check mark (a selected row), and a '1' shown in "
+ "the top toolbar?", RESULTS_DIR, tag="color")
+ # Toggle back: uncheck -> badge gone.
+ cb2 = node_by_id(ui(), "checkbox")
+ if cb2 is not None:
+ safe_tap(cb2)
+ settle("tap")
+ back_nodes = ui()
+ after2 = (node_by_id(back_nodes, "checkbox") or {}).get("checked")
+ badge_off = find_node(back_nodes, text="1") is None
+ ok = check_ok and after2 == "false" and badge_off
+ record("states_viewfiles_row_checkbox", ok,
+ "" if ok else
+ f"behavior_wrong: row checkbox {before}->{after} (badge_on={badge_on}), "
+ f"then ->{after2} (badge_off={badge_off})",
+ depth=1, jump_kind="transition",
+ expect="row checkbox false->true + toolbar count badge '1'; uncheck -> false, badge gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# D. SETTINGS / mode PERSISTENCE across process death (this lane owns it) — the
+# tests an in-memory recreation fails. depth 2 (drawer -> Settings -> dialog).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def open_settings_factory() -> bool:
+ """Factory-default entry into Settings: clear data, land on Home, drawer ->
+ Settings (depth 2, backed by and_enter_drawer + and_enter_settings)."""
+ if not home_ready_clear():
+ return False
+ return and_reach_settings()
+
+
+def _select_setting_radio(card_substr: str, choice_substr: str) -> bool:
+ """Open a Settings radio-dialog card, select `choice_substr`, tap OK. Returns
+ True when the choice's radio reported checked=true before OK."""
+ if not tap_card(card_substr):
+ return False
+ settle("tap")
+ radio = dialog_radio(ui(), choice_substr)
+ if radio is None or not tap_node(radio):
+ return False
+ settle("tap")
+ checked = (dialog_radio(ui(), choice_substr) or {}).get("checked") == "true"
+ tap_dialog_ok(ui())
+ settle("tap")
+ return checked
+
+
+@and_test(expects=("states_theme_persists", "states_theme_dark_vlm"))
+def test_theme_dark_persists():
+ if not open_settings_factory():
+ record("states_theme_persists", False,
+ "setup_failed: could not reach Settings from a factory-clean start",
+ depth=2, jump_kind="transition",
+ expect="Theme 'System'->'Dark'; still 'Dark' after force-stop relaunch")
+ vlm_assert("states_theme_dark",
+ "Is the app background a dark/near-black color with light text?",
+ RESULTS_DIR, tag="color", depth=2, jump_kind="transition")
+ return
+ before_label = label_value("Theme default value")
+ # Selecting Dark RECREATES the activity. Reading the label in the SAME session
+ # right afterwards is racy (the recreate can leave the app on a half-restored
+ # surface), so the DEFINITIVE proof the change took is the persisted label read
+ # after a full force-stop relaunch below: it cannot read 'Dark' unless the
+ # in-app selection actually applied AND was written to SharedPreferences.
+ dark_checked = _select_setting_radio("Theme default value", "Dark")
+ settle("launch")
+ # Capture the recolored UI for the VLM (the whole app recolors regardless of
+ # which surface the recreate left us on).
+ vlm_assert("states_theme_dark",
+ "Is the app background a dark / near-black color with light "
+ "(white/grey) text, rather than a light/white background?",
+ RESULTS_DIR, tag="color", depth=2, jump_kind="transition")
+ before_ok = before_label.strip() == "Theme default value : System" and dark_checked
+ # PERSISTENCE probe: kill + relaunch, re-open Settings, assert still Dark.
+ force_stop_and_relaunch()
+ survived = False
+ survived_label = ""
+ if reach_settings_after_relaunch():
+ survived_label = label_value("Theme default value")
+ survived = survived_label.strip() == "Theme default value : Dark"
+ ok = before_ok and survived
+ record("states_theme_persists", ok,
+ "" if ok else
+ f"behavior_wrong: before {before_label!r} (dark_checked={dark_checked}); "
+ f"after force-stop relaunch {survived_label!r} (expected 'Theme default value : Dark')",
+ depth=2, jump_kind="transition",
+ expect="Theme 'System'->'Dark'; still 'Dark' after force-stop relaunch")
+ # Cleanup: reset to System, then hard-clear so later lanes see the DEFAULT theme.
+ if label_value("Theme default value"):
+ _select_setting_radio("Theme default value", "System")
+ clear_data()
+
+
+@and_test(expects=("states_theme_white_vlm",))
+def test_theme_white_recolors():
+ if not open_settings_factory():
+ vlm_assert("states_theme_white",
+ "Is the app background a bright WHITE / light color (not dark)?",
+ RESULTS_DIR, tag="color", depth=2, jump_kind="transition")
+ clear_data()
+ return
+ white_checked = _select_setting_radio("Theme default value", "White")
+ settle("launch")
+ # Regardless of whether the label read back, capture a REAL screenshot so the
+ # VLM record is grounded in the app's rendered state.
+ vlm_assert("states_theme_white",
+ "Is the app background a bright WHITE / light color (not dark), "
+ "with the top toolbar in orange?",
+ RESULTS_DIR, tag="color", depth=2, jump_kind="transition")
+ del white_checked
+ # Cleanup: reset to System / wipe so later lanes get the default theme.
+ if label_value("Theme default value"):
+ _select_setting_radio("Theme default value", "System")
+ clear_data()
+
+
+@and_test(expects=("states_fontsize_default_persists",))
+def test_fontsize_default_persists():
+ if not open_settings_factory():
+ record("states_fontsize_default_persists", False,
+ "setup_failed: could not reach Settings from a factory-clean start",
+ depth=2, jump_kind="transition",
+ expect="Font size default 11->18; survives force-stop relaunch")
+ return
+ before_label = label_value("Font size default value")
+ changed = False
+ if tap_card("Font size default value"):
+ settle("tap")
+ ets = find_by_class(ui(), "EditText")
+ if ets and tap_node(ets[0]):
+ settle("keyboard")
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(6):
+ adb_shell("input", "keyevent", "67") # KEYCODE_DEL
+ settle("text")
+ fresh = find_by_class(ui(), "EditText")
+ if fresh:
+ type_text(fresh[0], "18", verify_focus=False)
+ settle("text")
+ tap_dialog_ok(ui())
+ settle("tap")
+ changed = True
+ after_label = label_value("Font size default value")
+ label_ok = (changed
+ and before_label.strip() == "Font size default value : 11"
+ and after_label.strip() == "Font size default value : 18")
+ force_stop_and_relaunch()
+ survived_label = ""
+ survived = False
+ if reach_settings_after_relaunch():
+ survived_label = label_value("Font size default value")
+ survived = survived_label.strip() == "Font size default value : 18"
+ ok = label_ok and survived
+ record("states_fontsize_default_persists", ok,
+ "" if ok else
+ f"behavior_wrong: font-size label {before_label!r}->{after_label!r}; "
+ f"after restart {survived_label!r}",
+ depth=2, jump_kind="transition",
+ expect="Font size default '11'->'18'; still '18' after force-stop relaunch")
+ clear_data()
+
+
+@and_test(expects=("states_pagesize_default_persists", "states_pagesize_default_dialog_vlm"))
+def test_pagesize_default_persists():
+ if not open_settings_factory():
+ record("states_pagesize_default_persists", False,
+ "setup_failed: could not reach Settings from a factory-clean start",
+ depth=2, jump_kind="transition",
+ expect="Page size default A4->LETTER; survives force-stop relaunch")
+ vlm_assert("states_pagesize_default_dialog",
+ "In this page-size radio dialog, is exactly one radio button "
+ "filled with a solid ORANGE dot while the others are empty grey "
+ "circles?", RESULTS_DIR, tag="color")
+ return
+ before_label = label_value("Page size default value")
+ dialog_open = tap_card("Page size default value")
+ settle("tap")
+ # Capture the highlighted default radio for the VLM while the dialog is open.
+ vlm_assert("states_pagesize_default_dialog",
+ "In this page-size radio dialog (options DEFAULT ( A4 ), Fit size, "
+ "LETTER, LEGAL, ...), is exactly one radio button filled with a solid "
+ "ORANGE dot while the others are empty grey circles?",
+ RESULTS_DIR, tag="color")
+ letter_checked = False
+ if dialog_open:
+ letter = dialog_radio(ui(), "LETTER")
+ if letter is not None and tap_node(letter):
+ settle("tap")
+ letter_checked = (dialog_radio(ui(), "LETTER") or {}).get("checked") == "true"
+ tap_dialog_ok(ui())
+ settle("tap")
+ after_label = label_value("Page size default value")
+ label_ok = (letter_checked
+ and before_label.strip() == "Page size default value : A4"
+ and after_label.strip() == "Page size default value : LETTER")
+ force_stop_and_relaunch()
+ survived_label = ""
+ survived = False
+ if reach_settings_after_relaunch():
+ survived_label = label_value("Page size default value")
+ survived = survived_label.strip() == "Page size default value : LETTER"
+ ok = label_ok and survived
+ record("states_pagesize_default_persists", ok,
+ "" if ok else
+ f"behavior_wrong: page-size label {before_label!r}->{after_label!r} "
+ f"(letter_checked={letter_checked}); after restart {survived_label!r}",
+ depth=2, jump_kind="transition",
+ expect="Page size default 'A4'->'LETTER'; still 'LETTER' after force-stop relaunch")
+ clear_data()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# E. DRAWER selected item (this lane owns selected/checked). The drawer is a
+# single-choice CheckedTextView group: on launch EXACTLY ONE item is checked
+# and it is "Home". (Drawer navigation does NOT move the highlight in this
+# app — observed live — so the discriminating state is the single-selection
+# invariant, asserted as a specific resulting value.)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_drawer_home_selected", "states_drawer_home_selected_vlm"))
+def test_drawer_home_single_checked():
+ if not home_ready() or not and_enter_drawer():
+ record("states_drawer_home_selected", False,
+ "setup_failed: could not open the navigation drawer",
+ depth=1, jump_kind="value",
+ expect="exactly one drawer item checked on launch, and it is 'Home'")
+ vlm_assert("states_drawer_home_selected",
+ "In the navigation drawer, is the 'Home' item highlighted with a "
+ "light ORANGE pill background and orange text/icon, unlike the "
+ "other plain items?", RESULTS_DIR, tag="color")
+ return
+ nodes = ui()
+ checked_items = [n.get("text", "") for n in nodes
+ if "CheckedTextView" in n.get("class", "")
+ and n.get("checked") == "true"]
+ home_item = (find_node(nodes, text="Home", checkable="true")
+ or find_node(nodes, text="Home"))
+ home_checked = (home_item or {}).get("checked")
+ # The app-authored single-choice invariant: exactly ONE checked item, = Home.
+ ok = home_checked == "true" and checked_items == ["Home"]
+ record("states_drawer_home_selected", ok,
+ "" if ok else
+ f"behavior_wrong: Home checked={home_checked}; the set of checked drawer "
+ f"items on launch is {checked_items!r} (expected exactly ['Home'])",
+ depth=1, jump_kind="value",
+ expect="drawer single-choice: exactly one checked item on launch, and it is 'Home' (checked=true)")
+ # Capture the highlighted Home pill for the VLM while the drawer is open.
+ vlm_assert("states_drawer_home_selected",
+ "In this open navigation drawer, is the 'Home' item highlighted with "
+ "a light ORANGE/pink pill-shaped background and orange text and icon, "
+ "while the other items (Create PDF, Text To PDF, ...) have a plain "
+ "white background?", RESULTS_DIR, tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# F. PASSWORD "Show password" toggle (Images-to-PDF -> Password Protect PDF).
+# Toggling reveals/obscures the field — a visibility/focus state consequence.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_password_show_toggle",))
+def test_password_show_toggle():
+ if not images_to_pdf_with_image():
+ record("states_password_show_toggle", False,
+ "setup_failed: could not reach Images-to-PDF with a selected image",
+ depth=1, jump_kind="transition",
+ expect="password field obscured->revealed (toggle desc 'Show password'->'Hide password')")
+ return
+ if not tap_card("Password Protect PDF"):
+ record("states_password_show_toggle", False,
+ "feature_missing: no 'Password Protect PDF' card",
+ depth=1, jump_kind="transition",
+ expect="password field obscured->revealed (toggle desc 'Show password'->'Hide password')")
+ return
+ settle("tap")
+ nodes = ui()
+ toggle = find_node(nodes, content_desc="Show password")
+ et = next((n for n in nodes if "EditText" in n.get("class", "")), None)
+ if toggle is None or et is None:
+ record("states_password_show_toggle", False,
+ "feature_missing: no 'Show password' toggle / password field in the dialog",
+ depth=1, jump_kind="transition",
+ expect="password field obscured->revealed (toggle desc 'Show password'->'Hide password')")
+ return
+ # Type something so the reveal is observable, then flip the toggle.
+ type_text(et, "secret1", verify_focus=False)
+ settle("text")
+ nodes2 = ui()
+ et_before = next((n for n in nodes2 if "EditText" in n.get("class", "")), None)
+ pw_before = (et_before or {}).get("password")
+ tg = (find_node(nodes2, content_desc="Show password")
+ or find_node(nodes2, content_desc="Hide password"))
+ tap_node(tg)
+ settle("tap")
+ nodes3 = ui()
+ et_after = next((n for n in nodes3 if "EditText" in n.get("class", "")), None)
+ pw_after = (et_after or {}).get("password")
+ desc_flipped = find_node(nodes3, content_desc="Hide password") is not None
+ # The consequence is observable either as the EditText's password attr flipping
+ # true->false OR the toggle's content-desc flipping to "Hide password".
+ ok = (pw_before == "true" and pw_after == "false") or desc_flipped
+ record("states_password_show_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: password attr {pw_before}->{pw_after}, "
+ f"desc flipped to 'Hide password'={desc_flipped}",
+ depth=1, jump_kind="transition",
+ expect="password field obscured->revealed (EditText password true->false or desc 'Show'->'Hide')")
+ # Close the dialog cleanly (CANCEL avoids setting a password).
+ cancel = find_node_ci(ui(), "CANCEL")
+ if cancel is not None:
+ tap_node(cancel)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+
+TESTS = [
+ test_create_pdf_disabled_before_image,
+ test_create_pdf_enabled_after_image,
+ test_pagesize_radio_letter,
+ test_scaletype_radio_stretch,
+ test_fontfamily_radio_helvetica,
+ test_set_as_default_checkbox,
+ test_viewfiles_row_checkbox,
+ test_theme_dark_persists,
+ test_theme_white_recolors,
+ test_fontsize_default_persists,
+ test_pagesize_default_persists,
+ test_drawer_home_single_checked,
+ test_password_show_toggle,
+]
+
+
+if __name__ == "__main__":
+ if not device_online():
+ print("Device not reachable — check the emulator/tunnel is up.")
+ sys.exit(2)
+ run_suite(TESTS, "states")
diff --git a/android/swati4star-images-to-pdf/tests/test_android_structure.py b/android/swati4star-images-to-pdf/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3044a44fdaaae5dae7ec7adc6278915750599c8
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_structure.py
@@ -0,0 +1,519 @@
+#!/usr/bin/env python3
+"""STRUCTURE-lane behavioral suite for the "PDF Converter" (image->PDF) app.
+
+Lane charter (see delegation): this file owns exactly two things —
+ 1. THE GATE: the app launches, reaches the foreground, and its top-level home
+ surface exists (toolbar "PDF Converter" host + the feature-card grid). These
+ are jump_kind="none" existence anchors, kept a minority of the suite.
+ 2. TREE-SHAPE DELTAS: a user interaction that changes the tree's SHAPE — the
+ nav drawer adding a whole class of CheckedTextView items, a dialog overlaying
+ a new window layer of RadioButtons, home->fragment replacing the grid with
+ fragment controls, scrolling revealing more cards. Recorded as
+ jump_kind="transition" and, where reversible, reversed to assert it restores.
+
+Everything is asserted on SHAPE (counts of a class, size of the surface key-set,
+container child counts, presence/absence of a discriminating container) — never
+on specific strings or values, which are ceded to the text/computation lanes.
+
+Only structure OBSERVED on the running original (recon dumps 01/02/03/04/22b/27
+and a live home screenshot) is tested here. Read-only kit; import, never edit.
+
+Run: python3 test_android_structure.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# Shared helpers. Names starting `and_enter_` are the depth family the kit's
+# audit looks for, so any depth>=1 claim below is BACKED by a real navigation.
+# ──────────────────────────────────────────────────────────────────────────────
+
+# First-run storage permission MaterialDialog ("Allow app to access files on your
+# device" / DENY / ALLOW). It sits OVER the home grid, which is already present
+# behind it. Dismiss it gracefully (never seed the grant) so the home surface is
+# what we assert against.
+def _dismiss_permission_if_present():
+ for _ in range(2):
+ nodes = ui()
+ title = find_node_ci(nodes, "Allow app to access files on your device")
+ deny = find_node(nodes, text="DENY") or find_node_ci(nodes, "DENY")
+ if not title and not deny:
+ return
+ # DENY keeps us in-app (ALLOW deep-links out to the system settings page).
+ if deny and safe_tap(deny):
+ settle("tap")
+ continue
+ back()
+ settle("tap")
+
+
+def _home_ready() -> list:
+ """Reach a known HOME state: relaunch, wait for foreground, clear the perm
+ dialog, return the home dump."""
+ restart_app()
+ wait_for_foreground()
+ _dismiss_permission_if_present()
+ return ui()
+
+
+# The hamburger is an icon-only ImageButton in the toolbar with content-desc
+# "PDF Converter" (a quirk — the same string is the toolbar title text and the
+# option_image content-desc, so we key on the CLICKABLE ImageButton specifically).
+def _hamburger(nodes):
+ for n in find_by_class(nodes, "ImageButton"):
+ if n.get("clickable") == "true" and n.get("content-desc") == "PDF Converter":
+ return n
+ return None
+
+
+def and_enter_drawer() -> bool:
+ """Open the navigation drawer via the hamburger; confirm the drawer's
+ RecyclerView (design_navigation_view) actually appeared. Counts one surface."""
+ hb = _hamburger(ui())
+ if not hb or not tap_node(hb):
+ # Fall back to the edge-swipe gesture the kit provides.
+ open_drawer()
+ if node_by_id(ui(), "design_navigation_view") is None:
+ open_drawer()
+ ok = node_by_id(ui(), "design_navigation_view") is not None
+ if ok:
+ and_enter("drawer")
+ return ok
+
+
+def and_enter_fragment(nodes, card_id: str, confirm_gone_card: str) -> bool:
+ """Tap a home feature CARD (clickable LinearLayout, matched by resource-id
+ LAST segment) and confirm we crossed into its fragment: the source home card
+ `confirm_gone_card` is no longer present. Counts one surface."""
+ card = node_by_id(nodes, card_id)
+ if not card or not tap_node(card):
+ return False
+ after = ui()
+ crossed = node_by_id(after, confirm_gone_card) is None
+ if crossed:
+ and_enter(card_id)
+ return crossed
+
+
+def and_enter_dialog(nodes, card_text: str) -> bool:
+ """Tap an enhancement/settings CARD by its label text to overlay its dialog;
+ confirm a dialog button layer (android:id/button1 = OK) appeared. Counts one
+ surface."""
+ if not tap_text(nodes, card_text):
+ return False
+ after = ui()
+ opened = (node_by_id(after, "button1") is not None
+ or bool(find_by_class(after, "RadioButton")))
+ if opened:
+ and_enter("dialog:" + card_text)
+ return opened
+
+
+def _select_one_image(nodes) -> bool:
+ """Core automatable flow: SELECT IMAGES -> Photo Picker -> tap a fixture photo
+ -> Add. Returns True once tvNoOfImages / an enabled CREATE PDF confirms an
+ image is selected.
+
+ The picker reads MediaStore, so the fixture PNGs must be on the device and
+ media-scanned. run_suite() does this once, but we call push_fixtures() again
+ here (idempotent) so the dependency on the pushed fixtures is explicit and a
+ fresh emulator is never missing them."""
+ push_fixtures()
+ if not fixture_names():
+ return False
+ if not tap_text(nodes, "SELECT IMAGES"):
+ return False
+ settle("launch")
+ pnodes = ui()
+ photo = None
+ for n in pnodes:
+ cd = n.get("content-desc", "")
+ if cd.startswith("Photo taken") and n.get("clickable") == "true":
+ photo = n
+ break
+ if photo is None: # some pickers put the click target on the parent container
+ for n in pnodes:
+ if n.get("content-desc", "").startswith("Photo taken"):
+ photo = n
+ break
+ if photo is None or not tap_node(photo):
+ return False
+ settle("tap")
+ anodes = ui()
+ # "Add (1)" / "Add" confirm button.
+ add = None
+ for n in anodes:
+ t = n.get("text", "")
+ if t.startswith("Add") and n.get("clickable") == "true":
+ add = n
+ break
+ if add is None:
+ add = find_node_ci(anodes, "Add (1)") or find_node_ci(anodes, "Add")
+ if add and tap_node(add):
+ settle("launch")
+ back_nodes = ui()
+ return (node_by_id(back_nodes, "tvNoOfImages") is not None
+ or (find_node(back_nodes, resource_id="pdfCreate", enabled=True) is not None)
+ or find_node_ci(back_nodes, "CREATE PDF") is not None)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE — jump_kind="none", depth=0. Top-level surfaces exist.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ nodes = _home_ready()
+ fg = wait_for_foreground()
+ # DrawerLayout is the single-Activity root host; a ViewGroup toolbar rides in it.
+ root = node_by_id(nodes, "drawer_layout") or find_by_class(nodes, "DrawerLayout")
+ ok = bool(fg) and bool(root)
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach the foreground with its "
+ "drawer_layout host",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_home_toolbar_present",))
+def test_home_toolbar_present():
+ nodes = _home_ready()
+ toolbar = node_by_id(nodes, "toolbar") or find_by_class(nodes, "Toolbar")
+ hamburger = _hamburger(nodes)
+ favourites = find_node(nodes, content_desc="Favourites")
+ ok = bool(toolbar) and bool(hamburger) and bool(favourites)
+ record("structure_home_toolbar_present", ok,
+ "" if ok else "feature_missing: toolbar host with hamburger + favourites "
+ "affordance not present on home",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_home_grid_cards",))
+def test_home_grid_cards():
+ nodes = _home_ready()
+ # The home grid is a set of clickable feature-card LinearLayouts keyed by id.
+ # We assert the SHAPE: at least 6 of the known card ids exist as clickable
+ # containers (recon showed 12 visible before scrolling).
+ card_ids = ["images_to_pdf", "text_to_pdf", "qr_barcode_to_pdf", "excel_to_pdf",
+ "view_files", "view_history", "add_password", "remove_password",
+ "add_text", "rotate_pages", "add_watermark", "add_images"]
+ present = [cid for cid in card_ids
+ if (c := node_by_id(nodes, cid)) is not None
+ and c.get("clickable") == "true"]
+ ok = len(present) >= 6
+ record("structure_home_grid_cards", ok,
+ "" if ok else f"feature_missing: expected >=6 feature cards, found "
+ f"{len(present)}",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_home_grid_vlm",))
+def test_home_grid_layout_vlm():
+ _home_ready()
+ # Fine-grained POSITION check derived from the live screenshot: the grid is a
+ # multi-column card layout. The "Create new PDF" section header sits directly
+ # above exactly two cards laid out side by side in one row (Images to PDF and
+ # Text To PDF) — an unambiguous two-across arrangement, NOT a single column.
+ vlm_assert("structure_home_grid",
+ "Directly below the 'Create new PDF' section heading, are there two "
+ "feature cards positioned side by side in the same horizontal row "
+ "(one on the left, one on the right)?",
+ RESULTS_DIR, depth=0, jump_kind="none", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TREE-SHAPE DELTAS — jump_kind="transition". Depth>=1 backed by and_enter_*.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_drawer_shape", "structure_drawer_shape_vlm"))
+def test_drawer_shape_delta():
+ nodes = _home_ready()
+ # Home has NO drawer nav list and NO CheckedTextView menu items.
+ before_nav = node_by_id(nodes, "design_navigation_view")
+ before_items = len(find_by_class(nodes, "CheckedTextView"))
+ before_surface = and_showing(nodes)
+
+ opened = and_enter_drawer() # depth -> 1, backed
+ after = ui()
+ after_nav = node_by_id(after, "design_navigation_view")
+ after_items = len(find_by_class(after, "CheckedTextView"))
+ after_surface = and_showing(after)
+
+ # SHAPE delta: a nav RecyclerView layer appears and a whole class of
+ # CheckedTextView items materialises (recon showed 13 visible), and the
+ # surface key-set changes materially.
+ grew = (before_nav is None and after_nav is not None
+ and after_items >= before_items + 8
+ and surface_changed(before_surface, after_surface))
+
+ # Reverse it: closing the drawer removes the nav list again (shape restores).
+ and_back() # depth -> 0
+ settle("tap")
+ restored = node_by_id(ui(), "design_navigation_view") is None
+
+ ok = bool(opened) and grew and restored
+ record("structure_drawer_shape", ok,
+ "" if ok else "behavior_wrong: drawer did not add the CheckedTextView "
+ f"item class (before={before_items}, after={after_items}) "
+ f"or did not restore on close",
+ depth=1, jump_kind="transition",
+ expect="drawer opens: design_navigation_view + >=8 new CheckedTextView "
+ "items appear; both gone again on close")
+
+ # Re-open for the visual check (drawer must be showing in the screenshot).
+ if and_enter_drawer():
+ vlm_assert("structure_drawer_shape",
+ "Is a navigation drawer open, covering roughly the left "
+ "two-thirds of the screen as a vertical list of menu items, "
+ "with the rest of the screen dimmed on the right?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="position")
+ and_back()
+ else:
+ vlm_assert("structure_drawer_shape",
+ "Is a navigation drawer open as a vertical list on the left?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="position")
+
+
+@and_test(expects=("structure_home_to_fragment_shape",))
+def test_home_to_fragment_shape_delta():
+ nodes = _home_ready()
+ # Home surface: the images_to_pdf card is present; text_to_pdf is a sibling
+ # card. Neither the SELECT IMAGES button nor the enhancement grid exists yet.
+ before_surface = and_showing(nodes)
+ before_select = find_node_ci(nodes, "SELECT IMAGES")
+ before_enh = node_by_id(nodes, "enhancement_options_recycle_view")
+
+ # Navigate into the Images-to-PDF fragment (depth -> 1, backed): the sibling
+ # home card text_to_pdf must be gone afterwards.
+ crossed = and_enter_fragment(nodes, "images_to_pdf", "text_to_pdf")
+ after = ui()
+ after_surface = and_showing(after)
+ after_select = find_node_ci(after, "SELECT IMAGES")
+ after_enh = node_by_id(after, "enhancement_options_recycle_view")
+
+ # SHAPE delta: the grid of home cards is replaced by fragment controls — a
+ # SELECT IMAGES button + the enhancement options GridView appear where they
+ # were absent, and the surface changes materially.
+ reshaped = (before_select is None and after_select is not None
+ and before_enh is None and after_enh is not None
+ and surface_changed(before_surface, after_surface))
+ ok = bool(crossed) and reshaped
+ record("structure_home_to_fragment_shape", ok,
+ "" if ok else "behavior_wrong: home grid was not replaced by the "
+ "Images-to-PDF fragment controls (SELECT IMAGES button + "
+ "enhancement grid)",
+ depth=1, jump_kind="transition",
+ expect="home grid -> img2pdf fragment: SELECT IMAGES button + "
+ "enhancement_options_recycle_view appear; text_to_pdf card gone")
+
+
+@and_test(expects=("structure_settings_grid_shape", "structure_settings_grid_vlm"))
+def test_settings_grid_shape_delta():
+ nodes = _home_ready()
+ before_settings = node_by_id(nodes, "settings_list")
+ before_surface = and_showing(nodes)
+
+ # Reach Settings via the drawer (depth -> 1) then the Settings item (depth -> 2).
+ if not and_enter_drawer():
+ record("structure_settings_grid_shape", False,
+ "setup_failed: could not open the navigation drawer",
+ depth=2, jump_kind="transition",
+ expect="settings_list GridView appears; home grid gone")
+ vlm_assert("structure_settings_grid",
+ "Is the screen a grid of setting cards arranged two per row?",
+ RESULTS_DIR, depth=2, jump_kind="none", tag="position")
+ return
+ dnodes = ui()
+ settings_item = scroll_into_view("Settings") or find_node_ci(dnodes, "Settings")
+ reached = False
+ if settings_item and tap_node(settings_item):
+ and_enter("settings")
+ reached = True
+ after = ui()
+ after_settings = node_by_id(after, "settings_list")
+ after_surface = and_showing(after)
+
+ # SHAPE delta: a settings GridView container (settings_list) appears that did
+ # not exist on home, and the home feature cards are gone.
+ reshaped = (before_settings is None and after_settings is not None
+ and node_by_id(after, "images_to_pdf") is None
+ and surface_changed(before_surface, after_surface))
+ ok = reached and reshaped
+ record("structure_settings_grid_shape", ok,
+ "" if ok else "behavior_wrong: Settings did not present its settings_list "
+ "card grid in place of the home grid",
+ depth=2, jump_kind="transition",
+ expect="drawer->Settings: settings_list GridView appears, home "
+ "images_to_pdf card gone")
+
+ vlm_assert("structure_settings_grid",
+ "Is the main content of this Settings screen a grid of option "
+ "cards arranged two per row (two evenly spaced columns)?",
+ RESULTS_DIR, depth=2, jump_kind="none", tag="position")
+
+
+@and_test(expects=("structure_home_scroll_reveals",))
+def test_home_scroll_reveals_cards():
+ nodes = _home_ready()
+ scroll = find_node(nodes, scrollable=True) or find_by_class(nodes, "ScrollView")
+ if not scroll:
+ record("structure_home_scroll_reveals", False,
+ "setup_failed: home scroll container not found",
+ depth=0, jump_kind="transition",
+ expect="scrolling home reveals additional feature cards")
+ return
+ _card_id_set = ("images_to_pdf", "text_to_pdf", "qr_barcode_to_pdf",
+ "excel_to_pdf", "view_files", "view_history", "add_password",
+ "remove_password", "add_text", "rotate_pages", "add_watermark",
+ "add_images", "merge", "split", "remove_pages", "compress_pdf",
+ "extract_text", "pdf_to_images", "zip_to_pdf", "invert_pdf",
+ "remove_duplicate_pages", "extract_images", "reorder_pages")
+
+ def _visible_cards(ns):
+ return {node_key(n) for n in ns
+ if n.get("clickable") == "true"
+ and n.get("resource-id", "").rsplit("/", 1)[-1] in _card_id_set}
+
+ before_cards = _visible_cards(nodes)
+ scroll_down(0.8)
+ scroll_down(0.8)
+ after = ui()
+ after_cards = _visible_cards(after)
+ # SHAPE delta: the set of visible feature cards changes (new ids scroll in).
+ newly = after_cards - before_cards
+ ok = len(newly) >= 1 and surface_changed(and_showing(nodes), and_showing(after))
+ record("structure_home_scroll_reveals", ok,
+ "" if ok else "behavior_wrong: scrolling the home grid revealed no "
+ "additional feature cards",
+ depth=0, jump_kind="transition",
+ expect="scrolling home reveals >=1 feature card not visible before")
+
+
+@and_test(expects=("structure_pagesize_dialog_shape", "structure_pagesize_dialog_vlm"))
+def test_pagesize_dialog_shape_delta():
+ nodes = _home_ready()
+ # Enter Images-to-PDF (depth -> 1). Set Page Size needs >=1 selected image,
+ # else a snackbar (no dialog) appears — so we select a fixture image first.
+ if not and_enter_fragment(nodes, "images_to_pdf", "text_to_pdf"):
+ record("structure_pagesize_dialog_shape", False,
+ "setup_failed: could not open the Images-to-PDF fragment",
+ depth=2, jump_kind="transition",
+ expect="Set Page Size overlays a dialog of RadioButtons")
+ vlm_assert("structure_pagesize_dialog",
+ "Is a dialog box centered on screen over a dimmed background?",
+ RESULTS_DIR, depth=2, jump_kind="none", tag="position")
+ return
+ if not _select_one_image(ui()):
+ record("structure_pagesize_dialog_shape", False,
+ "setup_failed: could not select a fixture image via the photo picker",
+ depth=2, jump_kind="transition",
+ expect="Set Page Size overlays a dialog of RadioButtons")
+ vlm_assert("structure_pagesize_dialog",
+ "Is a dialog box centered on screen over a dimmed background?",
+ RESULTS_DIR, depth=2, jump_kind="none", tag="position")
+ return
+
+ scroll_into_view("Set Page Size")
+ frag = ui()
+ before_radios = len(find_by_class(frag, "RadioButton"))
+ before_surface = and_showing(frag)
+
+ opened = and_enter_dialog(frag, "Set Page Size") # depth -> 2, backed
+ after = ui()
+ after_radios = len(find_by_class(after, "RadioButton"))
+ after_surface = and_showing(after)
+
+ # SHAPE delta: a dialog window layer overlays the fragment, adding a whole
+ # class of RadioButton widgets (recon showed DEFAULT(A4)/Fit/LETTER/... many),
+ # and the surface changes materially.
+ grew = (opened and after_radios >= before_radios + 3
+ and surface_changed(before_surface, after_surface))
+
+ # Screenshot the modal for the visual check BEFORE reversing it.
+ vlm_assert("structure_pagesize_dialog",
+ "Is there a dialog box centered on the screen, overlaying and "
+ "dimming the content behind it?",
+ RESULTS_DIR, depth=2, jump_kind="none", tag="position")
+
+ # Reverse it: CANCEL (or BACK) dismisses the dialog; the RadioButton class
+ # disappears and the fragment shape restores.
+ cancel = find_node(ui(), text="CANCEL") or find_node_ci(ui(), "CANCEL")
+ if cancel and safe_tap(cancel):
+ settle("tap")
+ else:
+ and_back()
+ restored = len(find_by_class(ui(), "RadioButton")) <= before_radios
+
+ ok = grew and restored
+ record("structure_pagesize_dialog_shape", ok,
+ "" if ok else "behavior_wrong: Set Page Size did not overlay a "
+ f"RadioButton dialog layer (before={before_radios}, "
+ f"after={after_radios}) or did not restore on cancel",
+ depth=2, jump_kind="transition",
+ expect="Set Page Size overlays a dialog adding >=3 RadioButtons; gone "
+ "again on cancel")
+
+
+@and_test(expects=("structure_history_toolbar_shape", "structure_toolbar_layout_vlm"))
+def test_history_toolbar_shape_delta():
+ nodes = _home_ready()
+ # Home toolbar has ONLY the Favourites affordance; no Delete/Filter buttons and
+ # no history list container.
+ before_delete = find_node(nodes, content_desc="Delete")
+ before_filter = find_node(nodes, content_desc="Filter")
+ before_list = node_by_id(nodes, "historyRecyclerView")
+ before_surface = and_showing(nodes)
+
+ # Navigate into History (depth -> 1, backed): the sibling home card view_files
+ # must be gone afterwards.
+ crossed = and_enter_fragment(nodes, "view_history", "view_files")
+ after = ui()
+ after_delete = find_node(after, content_desc="Delete")
+ after_filter = find_node(after, content_desc="Filter")
+ after_list = node_by_id(after, "historyRecyclerView")
+ after_surface = and_showing(after)
+
+ # SHAPE delta: the toolbar gains a Delete + Filter icon class and a history
+ # RecyclerView container appears — none of which existed on home. (Populated
+ # rows are NOT asserted: a fresh emulator may have no created PDFs.)
+ reshaped = (crossed
+ and before_delete is None and after_delete is not None
+ and before_filter is None and after_filter is not None
+ and before_list is None and after_list is not None
+ and surface_changed(before_surface, after_surface))
+ record("structure_history_toolbar_shape", reshaped,
+ "" if reshaped else "behavior_wrong: History did not add its Delete + "
+ "Filter toolbar icons and historyRecyclerView "
+ "container",
+ depth=1, jump_kind="transition",
+ expect="home->History: Delete+Filter toolbar icons + "
+ "historyRecyclerView appear (absent on home)")
+
+ # Toolbar layout visual check on the History surface (title + right-side icons
+ # in a single top row).
+ vlm_assert("structure_toolbar_layout",
+ "Is there a single horizontal top bar with a screen title text on "
+ "the left side and one or more icon buttons on the right side, all "
+ "in the same row?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="layout")
+
+
+TESTS = [
+ test_gate_launch,
+ test_home_toolbar_present,
+ test_home_grid_cards,
+ test_home_grid_layout_vlm,
+ test_drawer_shape_delta,
+ test_home_to_fragment_shape_delta,
+ test_settings_grid_shape_delta,
+ test_home_scroll_reveals_cards,
+ test_pagesize_dialog_shape_delta,
+ test_history_toolbar_shape_delta,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/swati4star-images-to-pdf/tests/test_android_text.py b/android/swati4star-images-to-pdf/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..741c630d2f61035ad652b9a41d24bcf0de69e751
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_android_text.py
@@ -0,0 +1,909 @@
+#!/usr/bin/env python3
+"""TEXT lane — CONTENT / OUTPUT text for "PDF Converter" (swati4star.createpdf).
+
+This lane owns EXACT-STRING equality: the app-authored strings a recreation must
+reproduce word-for-word — dynamic status lines a user interaction PRODUCES
+("1 image(s) selected."), app-unique static labels (enhancement-card labels,
+settings labels, the storage path), dialog TITLES an interaction opens, an
+input hint, and one genuinely opaque rendered core (the transient "PDF created!"
+snackbar, which never reaches the view tree -> VLM).
+
+Every string asserted here was OBSERVED live on the running original. The
+discriminating half, wherever possible, is the CHANGE: the string is ABSENT
+before the trigger and PRESENT after — a hardcoded label present at launch would
+pass on a dead shell, so those are anchored to a surface a navigation reaches.
+
+VLM budget for this lane: EXACTLY 2 (both tag="content"): the opaque success
+snackbar, and the Favourites empty-state as rendered.
+"""
+import os
+import sys
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else "/workspace/testgen/eval/eval_results"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Text helpers
+# ══════════════════════════════════════════════════════════════════════════════
+
+def all_text(nodes=None):
+ """All non-empty `text` values on the current surface joined with ' | '."""
+ nodes = ui() if nodes is None else nodes
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text", ""))
+
+
+def has_text(substr, nodes=None):
+ """Case-insensitive substring presence over the surface's text, tolerant of
+ the whitespace a faithful recreation may differ on (collapsed to single
+ spaces on both sides)."""
+ blob = " ".join((all_text(nodes)).split()).lower()
+ want = " ".join(substr.split()).lower()
+ return want in blob
+
+
+def has_all(substrs, nodes=None):
+ nodes = ui() if nodes is None else nodes
+ blob = " ".join(all_text(nodes).split()).lower()
+ return all(" ".join(s.split()).lower() in blob for s in substrs)
+
+
+def mark(suffix=""):
+ """A unique, filesystem-safe PDF base name so a created-file read-back never
+ collides with leftovers and reruns never clash."""
+ return f"kittxt{suffix}{int(time.time() * 1000) % 100000000}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Home entry — the app RESTORES its last fragment after a force-stop and grows a
+# "Recently Used Features" row once features are used, so a naive restart_app()
+# does NOT land on the Home grid. home_ready() kills + relaunches, backs out of
+# any restored fragment / dismisses the first-run storage-permission dialog, then
+# scrolls the grid to the top. (Proven pattern from the sibling lanes.)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def on_home(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ return (find_node(nodes, text="Create new PDF") is not None
+ or find_node(nodes, text="View PDFs") is not None)
+
+
+def _dismiss_permission_if_present():
+ """First-run storage-permission MaterialDialog: DENY keeps us in the app
+ WITHOUT granting (we never seed the permission). Tap it only if present."""
+ nodes = ui()
+ deny = find_node(nodes, text="DENY") or find_node(nodes, text="Deny")
+ if deny is not None and is_safe(deny):
+ tap_node(deny)
+ settle("tap")
+
+
+def home_ready():
+ """Deterministic Home surface. Returns True when the feature grid is showing."""
+ force_stop()
+ settle("key")
+ launch_app()
+ wait_for_foreground()
+ settle("launch")
+ for _ in range(4):
+ if on_home():
+ break
+ _dismiss_permission_if_present()
+ if on_home():
+ break
+ back()
+ settle("launch")
+ for _ in range(4):
+ scroll_up(0.8)
+ settle("tap")
+ return on_home()
+
+
+def clean_home_ready():
+ """Factory-default Home: wipe app data first, so settings labels read their
+ defaults ('30 %' / 'A4' / '11' / 'TIMES_ROMAN' / 'System') deterministically."""
+ clear_data()
+ settle("key")
+ return home_ready()
+
+
+def open_card(rid, label):
+ """Tap a Home feature card by resource-id suffix; fall back to a scroll-to by
+ its visible label if it is off screen. Taps the clickable card container."""
+ n = node_by_id(ui(), rid)
+ if n is None:
+ n = scroll_into_view(label)
+ return tap_node(n) if n is not None else False
+
+
+def _hamburger(nodes=None):
+ """The top-left drawer ImageButton (its content-desc is the quirky app title
+ 'PDF Converter', NOT a feature name). Falls back to the first toolbar
+ ImageButton by x-order."""
+ nodes = ui() if nodes is None else nodes
+ hb = find_node(nodes, content_desc="PDF Converter",
+ class_="android.widget.ImageButton")
+ if hb is not None:
+ return hb
+ ibs = sorted((x for x in nodes if "ImageButton" in x.get("class", "")
+ and "_bounds" in x), key=lambda n: n["_bounds"][0])
+ return ibs[0] if ibs else None
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Depth-backing navigation helpers. The and_enter_*/and_reach_* NAME is what
+# backs a declared depth>=1 (see android_testgen_kit.and_audit_depth). Each
+# confirms the destination surface actually rendered before counting a surface.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_enter_images_to_pdf():
+ """Home -> Images to PDF fragment. Confirmed by the SELECT IMAGES surface."""
+ if not open_card("images_to_pdf", "Images to PDF"):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "addImages") is None:
+ return False
+ and_enter("images_to_pdf")
+ return True
+
+
+def and_enter_text_to_pdf():
+ """Home -> Text To PDF fragment. Confirmed by the SELECT TEXT FILE control."""
+ if not open_card("text_to_pdf", "Text To PDF"):
+ return False
+ settle("launch")
+ if node_by_id(ui(), "selectFile") is None and find_node(
+ ui(), text="SELECT TEXT FILE") is None:
+ return False
+ and_enter("text_to_pdf")
+ return True
+
+
+def and_reach_favourites():
+ """Home -> Favourites (heart icon in the toolbar, content-desc 'Favourites').
+ Jump proven: the 'Favourites' screen title appears while the Home section
+ header 'Create new PDF' disappears."""
+ heart = (node_by_id(ui(), "menu_favourites_item")
+ or find_node(ui(), content_desc="Favourites"))
+ if heart is None:
+ return False
+ before = and_showing()
+ if not tap_node(heart):
+ return False
+ settle("launch")
+ after = and_showing()
+ ok = and_reach(before, after, "Favourites", "Create new PDF")
+ if ok:
+ and_enter("favourites")
+ return ok
+
+
+def and_enter_drawer():
+ """Open the navigation drawer via the hamburger. Confirmed by the 'Home'
+ drawer item appearing."""
+ hb = _hamburger()
+ if hb is not None and tap_node(hb):
+ settle("tap")
+ if find_node(ui(), text="Home") is None:
+ open_drawer() # fall back to an edge swipe
+ settle("tap")
+ if find_node(ui(), text="Home") is None:
+ return False
+ and_enter("drawer")
+ return True
+
+
+def and_enter_settings():
+ """From the open drawer, scroll to and tap 'Settings'. Confirmed by the
+ Settings storage-location card (unique to that fragment) appearing."""
+ target = None
+ for _ in range(8):
+ nodes = ui()
+ target = find_node(nodes, text="Settings")
+ if target is not None:
+ break
+ scrollers = [x for x in nodes
+ if x.get("scrollable") == "true" and "_bounds" in x]
+ if scrollers:
+ x1, y1, x2, y2 = scrollers[0]["_bounds"]
+ cx = (x1 + x2) // 2
+ swipe(cx, int(y1 + (y2 - y1) * 0.72), cx, int(y1 + (y2 - y1) * 0.28))
+ else:
+ scroll_down(0.5)
+ settle("tap")
+ if target is None or not tap_node(target):
+ return False
+ settle("launch")
+ if (node_by_id(ui(), "storagelocation") is None
+ and not has_text("Storage location")):
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_reach_settings():
+ """Home -> drawer -> Settings (depth 2)."""
+ return and_enter_drawer() and and_enter_settings()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Core selection helper: SELECT IMAGES -> Photo Picker -> pick n -> Add(n).
+# The picker is a SEPARATE process (com.google.android.providers.media.module);
+# photo items have content-desc starting "Photo taken on ...". We re-dump after
+# returning before reading tvNoOfImages. Returns the observed tvNoOfImages text.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def select_images(n):
+ """From the Images-to-PDF fragment: pick `n` photos and Add them. Returns the
+ observed tvNoOfImages text (re-dumped) or None on failure."""
+ add = node_by_id(ui(), "addImages")
+ if add is None or not tap_node(add):
+ return None
+ settle("launch")
+ settle("tap")
+ photos = []
+ for _ in range(5):
+ photos = [x for x in ui()
+ if x.get("content-desc", "").lower().startswith("photo taken")]
+ if len(photos) >= n:
+ break
+ settle("tap")
+ if len(photos) < n:
+ # picker empty — try re-pushing the fixtures once, then reopen
+ push_fixtures(force=True)
+ settle("tap")
+ for _ in range(4):
+ photos = [x for x in ui()
+ if x.get("content-desc", "").lower().startswith("photo taken")]
+ if len(photos) >= n:
+ break
+ settle("tap")
+ if len(photos) < n:
+ return None
+ for p in photos[:n]:
+ tap_node(p)
+ settle("tap")
+ addbtn = None
+ for _ in range(4):
+ addbtn = next((x for x in ui()
+ if x.get("text", "").strip().lower().startswith("add (")), None)
+ if addbtn is not None:
+ break
+ settle("tap")
+ if addbtn is None or not tap_node(addbtn):
+ return None
+ settle("launch")
+ settle("tap")
+ tv = node_by_id(ui(), "tvNoOfImages")
+ return tv.get("text") if tv is not None else None
+
+
+def open_enhancement_dialog(label_substr):
+ """From the Images-to-PDF fragment (with an image already selected), tap the
+ enhancement card whose option_name contains `label_substr`. The option_name
+ TextView is not itself clickable but its centre lies inside the clickable card
+ container, so tapping its centre opens the dialog (verified live). Scrolls it
+ into view first. Returns True if the tap landed."""
+ for _ in range(6):
+ nodes = ui()
+ for nd in nodes:
+ if (nd.get("resource-id", "").endswith("option_name")
+ and label_substr.lower() in nd.get("text", "").lower()):
+ if tap_node(nd):
+ settle("tap")
+ settle("tap")
+ return True
+ scrollers = [x for x in nodes
+ if x.get("scrollable") == "true" and "_bounds" in x]
+ if scrollers:
+ x1, y1, x2, y2 = scrollers[0]["_bounds"]
+ cx = (x1 + x2) // 2
+ swipe(cx, int(y1 + (y2 - y1) * 0.72), cx, int(y1 + (y2 - y1) * 0.28))
+ else:
+ scroll_down(0.5)
+ settle("tap")
+ return False
+
+
+def dismiss_dialog():
+ """Close an open value dialog without committing: prefer CANCEL, else BACK."""
+ c = find_node_ci(ui(), "CANCEL")
+ if c is not None and tap_node(c):
+ settle("tap")
+ return
+ back()
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+# ── 1. Home section headers (app-unique static content; the change is app-vs-OS-
+# home). depth 0, value. ──────────────────────────────────────────────────
+@and_test(expects=("text_home_section_headers",))
+def test_home_section_headers():
+ name = "text_home_section_headers"
+ absent = not has_text("Create new PDF") # not on the launcher / before app
+ if not home_ready():
+ record(name, False,
+ "setup_failed: could not reach the Home grid",
+ depth=0, jump_kind="value",
+ expect="headers 'Create new PDF' / 'View PDFs' / 'Enhance Created PDFs'")
+ return
+ present = has_all(["Create new PDF", "View PDFs", "Enhance Created PDFs"])
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Home section headers not all present "
+ f"(showing: {all_text()[:160]})",
+ depth=0, jump_kind="value",
+ expect="'Create new PDF' | 'View PDFs' | 'Enhance Created PDFs'")
+
+
+# ── 2. Images-to-PDF enhancement-card labels (renders on entering the fragment,
+# before any image is selected). depth 1, value. ───────────────────────────
+@and_test(expects=("text_img2pdf_card_labels",))
+def test_img2pdf_card_labels():
+ name = "text_img2pdf_card_labels"
+ if not home_ready():
+ record(name, False, "setup_failed: could not reach Home",
+ depth=0, jump_kind="value", expect="Images-to-PDF card labels")
+ return
+ absent = not has_text("Image compression : 30 %") # not on Home
+ if not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not enter the Images to PDF fragment",
+ depth=1, jump_kind="value", expect="Images-to-PDF card labels")
+ return
+ # Some cards are below the fold; pull each into view before reading.
+ for lbl in ("Image compression : 30 %", "Border width : 0"):
+ if not has_text(lbl):
+ scroll_into_view(lbl)
+ present = (has_text("Image compression : 30 %")
+ and has_text("Set Page Size")
+ and has_text("Set Image Scale Type")
+ and has_text("Border width : 0"))
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: enhancement-card labels not all present "
+ f"(showing: {all_text()[:200]})",
+ depth=1, jump_kind="value",
+ expect="'Image compression : 30 %' | 'Set Page Size' | "
+ "'Set Image Scale Type' | 'Border width : 0'")
+
+
+# ── 3. CORE: dynamic status "1 image(s) selected." PRODUCED by selecting one
+# image. tvNoOfImages is GONE before selection -> the discriminating change
+# is ABSENT then PRESENT. depth 1, value. ───────────────────────────────────
+@and_test(expects=("text_one_image_selected_status",))
+def test_one_image_selected_status():
+ name = "text_one_image_selected_status"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=1, jump_kind="value", expect="'1 image(s) selected.'")
+ return
+ absent = node_by_id(ui(), "tvNoOfImages") is None # GONE before selection
+ status = select_images(1)
+ if status is None:
+ record(name, False,
+ "setup_failed: Photo Picker had no images to select (fixtures)",
+ depth=1, jump_kind="value", expect="'1 image(s) selected.'")
+ return
+ ok = absent and (" ".join(status.split()).lower() == "1 image(s) selected.")
+ record(name, ok,
+ "" if ok else "behavior_wrong: tvNoOfImages did not read "
+ f"'1 image(s) selected.' (got {status!r})",
+ depth=1, jump_kind="value",
+ expect="tvNoOfImages == '1 image(s) selected.'")
+
+
+# ── 4. Dynamic status plural variant: "2 image(s) selected." after selecting 2.
+# depth 1, value. ────────────────────────────────────────────────────────
+@and_test(expects=("text_two_images_selected_status",))
+def test_two_images_selected_status():
+ name = "text_two_images_selected_status"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=1, jump_kind="value", expect="'2 image(s) selected.'")
+ return
+ absent = node_by_id(ui(), "tvNoOfImages") is None
+ status = select_images(2)
+ if status is None:
+ record(name, False,
+ "setup_failed: Photo Picker lacked 2 images to select (fixtures)",
+ depth=1, jump_kind="value", expect="'2 image(s) selected.'")
+ return
+ ok = absent and (" ".join(status.split()).lower() == "2 image(s) selected.")
+ record(name, ok,
+ "" if ok else "behavior_wrong: tvNoOfImages did not read "
+ f"'2 image(s) selected.' (got {status!r})",
+ depth=1, jump_kind="value",
+ expect="tvNoOfImages == '2 image(s) selected.'")
+
+
+# ── 5. Dialog TITLE produced by opening the compression card (needs an image).
+# depth 2, value. ────────────────────────────────────────────────────────
+@and_test(expects=("text_dialog_compression_title",))
+def test_dialog_compression_title():
+ name = "text_dialog_compression_title"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Change image compression value'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (dialog precondition)",
+ depth=2, jump_kind="value", expect="'Change image compression value'")
+ return
+ absent = not has_text("Change image compression value") # dialog not yet open
+ and_enter("compression_dialog")
+ if not open_enhancement_dialog("Image compression"):
+ record(name, False,
+ "setup_failed: could not open the Image compression dialog",
+ depth=2, jump_kind="value", expect="'Change image compression value'")
+ return
+ present = has_text("Change image compression value")
+ also = has_text("compression of image") # dialog body label
+ ok = absent and present and also
+ record(name, ok,
+ "" if ok else "behavior_wrong: compression dialog title/label wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Change image compression value' + label "
+ "'Enter %% compression of image :'")
+ dismiss_dialog()
+
+
+# ── 6. Dialog TITLE produced by opening the border card. depth 2, value. ───────
+@and_test(expects=("text_dialog_border_title",))
+def test_dialog_border_title():
+ name = "text_dialog_border_title"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Add Image Border'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (dialog precondition)",
+ depth=2, jump_kind="value", expect="'Add Image Border'")
+ return
+ absent = not has_text("Add Image Border")
+ and_enter("border_dialog")
+ if not open_enhancement_dialog("Border width"):
+ record(name, False,
+ "setup_failed: could not open the Border width dialog",
+ depth=2, jump_kind="value", expect="'Add Image Border'")
+ return
+ present = has_text("Add Image Border")
+ also = has_text("Enter border width units")
+ ok = absent and present and also
+ record(name, ok,
+ "" if ok else "behavior_wrong: border dialog title/label wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Add Image Border' + label 'Enter border width units'")
+ dismiss_dialog()
+
+
+# ── 7. Dialog TITLE + pre-selected option produced by the Set Page Size card.
+# depth 2, value. ────────────────────────────────────────────────────────
+@and_test(expects=("text_dialog_pagesize_title",))
+def test_dialog_pagesize_title():
+ name = "text_dialog_pagesize_title"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Set Page Size' dialog 'DEFAULT ( A4 )'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (dialog precondition)",
+ depth=2, jump_kind="value", expect="'DEFAULT ( A4 )'")
+ return
+ # 'Set Page Size' is also the card label, so the discriminating content is the
+ # dialog's radio option 'DEFAULT ( A4 )', absent until the dialog is open.
+ absent = not has_text("DEFAULT ( A4 )")
+ and_enter("pagesize_dialog")
+ if not open_enhancement_dialog("Set Page Size"):
+ record(name, False,
+ "setup_failed: could not open the Set Page Size dialog",
+ depth=2, jump_kind="value", expect="'DEFAULT ( A4 )'")
+ return
+ present = has_text("Set Page Size") and has_text("DEFAULT ( A4 )")
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Set Page Size dialog content wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Set Page Size' + option 'DEFAULT ( A4 )'")
+ dismiss_dialog()
+
+
+# ── 8. Dialog TITLE + option produced by the Set Image Scale Type card.
+# depth 2, value. ────────────────────────────────────────────────────────
+@and_test(expects=("text_dialog_scaletype_title",))
+def test_dialog_scaletype_title():
+ name = "text_dialog_scaletype_title"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Maintain aspect ratio of images'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (dialog precondition)",
+ depth=2, jump_kind="value", expect="'Maintain aspect ratio of images'")
+ return
+ absent = not has_text("Maintain aspect ratio of images")
+ and_enter("scaletype_dialog")
+ if not open_enhancement_dialog("Set Image Scale Type"):
+ record(name, False,
+ "setup_failed: could not open the Set Image Scale Type dialog",
+ depth=2, jump_kind="value", expect="'Maintain aspect ratio of images'")
+ return
+ present = (has_text("Set Image Scale Type")
+ and has_text("Maintain aspect ratio of images")
+ and has_text("Stretch image to fit on page"))
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Set Image Scale Type dialog content wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Set Image Scale Type' + options 'Maintain aspect ratio "
+ "of images' / 'Stretch image to fit on page'")
+ dismiss_dialog()
+
+
+# ── 9. Dialog TITLE + hint produced by the Password Protect PDF card.
+# depth 2, value. ────────────────────────────────────────────────────────
+@and_test(expects=("text_dialog_password_title",))
+def test_dialog_password_title():
+ name = "text_dialog_password_title"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Set Password' dialog hint 'pass@123'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (dialog precondition)",
+ depth=2, jump_kind="value", expect="'Set Password' hint 'pass@123'")
+ return
+ absent = not has_text("pass@123")
+ and_enter("password_dialog")
+ if not open_enhancement_dialog("Password Protect PDF"):
+ record(name, False,
+ "setup_failed: could not open the Set Password dialog",
+ depth=2, jump_kind="value", expect="'Set Password' hint 'pass@123'")
+ return
+ present = has_text("Set Password") and has_text("pass@123")
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Set Password dialog title/hint wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Set Password' + EditText hint 'pass@123'")
+ dismiss_dialog()
+
+
+# ── 10. "Creating PDF" dialog produced by tapping CREATE PDF (after selecting an
+# image). Title + hint 'Enter file name'. The prefilled auto-name is a
+# timestamp so it is NOT asserted. Cancel (do not create). depth 2, value. ─
+@and_test(expects=("text_creating_pdf_dialog",))
+def test_creating_pdf_dialog():
+ name = "text_creating_pdf_dialog"
+ if not home_ready() or not and_enter_images_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Images to PDF fragment",
+ depth=2, jump_kind="value", expect="'Creating PDF' + hint 'Enter file name'")
+ return
+ if select_images(1) is None:
+ record(name, False,
+ "setup_failed: could not select an image (create precondition)",
+ depth=2, jump_kind="value", expect="'Creating PDF' + hint 'Enter file name'")
+ return
+ absent = not has_text("Creating PDF") # dialog not yet open
+ pc = node_by_id(ui(), "pdfCreate")
+ if pc is None or pc.get("enabled") != "true" or not tap_node(pc):
+ record(name, False,
+ "setup_failed: CREATE PDF not enabled/tappable after selecting image",
+ depth=2, jump_kind="value", expect="'Creating PDF' + hint 'Enter file name'")
+ return
+ and_enter("creating_pdf_dialog")
+ settle("tap")
+ settle("tap")
+ present = has_text("Creating PDF") and has_text("Enter file name")
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Creating PDF dialog title/hint wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="title 'Creating PDF' + EditText hint 'Enter file name'")
+ dismiss_dialog() # CANCEL — creation itself belongs to the interaction lane
+
+
+# ── 11. Success snackbar "PDF created!" — VLM. This text is TRANSIENT and never
+# reaches the view tree (verified: no snackbar node in any dump), so it is a
+# genuinely OPAQUE rendered core -> the one legit VLM-content case here. We
+# complete one create with a unique marker, screenshot while the banner is up.
+# depth 2, content. ─────────────────────────────────────────────────────
+@and_test(expects=("text_create_pdf_snackbar_vlm",))
+def test_create_pdf_snackbar_vlm():
+ name = "text_create_pdf_snackbar"
+ if not home_ready() or not and_enter_images_to_pdf():
+ vlm_assert(name,
+ "Is there a dark banner across the bottom of the screen "
+ "showing the message 'PDF created!'?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="content")
+ return
+ if select_images(1) is None:
+ vlm_assert(name,
+ "Is there a dark banner across the bottom of the screen "
+ "showing the message 'PDF created!'?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="content")
+ return
+ pc = node_by_id(ui(), "pdfCreate")
+ if pc is None or pc.get("enabled") != "true" or not tap_node(pc):
+ vlm_assert(name,
+ "Is there a dark banner across the bottom of the screen "
+ "showing the message 'PDF created!'?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="content")
+ return
+ and_enter("creating_pdf_dialog")
+ settle("tap")
+ settle("tap")
+ ets = find_by_class(ui(), "EditText")
+ if ets:
+ et = ets[0]
+ if tap_node(et):
+ settle("keyboard")
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(40):
+ adb_shell("input", "keyevent", "67") # KEYCODE_DEL
+ settle("text")
+ fresh = find_by_class(ui(), "EditText")
+ if fresh:
+ type_text(fresh[0], mark(), verify_focus=False)
+ settle("text")
+ # Tap OK against a FRESH dump (coords shifted once the keyboard opened), then
+ # screenshot immediately — the snackbar shows for ~2.75s but is not in the tree.
+ ok = find_node_ci(ui(), "OK")
+ if ok is not None and "_center" in ok:
+ x, y = ok["_center"]
+ adb_shell("input", "tap", x, y)
+ time.sleep(1.0)
+ vlm_assert(name,
+ "Is there a dark banner across the bottom of the screen showing "
+ "the message 'PDF created!'?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="content")
+
+
+# ── 12. Text-to-PDF font card labels (INITIAL, deterministic after clear_data:
+# 'Font Size (Default : 11)' / 'Font Family (Default : TIMES_ROMAN)').
+# depth 1, value. ──────────────────────────────────────────────────────
+@and_test(expects=("text_text2pdf_font_labels",))
+def test_text2pdf_font_labels():
+ name = "text_text2pdf_font_labels"
+ if not clean_home_ready():
+ record(name, False, "setup_failed: could not reach a factory-clean Home",
+ depth=0, jump_kind="value", expect="Text-to-PDF font labels")
+ return
+ absent = not has_text("Font Size (Default : 11)") # not on Home
+ if not and_enter_text_to_pdf():
+ record(name, False,
+ "setup_failed: could not enter the Text To PDF fragment",
+ depth=1, jump_kind="value", expect="Text-to-PDF font labels")
+ return
+ for lbl in ("Font Size (Default : 11)", "Font Family (Default : TIMES_ROMAN)"):
+ if not has_text(lbl):
+ scroll_into_view(lbl)
+ present = (has_text("Font Size (Default : 11)")
+ and has_text("Font Family (Default : TIMES_ROMAN)"))
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Text-to-PDF font labels wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=1, jump_kind="value",
+ expect="'Font Size (Default : 11)' | 'Font Family (Default : TIMES_ROMAN)'")
+
+
+# ── 13. Font Size dialog content produced by the card (label 'Enter font size' +
+# hint 'Example : 10'; no file needed). depth 2, value. ────────────────────
+@and_test(expects=("text_text2pdf_fontsize_dialog",))
+def test_text2pdf_fontsize_dialog():
+ name = "text_text2pdf_fontsize_dialog"
+ if not clean_home_ready() or not and_enter_text_to_pdf():
+ record(name, False,
+ "setup_failed: could not reach the Text To PDF fragment",
+ depth=2, jump_kind="value", expect="'Enter font size' + hint 'Example : 10'")
+ return
+ absent = not has_text("Example : 10") # dialog not yet open
+ fs = find_node(ui(), text="Font Size (Default : 11)") or scroll_into_view(
+ "Font Size (Default : 11)")
+ if fs is None or not tap_node(fs):
+ record(name, False,
+ "setup_failed: could not open the Font Size dialog",
+ depth=2, jump_kind="value", expect="'Enter font size' + hint 'Example : 10'")
+ return
+ and_enter("fontsize_dialog")
+ settle("tap")
+ settle("tap")
+ present = has_text("Enter font size") and has_text("Example : 10")
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Font Size dialog label/hint wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=2, jump_kind="value",
+ expect="label 'Enter font size' + EditText hint 'Example : 10'")
+ dismiss_dialog()
+
+
+# ── 14. Favourites empty-state message (rule) — the exact wording rendered on the
+# Favourites screen reached via the heart icon. depth 1, value. ────────────
+@and_test(expects=("text_favourites_empty_state",))
+def test_favourites_empty_state():
+ name = "text_favourites_empty_state"
+ if not home_ready():
+ record(name, False, "setup_failed: could not reach Home",
+ depth=0, jump_kind="value",
+ expect="'Select + icon to add your favourite features!'")
+ return
+ absent = not has_text("Select + icon to add your favourite features") # not on Home
+ if not and_reach_favourites():
+ record(name, False,
+ "setup_failed: could not reach the Favourites screen (heart icon)",
+ depth=1, jump_kind="value",
+ expect="'Select + icon to add your favourite features!'")
+ return
+ present = (has_text("Favourites")
+ and has_text("Select + icon to add your favourite features"))
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Favourites empty-state wording wrong "
+ f"(showing: {all_text()[:200]})",
+ depth=1, jump_kind="value",
+ expect="title 'Favourites' + 'Select + icon to add your favourite features!'")
+
+
+# ── 15. Favourites empty-state as RENDERED — VLM (2nd of 2). The message is in the
+# dump (rule test #14 owns that), but the empty-state as a rendered surface
+# is a reasonable content check; asked as an exact-wording visual question.
+# depth 1, content. ──────────────────────────────────────────────────────
+@and_test(expects=("text_favourites_empty_state_vlm",))
+def test_favourites_empty_state_vlm():
+ name = "text_favourites_empty_state"
+ reached = home_ready() and and_reach_favourites()
+ if not reached:
+ vlm_assert(name,
+ "Does this screen show the message 'Select + icon to add your "
+ "favourite features!'?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="content")
+ return
+ vlm_assert(name,
+ "Does this screen show the message 'Select + icon to add your "
+ "favourite features!'?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="content")
+
+
+# ── 16. Settings storage-location path + card label (factory-clean). depth 2,
+# value (drawer -> Settings). ─────────────────────────────────────────────
+@and_test(expects=("text_settings_storage_path",))
+def test_settings_storage_path():
+ name = "text_settings_storage_path"
+ if not clean_home_ready():
+ record(name, False, "setup_failed: could not reach a factory-clean Home",
+ depth=0, jump_kind="value", expect="'/storage/emulated/0/PDF Converter/'")
+ return
+ absent = not has_text("/storage/emulated/0/PDF Converter/") # not on Home
+ if not and_reach_settings():
+ record(name, False,
+ "setup_failed: could not reach Settings via the drawer",
+ depth=2, jump_kind="value", expect="'/storage/emulated/0/PDF Converter/'")
+ return
+ present = (has_text("Storage location(non-changeable)")
+ and has_text("/storage/emulated/0/PDF Converter/"))
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Settings storage path/label wrong "
+ f"(showing: {all_text()[:220]})",
+ depth=2, jump_kind="value",
+ expect="'Storage location(non-changeable)' + "
+ "'/storage/emulated/0/PDF Converter/'")
+
+
+# ── 17. Settings default-value labels (factory-clean -> deterministic defaults).
+# depth 2, value. ──────────────────────────────────────────────────────
+@and_test(expects=("text_settings_default_labels",))
+def test_settings_default_labels():
+ name = "text_settings_default_labels"
+ if not clean_home_ready():
+ record(name, False, "setup_failed: could not reach a factory-clean Home",
+ depth=0, jump_kind="value", expect="Settings default-value labels")
+ return
+ absent = not has_text("Image Compression default value : 30 %") # not on Home
+ if not and_reach_settings():
+ record(name, False,
+ "setup_failed: could not reach Settings via the drawer",
+ depth=2, jump_kind="value", expect="Settings default-value labels")
+ return
+ for lbl in ("Font family default value : TIMES_ROMAN",
+ "Theme default value : System"):
+ if not has_text(lbl):
+ scroll_into_view(lbl)
+ present = has_all([
+ "Image Compression default value : 30 %",
+ "Page size default value : A4",
+ "Font size default value : 11",
+ "Font family default value : TIMES_ROMAN",
+ "Theme default value : System",
+ ])
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Settings default-value labels wrong "
+ f"(showing: {all_text()[:260]})",
+ depth=2, jump_kind="value",
+ expect="'Image Compression default value : 30 %' | 'Page size default "
+ "value : A4' | 'Font size default value : 11' | 'Font family "
+ "default value : TIMES_ROMAN' | 'Theme default value : System'")
+
+
+# ── 18. Settings intro line (app-unique static content on the Settings surface).
+# depth 2, value. ──────────────────────────────────────────────────────
+@and_test(expects=("text_settings_intro_line",))
+def test_settings_intro_line():
+ name = "text_settings_intro_line"
+ if not clean_home_ready():
+ record(name, False, "setup_failed: could not reach a factory-clean Home",
+ depth=0, jump_kind="value",
+ expect="'You can modify the default value for various settings here.'")
+ return
+ absent = not has_text("You can modify the default value for various settings here")
+ if not and_reach_settings():
+ record(name, False,
+ "setup_failed: could not reach Settings via the drawer",
+ depth=2, jump_kind="value",
+ expect="'You can modify the default value for various settings here.'")
+ return
+ present = has_text("You can modify the default value for various settings here")
+ ok = absent and present
+ record(name, ok,
+ "" if ok else "behavior_wrong: Settings intro line wrong "
+ f"(showing: {all_text()[:220]})",
+ depth=2, jump_kind="value",
+ expect="'You can modify the default value for various settings here.'")
+
+
+TESTS = [
+ test_home_section_headers,
+ test_img2pdf_card_labels,
+ test_one_image_selected_status,
+ test_two_images_selected_status,
+ test_dialog_compression_title,
+ test_dialog_border_title,
+ test_dialog_pagesize_title,
+ test_dialog_scaletype_title,
+ test_dialog_password_title,
+ test_creating_pdf_dialog,
+ test_create_pdf_snackbar_vlm,
+ test_text2pdf_font_labels,
+ test_text2pdf_fontsize_dialog,
+ test_favourites_empty_state,
+ test_favourites_empty_state_vlm,
+ test_settings_storage_path,
+ test_settings_default_labels,
+ test_settings_intro_line,
+]
+
+
+if __name__ == "__main__":
+ if not device_online():
+ print("device offline — aborting", file=sys.stderr)
+ sys.exit(2)
+ run_suite(TESTS, "text")
diff --git a/android/swati4star-images-to-pdf/tests/test_manifest.json b/android/swati4star-images-to-pdf/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..054d141f227548230c148d96db621d40ade18afa
--- /dev/null
+++ b/android/swati4star-images-to-pdf/tests/test_manifest.json
@@ -0,0 +1,710 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "images-to-pdf",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 101,
+ "manifest_sha": "3787096e41cf",
+ "tests": [
+ {
+ "name": "computation::computation_img_border_25",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_border_5",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_border_invalid_rejected",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_compression_50",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_compression_50_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_compression_80",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_compression_invalid_rejected",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_img_preview_color_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_settings_compression_45",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_settings_compression_invalid_rejected",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_settings_font_size_18",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_text_font_size_20",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_text_font_size_7",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_text_font_size_invalid_rejected",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_pdf_enabled_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_pdf_open_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_pdf_persists_disk",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_survives_process_death",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_created_pdf_in_history",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_created_pdf_in_viewfiles",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_created_pdf_in_viewfiles_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_pdf_actions",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_pdf_actions_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_image_count",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_image_count_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_pagesize_then_create_sequence",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_multiselect_badge",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_multiselect_badge_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_single_check",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_single_check_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_favourites_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_fragment_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_settings_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_2hop",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deep_picker",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_drawer_to_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_drawer_view_files",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_drawer",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_add_password",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_add_watermark",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_excel_to_pdf",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_favourites",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_history",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_images_to_pdf",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_merge_pdf",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_qr_barcode",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_rotate_pages",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_split_pdf",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_text_to_pdf",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_view_files",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_create_pdf_disabled",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_create_pdf_disabled_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_create_pdf_enabled_after_image",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_create_pdf_enabled_after_image_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_drawer_home_selected",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_drawer_home_selected_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_fontfamily_radio_helvetica",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_fontfamily_radio_helvetica_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_fontsize_default_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pagesize_default_dialog_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pagesize_default_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pagesize_radio_letter",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_pagesize_radio_letter_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_password_show_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_scaletype_radio_stretch",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_scaletype_radio_stretch_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_set_as_default_checkbox",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_set_as_default_checkbox_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_white_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_viewfiles_row_checkbox",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_viewfiles_row_checkbox_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_history_toolbar_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_grid_cards",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_scroll_reveals",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_to_fragment_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_toolbar_present",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_pagesize_dialog_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_grid_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_create_pdf_snackbar_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_creating_pdf_dialog",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dialog_border_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dialog_compression_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dialog_pagesize_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dialog_password_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dialog_scaletype_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_favourites_empty_state",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_favourites_empty_state_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_section_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_img2pdf_card_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_one_image_selected_status",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_default_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_intro_line",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_storage_path",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_text2pdf_font_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_text2pdf_fontsize_dialog",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_two_images_selected_status",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [
+ {
+ "name": "navigation::nav_drawer_to_settings_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "navigation::nav_open_drawer_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "navigation::nav_reach_favourites_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "navigation::nav_reach_history_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "navigation::nav_reach_images_to_pdf_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "navigation::nav_reach_view_files_vlm",
+ "module": "navigation",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "structure::structure_drawer_shape_vlm",
+ "module": "structure",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "structure::structure_home_grid_vlm",
+ "module": "structure",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "structure::structure_pagesize_dialog_vlm",
+ "module": "structure",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "structure::structure_settings_grid_vlm",
+ "module": "structure",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "structure::structure_toolbar_layout_vlm",
+ "module": "structure",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ }
+ ],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_img_compression_50_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "computation::computation_img_preview_color_vlm",
+ "module": "computation",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_create_pdf_enabled_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_create_pdf_open_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_created_pdf_in_viewfiles_vlm",
+ "module": "interaction",
+ "tag": "layout"
+ },
+ {
+ "name": "interaction::interaction_multi_image_count_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_single_check_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_viewfiles_multiselect_badge_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_longpress_pdf_actions_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "states::states_create_pdf_disabled_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_create_pdf_enabled_after_image_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_pagesize_radio_letter_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_scaletype_radio_stretch_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_fontfamily_radio_helvetica_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_set_as_default_checkbox_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_viewfiles_row_checkbox_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_white_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_pagesize_default_dialog_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_drawer_home_selected_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "text::text_create_pdf_snackbar_vlm",
+ "module": "text",
+ "tag": "content"
+ },
+ {
+ "name": "text::text_favourites_empty_state_vlm",
+ "module": "text",
+ "tag": "content"
+ }
+ ],
+ "vlm_total": 22,
+ "n_vlm_unverified": 11,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/swati4star-images-to-pdf/vlm_assertions.json b/android/swati4star-images-to-pdf/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..285f8a79057064f833d2d0d9bc126c367e24c170
--- /dev/null
+++ b/android/swati4star-images-to-pdf/vlm_assertions.json
@@ -0,0 +1,693 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/swati4star-images-to-pdf",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 33,
+ "with_verdict": 33,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 33,
+ "unbacked_records": 11,
+ "unbacked_sample": [
+ "nav_reach_images_to_pdf_vlm",
+ "nav_reach_view_files_vlm",
+ "nav_reach_history_vlm",
+ "nav_reach_favourites_vlm",
+ "nav_open_drawer_vlm",
+ "nav_drawer_to_settings_vlm",
+ "structure_home_grid_vlm",
+ "structure_drawer_shape_vlm"
+ ]
+ },
+ "assertions": [
+ {
+ "id": "interaction_create_pdf_enabled_vlm",
+ "screenshot": "interaction_create_pdf_enabled_vlm.png",
+ "assertion": "Is there a large solid ORANGE (not greyed-out) 'CREATE PDF' button visible below the 'SELECT IMAGES' button?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_create_pdf_enabled",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_create_pdf_open_vlm",
+ "screenshot": "interaction_create_pdf_open_vlm.png",
+ "assertion": "Is there a solid ORANGE button labelled 'OPEN PDF' visible near the top of the screen (replacing the earlier CREATE PDF button)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_create_pdf_open",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_created_pdf_in_viewfiles_vlm",
+ "screenshot": "interaction_created_pdf_in_viewfiles_vlm.png",
+ "assertion": "Does the list show one or more file rows, each laid out as a checkbox on the left, a '.pdf' file name in the middle, and a size ('MB') plus a date on the right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_created_pdf_in_viewfiles",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_multi_image_count_vlm",
+ "screenshot": "interaction_multi_image_count_vlm.png",
+ "assertion": "Is there a status line reading 'image(s) selected.' positioned at the very BOTTOM of the screen, below the enhancement option cards?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "interaction_multi_image_count",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_viewfiles_single_check_vlm",
+ "screenshot": "interaction_viewfiles_single_check_vlm.png",
+ "assertion": "Look at the checkbox on the LEFT of the first file row. Is it a FILLED solid orange square with a white check mark (i.e. checked), rather than an empty/outlined box?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_viewfiles_single_check",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_viewfiles_multiselect_badge_vlm",
+ "screenshot": "interaction_viewfiles_multiselect_badge_vlm.png",
+ "assertion": "Is there a bold number '2' displayed in the TOP toolbar area (to the right of the hamburger menu icon)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "interaction_viewfiles_multiselect_badge",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_longpress_pdf_actions_vlm",
+ "screenshot": "interaction_longpress_pdf_actions_vlm.png",
+ "assertion": "Is a pop-up menu titled 'PDF Actions' shown, listing several file actions such as 'Open File', 'Rename File' and 'Share File'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_longpress_pdf_actions",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_img_compression_50_vlm",
+ "screenshot": "computation_img_compression_50_vlm.png",
+ "assertion": "In this dialog, is a percent sign '%' rendered immediately to the RIGHT of the number input field that contains '50'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "computation_img_compression_50",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_img_preview_color_vlm",
+ "screenshot": "computation_img_preview_color_vlm.png",
+ "assertion": "Is the large image preview in the centre of the screen a solid RED rectangle?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "computation_img_preview_color",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_create_pdf_disabled_vlm",
+ "screenshot": "states_create_pdf_disabled_vlm.png",
+ "assertion": "The button labelled 'CREATE PDF' below the orange 'SELECT IMAGES' button — is it rendered in a muted GREY (disabled) fill rather than a saturated orange?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_create_pdf_disabled",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_create_pdf_enabled_after_image_vlm",
+ "screenshot": "states_create_pdf_enabled_after_image_vlm.png",
+ "assertion": "The button labelled 'CREATE PDF' — is it now rendered in a saturated ORANGE (enabled) fill, the same orange as the 'SELECT IMAGES' button above it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_create_pdf_enabled_after_image",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_pagesize_radio_letter_vlm",
+ "screenshot": "states_pagesize_radio_letter_vlm.png",
+ "assertion": "In this 'Set Page Size' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other options are empty grey circles?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_pagesize_radio_letter",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_scaletype_radio_stretch_vlm",
+ "screenshot": "states_scaletype_radio_stretch_vlm.png",
+ "assertion": "In this 'Set Image Scale Type' radio dialog, is exactly one radio button filled with a solid ORANGE dot while the other is an empty grey circle?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_scaletype_radio_stretch",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_fontfamily_radio_helvetica_vlm",
+ "screenshot": "states_fontfamily_radio_helvetica_vlm.png",
+ "assertion": "In this 'Font Family' radio dialog listing COURIER, HELVETICA, TIMES_ROMAN, SYMBOL, etc, is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_fontfamily_radio_helvetica",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_set_as_default_checkbox_vlm",
+ "screenshot": "states_set_as_default_checkbox_vlm.png",
+ "assertion": "Is the checkbox next to the label 'Set as default' a FILLED square with a check mark, rather than an empty outlined square?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_set_as_default_checkbox",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_viewfiles_row_checkbox_vlm",
+ "screenshot": "states_viewfiles_row_checkbox_vlm.png",
+ "assertion": "Is there a file row whose leading checkbox is a FILLED ORANGE square with a white check mark (a selected row), and a '1' shown in the top toolbar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_viewfiles_row_checkbox",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_dark_vlm",
+ "screenshot": "states_theme_dark_vlm.png",
+ "assertion": "Is the app background a dark / near-black color with light (white/grey) text, rather than a light/white background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_dark",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_white_vlm",
+ "screenshot": "states_theme_white_vlm.png",
+ "assertion": "Is the app background a bright WHITE / light color (not dark), with the top toolbar in orange?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_white",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_pagesize_default_dialog_vlm",
+ "screenshot": "states_pagesize_default_dialog_vlm.png",
+ "assertion": "In this page-size radio dialog (options DEFAULT ( A4 ), Fit size, LETTER, LEGAL, ...), is exactly one radio button filled with a solid ORANGE dot while the others are empty grey circles?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_pagesize_default_dialog",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_drawer_home_selected_vlm",
+ "screenshot": "states_drawer_home_selected_vlm.png",
+ "assertion": "In this open navigation drawer, is the 'Home' item highlighted with a light ORANGE/pink pill-shaped background and orange text and icon, while the other items (Create PDF, Text To PDF, ...) have a plain white background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_drawer_home_selected",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_create_pdf_snackbar_vlm",
+ "screenshot": "text_create_pdf_snackbar_vlm.png",
+ "assertion": "Is there a dark banner across the bottom of the screen showing the message 'PDF created!'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "text_create_pdf_snackbar",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_favourites_empty_state_vlm",
+ "screenshot": "text_favourites_empty_state_vlm.png",
+ "assertion": "Does this screen show the message 'Select + icon to add your favourite features!'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "text_favourites_empty_state",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_images_to_pdf_vlm",
+ "screenshot": "nav_reach_images_to_pdf_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_reach_images_to_pdf",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_view_files_vlm",
+ "screenshot": "nav_reach_view_files_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_reach_view_files",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_history_vlm",
+ "screenshot": "nav_reach_history_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_reach_history",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_favourites_vlm",
+ "screenshot": "nav_reach_favourites_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_reach_favourites",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_open_drawer_vlm",
+ "screenshot": "nav_open_drawer_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_open_drawer",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_drawer_to_settings_vlm",
+ "screenshot": "nav_drawer_to_settings_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "nav_drawer_to_settings",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_home_grid_vlm",
+ "screenshot": "structure_home_grid_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "structure_home_grid",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_drawer_shape_vlm",
+ "screenshot": "structure_drawer_shape_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "structure_drawer_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_settings_grid_vlm",
+ "screenshot": "structure_settings_grid_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "structure_settings_grid",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_pagesize_dialog_vlm",
+ "screenshot": "structure_pagesize_dialog_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "structure_pagesize_dialog",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_toolbar_layout_vlm",
+ "screenshot": "structure_toolbar_layout_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "structure_toolbar_layout",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/LICENSE.txt b/android/teamamaze-amazefilemanager/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..20d40b6bceca3a6c0237d7455ebf1820aeff3680
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/LICENSE.txt
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/instance.json b/android/teamamaze-amazefilemanager/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..b58886e79e987a5a65e2bf7eb7205023934bc55e
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/teamamaze-amazefilemanager",
+ "platform": "android",
+ "repo": "https://github.com/TeamAmaze/AmazeFileManager",
+ "commit": "e28d3751a5003aa2299cb2222a998d0ecd3cf5c7",
+ "patches": [],
+ "package": "com.amaze.filemanager.debug",
+ "license": null
+}
diff --git a/android/teamamaze-amazefilemanager/reference/launch.sh b/android/teamamaze-amazefilemanager/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/teamamaze-amazefilemanager/tests/android_computation_eval.json b/android/teamamaze-amazefilemanager/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..94b23b8548d3ae4a545beca5215549a2fd789dbb
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_computation_eval.json
@@ -0,0 +1,188 @@
+{
+ "module": "computation",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 3,
+ "passed": 3,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.2143,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 17,
+ "depth_ge2": 14,
+ "value": 17,
+ "vlm_fine": 3
+ },
+ "results": [
+ {
+ "test": "computation_count_probe",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "pathname == '0 folders and 3 files'"
+ },
+ {
+ "test": "computation_count_probe_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a circular or segmented storage-usage graphic (a ring/pie chart) rendered inside this Properties dialog?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is a circular or segmented storage-usage graphic (a ring/pie chart) rendered inside this Properties dialog?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_count_download",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "pathname == '1 folders and 0 files'"
+ },
+ {
+ "test": "computation_count_after_create_folder",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'1 folders and 3 files' (folders +1)"
+ },
+ {
+ "test": "computation_count_after_create_file",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'0 folders and 4 files' (files +1)"
+ },
+ {
+ "test": "computation_count_delete_restores",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "pathname recomputes to '0 folders and 3 files'"
+ },
+ {
+ "test": "computation_props_alpha_name",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Name == 'alpha.txt'"
+ },
+ {
+ "test": "computation_props_alpha_location",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Location == '/storage/emulated/0/Download/amaze_probe'"
+ },
+ {
+ "test": "computation_props_alpha_size",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Size is a non-empty byte size (contains 'B')"
+ },
+ {
+ "test": "computation_props_folder_name",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Name == 'amaze_probe'"
+ },
+ {
+ "test": "computation_props_folder_items",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Size starts '3 items' (3 children)"
+ },
+ {
+ "test": "computation_props_folder_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a circular or ring-shaped storage-usage chart rendered inside this Properties dialog?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is a circular or ring-shaped storage-usage chart rendered inside this Properties dialog?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_sort_name_asc_first",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "first row == 'alpha.txt'"
+ },
+ {
+ "test": "computation_sort_name_desc_first",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "first row == 'gamma.txt'"
+ },
+ {
+ "test": "computation_sort_order_flips",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "asc first 'alpha.txt' flips to desc first 'gamma.txt'"
+ },
+ {
+ "test": "computation_storage_props_items",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Size contains 'items' (volume child count)"
+ },
+ {
+ "test": "computation_storage_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a circular/ring storage-usage chart graphic rendered in this dialog showing how full the storage is?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is a circular/ring storage-usage chart graphic rendered in this dialog showing how full the storage is?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/android_interaction_eval.json b/android/teamamaze-amazefilemanager/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..ec546777a438943720a6bba5dc0c4235ed966fc5
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_interaction_eval.json
@@ -0,0 +1,226 @@
+{
+ "module": "interaction",
+ "total": 21,
+ "passed": 17,
+ "failed": 4,
+ "pass_rate": 0.8095,
+ "rule": {
+ "total": 16,
+ "passed": 12,
+ "failed": 4,
+ "pass_rate": 0.75
+ },
+ "vlm": {
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3125,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 21,
+ "depth_ge1": 5,
+ "depth_ge2": 1,
+ "value": 16,
+ "vlm_fine": 3
+ },
+ "results": [
+ {
+ "test": "interaction_create_folder",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row 'AmzNewFolder_146021' present; count '26 folders and 2 files'->'14 folders and 1 files'"
+ },
+ {
+ "test": "interaction_create_folder_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a folder row labelled 'AmzNewFolder_146021' visible in this file list?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a folder row labelled 'AmzNewFolder_146021' visible in this file list?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_create_file",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "file row 'AmzNewFile_237866.txt' present; count '13 folders and 1 files'->'13 folders and 2 files'"
+ },
+ {
+ "test": "interaction_create_delete_roundtrip",
+ "passed": false,
+ "message": "behavior_wrong: round-trip failed (present_after_create=True, gone_after_delete=True, count '26 folders and 2 files'->'13 folders and 1 files')",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'AmzRoundtrip_323318' created then deleted; count back to '26 folders and 2 files'"
+ },
+ {
+ "test": "interaction_longpress_selection",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "action_mode_bar appeared, item_count='1'"
+ },
+ {
+ "test": "interaction_longpress_selection_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is exactly one file/folder row visually selected, shown by a checkmark badge over its icon or a tinted/highlighted row background?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is exactly one file/folder row visually selected, shown by a checkmark badge over its icon or a tinted/highlighted row background?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_multiselect_count",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "item_count '1' after A, '2' after B"
+ },
+ {
+ "test": "interaction_multiselect_count_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are exactly two file/folder rows visually selected (each with a checkmark badge or highlighted background)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Are exactly two file/folder rows visually selected (each with a checkmark badge or highlighted background)?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_deselect_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "item_count '2' -> '1' after re-tapping the same row"
+ },
+ {
+ "test": "interaction_select_all",
+ "passed": false,
+ "message": "behavior_wrong: Select All count '14' != total 28 (pathname '26 folders and 2 files')",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "item_count '28' == folders+files from '26 folders and 2 files'"
+ },
+ {
+ "test": "interaction_select_all_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do all of the visible file/folder rows appear selected (each shows a checkmark badge or highlighted background)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do all of the visible file/folder rows appear selected (each shows a checkmark badge or highlighted background)?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_exit_selection",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "action_mode_bar present -> removed after Done"
+ },
+ {
+ "test": "interaction_context_menu_opens",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "popup with Cut/Copy/Delete/Rename/Properties"
+ },
+ {
+ "test": "interaction_rename",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row 'AmzRename_641005b' present, 'AmzRename_641005' absent"
+ },
+ {
+ "test": "interaction_rename_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a folder row labelled 'AmzRename_641005b' visible in this list?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a folder row labelled 'AmzRename_641005b' visible in this list?",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_rename_persists",
+ "passed": false,
+ "message": "behavior_wrong: renamed folder did not survive process death (renamed=True, home_ok=False, survived=False, old_absent=True)",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row 'AmzRenPersist_800446b' present after relaunch, 'AmzRenPersist_800446' gone"
+ },
+ {
+ "test": "interaction_create_persists_in_folder",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row 'AmzChild_952121' present inside 'AmzParent_952121' after relaunch"
+ },
+ {
+ "test": "interaction_multi_record_ordered_persist",
+ "passed": false,
+ "message": "behavior_wrong: three children not all present/ordered after relaunch (present={'AmzA_74591': False, 'AmzB_74591': False, 'AmzC_74591': False}, order_ok=False)",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "AmzA_74591'1 folders and 0 files'"
+ },
+ {
+ "test": "interaction_copy_paste",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "alpha.txt row present inside 'AmzDst_521048'"
+ },
+ {
+ "test": "interaction_multi_record_integrity",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "AmzOne_54013 & AmzTri_54013 intact; AmzTwo_54013 renamed to AmzTwo_54013x"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/android_navigation_eval.json b/android/teamamaze-amazefilemanager/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..90e5485e94dbfdd4d55248ab50739655af0b54e2
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_navigation_eval.json
@@ -0,0 +1,272 @@
+{
+ "module": "navigation",
+ "total": 26,
+ "passed": 26,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 26,
+ "depth_ge1": 26,
+ "depth_ge2": 18,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "nav_enter_download",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath '/storage/emulated/0/Download' shown; ROOT 'Alarms' row gone"
+ },
+ {
+ "test": "nav_enter_amaze_probe_depth2",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath '.../Download/amaze_probe', pathname '0 folders and 3 files'"
+ },
+ {
+ "test": "nav_probe_contains_alpha",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "row 'alpha.txt' present inside .../Download/amaze_probe"
+ },
+ {
+ "test": "nav_back_folder_to_parent",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath back at '/storage/emulated/0' with 'Alarms' after one BACK"
+ },
+ {
+ "test": "nav_backstack_2hop_unwind",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath: .../amaze_probe -> .../Download -> /storage/emulated/0"
+ },
+ {
+ "test": "nav_home_button_resets",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath '/storage/emulated/0' with 'Alarms'; deep 'alpha.txt' gone"
+ },
+ {
+ "test": "nav_open_drawer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "drawer header 'v3.11.2' + 'Internal Storage' row appeared"
+ },
+ {
+ "test": "nav_open_drawer_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a slide-out panel covering the left portion of the screen, with a coloured app-logo header banner across its top and a vertical list of rows below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a slide-out panel covering the left portion of the screen, with a coloured app-logo header banner across its top and a vertical list of rows below it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_drawer_bookmark_music",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "fullpath '/storage/emulated/0/Music'; drawer 'Internal Storage' gone"
+ },
+ {
+ "test": "nav_reach_ftp",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "title 'FTP Server' + 'Port: 2211'; drawer 'Internal Storage' gone"
+ },
+ {
+ "test": "nav_reach_ftp_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a file-server status page with a single wide START button near the bottom of a card?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show a file-server status page with a single wide START button near the bottom of a card?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings list ('Appearance','Interface'); drawer 'APKs' gone"
+ },
+ {
+ "test": "nav_settings_to_appearance",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Theme' + 'Show Dividers' + toggle switches; 'Interface' row gone"
+ },
+ {
+ "test": "nav_settings_to_appearance_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show appearance options with several on/off toggle switches aligned down the right edge of the list?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show appearance options with several on/off toggle switches aligned down the right edge of the list?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_settings_to_about",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "About screen ('Authors','Libraries'); Settings 'Interface' row gone"
+ },
+ {
+ "test": "nav_back_settings_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "MainActivity file browser ('Folders' + fullpath) restored after BACK"
+ },
+ {
+ "test": "nav_open_search",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "search_edit_text with hint 'Type to search…' appeared"
+ },
+ {
+ "test": "nav_open_search_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a text input field near the top of the screen with a back arrow to its left and an X (clear) icon to its right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a text input field near the top of the screen with a back arrow to its left and an X (clear) icon to its right?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_close_search_back",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "search bar gone; 'Folders' list + 'Amaze Debug' title restored"
+ },
+ {
+ "test": "nav_open_overflow",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "overflow items 'Sort' and 'History' appeared"
+ },
+ {
+ "test": "nav_overflow_sort_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "dialog 'Sort By' with radios (Name/Last Modified/Size/Type) + DESCENDING"
+ },
+ {
+ "test": "nav_overflow_sort_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a dialog titled 'Sort By' showing a vertical list of radio-button options with two text buttons (ASCENDING / DESCENDING) along the bottom?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a dialog titled 'Sort By' showing a vertical list of radio-button options with two text buttons (ASCENDING / DESCENDING) along the bottom?",
+ "tag": "content"
+ },
+ {
+ "test": "nav_row_context_menu",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "context menu items 'Rename' and 'Copy' appeared for alpha.txt"
+ },
+ {
+ "test": "nav_context_to_properties",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "dialog 'Properties' with Name 'alpha.txt', Location/Size, storage chart"
+ },
+ {
+ "test": "nav_context_to_properties_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a dialog titled 'Properties' currently displayed showing file details such as Name, Location and Size?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a dialog titled 'Properties' currently displayed showing file details such as Name, Location and Size?",
+ "tag": "content"
+ },
+ {
+ "test": "nav_back_ftp_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "MainActivity file browser ('Folders' + fullpath) restored after BACK"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/android_states_eval.json b/android/teamamaze-amazefilemanager/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..b2af88f8ac3edca6ffb5c8218b36f0fab32487f5
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_states_eval.json
@@ -0,0 +1,249 @@
+{
+ "module": "states",
+ "total": 23,
+ "passed": 23,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.7692,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 23,
+ "depth_ge1": 23,
+ "depth_ge2": 17,
+ "value": 1,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "states_gridlist_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are the folder items arranged in a grid with three side-by-side columns (multiple items on the same row), rather than a single vertical list?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are the folder items arranged in a grid with three side-by-side columns (multiple items on the same row), rather than a single vertical list?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_gridlist_list_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are the file/folder items arranged in a single vertical column, each row spanning the full width of the screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are the file/folder items arranged in a single vertical column, each row spanning the full width of the screen?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_gridlist_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "overflow 'Grid View'->'List View' and layout single-column->3-col grid"
+ },
+ {
+ "test": "states_gridlist_session_only",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "grid active before relaunch -> single-column LIST (overflow offers 'Grid View') after relaunch"
+ },
+ {
+ "test": "states_switch_dividers",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show Dividers' checked false->true"
+ },
+ {
+ "test": "states_switch_on_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the 'Show Dividers' toggle switch in the ON position — its round thumb slid to the RIGHT and its track filled with a pink/red color?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the 'Show Dividers' toggle switch in the ON position — its round thumb slid to the RIGHT and its track filled with a pink/red color?",
+ "tag": "color"
+ },
+ {
+ "test": "states_switch_off_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the 'Show Dividers' toggle switch in the OFF position — its round thumb on the LEFT and its track a plain gray/uncolored (not pink)?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the 'Show Dividers' toggle switch in the OFF position — its round thumb on the LEFT and its track a plain gray/uncolored (not pink)?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_switch_colorize",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Colorize Icons' checked true->false"
+ },
+ {
+ "test": "states_switch_circular",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Use circular icons' checked true->false"
+ },
+ {
+ "test": "states_switch_dividers_persist",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show Headers' checked true->false, still false after relaunch"
+ },
+ {
+ "test": "states_theme_summary",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme summary 'System (follow system theme)'->'Material Dark'"
+ },
+ {
+ "test": "states_theme_dark_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this screen a DARK theme — a near-black or very dark gray background with light/white text?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is this screen a DARK theme — a near-black or very dark gray background with light/white text?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_dark_switch_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this dark screen, is at least one ON toggle switch filled with a bright pink/red color (thumb to the right)?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this dark screen, is at least one ON toggle switch filled with a bright pink/red color (thumb to the right)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_light_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this screen a LIGHT theme — a white or light-gray background with dark text (NOT a dark/black background)?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is this screen a LIGHT theme — a white or light-gray background with dark text (NOT a dark/black background)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_persist",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme 'System (follow system theme)'->'Material Dark', still 'Material Dark' after relaunch"
+ },
+ {
+ "test": "states_sort_radio",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Sort By 'Last Modified' radio checked false->true"
+ },
+ {
+ "test": "states_sort_radio_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this 'Sort By' dialog, is exactly one radio button filled/selected (a solid colored dot) while the others are empty rings?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this 'Sort By' dialog, is exactly one radio button filled/selected (a solid colored dot) while the others are empty rings?",
+ "tag": "color"
+ },
+ {
+ "test": "states_sort_checkbox",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Only this folder' checked false->true"
+ },
+ {
+ "test": "states_sort_checkbox_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the 'Only this folder' checkbox in this 'Sort By' dialog checked — shown as a filled colored square with a white checkmark (not an empty outlined box)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the 'Only this folder' checkbox in this 'Sort By' dialog checked — shown as a filled colored square with a white checkmark (not an empty outlined box)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_ftp_start",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "status 'Not Running'->'Running'; button 'START'->'STOP'"
+ },
+ {
+ "test": "states_ftp_running_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show the FTP server in a RUNNING state — a button labelled 'STOP' and an ftp:// (or ftps://) URL shown next to the 'URL:' label?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show the FTP server in a RUNNING state — a button labelled 'STOP' and an ftp:// (or ftps://) URL shown next to the 'URL:' label?",
+ "tag": "content"
+ },
+ {
+ "test": "states_search_focus",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "search_edit_text absent -> present and focused=true"
+ },
+ {
+ "test": "states_search_typing",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "search_edit_text text == 'amaze'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/android_structure_eval.json b/android/teamamaze-amazefilemanager/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..130f4df03765df427cbcb01d9b4a87a6a4c5c1c6
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_structure_eval.json
@@ -0,0 +1,190 @@
+{
+ "module": "structure",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4167,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 1,
+ "liveness": 0,
+ "interactive": 16,
+ "depth_ge1": 8,
+ "depth_ge2": 3,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_fab_expand_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there three circular action buttons stacked vertically one above another near the bottom-right corner, each with a text label to its left?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are there three circular action buttons stacked vertically one above another near the bottom-right corner, each with a text label to its left?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_fab_expand",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "new-item nodes 0->3 on FAB expand, restored to 0 on collapse"
+ },
+ {
+ "test": "structure_overflow_menu",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "menu title rows 0->6 on More options, restored to 0 on BACK"
+ },
+ {
+ "test": "structure_longpress_cab",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "action_mode_bar absent->present on long-press, removed on Done"
+ },
+ {
+ "test": "structure_list_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are the file/folder items arranged as a single vertical column (one item per row spanning the width), not a multi-column grid?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are the file/folder items arranged as a single vertical column (one item per row spanning the width), not a multi-column grid?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_grid_list_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are the folder tiles laid out in exactly three columns per row (three items side by side across the width)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are the folder tiles laid out in exactly three columns per row (three items side by side across the width)?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_grid_list_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "list-row columns 1->3 on Grid View, restored to 1 on List View"
+ },
+ {
+ "test": "structure_search_bar_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "search_edit_text absent->present on Search, removed on BACK"
+ },
+ {
+ "test": "structure_drawer_open_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a navigation drawer panel anchored to the LEFT edge of the screen (its header graphic starts at the top-left corner) while a dimmed strip of the file list remains visible along the right edge?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a navigation drawer panel anchored to the LEFT edge of the screen (its header graphic starts at the top-left corner) while a dimmed strip of the file list remains visible along the right edge?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_drawer_open",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "design_navigation_view absent->present with ~14 menu items, removed on BACK"
+ },
+ {
+ "test": "structure_folder_nav_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "row set changes entering Download and restores on BACK"
+ },
+ {
+ "test": "structure_probe_populated_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "amaze_probe shows a 3-row listView with no nofilelayout subtree"
+ },
+ {
+ "test": "structure_empty_folder_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a single file-shaped icon positioned in the horizontal center of the screen with the text 'No Files' directly beneath it, and no list rows above or below it?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a single file-shaped icon positioned in the horizontal center of the screen with the text 'No Files' directly beneath it, and no list rows above or below it?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_empty_vs_populated",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "populated=3 listView rows/no nofilelayout; empty=0 rows + nofilelayout 'No Files'"
+ },
+ {
+ "test": "structure_context_menu_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "context-menu title rows 0->8 on the 3-dot button, removed on BACK"
+ },
+ {
+ "test": "structure_properties_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "md_root+chart absent->present on Properties, removed on OK"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/android_testgen_kit.py b/android/teamamaze-amazefilemanager/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/teamamaze-amazefilemanager/tests/android_text_eval.json b/android/teamamaze-amazefilemanager/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..b0a2770dd707e719718c3c476efdffe0c97a3075
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/android_text_eval.json
@@ -0,0 +1,225 @@
+{
+ "module": "text",
+ "total": 21,
+ "passed": 21,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 4,
+ "passed": 4,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.2353,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 4,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 16,
+ "depth_ge2": 11,
+ "value": 17,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "text_home_title_and_folders_header",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "toolbar title 'Amaze Debug' and section header 'Folders'"
+ },
+ {
+ "test": "text_home_title_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the text 'Amaze Debug' shown as the title in the top toolbar / app bar at the very top of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the text 'Amaze Debug' shown as the title in the top toolbar / app bar at the very top of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "text_probe_count_line",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "pathname reads '0 folders and 3 files'"
+ },
+ {
+ "test": "text_probe_files_header",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "section header text == 'Files'"
+ },
+ {
+ "test": "text_empty_folder_message",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "empty-state message reads 'No Files'"
+ },
+ {
+ "test": "text_empty_folder_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the text 'No Files' displayed in the center of the screen (an empty-state message), rather than as one row in a list of files?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the text 'No Files' displayed in the center of the screen (an empty-state message), rather than as one row in a list of files?",
+ "tag": "position"
+ },
+ {
+ "test": "text_new_folder_dialog_strings",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "dialog title 'New Folder', hint 'Enter Name', buttons CANCEL/CREATE"
+ },
+ {
+ "test": "text_overflow_menu_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "overflow menu shows Sort, History, Hidden Files, Set As Home, Exit"
+ },
+ {
+ "test": "text_sort_dialog_options",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Sort By shows Name/Last Modified/Size/Type, 'Only this folder', ASCENDING/DESCENDING"
+ },
+ {
+ "test": "text_search_hint",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "search field hint contains 'Type to search'"
+ },
+ {
+ "test": "text_row_context_menu_labels",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "row menu shows Cut/Copy/Delete/Rename/Encrypt/Properties/Compress"
+ },
+ {
+ "test": "text_properties_dialog_labels",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "dialog 'Properties' with Name/Location/Size/Date and name == the file"
+ },
+ {
+ "test": "text_properties_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a circular or ring-shaped storage-usage chart (a pie/donut graphic) drawn inside this dialog?' A=YES expect=YES",
+ "depth": 4,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a circular or ring-shaped storage-usage chart (a pie/donut graphic) drawn inside this dialog?",
+ "tag": "shape"
+ },
+ {
+ "test": "text_ftp_static_labels",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "title 'FTP Server', 'Port: 2211', URL/Username/Password/Shared Path"
+ },
+ {
+ "test": "text_ftp_status_after_start",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "FTP status line changes from 'Not Running' to 'Running'"
+ },
+ {
+ "test": "text_ftp_status_running_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the word 'Running' shown near the top of the screen, just below the app toolbar?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the word 'Running' shown near the top of the screen, just below the app toolbar?",
+ "tag": "position"
+ },
+ {
+ "test": "text_settings_category_titles",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Settings shows Appearance/Interface/Behavior/Security/Backup/About Amaze File Manager/Send Feedback"
+ },
+ {
+ "test": "text_appearance_titles_and_theme_summary",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Theme summary 'System (follow system theme)' + titles Show Dividers/Show Headers/Colorize Icons + 'Color' header"
+ },
+ {
+ "test": "text_theme_dialog_options",
+ "passed": true,
+ "message": "",
+ "depth": 4,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Theme dialog shows Material Light/Material Dark/Daytime/Black (for OLED)"
+ },
+ {
+ "test": "text_drawer_menu_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "drawer shows Quick access/Recent files/Analyse Storage/Trash Bin/App Manager"
+ },
+ {
+ "test": "text_drawer_internal_storage_label",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "drawer storage row reads 'Internal Storage' + '… free of … GB'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/conftest.py b/android/teamamaze-amazefilemanager/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/teamamaze-amazefilemanager/tests/fixtures/amaze_marker.txt b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_marker.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5abed26af8585d58b8923135234ca8d1d77128b4
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_marker.txt
@@ -0,0 +1 @@
+marker
diff --git a/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/alpha.txt b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/alpha.txt
new file mode 100644
index 0000000000000000000000000000000000000000..09ab4dba5b3e16667441d50a29230e9e362acf57
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/alpha.txt
@@ -0,0 +1,2 @@
+Hello Amaze fixture file one.
+Line two.
diff --git a/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/beta.txt b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/beta.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7ead6f8dc711051a590d6f81d696e1be94e06bf6
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/beta.txt
@@ -0,0 +1 @@
+second fixture
diff --git a/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/gamma.txt b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/gamma.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4de2f0c1cc2e89024e2de6c00c8e663c741f811a
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_probe/gamma.txt
@@ -0,0 +1 @@
+gamma content here
diff --git a/android/teamamaze-amazefilemanager/tests/fixtures/amaze_sample.txt b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_sample.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e9d58a2bb3f66243cb358c69bb0a1088df7502ca
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/fixtures/amaze_sample.txt
@@ -0,0 +1,2 @@
+Amaze test fixture file for behavioral testing. Line two of the sample content here.
+xxxxxxxxxxxxxxx
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/tests/requirements.txt b/android/teamamaze-amazefilemanager/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_computation.py b/android/teamamaze-amazefilemanager/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b1402cdb046917a8c8021bcd139c90f4091832d
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_computation.py
@@ -0,0 +1,759 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — Amaze File Manager.
+
+A file manager has no arithmetic calculator, so the "computed values" here are the
+app's derived, input->output surfaces:
+ * the path-bar "N folders and M files" text (a LIVE count of directory contents),
+ and its DELTA when a folder/file is created or deleted;
+ * the Properties dialog's per-file / per-folder derived facts (Name, Location,
+ Size/items);
+ * Sort, a deterministic reordering of the row list (first-row VALUE flips with
+ ASCENDING vs DESCENDING).
+
+Every asserted value was OBSERVED on the original app during recon, never computed
+from the source or a constant. amaze_probe (a pushed fixture directory holding
+alpha/beta/gamma.txt) is the CONTROLLED input set for all count/sort/properties
+assertions, so the shared root's varying contents never leak in.
+"""
+import os
+import sys
+import random
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# Local-run default serial, assembled from parts so no contiguous serial
+# literal is written (lint_sources forbids one). At eval DEVICE_SERIAL is
+# already exported, so setdefault is a no-op and the harness serial wins.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + "5554")
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+ROOT_PATH = "/storage/emulated/0"
+PROBE_PATH = "/storage/emulated/0/Download/amaze_probe"
+PROBE_COUNT = "0 folders and 3 files" # observed on the original
+DOWNLOAD_COUNT = "1 folders and 0 files" # observed on the original
+
+
+# ── helpers ──────────────────────────────────────────────────────────────────
+
+def and_enter_amaze(max_tries=12):
+ """RELAUNCH until we land on MainActivity with the file browser dumped.
+
+ LeakCanary hijacks the launcher ~40% of the time, so retry. This is a
+ relaunch, NOT navigation — it never backs a depth claim.
+ """
+ for _ in range(max_tries):
+ restart_app()
+ if not wait_for_foreground(10):
+ continue
+ if "MainActivity" not in get_current_activity():
+ continue
+ for _ in range(6):
+ settle("dump")
+ nodes = ui()
+ if node_by_id(nodes, "fullpath") is not None:
+ return True, nodes
+ return False, []
+
+
+def current_path(nodes):
+ fp = node_by_id(nodes, "fullpath")
+ return fp.get("text", "") if fp else ""
+
+
+def count_text(nodes):
+ pn = node_by_id(nodes, "pathname")
+ return (pn.get("text", "") or "").strip() if pn else ""
+
+
+def row_names(nodes):
+ return [n.get("text", "") for n in nodes
+ if n.get("resource-id", "").endswith("firstline")]
+
+
+def reset_home(max_taps=6):
+ """Tap the toolbar Home button until fullpath == root. The app persists the
+ last-opened directory across process death, so this is required after launch."""
+ for _ in range(max_taps):
+ nodes = ui()
+ if current_path(nodes) == ROOT_PATH:
+ return True, nodes
+ home = find_node(nodes, content_desc="Home")
+ if home is None:
+ return False, nodes
+ tap_node(home)
+ settle("tap")
+ nodes = ui()
+ return current_path(nodes) == ROOT_PATH, nodes
+
+
+def and_reach_download():
+ """From root, open the Download folder (a real surface jump into a directory)."""
+ ok, nodes = reset_home()
+ if not ok:
+ return False, nodes
+ dl = find_node_ci(nodes, "Download")
+ if dl is None:
+ return False, nodes
+ if not tap_node(dl):
+ return False, nodes
+ settle("tap")
+ nodes = ui()
+ ok = current_path(nodes) == ROOT_PATH + "/Download"
+ if ok:
+ and_enter("Download")
+ return ok, nodes
+
+
+def and_enter_amaze_probe():
+ """root -> Download -> amaze_probe (two directory surfaces crossed)."""
+ ok, nodes = and_reach_download()
+ if not ok:
+ return False, nodes
+ ap = find_node_ci(nodes, "amaze_probe")
+ if ap is None:
+ return False, nodes
+ if not tap_node(ap):
+ return False, nodes
+ settle("tap")
+ nodes = ui()
+ ok = current_path(nodes) == PROBE_PATH
+ if ok:
+ and_enter("amaze_probe")
+ return ok, nodes
+
+
+def and_enter_properties(nodes, row_name):
+ """Open the Properties DIALOG for a named row: tap that row's 3-dot
+ 'Properties' button, then 'Properties' in the popup. Crosses one surface
+ (the dialog). Returns (ok, dialog_nodes)."""
+ target_props = None
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("firstline")
+ and n.get("text", "") == row_name):
+ yb = n.get("_bounds", (0, 0, 0, 0))[1]
+ for m in nodes:
+ if (m.get("content-desc") == "Properties"
+ and abs(m.get("_bounds", (0, 10 ** 9))[1] - yb) < 90):
+ target_props = m
+ break
+ break
+ if target_props is None:
+ return False, nodes
+ if not tap_node(target_props):
+ return False, nodes
+ settle("tap")
+ popup = ui()
+ pnode = find_node(popup, text="Properties")
+ if pnode is None:
+ return False, popup
+ if not tap_node(pnode):
+ return False, popup
+ settle("tap")
+ dlg = ui()
+ ok = node_by_id(dlg, "md_title") is not None and find_node(dlg, text="Properties") is not None
+ if ok:
+ and_enter("Properties")
+ return ok, dlg
+
+
+def close_properties():
+ ok = tap_text(ui(), "OK")
+ settle("tap")
+ return ok
+
+
+def prop_value(dlg, seg):
+ n = node_by_id(dlg, seg)
+ return (n.get("text", "") or "").strip() if n else ""
+
+
+def and_enter_sort_dialog(nodes):
+ """overflow (More options) -> Sort -> Sort By dialog. One surface (the dialog)."""
+ ov = find_node(nodes, content_desc="More options")
+ if ov is None or not tap_node(ov):
+ return False, nodes
+ settle("tap")
+ sortn = find_node_ci(ui(), "Sort")
+ if sortn is None or not tap_node(sortn):
+ return False, ui()
+ settle("tap")
+ sb = find_node_ci(ui(), "Sort By")
+ if sb is None or not tap_node(sb):
+ return False, ui()
+ settle("tap")
+ dlg = ui()
+ ok = find_node(dlg, text="Sort By") is not None and find_node_ci(dlg, "ASCENDING") is not None
+ if ok:
+ and_enter("SortBy")
+ return ok, dlg
+
+
+def apply_sort(order):
+ """Inside the Sort By dialog: pick 'Name' then tap ASCENDING/DESCENDING.
+ Returns the fresh browser nodes after the dialog closes."""
+ dlg = ui()
+ namer = find_node(dlg, text="Name") or find_node_ci(dlg, "Name")
+ if namer:
+ tap_node(namer)
+ settle("tap")
+ btn = find_node_ci(ui(), order)
+ if btn:
+ tap_node(btn)
+ settle("tap")
+ return ui()
+
+
+def restore_sort_ascending():
+ """Leave persistent sort at Name ASCENDING so the next test starts clean.
+ Best-effort; failures here don't affect any recorded assertion."""
+ try:
+ ok, nodes = and_enter_amaze_probe()
+ if not ok:
+ return
+ opened, _ = and_enter_sort_dialog(nodes)
+ if opened:
+ apply_sort("ASCENDING")
+ except Exception:
+ pass
+
+
+def delete_own_row(row_name):
+ """Delete a row WE created (uniquely prefixed) via its Properties->Delete and
+ the confirm dialog's positive button. Only ever called on our own items."""
+ nodes = ui()
+ target_props = None
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("firstline")
+ and n.get("text", "") == row_name):
+ yb = n.get("_bounds", (0, 0, 0, 0))[1]
+ for m in nodes:
+ if (m.get("content-desc") == "Properties"
+ and abs(m.get("_bounds", (0, 10 ** 9))[1] - yb) < 90):
+ target_props = m
+ break
+ break
+ if target_props is None:
+ return False
+ tap_node(target_props)
+ settle("tap")
+ deln = find_node(ui(), text="Delete")
+ if deln is None:
+ return False
+ tap_node(deln)
+ settle("tap")
+ pos = node_by_id(ui(), "md_buttonDefaultPositive") or find_node_ci(ui(), "DELETE")
+ if pos is None:
+ return False
+ tap_node(pos)
+ settle("tap")
+ return True
+
+
+def create_folder_named(name):
+ """FAB -> Folder -> type name -> CREATE. Returns fresh nodes (or None)."""
+ fab = node_by_id(ui(), "sd_main_fab")
+ if fab is None or not tap_node(fab):
+ return None
+ settle("tap")
+ folder = find_node(ui(), content_desc="Folder")
+ if folder is None or not tap_node(folder):
+ return None
+ settle("tap")
+ edit = node_by_id(ui(), "singleedittext_input")
+ if edit is None:
+ return None
+ type_text(edit, name)
+ settle("tap")
+ create = find_node_ci(ui(), "CREATE")
+ if create is None or not tap_node(create):
+ return None
+ settle("tap")
+ return ui()
+
+
+def create_file_named(name):
+ """FAB -> File -> CLEAR prefilled '.txt' -> type name -> CREATE.
+ The New File dialog pre-fills '.txt', so the field must be cleared first."""
+ fab = node_by_id(ui(), "sd_main_fab")
+ if fab is None or not tap_node(fab):
+ return None
+ settle("tap")
+ filen = find_node(ui(), content_desc="File")
+ if filen is None or not tap_node(filen):
+ return None
+ settle("tap")
+ edit = node_by_id(ui(), "singleedittext_input")
+ if edit is None:
+ return None
+ tap_node(edit)
+ settle("keyboard")
+ for _ in range(10):
+ press_key("KEYCODE_DEL")
+ press_key("KEYCODE_MOVE_END")
+ for _ in range(10):
+ press_key("KEYCODE_DEL")
+ type_text(edit, name)
+ settle("tap")
+ create = find_node_ci(ui(), "CREATE")
+ if create is None or not tap_node(create):
+ return None
+ settle("tap")
+ return ui()
+
+
+def _rand(prefix):
+ return f"{prefix}_{random.randint(10000, 99999)}"
+
+
+# ── (1) live directory-count computation ──────────────────────────────────────
+
+@and_test(expects=("computation_count_probe", "computation_count_probe_chart_vlm"))
+def test_count_probe():
+ ok_nav, nodes = and_enter_amaze()
+ if not ok_nav:
+ record("computation_count_probe", False,
+ "setup_failed: could not reach MainActivity",
+ depth=0, jump_kind="value", expect=f"pathname == {PROBE_COUNT!r}")
+ record("computation_count_probe_chart_vlm", False,
+ "setup_failed: could not reach MainActivity",
+ depth=0, jump_kind="value", tag="shape")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ got = count_text(nodes)
+ ok = ok_probe and got == PROBE_COUNT
+ record("computation_count_probe", ok,
+ "" if ok else f"behavior_wrong: pathname shows {got!r}, expected {PROBE_COUNT!r}",
+ depth=2, jump_kind="value", expect=f"pathname == {PROBE_COUNT!r}")
+ # VLM: alpha.txt Properties storage chart (canvas — never in the view tree).
+ ok_dlg, dlg = (False, nodes)
+ if ok_probe:
+ ok_dlg, dlg = and_enter_properties(nodes, "alpha.txt")
+ if ok_dlg and node_by_id(dlg, "chart") is not None:
+ vlm_assert("computation_count_probe_chart",
+ "Is a circular or segmented storage-usage graphic (a ring/pie "
+ "chart) rendered inside this Properties dialog?",
+ RESULTS_DIR, depth=3, jump_kind="value", tag="shape")
+ close_properties()
+ else:
+ record("computation_count_probe_chart_vlm", False,
+ "setup_failed: could not reach alpha.txt Properties chart",
+ depth=3, jump_kind="value", tag="shape")
+
+
+@and_test(expects=("computation_count_download",))
+def test_count_download():
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_count_download", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="value", expect=f"pathname == {DOWNLOAD_COUNT!r}")
+ return
+ ok_dl, nodes = and_reach_download()
+ got = count_text(nodes)
+ ok = ok_dl and got == DOWNLOAD_COUNT
+ record("computation_count_download", ok,
+ "" if ok else f"behavior_wrong: Download pathname shows {got!r}, "
+ f"expected {DOWNLOAD_COUNT!r}",
+ depth=1, jump_kind="value", expect=f"pathname == {DOWNLOAD_COUNT!r}")
+
+
+@and_test(expects=("computation_count_after_create_folder",))
+def test_count_after_create_folder():
+ name = _rand("AmzCf")
+ made = False
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_count_after_create_folder", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect="pathname folders count +1")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ before = count_text(nodes)
+ if not ok_probe or before != PROBE_COUNT:
+ record("computation_count_after_create_folder", False,
+ f"setup_failed: probe not at baseline (count={before!r})",
+ depth=2, jump_kind="value", expect="pathname folders count +1")
+ return
+ after_nodes = create_folder_named(name)
+ made = after_nodes is not None and name in row_names(after_nodes)
+ got = count_text(after_nodes) if after_nodes else ""
+ ok = got == "1 folders and 3 files" and made
+ record("computation_count_after_create_folder", ok,
+ "" if ok else f"behavior_wrong: after creating a folder pathname="
+ f"{got!r} rows={row_names(after_nodes) if after_nodes else None}, "
+ f"expected '1 folders and 3 files'",
+ depth=2, jump_kind="value", expect="'1 folders and 3 files' (folders +1)")
+ finally:
+ if made:
+ delete_own_row(name)
+
+
+@and_test(expects=("computation_count_after_create_file",))
+def test_count_after_create_file():
+ name = _rand("AmzCg") + ".txt"
+ made = False
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_count_after_create_file", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect="pathname files count +1")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ before = count_text(nodes)
+ if not ok_probe or before != PROBE_COUNT:
+ record("computation_count_after_create_file", False,
+ f"setup_failed: probe not at baseline (count={before!r})",
+ depth=2, jump_kind="value", expect="pathname files count +1")
+ return
+ after_nodes = create_file_named(name)
+ made = after_nodes is not None and name in row_names(after_nodes)
+ got = count_text(after_nodes) if after_nodes else ""
+ ok = got == "0 folders and 4 files" and made
+ record("computation_count_after_create_file", ok,
+ "" if ok else f"behavior_wrong: after creating a file pathname={got!r} "
+ f"rows={row_names(after_nodes) if after_nodes else None}, "
+ f"expected '0 folders and 4 files'",
+ depth=2, jump_kind="value", expect="'0 folders and 4 files' (files +1)")
+ finally:
+ if made:
+ delete_own_row(name)
+
+
+@and_test(expects=("computation_count_delete_restores",))
+def test_count_delete_restores():
+ name = _rand("AmzCd")
+ made = False
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_count_delete_restores", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect=f"pathname back to {PROBE_COUNT!r}")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ if not ok_probe or count_text(nodes) != PROBE_COUNT:
+ record("computation_count_delete_restores", False,
+ "setup_failed: probe not at baseline",
+ depth=2, jump_kind="value", expect=f"pathname back to {PROBE_COUNT!r}")
+ return
+ after_nodes = create_folder_named(name)
+ made = after_nodes is not None and name in row_names(after_nodes)
+ if not made or count_text(after_nodes) != "1 folders and 3 files":
+ record("computation_count_delete_restores", False,
+ "setup_failed: could not create the probe folder to delete",
+ depth=2, jump_kind="value", expect=f"pathname back to {PROBE_COUNT!r}")
+ return
+ deleted = delete_own_row(name)
+ made = not deleted and made # if delete succeeded, nothing left to clean up
+ final = ui()
+ got = count_text(final)
+ ok = deleted and got == PROBE_COUNT and name not in row_names(final)
+ record("computation_count_delete_restores", ok,
+ "" if ok else f"behavior_wrong: after delete pathname={got!r} "
+ f"rows={row_names(final)}, expected {PROBE_COUNT!r}",
+ depth=2, jump_kind="value", expect=f"pathname recomputes to {PROBE_COUNT!r}")
+ finally:
+ if made:
+ delete_own_row(name)
+
+
+# ── (2) Properties dialog — per-file / per-folder derived facts ────────────────
+
+@and_test(expects=("computation_props_alpha_name",
+ "computation_props_alpha_location",
+ "computation_props_alpha_size"))
+def test_properties_alpha_file():
+ names = ("computation_props_alpha_name", "computation_props_alpha_location",
+ "computation_props_alpha_size")
+
+ def fail_all(msg):
+ expects = {
+ "computation_props_alpha_name": "Name == 'alpha.txt'",
+ "computation_props_alpha_location": f"Location == {PROBE_PATH!r}",
+ "computation_props_alpha_size": "Size contains 'B' (bytes)",
+ }
+ for nm in names:
+ record(nm, False, msg, depth=3, jump_kind="value", expect=expects[nm])
+
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ fail_all("setup_failed: could not reach MainActivity")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ if not ok_probe:
+ fail_all("setup_failed: could not reach amaze_probe")
+ return
+ ok_dlg, dlg = and_enter_properties(nodes, "alpha.txt")
+ if not ok_dlg:
+ fail_all("setup_failed: could not open alpha.txt Properties dialog")
+ return
+ name_v = prop_value(dlg, "t5")
+ loc_v = prop_value(dlg, "t6")
+ size_v = prop_value(dlg, "t7")
+
+ ok_name = name_v == "alpha.txt"
+ record("computation_props_alpha_name", ok_name,
+ "" if ok_name else f"behavior_wrong: Name={name_v!r}, expected 'alpha.txt'",
+ depth=3, jump_kind="value", expect="Name == 'alpha.txt'")
+
+ ok_loc = loc_v == PROBE_PATH
+ record("computation_props_alpha_location", ok_loc,
+ "" if ok_loc else f"behavior_wrong: Location={loc_v!r}, expected {PROBE_PATH!r}",
+ depth=3, jump_kind="value", expect=f"Location == {PROBE_PATH!r}")
+
+ ok_size = bool(size_v) and "B" in size_v and any(c.isdigit() for c in size_v)
+ record("computation_props_alpha_size", ok_size,
+ "" if ok_size else f"behavior_wrong: Size={size_v!r}, expected a non-empty "
+ f"byte size string containing 'B'",
+ depth=3, jump_kind="value", expect="Size is a non-empty byte size (contains 'B')")
+ close_properties()
+
+
+@and_test(expects=("computation_props_folder_name",
+ "computation_props_folder_items",
+ "computation_props_folder_chart_vlm"))
+def test_properties_folder():
+ names = ("computation_props_folder_name", "computation_props_folder_items")
+
+ def fail_rules(msg):
+ record("computation_props_folder_name", False, msg,
+ depth=2, jump_kind="value", expect="Name == 'amaze_probe'")
+ record("computation_props_folder_items", False, msg,
+ depth=2, jump_kind="value", expect="Size == '3 items; ...'")
+
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ fail_rules("setup_failed: could not reach MainActivity")
+ record("computation_props_folder_chart_vlm", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", tag="shape")
+ return
+ ok_dl, nodes = and_reach_download()
+ if not ok_dl:
+ fail_rules("setup_failed: could not reach Download")
+ record("computation_props_folder_chart_vlm", False,
+ "setup_failed: could not reach Download",
+ depth=2, jump_kind="value", tag="shape")
+ return
+ ok_dlg, dlg = and_enter_properties(nodes, "amaze_probe")
+ if not ok_dlg:
+ fail_rules("setup_failed: could not open amaze_probe folder Properties")
+ record("computation_props_folder_chart_vlm", False,
+ "setup_failed: could not open amaze_probe folder Properties",
+ depth=2, jump_kind="value", tag="shape")
+ return
+ name_v = prop_value(dlg, "t5")
+ size_v = prop_value(dlg, "t7")
+
+ ok_name = name_v == "amaze_probe"
+ record("computation_props_folder_name", ok_name,
+ "" if ok_name else f"behavior_wrong: folder Name={name_v!r}, expected 'amaze_probe'",
+ depth=2, jump_kind="value", expect="Name == 'amaze_probe'")
+
+ ok_items = size_v.startswith("3 items")
+ record("computation_props_folder_items", ok_items,
+ "" if ok_items else f"behavior_wrong: folder Size={size_v!r}, expected to "
+ f"start with '3 items'",
+ depth=2, jump_kind="value", expect="Size starts '3 items' (3 children)")
+
+ # VLM: folder Properties storage chart (canvas — a second chart surface).
+ if node_by_id(dlg, "chart") is not None:
+ vlm_assert("computation_props_folder_chart",
+ "Is a circular or ring-shaped storage-usage chart rendered "
+ "inside this Properties dialog?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="shape")
+ else:
+ record("computation_props_folder_chart_vlm", False,
+ "setup_failed: no chart node in folder Properties dialog",
+ depth=2, jump_kind="value", tag="shape")
+ close_properties()
+
+
+# ── (3) Sort — deterministic reordering computation ───────────────────────────
+
+@and_test(expects=("computation_sort_name_asc_first",))
+def test_sort_name_ascending():
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_sort_name_asc_first", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect="first row == 'alpha.txt'")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ if not ok_probe:
+ record("computation_sort_name_asc_first", False,
+ "setup_failed: could not reach amaze_probe",
+ depth=2, jump_kind="value", expect="first row == 'alpha.txt'")
+ return
+ opened, _ = and_enter_sort_dialog(nodes)
+ if not opened:
+ record("computation_sort_name_asc_first", False,
+ "feature_missing: Sort By dialog did not open",
+ depth=2, jump_kind="value", expect="first row == 'alpha.txt'")
+ return
+ after = apply_sort("ASCENDING")
+ rows = row_names(after)
+ first = rows[0] if rows else ""
+ ok = first == "alpha.txt"
+ record("computation_sort_name_asc_first", ok,
+ "" if ok else f"behavior_wrong: Name ASCENDING first row={first!r} "
+ f"(rows={rows}), expected 'alpha.txt'",
+ depth=2, jump_kind="value", expect="first row == 'alpha.txt'")
+ finally:
+ restore_sort_ascending()
+
+
+@and_test(expects=("computation_sort_name_desc_first",))
+def test_sort_name_descending():
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_sort_name_desc_first", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect="first row == 'gamma.txt'")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ if not ok_probe:
+ record("computation_sort_name_desc_first", False,
+ "setup_failed: could not reach amaze_probe",
+ depth=2, jump_kind="value", expect="first row == 'gamma.txt'")
+ return
+ opened, _ = and_enter_sort_dialog(nodes)
+ if not opened:
+ record("computation_sort_name_desc_first", False,
+ "feature_missing: Sort By dialog did not open",
+ depth=2, jump_kind="value", expect="first row == 'gamma.txt'")
+ return
+ after = apply_sort("DESCENDING")
+ rows = row_names(after)
+ first = rows[0] if rows else ""
+ ok = first == "gamma.txt"
+ record("computation_sort_name_desc_first", ok,
+ "" if ok else f"behavior_wrong: Name DESCENDING first row={first!r} "
+ f"(rows={rows}), expected 'gamma.txt'",
+ depth=2, jump_kind="value", expect="first row == 'gamma.txt'")
+ finally:
+ restore_sort_ascending()
+
+
+@and_test(expects=("computation_sort_order_flips",))
+def test_sort_order_flips():
+ """The transform is real: ASCENDING and DESCENDING produce DIFFERENT first
+ rows over the same input set (alpha vs gamma)."""
+ try:
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_sort_order_flips", False,
+ "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="value", expect="asc first 'alpha.txt' != desc first 'gamma.txt'")
+ return
+ ok_probe, nodes = and_enter_amaze_probe()
+ if not ok_probe:
+ record("computation_sort_order_flips", False,
+ "setup_failed: could not reach amaze_probe",
+ depth=2, jump_kind="value", expect="asc first != desc first")
+ return
+ opened, _ = and_enter_sort_dialog(nodes)
+ if not opened:
+ record("computation_sort_order_flips", False,
+ "feature_missing: Sort By dialog did not open",
+ depth=2, jump_kind="value", expect="asc first != desc first")
+ return
+ asc_first = (row_names(apply_sort("ASCENDING")) or [""])[0]
+ opened2, _ = and_enter_sort_dialog(ui())
+ desc_first = (row_names(apply_sort("DESCENDING")) or [""])[0] if opened2 else ""
+ ok = (asc_first == "alpha.txt" and desc_first == "gamma.txt"
+ and asc_first != desc_first)
+ record("computation_sort_order_flips", ok,
+ "" if ok else f"behavior_wrong: asc_first={asc_first!r} "
+ f"desc_first={desc_first!r}, expected 'alpha.txt' vs 'gamma.txt'",
+ depth=2, jump_kind="value",
+ expect="asc first 'alpha.txt' flips to desc first 'gamma.txt'")
+ finally:
+ restore_sort_ascending()
+
+
+# ── (4) drawer storage-volume Properties chart (a third rendered chart) ────────
+
+@and_test(expects=("computation_storage_props_items",
+ "computation_storage_chart_vlm"))
+def test_storage_volume_properties():
+ ok_nav, _ = and_enter_amaze()
+ if not ok_nav:
+ record("computation_storage_props_items", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="value", expect="Size contains 'items'")
+ record("computation_storage_chart_vlm", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="value", tag="shape")
+ return
+ ok_home, _ = reset_home()
+ ham = find_node(ui(), content_desc="Navigate up")
+ if not ok_home or ham is None or not tap_node(ham):
+ record("computation_storage_props_items", False,
+ "setup_failed: could not open the navigation drawer",
+ depth=1, jump_kind="value", expect="Size contains 'items'")
+ record("computation_storage_chart_vlm", False,
+ "setup_failed: could not open the navigation drawer",
+ depth=1, jump_kind="value", tag="shape")
+ return
+ settle("tap")
+ dnodes = ui()
+ # The Internal Storage row's action button opens its volume Properties.
+ target = None
+ for n in dnodes:
+ if n.get("resource-id", "").endswith("imageButton"):
+ b = n.get("_bounds")
+ if b and b[1] < 720:
+ target = n
+ break
+ and_enter("drawer")
+ if target is None or not safe_tap(target):
+ record("computation_storage_props_items", False,
+ "setup_failed: no Internal Storage action button in drawer",
+ depth=1, jump_kind="value", expect="Size contains 'items'")
+ record("computation_storage_chart_vlm", False,
+ "setup_failed: no Internal Storage action button in drawer",
+ depth=1, jump_kind="value", tag="shape")
+ return
+ settle("tap")
+ dlg = ui()
+ size_v = prop_value(dlg, "t7")
+ is_props = node_by_id(dlg, "md_title") is not None and prop_value(dlg, "title_size") == "Size"
+ ok = is_props and "items" in size_v
+ record("computation_storage_props_items", ok,
+ "" if ok else f"behavior_wrong: storage volume Size={size_v!r}, expected a "
+ f"string containing 'items'",
+ depth=1, jump_kind="value", expect="Size contains 'items' (volume child count)")
+ # VLM: the storage volume's usage chart (canvas).
+ if node_by_id(dlg, "chart") is not None:
+ vlm_assert("computation_storage_chart",
+ "Is a circular/ring storage-usage chart graphic rendered in this "
+ "dialog showing how full the storage is?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="shape")
+ else:
+ record("computation_storage_chart_vlm", False,
+ "setup_failed: no chart node in storage volume Properties",
+ depth=1, jump_kind="value", tag="shape")
+ close_properties()
+
+
+TESTS = [
+ test_count_probe,
+ test_count_download,
+ test_count_after_create_folder,
+ test_count_after_create_file,
+ test_count_delete_restores,
+ test_properties_alpha_file,
+ test_properties_folder,
+ test_sort_name_ascending,
+ test_sort_name_descending,
+ test_sort_order_flips,
+ test_storage_volume_properties,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_interaction.py b/android/teamamaze-amazefilemanager/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..976c2a463ab037fd8423eda8cb21a7e430a52b4d
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_interaction.py
@@ -0,0 +1,1265 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — Amaze File Manager.
+
+Owns EFFECT-BY-CONSEQUENCE on user DATA: file/folder CRUD, 3+-step sequences,
+multi-record integrity, DATA persistence across process death, and (sole owner)
+long-press / context menus. Every case drives the running app to the surface via
+the real user path, performs the mutation, then reads the CONSEQUENCE back out of
+a FRESH ui() and asserts it against what was observed — never mere existence.
+
+Three app quirks the whole file respects (recon.md + live probing):
+ * LeakCanary hijacks the launcher, so a `monkey` launch lands on the system
+ launcher ~40-67% of the time. and_enter_amaze() RELAUNCHES (restart_app) up to
+ 12x until get_current_activity() contains "MainActivity", then polls the dump
+ until the browser's `fullpath` has actually rendered (the first post-launch
+ dump is often empty). RELAUNCH is never a jump — it does not back a depth claim.
+ * The app persists the last-opened directory across process death, so after a
+ relaunch it may NOT be at root. reset_home() taps the Home toolbar button until
+ the browser shows /storage/emulated/0.
+ * The "New File" dialog PRE-FILLS its input with ".txt"; the "New Folder" dialog
+ starts empty. create_file() therefore clears the field before typing, so the
+ name is exactly what we assert (verified live: a raw type_text produced the
+ invalid ".txtAmzF_..." and no file was created).
+
+SAFETY: this lane creates and deletes DATA. Every created item has a unique
+marker name (AmzTest__), so reruns never collide and a stray row can
+never match pre-existing content. We delete ONLY items we just created, by driving
+the GUI (long-press -> CAB Delete -> confirm the "Delete items permanently?"
+positive button, which we accept ONLY for our own Amz* items). The fixture folder
+amaze_probe (alpha/beta/gamma.txt) and shared system folders are never mutated;
+copy is non-destructive and leaves the original in place (verified).
+"""
+import os, sys, time
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+require_kit(1)
+
+ROOT = "/storage/emulated/0"
+
+
+def uniq(tag):
+ """A collision-proof marker for a created item. The Amz prefix guarantees a
+ read-back can never accidentally match a pre-existing row, and per-test tag +
+ millisecond suffix keep reruns from colliding with each other."""
+ return f"Amz{tag}_{int(time.time() * 1000) % 1000000}"
+
+
+# ── setup helpers (RELAUNCH / navigation — the and_reach_*/and_enter_* NAME is what
+# the depth audit keys off; the implementation is ours) ─────────────────────────
+def and_enter_amaze(max_tries=12):
+ """Land on Amaze's MainActivity with the file browser rendered. Retries past
+ LeakCanary's launcher hijack / a stalled monkey launch, then polls the dump
+ until `fullpath` exists. Returns (ok, nodes). A RELAUNCH, not navigation."""
+ for _ in range(max_tries):
+ restart_app()
+ if not wait_for_foreground(10):
+ continue
+ if "MainActivity" not in get_current_activity():
+ continue
+ for _ in range(6):
+ settle("dump")
+ nodes = ui()
+ if node_by_id(nodes, "fullpath") is not None:
+ return True, nodes
+ return False, []
+
+
+def reset_home():
+ """Tap the Home toolbar button until the browser shows ROOT, defeating the
+ persisted last-opened directory. Returns (ok, nodes)."""
+ for _ in range(5):
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ if fp is not None and fp.get("text", "") == ROOT:
+ return True, nodes
+ h = find_node(nodes, content_desc="Home")
+ if h:
+ tap_node(h)
+ else:
+ settle("dump")
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ return (fp is not None and fp.get("text", "") == ROOT), nodes
+
+
+def at_amaze_home(tries=3):
+ """(ok, nodes): freshly on MainActivity showing the ROOT listing. Retries the
+ whole enter+home sequence so a single flaky dump does not strand a test."""
+ for _ in range(tries):
+ ok, _ = and_enter_amaze()
+ if ok:
+ home_ok, nodes = reset_home()
+ if home_ok:
+ return True, nodes
+ return False, []
+
+
+def row_by_name(nodes, name):
+ """The list row's `firstline` TextView whose text == name (exact)."""
+ for n in nodes:
+ if n.get("resource-id", "").endswith("/firstline") and n.get("text", "") == name:
+ return n
+ return None
+
+
+def has_row(nodes, name):
+ return row_by_name(nodes, name) is not None
+
+
+def count_text(nodes):
+ """`pathname` text, e.g. '13 folders and 2 files' — the live folder count."""
+ pn = node_by_id(nodes, "pathname")
+ return pn.get("text", "") if pn else ""
+
+
+def folder_count(nodes):
+ """The integer 'N folders' from the pathname bar, or None if not parseable.
+ Re-reads a settled dump-derived text, so callers get the current live count."""
+ import re as _re
+ m = _re.search(r"(\d+)\s+folders?", count_text(nodes))
+ return int(m.group(1)) if m else None
+
+
+def open_fab_menu():
+ """Expand the collapsed FAB (`sd_main_fab`); return True once Folder/File show."""
+ fab = node_by_id(ui(), "sd_main_fab")
+ if not tap_node(fab):
+ return False
+ settle("tap")
+ return find_node(ui(), content_desc="Folder") is not None
+
+
+def clear_input(node):
+ """Empty an EditText via MOVE_END + repeated DEL/FORWARD_DEL. Used for the
+ ".txt"-prefilled New File field and the pre-filled Rename field. Not a pixel
+ tap — it drives keyevents on the focused field."""
+ tap_node(node)
+ settle("keyboard")
+ adb_shell("input", "keyevent", "KEYCODE_MOVE_END")
+ for _ in range(48):
+ adb_shell("input", "keyevent", "KEYCODE_DEL")
+ for _ in range(12):
+ adb_shell("input", "keyevent", "KEYCODE_FORWARD_DEL")
+ settle("text")
+
+
+def create_folder(name):
+ """FAB -> Folder -> type name -> CREATE. Returns True if the CREATE button
+ ended up enabled and was tapped (i.e. the name was accepted)."""
+ if not open_fab_menu():
+ return False
+ if not tap_node(find_node(ui(), content_desc="Folder")):
+ return False
+ settle("tap")
+ inp = node_by_id(ui(), "singleedittext_input")
+ if inp is None:
+ return False
+ type_text(inp, name)
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ if pos is None or pos.get("enabled") != "true":
+ return False
+ tap_node(pos)
+ settle("tap")
+ return True
+
+
+def create_file(name):
+ """FAB -> File -> CLEAR the '.txt' prefill -> type name -> CREATE."""
+ if not open_fab_menu():
+ return False
+ if not tap_node(find_node(ui(), content_desc="File")):
+ return False
+ settle("tap")
+ inp = node_by_id(ui(), "singleedittext_input")
+ if inp is None:
+ return False
+ clear_input(inp)
+ inp = node_by_id(ui(), "singleedittext_input") or inp
+ type_text(inp, name)
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ if pos is None or pos.get("enabled") != "true":
+ return False
+ tap_node(pos)
+ settle("tap")
+ return True
+
+
+def open_context_menu(name):
+ """Open the per-row 3-dot context menu for the row whose firstline == name.
+ Returns (before_snapshot, ok). The row's Properties (3-dot) button sits on the
+ same visual row, far right."""
+ nodes = ui()
+ row = row_by_name(nodes, name)
+ if not row or "_bounds" not in row:
+ return set(), False
+ ry = row["_bounds"][1]
+ best, best_dy = None, 10 ** 9
+ for n in nodes:
+ if n.get("resource-id", "").endswith("/properties") and "_bounds" in n:
+ dy = abs(n["_bounds"][1] - ry)
+ if dy < best_dy:
+ best, best_dy = n, dy
+ if not best or best_dy > 200:
+ return set(), False
+ before = and_showing(nodes)
+ tap_node(best)
+ settle("tap")
+ return before, True
+
+
+def cab_delete_confirm(name):
+ """Long-press the row `name`, tap the CAB Delete, confirm the
+ 'Delete items permanently?' positive button. Accepts the destructive confirm
+ ONLY because `name` is a marker item this suite created. Returns True if the
+ row is gone afterwards."""
+ row = scroll_into_view(name)
+ if row is None:
+ return False
+ long_press(row)
+ settle("tap")
+ dele = node_by_id(ui(), "delete") or find_node(ui(), content_desc="Delete")
+ if not tap_node(dele):
+ return False
+ settle("tap")
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ if pos is not None and pos.get("text", "").strip().lower() == "delete":
+ tap_node(pos)
+ settle("tap")
+ return scroll_into_view(name, max_swipes=2) is None
+
+
+def cleanup(name):
+ """Best-effort GUI cleanup of a created item: return to ROOT and delete it."""
+ try:
+ h = find_node(ui(), content_desc="Home")
+ if h:
+ tap_node(h)
+ settle("tap")
+ cab_delete_confirm(name)
+ except Exception:
+ pass
+
+
+def and_enter_folder(name):
+ """Tap the row `name` to descend into it; confirm the fullpath now ends with
+ the folder name. Counts one surface (backs a depth>=1 claim)."""
+ row = scroll_into_view(name)
+ if row is None:
+ return False
+ tap_node(row)
+ settle("tap")
+ fp = node_by_id(ui(), "fullpath")
+ if fp is not None and fp.get("text", "").rstrip("/").endswith(name):
+ and_enter(name)
+ return True
+ return False
+
+
+def selection_count(nodes=None):
+ """The `item_count` text in the CAB, or '' when not in selection mode."""
+ nodes = ui() if nodes is None else nodes
+ ic = node_by_id(nodes, "item_count")
+ return ic.get("text", "") if ic else ""
+
+
+SS = os.path.join(RESULTS_DIR, "screenshots")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# CREATE — a row appears and the folder count increments
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_create_folder", "interaction_create_folder_vlm"))
+def test_create_folder():
+ ok, nodes = at_amaze_home()
+ name = uniq("NewFolder")
+ if not ok:
+ record("interaction_create_folder", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"row {name!r} present + count +1")
+ vlm_assert("interaction_create_folder", "unreached", SS,
+ jump_kind="value", tag="content")
+ return
+ absent_before = not has_row(nodes, name)
+ before_count = count_text(nodes)
+ if not create_folder(name):
+ record("interaction_create_folder", False,
+ "feature_missing: FAB->Folder->CREATE path not available",
+ jump_kind="value", expect=f"row {name!r} present + count +1")
+ vlm_assert("interaction_create_folder", "unreached", SS,
+ jump_kind="value", tag="content")
+ return
+ row = scroll_into_view(name)
+ after = ui()
+ after_count = count_text(after)
+ present_after = row is not None
+ count_grew = ("folders" in before_count and "folders" in after_count
+ and after_count != before_count)
+ ok2 = absent_before and present_after and count_grew
+ record("interaction_create_folder", ok2,
+ "" if ok2 else f"behavior_wrong: create did not land "
+ f"(absent_before={absent_before}, present_after={present_after}, "
+ f"{before_count!r}->{after_count!r})",
+ jump_kind="value",
+ expect=f"row {name!r} present; count {before_count!r}->{after_count!r}")
+ # VLM: the freshly created folder row is visible in the list
+ vlm_assert("interaction_create_folder",
+ f"Is there a folder row labelled '{name}' visible in this file list?",
+ SS, jump_kind="value", tag="content")
+ cleanup(name)
+
+
+@and_test(expects=("interaction_create_file",))
+def test_create_file():
+ ok, nodes = at_amaze_home()
+ name = uniq("NewFile") + ".txt"
+ if not ok:
+ record("interaction_create_file", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"file row {name!r} present + count +1")
+ return
+ absent_before = not has_row(nodes, name)
+ before_count = count_text(nodes)
+ if not create_file(name):
+ record("interaction_create_file", False,
+ "feature_missing: FAB->File->CREATE path not available",
+ jump_kind="value", expect=f"file row {name!r} present + count +1")
+ return
+ row = scroll_into_view(name, max_swipes=6)
+ after_count = count_text(ui())
+ present_after = row is not None
+ count_grew = ("files" in before_count and "files" in after_count
+ and after_count != before_count)
+ ok2 = absent_before and present_after and count_grew
+ record("interaction_create_file", ok2,
+ "" if ok2 else f"behavior_wrong: create-file did not land "
+ f"(absent_before={absent_before}, present_after={present_after}, "
+ f"{before_count!r}->{after_count!r})",
+ jump_kind="value",
+ expect=f"file row {name!r} present; count {before_count!r}->{after_count!r}")
+ cleanup(name)
+
+
+@and_test(expects=("interaction_create_delete_roundtrip",))
+def test_create_delete_roundtrip():
+ """3-step data lifecycle: create A (present) -> long-press -> CAB Delete ->
+ confirm -> A gone and count back down. Asserts the absent->present->absent flip
+ AND the count returning, which an in-memory stub that never truly deletes fails."""
+ ok, nodes = at_amaze_home()
+ name = uniq("Roundtrip")
+ if not ok:
+ record("interaction_create_delete_roundtrip", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"{name!r} present then absent")
+ return
+ # Re-read the base folder count from a freshly settled dump right before create,
+ # so a stale first dump can't poison the comparison. Assert a NUMERIC delta
+ # (create -> +1 folder, delete -> back to base) plus the row absent->present->
+ # absent flip — the flip is the deterministic core; the delta corroborates it.
+ settle("dump")
+ base_n = folder_count(ui())
+ if not create_folder(name):
+ record("interaction_create_delete_roundtrip", False,
+ "feature_missing: create path unavailable",
+ jump_kind="value", expect=f"{name!r} present then absent")
+ return
+ present = scroll_into_view(name) is not None
+ after_create_n = folder_count(ui())
+ gone = cab_delete_confirm(name)
+ settle("dump")
+ final_n = folder_count(ui())
+ # count went up by 1 on create and back down to base on delete
+ count_ok = (base_n is not None and after_create_n is not None
+ and final_n is not None
+ and after_create_n == base_n + 1 and final_n == base_n)
+ ok2 = present and gone and count_ok
+ record("interaction_create_delete_roundtrip", ok2,
+ "" if ok2 else f"behavior_wrong: round-trip failed "
+ f"(present_after_create={present}, gone_after_delete={gone}, "
+ f"folders base={base_n} after_create={after_create_n} final={final_n})",
+ jump_kind="value",
+ expect=f"{name!r} created (folders {base_n}->{base_n+1 if base_n is not None else '?'}) "
+ f"then deleted (folders back to {base_n})")
+ if not gone:
+ cleanup(name)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# LONG-PRESS / SELECTION — sole owner
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_longpress_selection",
+ "interaction_longpress_selection_vlm"))
+def test_longpress_selection():
+ """Long-press a row -> selection mode: action_mode_bar appears, item_count=1,
+ the row shows a check overlay. An absent->present state flip (transition)."""
+ ok, nodes = at_amaze_home()
+ if not ok:
+ record("interaction_longpress_selection", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="transition", expect="action_mode_bar + item_count=1")
+ vlm_assert("interaction_longpress_selection", "unreached", SS,
+ jump_kind="transition", tag="color")
+ return
+ bar_before = node_by_id(nodes, "action_mode_bar") is not None
+ target = row_by_name(nodes, "Alarms") or find_node(nodes, text="Android")
+ if target is None:
+ record("interaction_longpress_selection", False,
+ "setup_failed: no folder row to long-press",
+ jump_kind="transition", expect="action_mode_bar + item_count=1")
+ vlm_assert("interaction_longpress_selection", "unreached", SS,
+ jump_kind="transition", tag="color")
+ return
+ long_press(target)
+ settle("tap")
+ after = ui()
+ bar_after = node_by_id(after, "action_mode_bar") is not None
+ count1 = selection_count(after) == "1"
+ check = node_by_id(after, "check_icon") is not None
+ ok2 = (not bar_before) and bar_after and count1
+ record("interaction_longpress_selection", ok2,
+ "" if ok2 else f"behavior_wrong: long-press did not enter selection "
+ f"(bar_before={bar_before}, bar_after={bar_after}, "
+ f"item_count={selection_count(after)!r}, check_icon={check})",
+ jump_kind="transition",
+ expect="action_mode_bar appeared, item_count='1'")
+ # VLM: the selected row is visually highlighted with a check overlay
+ vlm_assert("interaction_longpress_selection",
+ "Is exactly one file/folder row visually selected, shown by a "
+ "checkmark badge over its icon or a tinted/highlighted row "
+ "background?", SS, jump_kind="transition", tag="color")
+ # exit selection without touching data
+ done = node_by_id(ui(), "action_mode_close_button") or find_node(ui(), content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+
+
+@and_test(expects=("interaction_multiselect_count",
+ "interaction_multiselect_count_vlm"))
+def test_multiselect_count():
+ """Long-press row A (count 1), tap row B -> item_count='2'. The count VALUE is
+ the consequence; a dead shell that only echoes the first selection stays at 1."""
+ ok, nodes = at_amaze_home()
+ if not ok:
+ record("interaction_multiselect_count", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect="item_count='2'")
+ vlm_assert("interaction_multiselect_count", "unreached", SS,
+ jump_kind="value", tag="color")
+ return
+ a = row_by_name(nodes, "Alarms")
+ b = row_by_name(nodes, "Android")
+ if a is None or b is None:
+ record("interaction_multiselect_count", False,
+ "setup_failed: need two distinct folder rows",
+ jump_kind="value", expect="item_count='2'")
+ vlm_assert("interaction_multiselect_count", "unreached", SS,
+ jump_kind="value", tag="color")
+ return
+ long_press(a)
+ settle("tap")
+ count_one = selection_count() == "1"
+ b = row_by_name(ui(), "Android")
+ tap_node(b)
+ settle("tap")
+ count_two = selection_count() == "2"
+ ok2 = count_one and count_two
+ record("interaction_multiselect_count", ok2,
+ "" if ok2 else f"behavior_wrong: multi-select count wrong "
+ f"(after A={count_one}, after B item_count={selection_count()!r})",
+ jump_kind="value", expect="item_count '1' after A, '2' after B")
+ # VLM: two rows now show as selected
+ vlm_assert("interaction_multiselect_count",
+ "Are exactly two file/folder rows visually selected (each with a "
+ "checkmark badge or highlighted background)?",
+ SS, jump_kind="value", tag="color")
+ done = node_by_id(ui(), "action_mode_close_button") or find_node(ui(), content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+
+
+@and_test(expects=("interaction_deselect_toggle",))
+def test_deselect_toggle():
+ """Select A (count 1), tap A again -> deselected (count drops to '' as
+ selection exits, or back to a lower count). A before->after state flip."""
+ ok, nodes = at_amaze_home()
+ if not ok:
+ record("interaction_deselect_toggle", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="transition", expect="selection cleared after re-tap")
+ return
+ # select two so that re-tapping one leaves a well-defined lower count
+ a = row_by_name(nodes, "Alarms")
+ b = row_by_name(nodes, "Android")
+ if a is None or b is None:
+ record("interaction_deselect_toggle", False,
+ "setup_failed: need two folder rows",
+ jump_kind="transition", expect="count decremented after re-tap")
+ return
+ long_press(a)
+ settle("tap")
+ b = row_by_name(ui(), "Android")
+ tap_node(b)
+ settle("tap")
+ count_two = selection_count() == "2"
+ # re-tap Android to deselect it -> count back to 1
+ b = row_by_name(ui(), "Android")
+ tap_node(b)
+ settle("tap")
+ count_back_one = selection_count() == "1"
+ ok2 = count_two and count_back_one
+ record("interaction_deselect_toggle", ok2,
+ "" if ok2 else f"behavior_wrong: re-tap did not deselect "
+ f"(count_two={count_two}, after re-tap item_count={selection_count()!r})",
+ jump_kind="transition",
+ expect="item_count '2' -> '1' after re-tapping the same row")
+ done = node_by_id(ui(), "action_mode_close_button") or find_node(ui(), content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+
+
+@and_test(expects=("interaction_select_all", "interaction_select_all_vlm"))
+def test_select_all():
+ """In selection, CAB overflow -> 'Select All' -> item_count equals the folder's
+ row count. Run inside the fixture folder amaze_probe (exactly 3 files, all
+ rendered) so the count is deterministic — at the shared root the RecyclerView
+ lazy-loads only a subset of rows, so item_count would not match the disk count."""
+ ok, nodes = at_amaze_home()
+ reached = ok and and_enter_folder("Download") and and_enter_folder("amaze_probe")
+ if not reached:
+ record("interaction_select_all", False,
+ "setup_failed: could not reach Download/amaze_probe",
+ depth=2, jump_kind="value", expect="item_count == 3 (amaze_probe files)")
+ vlm_assert("interaction_select_all", "unreached", SS,
+ jump_kind="value", tag="color")
+ return
+ nodes = ui()
+ # amaze_probe holds exactly the 3 fixture files.
+ total = 3
+ a = row_by_name(nodes, "alpha.txt") or find_node(nodes, text="alpha.txt")
+ if a is None:
+ record("interaction_select_all", False,
+ "setup_failed: alpha.txt row not visible in amaze_probe",
+ depth=2, jump_kind="value", expect="item_count == 3 (amaze_probe files)")
+ vlm_assert("interaction_select_all", "unreached", SS,
+ jump_kind="value", tag="color")
+ return
+ long_press(a)
+ settle("tap")
+ # CAB overflow: the "More options" whose y is inside the action_mode_bar band
+ over = None
+ for n in ui():
+ if (n.get("content-desc") == "More options" and "_bounds" in n
+ and 100 < n["_bounds"][1] < 320):
+ over = n
+ if over is None or not tap_node(over):
+ record("interaction_select_all", False,
+ "feature_missing: CAB overflow not found",
+ depth=2, jump_kind="value", expect="item_count == 3 (amaze_probe files)")
+ vlm_assert("interaction_select_all", "unreached", SS,
+ jump_kind="value", tag="color")
+ done = node_by_id(ui(), "action_mode_close_button")
+ if done:
+ tap_node(done)
+ return
+ settle("tap")
+ sa = find_node(ui(), text="Select All") or find_node_ci(ui(), "Select all")
+ if sa is None or not tap_node(sa):
+ record("interaction_select_all", False,
+ "feature_missing: 'Select All' item not in CAB overflow",
+ depth=2, jump_kind="value", expect="item_count == 3 (amaze_probe files)")
+ vlm_assert("interaction_select_all", "unreached", SS,
+ jump_kind="value", tag="color")
+ back()
+ done = node_by_id(ui(), "action_mode_close_button")
+ if done:
+ tap_node(done)
+ return
+ settle("tap")
+ got = selection_count()
+ ok2 = got == str(total)
+ record("interaction_select_all", ok2,
+ "" if ok2 else f"behavior_wrong: Select All count {got!r} != {total} "
+ f"(amaze_probe has 3 files)",
+ depth=2, jump_kind="value", expect=f"item_count '{total}' after Select All in amaze_probe")
+ # VLM: all visible rows now read as selected
+ vlm_assert("interaction_select_all",
+ "Do all of the visible file/folder rows appear selected (each shows "
+ "a checkmark badge or highlighted background)?",
+ SS, jump_kind="value", tag="color")
+ done = node_by_id(ui(), "action_mode_close_button") or find_node(ui(), content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+
+
+@and_test(expects=("interaction_exit_selection",))
+def test_exit_selection():
+ """Enter selection, tap Done -> action_mode_bar gone, item_count no longer
+ present. The reverse state flip of long-press."""
+ ok, nodes = at_amaze_home()
+ if not ok:
+ record("interaction_exit_selection", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="transition", expect="action_mode_bar removed after Done")
+ return
+ a = row_by_name(nodes, "Alarms") or find_node(nodes, text="Android")
+ if a is None:
+ record("interaction_exit_selection", False,
+ "setup_failed: no row to select",
+ jump_kind="transition", expect="action_mode_bar removed after Done")
+ return
+ long_press(a)
+ settle("tap")
+ bar_on = node_by_id(ui(), "action_mode_bar") is not None
+ done = node_by_id(ui(), "action_mode_close_button") or find_node(ui(), content_desc="Done")
+ if done is None or not tap_node(done):
+ record("interaction_exit_selection", False,
+ "feature_missing: Done (action_mode_close_button) not found",
+ jump_kind="transition", expect="action_mode_bar removed after Done")
+ return
+ settle("tap")
+ after = ui()
+ bar_off = node_by_id(after, "action_mode_bar") is None
+ count_gone = node_by_id(after, "item_count") is None
+ ok2 = bar_on and bar_off and count_gone
+ record("interaction_exit_selection", ok2,
+ "" if ok2 else f"behavior_wrong: selection did not exit "
+ f"(bar_on={bar_on}, bar_off={bar_off}, count_gone={count_gone})",
+ jump_kind="transition",
+ expect="action_mode_bar present -> removed after Done")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# CONTEXT MENU + RENAME (sole owner of context menus)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_context_menu_opens",))
+def test_context_menu_opens():
+ """Tap a row's 3-dot -> popup with Cut/Copy/Delete/Rename/... appears. A real
+ overlay-surface transition: the menu items are new keys not in the list."""
+ ok, nodes = at_amaze_home()
+ if not ok:
+ record("interaction_context_menu_opens", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="transition", expect="context menu Rename/Copy appeared")
+ return
+ target = row_by_name(nodes, "Alarms") or find_node(nodes, text="Android")
+ if target is None:
+ record("interaction_context_menu_opens", False,
+ "setup_failed: no row for context menu",
+ jump_kind="transition", expect="context menu Rename/Copy appeared")
+ return
+ name = target.get("text")
+ before, opened = open_context_menu(name)
+ if not opened:
+ record("interaction_context_menu_opens", False,
+ "feature_missing: per-row Properties 3-dot not found",
+ jump_kind="transition", expect="context menu Rename/Copy appeared")
+ return
+ after = and_showing()
+ items = [find_node(ui(), text=t) is not None
+ for t in ("Cut", "Copy", "Delete", "Rename", "Properties")]
+ appeared = and_reach(before, after, "Rename")
+ ok2 = appeared and sum(items) >= 4
+ record("interaction_context_menu_opens", ok2,
+ "" if ok2 else f"behavior_wrong: context menu incomplete "
+ f"(Rename appeared={appeared}, items_found={sum(items)}/5)",
+ jump_kind="transition",
+ expect="popup with Cut/Copy/Delete/Rename/Properties")
+ back() # dismiss the popup, mutating nothing
+
+
+@and_test(expects=("interaction_rename", "interaction_rename_vlm"))
+def test_rename():
+ """Create R, context -> Rename -> clear -> type R2 -> SAVE. Read back: R2 row
+ present, R row absent. The name VALUE changed on disk."""
+ ok, _ = at_amaze_home()
+ old = uniq("Rename")
+ new = old + "b"
+ if not ok:
+ record("interaction_rename", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"row {new!r} present, {old!r} absent")
+ vlm_assert("interaction_rename", "unreached", SS,
+ jump_kind="value", tag="content")
+ return
+ if not create_folder(old):
+ record("interaction_rename", False,
+ "feature_missing: create path unavailable",
+ jump_kind="value", expect=f"row {new!r} present, {old!r} absent")
+ vlm_assert("interaction_rename", "unreached", SS,
+ jump_kind="value", tag="content")
+ return
+ scroll_into_view(old)
+ _before, opened = open_context_menu(old)
+ rn = find_node(ui(), text="Rename")
+ if not opened or rn is None or not tap_node(rn):
+ record("interaction_rename", False,
+ "feature_missing: Rename not in context menu",
+ jump_kind="value", expect=f"row {new!r} present, {old!r} absent")
+ vlm_assert("interaction_rename", "unreached", SS,
+ jump_kind="value", tag="content")
+ cleanup(old)
+ return
+ settle("tap")
+ inp = node_by_id(ui(), "singleedittext_input")
+ if inp is None:
+ record("interaction_rename", False,
+ "setup_failed: Rename dialog has no input",
+ jump_kind="value", expect=f"row {new!r} present, {old!r} absent")
+ vlm_assert("interaction_rename", "unreached", SS,
+ jump_kind="value", tag="content")
+ cleanup(old)
+ return
+ clear_input(inp)
+ inp = node_by_id(ui(), "singleedittext_input") or inp
+ type_text(inp, new)
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ tap_node(pos)
+ settle("tap")
+ new_present = scroll_into_view(new) is not None
+ after = ui()
+ old_absent = not has_row(after, old)
+ ok2 = new_present and old_absent
+ record("interaction_rename", ok2,
+ "" if ok2 else f"behavior_wrong: rename did not land "
+ f"(new_present={new_present}, old_absent={old_absent})",
+ jump_kind="value", expect=f"row {new!r} present, {old!r} absent")
+ # VLM: the renamed row is visible with its new name
+ vlm_assert("interaction_rename",
+ f"Is there a folder row labelled '{new}' visible in this list?",
+ SS, jump_kind="value", tag="content")
+ cleanup(new)
+ cleanup(old)
+
+
+@and_test(expects=("interaction_rename_persists",))
+def test_rename_persists():
+ """DATA persistence: create + rename, then force_stop_and_relaunch, navigate
+ back to ROOT and assert the renamed folder is STILL there and the old name is
+ gone. An in-memory-only recreation cannot survive the process kill."""
+ ok, _ = at_amaze_home()
+ old = uniq("RenPersist")
+ new = old + "b"
+ if not ok:
+ record("interaction_rename_persists", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"{new!r} survives relaunch")
+ return
+ if not create_folder(old):
+ record("interaction_rename_persists", False,
+ "feature_missing: create path unavailable",
+ jump_kind="value", expect=f"{new!r} survives relaunch")
+ return
+ scroll_into_view(old)
+ _before, opened = open_context_menu(old)
+ rn = find_node(ui(), text="Rename")
+ if not opened or rn is None or not tap_node(rn):
+ record("interaction_rename_persists", False,
+ "feature_missing: Rename not available",
+ jump_kind="value", expect=f"{new!r} survives relaunch")
+ cleanup(old)
+ return
+ settle("tap")
+ inp = node_by_id(ui(), "singleedittext_input")
+ if inp is None:
+ record("interaction_rename_persists", False,
+ "setup_failed: Rename dialog has no input",
+ jump_kind="value", expect=f"{new!r} survives relaunch")
+ cleanup(old)
+ return
+ clear_input(inp)
+ inp = node_by_id(ui(), "singleedittext_input") or inp
+ type_text(inp, new)
+ tap_node(node_by_id(ui(), "md_buttonDefaultPositive"))
+ settle("tap")
+ renamed = scroll_into_view(new) is not None
+ # Kill the process to prove the rename hit disk, then relaunch via the
+ # MainActivity-guaranteed path (raw launch_app lands on LeakCanary ~40%) and
+ # return to ROOT explicitly.
+ force_stop()
+ settle("key")
+ relaunched, _ = and_enter_amaze()
+ home_ok, _ = reset_home() if relaunched else (False, [])
+ survived = scroll_into_view(new) is not None if home_ok else False
+ old_absent = (not has_row(ui(), old)) if home_ok else False
+ ok2 = renamed and home_ok and survived and old_absent
+ record("interaction_rename_persists", ok2,
+ "" if ok2 else f"behavior_wrong: renamed folder did not survive "
+ f"process death (renamed={renamed}, relaunched={relaunched}, "
+ f"home_ok={home_ok}, survived={survived}, old_absent={old_absent})",
+ jump_kind="value", expect=f"row {new!r} present after relaunch, {old!r} gone")
+ cleanup(new)
+ cleanup(old)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# PERSISTENCE ACROSS PROCESS DEATH — the highest-value probes
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_create_persists_in_folder",))
+def test_create_persists_in_folder():
+ """Create parent P at ROOT, descend into it (depth 1), create child C inside,
+ then force_stop_and_relaunch. The app reopens at P's path; assert C is still
+ there. This is the lane's headline test — an in-memory stub loses C."""
+ ok, _ = at_amaze_home()
+ parent = uniq("Parent")
+ child = uniq("Child")
+ if not ok:
+ record("interaction_create_persists_in_folder", False,
+ "setup_failed: could not reach Amaze home",
+ depth=1, jump_kind="value", expect=f"{child!r} survives in {parent!r}")
+ return
+ if not create_folder(parent):
+ record("interaction_create_persists_in_folder", False,
+ "feature_missing: create path unavailable",
+ depth=1, jump_kind="value", expect=f"{child!r} survives in {parent!r}")
+ return
+ if not and_enter_folder(parent):
+ record("interaction_create_persists_in_folder", False,
+ "setup_failed: could not descend into the created folder",
+ depth=1, jump_kind="value", expect=f"{child!r} survives in {parent!r}")
+ cleanup(parent)
+ return
+ if not create_folder(child):
+ record("interaction_create_persists_in_folder", False,
+ "behavior_wrong: could not create a child inside the folder",
+ depth=1, jump_kind="value", expect=f"{child!r} survives in {parent!r}")
+ cleanup(parent)
+ return
+ child_made = scroll_into_view(child) is not None
+ # Kill the process to prove DATA (not just in-memory state) survived. Relaunch
+ # via the MainActivity-guaranteed path (raw launch_app lands on LeakCanary ~40%),
+ # then navigate EXPLICITLY back to parent rather than trusting last-dir
+ # persistence — the disk record of child is what we assert.
+ force_stop()
+ settle("key")
+ relaunched, _ = and_enter_amaze()
+ home_ok, _ = reset_home() if relaunched else (False, [])
+ entered_parent = home_ok and and_enter_folder(parent)
+ survived = entered_parent and scroll_into_view(child) is not None
+ ok2 = child_made and survived
+ record("interaction_create_persists_in_folder", ok2,
+ "" if ok2 else f"behavior_wrong: child did not survive process death "
+ f"(child_made={child_made}, relaunched={relaunched}, home_ok={home_ok}, "
+ f"entered_parent={entered_parent}, survived={survived})",
+ depth=1, jump_kind="value",
+ expect=f"row {child!r} present inside {parent!r} after relaunch")
+ # cleanup: back to root, delete parent (removes child too)
+ cleanup(parent)
+
+
+@and_test(expects=("interaction_multi_record_ordered_persist",))
+def test_multi_record_ordered_persist():
+ """Multi-record integrity across process death: create folder P, put THREE
+ children A/B/C inside (depth 1), kill+relaunch, then assert ALL THREE are still
+ present and in Name-ascending order (A before B before C). A recreation that
+ keeps only one row, or loses order, fails here."""
+ ok, _ = at_amaze_home()
+ parent = uniq("MRP")
+ tag = str(int(time.time() * 1000) % 100000)
+ a, b, c = f"AmzA_{tag}", f"AmzB_{tag}", f"AmzC_{tag}"
+ if not ok:
+ record("interaction_multi_record_ordered_persist", False,
+ "setup_failed: could not reach Amaze home",
+ depth=1, jump_kind="value", expect=f"{a},{b},{c} survive ordered")
+ return
+ if not create_folder(parent) or not and_enter_folder(parent):
+ record("interaction_multi_record_ordered_persist", False,
+ "feature_missing: create/descend path unavailable",
+ depth=1, jump_kind="value", expect=f"{a},{b},{c} survive ordered")
+ cleanup(parent)
+ return
+ made = all(create_folder(x) and scroll_into_view(x) is not None for x in (a, b, c))
+ if not made:
+ record("interaction_multi_record_ordered_persist", False,
+ "behavior_wrong: could not create all three children",
+ depth=1, jump_kind="value", expect=f"{a},{b},{c} survive ordered")
+ cleanup(parent)
+ return
+ # Kill the process to prove the DATA survived, then relaunch via the
+ # MainActivity-guaranteed path (raw launch_app lands on LeakCanary ~40%) and
+ # navigate EXPLICITLY back into parent — trusting last-dir persistence after a
+ # force-stop is a coin flip that makes this test flaky.
+ force_stop()
+ settle("key")
+ relaunched, _ = and_enter_amaze()
+ home_ok, _ = reset_home() if relaunched else (False, [])
+ entered_parent = home_ok and and_enter_folder(parent)
+ # read the full ordered list of firstline rows (page from top)
+ seen = []
+ if entered_parent:
+ scroll_into_view(a)
+ for _ in range(6):
+ for n in ui():
+ if n.get("resource-id", "").endswith("/firstline"):
+ t = n.get("text", "")
+ if t and t not in seen:
+ seen.append(t)
+ scroll_down(0.5)
+ present = {x: (x in seen) for x in (a, b, c)}
+ all_present = all(present.values())
+ order_ok = False
+ if all_present:
+ ia, ib, ic = seen.index(a), seen.index(b), seen.index(c)
+ order_ok = ia < ib < ic
+ ok2 = all_present and order_ok
+ record("interaction_multi_record_ordered_persist", ok2,
+ "" if ok2 else f"behavior_wrong: three children not all present/ordered "
+ f"after relaunch (relaunched={relaunched}, entered_parent={entered_parent}, "
+ f"present={present}, order_ok={order_ok})",
+ depth=1, jump_kind="value",
+ expect=f"{a}<{b}<{c} all present and Name-ascending after relaunch")
+ cleanup(parent)
+
+
+@and_test(expects=("interaction_delete_reduces_count",))
+def test_delete_reduces_count():
+ """Multi-record integrity inside a folder (depth 1): create two children, then
+ delete ONE and assert the OTHER stays and the count drops by exactly one — a
+ recreation that recreates the whole list on any edit fails to keep the sibling."""
+ ok, _ = at_amaze_home()
+ parent = uniq("DelCount")
+ keep = uniq("Keep")
+ drop = uniq("Drop")
+ if not ok:
+ record("interaction_delete_reduces_count", False,
+ "setup_failed: could not reach Amaze home",
+ depth=1, jump_kind="value", expect=f"{keep!r} stays, count -1")
+ return
+ if not create_folder(parent) or not and_enter_folder(parent):
+ record("interaction_delete_reduces_count", False,
+ "feature_missing: create/descend path unavailable",
+ depth=1, jump_kind="value", expect=f"{keep!r} stays, count -1")
+ cleanup(parent)
+ return
+ if not (create_folder(keep) and create_folder(drop)):
+ record("interaction_delete_reduces_count", False,
+ "behavior_wrong: could not create both children",
+ depth=1, jump_kind="value", expect=f"{keep!r} stays, count -1")
+ cleanup(parent)
+ return
+ count_two = count_text(ui())
+ gone = cab_delete_confirm(drop)
+ after = ui()
+ keep_row = scroll_into_view(keep) is not None
+ count_one = count_text(after)
+ dropped = count_two != count_one and gone
+ ok2 = gone and keep_row and dropped
+ record("interaction_delete_reduces_count", ok2,
+ "" if ok2 else f"behavior_wrong: sibling integrity failed "
+ f"(dropped={gone}, keep_present={keep_row}, "
+ f"count {count_two!r}->{count_one!r})",
+ depth=1, jump_kind="value",
+ expect=f"{drop!r} deleted, {keep!r} stays; count {count_two!r}->{count_one!r}")
+ cleanup(parent)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# COPY / PASTE and multi-record edit
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_copy_paste",))
+def test_copy_paste():
+ """Copy a fixture file into a folder we own. Navigate to Download/amaze_probe
+ (depth 2), long-press alpha.txt -> CAB Copy, navigate into the created dst
+ folder, tap the Paste affordance, assert alpha.txt now ALSO lives in dst. Copy
+ is non-destructive: the fixture keeps its original (asserted separately)."""
+ ok, _ = at_amaze_home()
+ dst = uniq("Dst")
+ if not ok:
+ record("interaction_copy_paste", False,
+ "setup_failed: could not reach Amaze home",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ return
+ if not create_folder(dst):
+ record("interaction_copy_paste", False,
+ "feature_missing: create path unavailable",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ return
+ # ROOT -> Download -> amaze_probe (two surfaces down)
+ reset_home()
+ dl = scroll_into_view("Download")
+ if dl is None or not and_enter_folder("Download"):
+ record("interaction_copy_paste", False,
+ "setup_failed: could not open Download",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ if not and_enter_folder("amaze_probe"):
+ record("interaction_copy_paste", False,
+ "setup_failed: could not open the amaze_probe fixture folder",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ alpha = row_by_name(ui(), "alpha.txt")
+ if alpha is None:
+ record("interaction_copy_paste", False,
+ "setup_failed: alpha.txt fixture row missing",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ long_press(alpha)
+ settle("tap")
+ cpy = node_by_id(ui(), "cpy") or find_node(ui(), content_desc="Copy")
+ if cpy is None or not tap_node(cpy):
+ record("interaction_copy_paste", False,
+ "feature_missing: CAB Copy not found",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ settle("tap")
+ # back to ROOT then into dst
+ reset_home()
+ if not and_enter_folder(dst):
+ record("interaction_copy_paste", False,
+ "setup_failed: could not re-open the destination folder",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ paste = find_node(ui(), content_desc="Paste") or find_node_ci(ui(), "Paste")
+ if paste is None or not tap_node(paste):
+ record("interaction_copy_paste", False,
+ "feature_missing: no Paste affordance in the destination",
+ depth=2, jump_kind="value", expect=f"alpha.txt copied into {dst!r}")
+ cleanup(dst)
+ return
+ settle("tap")
+ settle("tap")
+ # some builds show a paste-confirm positive button; accept it if present
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ if pos is not None and pos.get("text", "").strip() and pos.get("text", "").strip().upper() != "OK":
+ # only tap if it clearly confirms a paste (avoid dismissing something else)
+ if pos.get("text", "").strip().lower() in ("paste", "yes", "overwrite", "keep both"):
+ tap_node(pos)
+ settle("tap")
+ pasted = scroll_into_view("alpha.txt", max_swipes=4) is not None
+ record("interaction_copy_paste", pasted,
+ "" if pasted else "behavior_wrong: alpha.txt did not appear in the "
+ "destination after paste",
+ depth=2, jump_kind="value",
+ expect=f"alpha.txt row present inside {dst!r}")
+ cleanup(dst)
+
+
+@and_test(expects=("interaction_multi_record_integrity",))
+def test_multi_record_integrity():
+ """Create THREE folders in a container, rename the 2nd, then assert the 1st and
+ 3rd are UNCHANGED and the 2nd now shows its new name. Catches a recreation that
+ rebuilds the whole list on an edit and drops the untouched siblings."""
+ ok, _ = at_amaze_home()
+ parent = uniq("MRI")
+ tag = str(int(time.time() * 1000) % 100000)
+ r1, r2, r3 = f"AmzOne_{tag}", f"AmzTwo_{tag}", f"AmzTri_{tag}"
+ r2b = r2 + "x"
+ if not ok:
+ record("interaction_multi_record_integrity", False,
+ "setup_failed: could not reach Amaze home",
+ depth=1, jump_kind="value",
+ expect=f"{r1} & {r3} intact, {r2}->{r2b}")
+ return
+ if not create_folder(parent) or not and_enter_folder(parent):
+ record("interaction_multi_record_integrity", False,
+ "feature_missing: create/descend path unavailable",
+ depth=1, jump_kind="value",
+ expect=f"{r1} & {r3} intact, {r2}->{r2b}")
+ cleanup(parent)
+ return
+ if not all(create_folder(x) and scroll_into_view(x) is not None for x in (r1, r2, r3)):
+ record("interaction_multi_record_integrity", False,
+ "behavior_wrong: could not create all three records",
+ depth=1, jump_kind="value",
+ expect=f"{r1} & {r3} intact, {r2}->{r2b}")
+ cleanup(parent)
+ return
+ # rename the 2nd
+ scroll_into_view(r2)
+ _before, opened = open_context_menu(r2)
+ rn = find_node(ui(), text="Rename")
+ if not opened or rn is None or not tap_node(rn):
+ record("interaction_multi_record_integrity", False,
+ "feature_missing: Rename not available",
+ depth=1, jump_kind="value",
+ expect=f"{r1} & {r3} intact, {r2}->{r2b}")
+ cleanup(parent)
+ return
+ settle("tap")
+ inp = node_by_id(ui(), "singleedittext_input")
+ clear_input(inp)
+ inp = node_by_id(ui(), "singleedittext_input") or inp
+ type_text(inp, r2b)
+ tap_node(node_by_id(ui(), "md_buttonDefaultPositive"))
+ settle("tap")
+ # read back: 1st and 3rd unchanged, 2nd renamed, old 2nd gone
+ scroll_into_view(r1)
+ seen = set()
+ for _ in range(5):
+ for n in ui():
+ if n.get("resource-id", "").endswith("/firstline") and n.get("text"):
+ seen.add(n["text"])
+ scroll_down(0.5)
+ one_ok = r1 in seen
+ three_ok = r3 in seen
+ two_new = r2b in seen
+ two_old_gone = r2 not in seen
+ ok2 = one_ok and three_ok and two_new and two_old_gone
+ record("interaction_multi_record_integrity", ok2,
+ "" if ok2 else f"behavior_wrong: multi-record edit corrupted siblings "
+ f"({r1}={one_ok}, {r3}={three_ok}, {r2b}={two_new}, "
+ f"old_gone={two_old_gone})",
+ depth=1, jump_kind="value",
+ expect=f"{r1} & {r3} intact; {r2} renamed to {r2b}")
+ cleanup(parent)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# PROPERTIES + BOOKMARK (context-menu consequences)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_properties_shows_name",
+ "interaction_properties_shows_name_vlm"))
+def test_properties_shows_name():
+ """Create a folder, open its context menu -> Properties, and assert the dialog
+ reports OUR folder's exact name (t5). depth 1: Properties is a dialog surface we
+ opened over the list."""
+ ok, _ = at_amaze_home()
+ name = uniq("Props")
+ if not ok:
+ record("interaction_properties_shows_name", False,
+ "setup_failed: could not reach Amaze home",
+ depth=1, jump_kind="value", expect=f"Properties Name == {name!r}")
+ vlm_assert("interaction_properties_shows_name", "unreached", SS,
+ depth=1, jump_kind="value", tag="shape")
+ return
+ if not create_folder(name):
+ record("interaction_properties_shows_name", False,
+ "feature_missing: create path unavailable",
+ depth=1, jump_kind="value", expect=f"Properties Name == {name!r}")
+ vlm_assert("interaction_properties_shows_name", "unreached", SS,
+ depth=1, jump_kind="value", tag="shape")
+ return
+ scroll_into_view(name)
+ _before, opened = open_context_menu(name)
+ prop = find_node(ui(), text="Properties")
+ if not opened or prop is None or not tap_node(prop):
+ record("interaction_properties_shows_name", False,
+ "feature_missing: Properties not in context menu",
+ depth=1, jump_kind="value", expect=f"Properties Name == {name!r}")
+ vlm_assert("interaction_properties_shows_name", "unreached", SS,
+ depth=1, jump_kind="value", tag="shape")
+ cleanup(name)
+ return
+ and_enter("properties")
+ settle("tap")
+ nodes = ui()
+ title = node_by_id(nodes, "md_title")
+ is_props = title is not None and title.get("text") == "Properties"
+ name_val = None
+ for n in nodes:
+ if n.get("resource-id", "").endswith("/t5"):
+ name_val = n.get("text")
+ if name_val is None:
+ tn = node_by_id(nodes, "title_name")
+ name_val = tn.get("text") if tn else None
+ ok2 = is_props and name_val == name
+ record("interaction_properties_shows_name", ok2,
+ "" if ok2 else f"behavior_wrong: Properties name mismatch "
+ f"(is_props={is_props}, name_val={name_val!r}, want={name!r})",
+ depth=1, jump_kind="value",
+ expect=f"Properties dialog Name field == {name!r}")
+ # VLM: the storage-usage ring/pie chart (canvas — not in the dump) is rendered
+ vlm_assert("interaction_properties_shows_name",
+ "Is a circular pie or ring chart of storage usage displayed inside "
+ "this Properties dialog?", SS, depth=1, jump_kind="value", tag="shape")
+ okbtn = node_by_id(ui(), "md_buttonDefaultPositive")
+ if okbtn:
+ tap_node(okbtn)
+ settle("tap")
+ cleanup(name)
+
+
+@and_test(expects=("interaction_add_bookmark",))
+def test_add_bookmark():
+ """Create a folder, context -> Add to Bookmarks, then open the drawer and
+ assert the folder now appears as a drawer bookmark row (its name is a NEW
+ `design_menu_item_text` entry)."""
+ ok, _ = at_amaze_home()
+ name = uniq("Bmk")
+ if not ok:
+ record("interaction_add_bookmark", False,
+ "setup_failed: could not reach Amaze home",
+ jump_kind="value", expect=f"drawer bookmark {name!r} present")
+ return
+ if not create_folder(name):
+ record("interaction_add_bookmark", False,
+ "feature_missing: create path unavailable",
+ jump_kind="value", expect=f"drawer bookmark {name!r} present")
+ return
+ scroll_into_view(name)
+ _before, opened = open_context_menu(name)
+ addbm = find_node(ui(), text="Add to Bookmarks") or find_node_ci(ui(), "Add to Bookmarks")
+ if not opened or addbm is None or not tap_node(addbm):
+ record("interaction_add_bookmark", False,
+ "feature_missing: 'Add to Bookmarks' not in context menu",
+ jump_kind="value", expect=f"drawer bookmark {name!r} present")
+ cleanup(name)
+ return
+ settle("tap")
+ # some builds show a name-the-bookmark dialog; confirm it if present
+ pos = node_by_id(ui(), "md_buttonDefaultPositive")
+ if pos is not None and pos.get("text", "").strip():
+ tap_node(pos)
+ settle("tap")
+ # open the drawer and look for the bookmark row by its exact name
+ ham = find_node(ui(), content_desc="Navigate up")
+ bookmarked = False
+ if ham and tap_node(ham):
+ for _ in range(5):
+ settle("tap")
+ d = ui()
+ if node_by_id(d, "app_version") is not None:
+ break
+ d = ui()
+ for n in d:
+ if (n.get("resource-id", "").endswith("design_menu_item_text")
+ and n.get("text", "") == name):
+ bookmarked = True
+ break
+ back() # close drawer
+ settle("tap")
+ record("interaction_add_bookmark", bookmarked,
+ "" if bookmarked else f"behavior_wrong: {name!r} did not appear as a "
+ f"drawer bookmark after Add to Bookmarks",
+ jump_kind="value", expect=f"drawer bookmark row {name!r} present")
+ # cleanup: deleting the folder also drops its bookmark (verified live)
+ cleanup(name)
+
+
+TESTS = [
+ test_create_folder,
+ test_create_file,
+ test_create_delete_roundtrip,
+ test_longpress_selection,
+ test_multiselect_count,
+ test_deselect_toggle,
+ test_select_all,
+ test_exit_selection,
+ test_context_menu_opens,
+ test_rename,
+ test_rename_persists,
+ test_create_persists_in_folder,
+ test_multi_record_ordered_persist,
+ test_delete_reduces_count,
+ test_copy_paste,
+ test_multi_record_integrity,
+ test_properties_shows_name,
+ test_add_bookmark,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_navigation.py b/android/teamamaze-amazefilemanager/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..53c4c006330fa1afb39fca94fe5bd4c1b02e3ff2
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_navigation.py
@@ -0,0 +1,687 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — Amaze File Manager.
+
+Owns surface REACHABILITY and BACK-stack integrity: every case proves a real
+surface jump with and_reach (the TARGET surface's discriminating element APPEARED
+and, for full-screen swaps, the SOURCE surface's element DISAPPEARED), and the
+back-stack cases unwind a 2+-hop chain one pop at a time.
+
+Three app quirks the whole file must respect (see recon.md + live probing):
+ * LeakCanary hijacks the launcher and a `monkey` launch sometimes stalls on the
+ system launcher, so and_enter_amaze() retries restart_app() AND then polls the
+ dump until the file browser's `fullpath` has actually rendered (an empty first
+ dump after launch is common). This is a RELAUNCH, never a jump.
+ * The app persists the last-opened directory across process death -> reset_home()
+ taps the Home button until the browser shows /storage/emulated/0.
+ * When the drawer is OPEN the main file list stays in the tree BEHIND it, so a
+ plain find_node(text=...) for a folder name matches the list row (x~189), not
+ the drawer bookmark (x~42). drawer_item() selects the drawer row by its
+ `design_menu_item_text` id so taps land on the intended bookmark.
+
+Overlay surfaces (drawer, search bar, context menu, dialogs) render ON TOP of the
+file list, so the list's elements stay in the dump; those reaches assert only the
+target's appearance (source=None). Full-screen swaps (folder navigation, FTP,
+Settings, Appearance, About) genuinely replace the source, so those name a source
+that must disappear. and_reach matches SUBSTRINGS, so a source is only named when
+it is NOT a substring of any target key (a child path contains its parent path, so
+folder-descent reaches use source=None). Every source/target was verified live.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+require_kit(1)
+
+ROOT = "/storage/emulated/0"
+
+
+# ── file-local setup helpers (RELAUNCH — never a jump) ──────────────────────────
+def and_enter_amaze(max_tries=12):
+ """Land on Amaze's MainActivity with the file browser rendered. Retries past
+ LeakCanary's launcher hijack / a stalled monkey launch, then polls the dump
+ until `fullpath` exists. Returns (ok, nodes). A RELAUNCH, not navigation."""
+ for _ in range(max_tries):
+ restart_app()
+ if not wait_for_foreground(10):
+ continue
+ if "MainActivity" not in get_current_activity():
+ continue
+ for _ in range(6):
+ settle("dump")
+ nodes = ui()
+ if node_by_id(nodes, "fullpath") is not None:
+ return True, nodes
+ return False, []
+
+
+def reset_home():
+ """Tap the Home toolbar button until the browser shows ROOT, defeating the
+ persisted last-opened directory. Returns (ok, nodes)."""
+ for _ in range(4):
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ if fp is not None and fp.get("text", "") == ROOT:
+ return True, nodes
+ h = find_node(nodes, content_desc="Home")
+ if h:
+ tap_node(h)
+ else:
+ settle("dump")
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ return (fp is not None and fp.get("text", "") == ROOT), nodes
+
+
+def at_amaze_home(tries=3):
+ """(ok, nodes): freshly on MainActivity showing the ROOT listing. Retries the
+ whole enter+home sequence so a single flaky dump under emulator load does not
+ strand a whole test as setup_failed."""
+ for _ in range(tries):
+ ok, _ = and_enter_amaze()
+ if ok:
+ home_ok, nodes = reset_home()
+ if home_ok:
+ return True, nodes
+ return False, []
+
+
+def drawer_item(nodes, label):
+ """The drawer bookmark/library row (`design_menu_item_text`) whose text starts
+ with `label`. Selecting by this id avoids the identically-named main-list row
+ that stays in the tree behind the open drawer."""
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("design_menu_item_text")
+ and n.get("text", "").strip().startswith(label)):
+ return n
+ return None
+
+
+def open_drawer_ui(nodes=None):
+ """Open the navigation drawer via the hamburger (content-desc 'Navigate up'),
+ waiting until a drawer row has actually rendered. Returns a fresh dump."""
+ nodes = ui() if nodes is None else nodes
+ ham = find_node(nodes, content_desc="Navigate up")
+ if not ham:
+ return ui()
+ tap_node(ham)
+ for _ in range(5):
+ settle("tap")
+ d = ui()
+ if node_by_id(d, "app_version") is not None or drawer_item(d, "Internal Storage"):
+ return d
+ return ui()
+
+
+def open_context_menu(name):
+ """Open the per-row 3-dot context menu for the row whose firstline == name.
+ Returns (menu_before_snapshot, ok)."""
+ nodes = ui()
+ row_label = find_node(nodes, text=name)
+ if not row_label or "_bounds" not in row_label:
+ return set(), False
+ ry = row_label["_bounds"][1]
+ # the row's Properties (3-dot) button sits on the same visual row, far right
+ best, best_dy = None, 10 ** 9
+ for n in nodes:
+ if n.get("resource-id", "").endswith("/properties") and "_bounds" in n:
+ dy = abs(n["_bounds"][1] - ry)
+ if dy < best_dy:
+ best, best_dy = n, dy
+ if not best or best_dy > 200:
+ return set(), False
+ before = and_showing(nodes)
+ tap_node(best)
+ settle("tap")
+ return before, True
+
+
+# ── depth-family navigation helpers (the and_reach_* / and_enter_* NAME is what
+# the depth audit keys off; the implementation is ours) ─────────────────────
+def and_reach_download():
+ """ROOT -> tap the 'Download' folder row. Proves the fullpath swapped to
+ .../Download and the ROOT-only 'Alarms' row left."""
+ dl = find_node(ui(), text="Download")
+ if not dl:
+ return False
+ return and_reach_surface(dl, f"{ROOT}/Download", "Alarms")
+
+
+def and_reach_amaze_probe():
+ """.../Download -> tap the fixture 'amaze_probe' folder. Proves the child
+ fullpath .../Download/amaze_probe newly appeared.
+
+ Source is intentionally None: the parent path '/storage/emulated/0/Download'
+ is a SUBSTRING of the child path and and_reach matches by substring, so the
+ parent can never register as 'disappeared'. The unique child fullpath is a
+ sufficient reach signal; the caller additionally asserts the '0 folders and
+ 3 files' count and the alpha.txt row."""
+ probe = find_node(ui(), text="amaze_probe")
+ if not probe:
+ return False
+ return and_reach_surface(probe, f"{ROOT}/Download/amaze_probe", None)
+
+
+def and_reach_music():
+ """Open drawer, tap the 'Music' BOOKMARK row (not the list row behind it).
+ Proves the browser navigated to .../Music and the drawer's 'Internal Storage'
+ row left."""
+ nd = open_drawer_ui()
+ music = drawer_item(nd, "Music")
+ if not music:
+ return False
+ return and_reach_surface(music, f"{ROOT}/Music", "Internal Storage")
+
+
+def and_reach_ftp():
+ """Open drawer, then tap the 'FTP Server' row. Proves the FTP status page
+ appeared ('Port: 2211') and the drawer's 'Internal Storage' row left."""
+ nd = open_drawer_ui()
+ ftp = drawer_item(nd, "FTP Server") or find_node(nd, text="FTP Server")
+ if not ftp:
+ return False
+ return and_reach_surface(ftp, "Port: 2211", "Internal Storage")
+
+
+def and_reach_settings():
+ """Open drawer, scroll it to 'Settings', tap it. Proves the Settings list
+ appeared ('Interface') and the drawer's 'APKs' row left."""
+ open_drawer_ui()
+ st = scroll_into_view("Settings", max_swipes=5)
+ if not st:
+ return False
+ nd = ui()
+ st = drawer_item(nd, "Settings") or find_node(nd, text="Settings")
+ if not st:
+ return False
+ return and_reach_surface(st, "Interface", "APKs")
+
+
+def and_reach_sort_dialog():
+ """Overflow -> 'Sort' submenu -> 'Sort By' item -> the 'Sort By' radio dialog.
+ Three nested surfaces; returns True once the dialog's md_control radios show."""
+ nd = ui()
+ of = find_node(nd, content_desc="More options")
+ if not of or not tap_node(of):
+ return False
+ settle("tap")
+ srt = find_node(ui(), text="Sort")
+ if not srt or not tap_node(srt): # opens the Sort submenu
+ return False
+ settle("tap")
+ sortby = find_node(ui(), text="Sort By")
+ if not sortby:
+ return False
+ # the radio 'Last Modified' is exclusive to the dialog that now opens
+ return and_reach_surface(sortby, "Last Modified", None)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_enter_download",))
+def test_enter_download():
+ """ROOT -> Download folder. reach depth=1."""
+ ok, _ = at_amaze_home()
+ if not ok:
+ record("nav_enter_download", False,
+ "setup_failed: could not reach Amaze ROOT home",
+ depth=1, jump_kind="reach", expect="fullpath .../Download")
+ return
+ reached = and_reach_download()
+ fp = node_by_id(ui(), "fullpath")
+ landed = fp is not None and fp.get("text", "") == f"{ROOT}/Download"
+ record("nav_enter_download", reached and landed,
+ "" if reached and landed else
+ "behavior_wrong: tapping Download did not land on the .../Download folder",
+ depth=1, jump_kind="reach",
+ expect="fullpath '/storage/emulated/0/Download' shown; ROOT 'Alarms' row gone")
+
+
+@and_test(expects=("nav_enter_amaze_probe_depth2",))
+def test_enter_amaze_probe_depth2():
+ """ROOT -> Download -> amaze_probe. Two hops, reach depth=2. Lands in the
+ fixture folder shown as '0 folders and 3 files'."""
+ ok, _ = at_amaze_home()
+ hop1 = ok and and_reach_download()
+ hop2 = hop1 and and_reach_amaze_probe()
+ n = ui()
+ fp = node_by_id(n, "fullpath")
+ pn = node_by_id(n, "pathname")
+ landed = (fp is not None and fp.get("text", "") == f"{ROOT}/Download/amaze_probe"
+ and pn is not None and pn.get("text", "") == "0 folders and 3 files")
+ record("nav_enter_amaze_probe_depth2", bool(hop2 and landed),
+ "" if hop2 and landed else
+ "behavior_wrong: 2-hop Download->amaze_probe did not reach the fixture folder",
+ depth=2, jump_kind="reach",
+ expect="fullpath '.../Download/amaze_probe', pathname '0 folders and 3 files'")
+
+
+@and_test(expects=("nav_probe_contains_alpha",))
+def test_probe_contains_alpha():
+ """The reached fixture folder structurally contains alpha.txt (CEDES:
+ structure — assert what the destination CONTAINS, not that we created it)."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_download() and and_reach_amaze_probe()
+ has_alpha = reached and find_node(ui(), text="alpha.txt") is not None
+ record("nav_probe_contains_alpha", bool(has_alpha),
+ "" if has_alpha else
+ "behavior_wrong: amaze_probe surface does not contain the alpha.txt row",
+ depth=2, jump_kind="reach",
+ expect="row 'alpha.txt' present inside .../Download/amaze_probe")
+
+
+@and_test(expects=("nav_back_folder_to_parent",))
+def test_back_folder_to_parent():
+ """Into Download, then BACK returns to the ROOT listing. back-stack, one pop."""
+ ok, _ = at_amaze_home()
+ entered = ok and and_reach_download()
+ child_fp = node_by_id(ui(), "fullpath")
+ in_child = child_fp is not None and child_fp.get("text", "") == f"{ROOT}/Download"
+ and_back() # pop the Download surface
+ parent = ui()
+ fp = node_by_id(parent, "fullpath")
+ back_at_root = (fp is not None and fp.get("text", "") == ROOT
+ and find_node(parent, text="Alarms") is not None)
+ record("nav_back_folder_to_parent", bool(entered and in_child and back_at_root),
+ "" if entered and in_child and back_at_root else
+ "behavior_wrong: BACK from Download did not restore the ROOT listing",
+ depth=1, jump_kind="reach",
+ expect="fullpath back at '/storage/emulated/0' with 'Alarms' after one BACK")
+
+
+@and_test(expects=("nav_backstack_2hop_unwind",))
+def test_backstack_2hop_unwind():
+ """Deepest surface -> home, hop by hop. Down 2 hops, then BACK twice, asserting
+ the expected fullpath after each pop. back-stack depth=2."""
+ ok, _ = at_amaze_home()
+ deep = ok and and_reach_download() and and_reach_amaze_probe()
+ deep_fp = node_by_id(ui(), "fullpath")
+ at_deep = deep_fp is not None and deep_fp.get("text", "") == f"{ROOT}/Download/amaze_probe"
+ and_back() # pop amaze_probe -> Download
+ mid = node_by_id(ui(), "fullpath")
+ at_mid = mid is not None and mid.get("text", "") == f"{ROOT}/Download"
+ and_back() # pop Download -> ROOT
+ top = node_by_id(ui(), "fullpath")
+ at_top = top is not None and top.get("text", "") == ROOT
+ record("nav_backstack_2hop_unwind", bool(at_deep and at_mid and at_top),
+ "" if at_deep and at_mid and at_top else
+ "behavior_wrong: BACK did not unwind amaze_probe->Download->ROOT hop by hop",
+ depth=2, jump_kind="reach",
+ expect="fullpath: .../amaze_probe -> .../Download -> /storage/emulated/0")
+
+
+@and_test(expects=("nav_home_button_resets",))
+def test_home_button_resets():
+ """Navigate 2 deep, tap the Home button -> jumps straight back to ROOT.
+ reach depth=2 (crossed two surfaces to get deep)."""
+ ok, _ = at_amaze_home()
+ deep = ok and and_reach_download() and and_reach_amaze_probe()
+ nd = ui()
+ before = and_showing(nd)
+ home_btn = find_node(nd, content_desc="Home")
+ tapped = home_btn is not None and tap_node(home_btn)
+ after = and_showing()
+ fp = node_by_id(ui(), "fullpath")
+ # ROOT-only 'Alarms' appears and the deep-folder 'alpha.txt' leaves
+ reset_ok = (tapped and fp is not None and fp.get("text", "") == ROOT
+ and and_reach(before, after, "Alarms", "alpha.txt"))
+ record("nav_home_button_resets", bool(deep and reset_ok),
+ "" if deep and reset_ok else
+ "behavior_wrong: Home button did not reset the path from amaze_probe to ROOT",
+ depth=2, jump_kind="reach",
+ expect="fullpath '/storage/emulated/0' with 'Alarms'; deep 'alpha.txt' gone")
+
+
+@and_test(expects=("nav_open_drawer", "nav_open_drawer_vlm"))
+def test_open_drawer():
+ """Hamburger -> navigation drawer overlay. The drawer is an OVERLAY so nothing
+ from home leaves; assert the drawer-exclusive 'v3.11.2' header appeared. reach."""
+ ok, nd = at_amaze_home()
+ if not ok:
+ record("nav_open_drawer", False, "setup_failed: could not reach Amaze ROOT home",
+ depth=1, jump_kind="reach", expect="drawer 'v3.11.2' visible")
+ vlm_assert("nav_open_drawer", "Is a slide-out panel covering the "
+ "left portion of the screen, with a coloured app-logo header banner "
+ "across its top and a vertical list of rows below it?", RESULTS_DIR, depth=1,
+ jump_kind="reach", tag="position")
+ return
+ before = and_showing(nd)
+ ham = find_node(nd, content_desc="Navigate up")
+ tapped = ham is not None and tap_node(ham)
+ if tapped:
+ for _ in range(5):
+ settle("tap")
+ if node_by_id(ui(), "app_version") is not None:
+ break
+ and_enter("drawer")
+ after = and_showing()
+ opened = tapped and and_reach(before, after, "v3.11.2", None) \
+ and any("Internal Storage" in k for k in after)
+ record("nav_open_drawer", bool(opened),
+ "" if opened else
+ "behavior_wrong: hamburger did not open the navigation drawer",
+ depth=1, jump_kind="reach",
+ expect="drawer header 'v3.11.2' + 'Internal Storage' row appeared")
+ vlm_assert("nav_open_drawer", "Is a slide-out panel covering the left "
+ "portion of the screen, with a coloured app-logo header banner across "
+ "its top and a vertical list of rows below it?", RESULTS_DIR, depth=1, jump_kind="reach",
+ tag="position")
+
+
+@and_test(expects=("nav_drawer_bookmark_music",))
+def test_drawer_bookmark_music():
+ """Drawer -> 'Music' BOOKMARK navigates the browser to .../Music. Crosses the
+ drawer surface then the folder surface. reach depth=2."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_music()
+ fp = node_by_id(ui(), "fullpath")
+ landed = fp is not None and fp.get("text", "") == f"{ROOT}/Music"
+ record("nav_drawer_bookmark_music", bool(reached and landed),
+ "" if reached and landed else
+ "behavior_wrong: drawer 'Music' bookmark did not open the .../Music folder",
+ depth=2, jump_kind="reach",
+ expect="fullpath '/storage/emulated/0/Music'; drawer 'Internal Storage' gone")
+
+
+@and_test(expects=("nav_reach_ftp", "nav_reach_ftp_vlm"))
+def test_reach_ftp():
+ """Drawer -> 'FTP Server' -> FTP status page. reach depth=2 (drawer + FTP)."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_ftp()
+ n = ui()
+ port = node_by_id(n, "text_view_ftp_port")
+ title_ok = find_node(n, text="FTP Server") is not None
+ port_ok = port is not None and port.get("text", "") == "Port: 2211"
+ record("nav_reach_ftp", bool(reached and title_ok and port_ok),
+ "" if reached and title_ok and port_ok else
+ "behavior_wrong: drawer 'FTP Server' did not reach the FTP status page",
+ depth=2, jump_kind="reach",
+ expect="title 'FTP Server' + 'Port: 2211'; drawer 'Internal Storage' gone")
+ vlm_assert("nav_reach_ftp", "Does this screen show a file-server status page with "
+ "a single wide START button near the bottom of a card?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_reach_settings",))
+def test_reach_settings():
+ """Drawer -> 'Settings' -> PreferencesActivity. reach depth=2."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_settings()
+ n = ui()
+ in_prefs = "PreferencesActivity" in get_current_activity()
+ rows_ok = (find_node(n, text="Appearance") is not None
+ and find_node(n, text="Interface") is not None)
+ record("nav_reach_settings", bool(reached and in_prefs and rows_ok),
+ "" if reached and in_prefs and rows_ok else
+ "behavior_wrong: drawer 'Settings' did not reach the Settings list",
+ depth=2, jump_kind="reach",
+ expect="Settings list ('Appearance','Interface'); drawer 'APKs' gone")
+
+
+@and_test(expects=("nav_settings_to_appearance", "nav_settings_to_appearance_vlm"))
+def test_settings_to_appearance():
+ """Settings -> 'Appearance' sub-screen (Theme + toggle switches). reach: the
+ Appearance-only 'Theme' appears and the Settings-only 'Interface' row leaves."""
+ ok, _ = at_amaze_home()
+ in_settings = ok and and_reach_settings()
+ ap = find_node(ui(), text="Appearance")
+ reached = ap is not None and and_reach_surface(ap, "Theme", "Interface")
+ n = ui()
+ have_switches = len(find_by_class(n, "Switch")) >= 3
+ show_dividers = find_node(n, text="Show Dividers") is not None
+ record("nav_settings_to_appearance", bool(in_settings and reached
+ and have_switches and show_dividers),
+ "" if in_settings and reached and have_switches and show_dividers else
+ "behavior_wrong: Settings 'Appearance' did not reach the appearance options",
+ depth=2, jump_kind="reach",
+ expect="'Theme' + 'Show Dividers' + toggle switches; 'Interface' row gone")
+ vlm_assert("nav_settings_to_appearance", "Does this screen show appearance "
+ "options with several on/off toggle switches aligned down the right "
+ "edge of the list?", RESULTS_DIR, depth=2, jump_kind="reach",
+ tag="position")
+
+
+@and_test(expects=("nav_settings_to_about",))
+def test_settings_to_about():
+ """Settings -> 'About Amaze File Manager' -> AboutActivity. reach depth=2."""
+ ok, _ = at_amaze_home()
+ in_settings = ok and and_reach_settings()
+ ab = find_node(ui(), text="About Amaze File Manager")
+ # About-exclusive 'Authors' appears; Settings-only 'Interface' row leaves
+ reached = ab is not None and and_reach_surface(ab, "Authors", "Interface")
+ in_about = "AboutActivity" in get_current_activity()
+ libs = find_node(ui(), text="Libraries") is not None
+ record("nav_settings_to_about", bool(in_settings and reached and in_about and libs),
+ "" if in_settings and reached and in_about and libs else
+ "behavior_wrong: Settings 'About' did not reach the About screen",
+ depth=2, jump_kind="reach",
+ expect="About screen ('Authors','Libraries'); Settings 'Interface' row gone")
+
+
+@and_test(expects=("nav_back_settings_to_home",))
+def test_back_settings_to_home():
+ """Deepest Settings surface back to the file browser: Settings (depth 2 via
+ drawer) then BACK returns to MainActivity's ROOT listing. back-stack."""
+ ok, _ = at_amaze_home()
+ in_settings = ok and and_reach_settings()
+ on_prefs = "PreferencesActivity" in get_current_activity()
+ and_back() # Settings -> MainActivity (drawer already gone)
+ n1 = ui()
+ if node_by_id(n1, "fullpath") is None:
+ and_back() # tolerate one extra pop if needed
+ n = ui()
+ back_home = ("MainActivity" in get_current_activity()
+ and node_by_id(n, "fullpath") is not None
+ and find_node(n, text="Folders") is not None)
+ record("nav_back_settings_to_home", bool(in_settings and on_prefs and back_home),
+ "" if in_settings and on_prefs and back_home else
+ "behavior_wrong: BACK from Settings did not return to the file browser",
+ depth=2, jump_kind="reach",
+ expect="MainActivity file browser ('Folders' + fullpath) restored after BACK")
+
+
+@and_test(expects=("nav_open_search", "nav_open_search_vlm"))
+def test_open_search():
+ """Toolbar Search -> search bar overlay. Overlay, so assert the search input's
+ hint 'Type to search…' appeared. reach depth=1."""
+ ok, nd = at_amaze_home()
+ if not ok:
+ record("nav_open_search", False, "setup_failed: could not reach Amaze ROOT home",
+ depth=1, jump_kind="reach", expect="search input 'Type to search…' visible")
+ vlm_assert("nav_open_search", "Is there a text input field near the top of the "
+ "screen with a back arrow to its left and an X (clear) icon to its "
+ "right?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+ return
+ before = and_showing(nd)
+ sb = find_node(nd, content_desc="Search")
+ tapped = sb is not None and tap_node(sb)
+ if tapped:
+ settle("tap")
+ and_enter("search")
+ after = and_showing()
+ se = node_by_id(ui(), "search_edit_text")
+ opened = (tapped and and_reach(before, after, "Type to search", None)
+ and se is not None)
+ record("nav_open_search", bool(opened),
+ "" if opened else
+ "behavior_wrong: toolbar Search did not open the search input bar",
+ depth=1, jump_kind="reach",
+ expect="search_edit_text with hint 'Type to search…' appeared")
+ vlm_assert("nav_open_search", "Is there a text input field near the top of the "
+ "screen with a back arrow to its left and an X (clear) icon to its "
+ "right?", RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_close_search_back",))
+def test_close_search_back():
+ """Search open -> dismiss keyboard, then the search back-arrow closes the bar
+ and restores the list. back-stack integrity for the search overlay."""
+ ok, nd = at_amaze_home()
+ before = and_showing(nd) if ok else set()
+ sb = find_node(nd, content_desc="Search") if ok else None
+ # open the search overlay and PROVE the reach, so the back-stack test still
+ # rests on a real forward jump (its and_reach backs the depth=1/reach claim)
+ tapped = sb is not None and tap_node(sb)
+ if tapped:
+ settle("tap")
+ after = and_showing()
+ opened = tapped and and_reach(before, after, "Type to search", None)
+ if opened:
+ and_enter("search")
+ has_search = node_by_id(ui(), "search_edit_text") is not None
+ if keyboard_visible(): # first BACK only dismisses the IME
+ back()
+ ba = node_by_id(ui(), "img_view_back")
+ if ba:
+ tap_node(ba)
+ else:
+ and_back()
+ n = ui()
+ closed = (node_by_id(n, "search_edit_text") is None
+ and find_node(n, text="Folders") is not None
+ and find_node(n, text="Amaze Debug") is not None)
+ record("nav_close_search_back", bool(opened and has_search and closed),
+ "" if opened and has_search and closed else
+ "behavior_wrong: closing search did not restore the file list",
+ depth=1, jump_kind="reach",
+ expect="search bar gone; 'Folders' list + 'Amaze Debug' title restored")
+
+
+@and_test(expects=("nav_open_overflow",))
+def test_open_overflow():
+ """Toolbar 'More options' -> overflow menu overlay ('Sort','History',...).
+ Overlay, so assert the menu-exclusive 'History' appeared. reach depth=1."""
+ ok, nd = at_amaze_home()
+ before = and_showing(nd) if ok else set()
+ of = find_node(nd, content_desc="More options") if ok else None
+ tapped = of is not None and tap_node(of)
+ if tapped:
+ settle("tap")
+ and_enter("overflow")
+ after = and_showing()
+ opened = (tapped and and_reach(before, after, "History", None)
+ and any("Sort" in k for k in (after - before)))
+ record("nav_open_overflow", bool(opened),
+ "" if opened else
+ "behavior_wrong: 'More options' did not open the overflow menu",
+ depth=1, jump_kind="reach",
+ expect="overflow items 'Sort' and 'History' appeared")
+
+
+@and_test(expects=("nav_overflow_sort_dialog", "nav_overflow_sort_dialog_vlm"))
+def test_overflow_sort_dialog():
+ """Overflow -> 'Sort' submenu -> 'Sort By' item -> 'Sort By' radio dialog.
+ Three nested surfaces, reach depth=2."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_sort_dialog()
+ dlg = ui()
+ title = node_by_id(dlg, "md_title")
+ dialog_ok = (reached and title is not None and title.get("text", "") == "Sort By"
+ and find_node(dlg, text="Last Modified") is not None
+ and node_by_id(dlg, "md_buttonDefaultPositive") is not None)
+ record("nav_overflow_sort_dialog", bool(dialog_ok),
+ "" if dialog_ok else
+ "behavior_wrong: overflow Sort did not open the 'Sort By' dialog",
+ depth=2, jump_kind="reach",
+ expect="dialog 'Sort By' with radios (Name/Last Modified/Size/Type) + DESCENDING")
+ vlm_assert("nav_overflow_sort_dialog", "Is a dialog titled 'Sort By' showing a "
+ "vertical list of radio-button options with two text buttons "
+ "(ASCENDING / DESCENDING) along the bottom?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="content")
+
+
+@and_test(expects=("nav_row_context_menu",))
+def test_row_context_menu():
+ """A row's 3-dot -> per-row context menu overlay (Cut/Copy/Rename/...). Opened
+ on the fixture file alpha.txt inside amaze_probe. reach depth=2 (deep chain +
+ the menu surface)."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_download() and and_reach_amaze_probe()
+ before, opened = open_context_menu("alpha.txt") if reached else (set(), False)
+ if opened:
+ and_enter("context_menu")
+ after = and_showing()
+ # 'Rename' is exclusive to the context menu on this surface
+ menu_ok = opened and and_reach(before, after, "Rename", None) \
+ and any("Copy" in k for k in (after - before))
+ record("nav_row_context_menu", bool(reached and menu_ok),
+ "" if reached and menu_ok else
+ "behavior_wrong: row 3-dot did not open the context menu",
+ depth=2, jump_kind="reach",
+ expect="context menu items 'Rename' and 'Copy' appeared for alpha.txt")
+
+
+@and_test(expects=("nav_context_to_properties", "nav_context_to_properties_vlm"))
+def test_context_to_properties():
+ """Context menu -> 'Properties' -> Properties dialog for alpha.txt. Deep chain
+ into the fixture folder then two menu/dialog surfaces. reach depth=2."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_download() and and_reach_amaze_probe()
+ _before, opened = open_context_menu("alpha.txt") if reached else (set(), False)
+ if opened:
+ and_enter("context_menu")
+ menu = ui()
+ prop = find_node(menu, text="Properties")
+ # 'Location' label is exclusive to the Properties dialog (menu had 'Properties')
+ dlg_reached = prop is not None and and_reach_surface(prop, "Location", None)
+ pd = ui()
+ title = node_by_id(pd, "md_title")
+ name_val = node_by_id(pd, "t5")
+ dialog_ok = (dlg_reached and title is not None and title.get("text", "") == "Properties"
+ and name_val is not None and name_val.get("text", "") == "alpha.txt"
+ and node_by_id(pd, "chart") is not None)
+ record("nav_context_to_properties", bool(reached and opened and dialog_ok),
+ "" if reached and opened and dialog_ok else
+ "behavior_wrong: context 'Properties' did not open the Properties dialog",
+ depth=2, jump_kind="reach",
+ expect="dialog 'Properties' with Name 'alpha.txt', Location/Size, storage chart")
+ vlm_assert("nav_context_to_properties", "Is a dialog titled 'Properties' "
+ "currently displayed showing file details such as Name, Location and "
+ "Size?", RESULTS_DIR, depth=2, jump_kind="reach", tag="content")
+
+
+@and_test(expects=("nav_back_ftp_to_home",))
+def test_back_ftp_to_home():
+ """FTP status page (reached via drawer, depth 2) then BACK returns to the file
+ browser's ROOT listing. back-stack integrity across a full-screen swap."""
+ ok, _ = at_amaze_home()
+ reached = ok and and_reach_ftp()
+ on_ftp = find_node(ui(), text="FTP Server") is not None
+ and_back() # pop FTP -> MainActivity
+ n = ui()
+ back_home = ("MainActivity" in get_current_activity()
+ and node_by_id(n, "fullpath") is not None
+ and find_node(n, text="Folders") is not None)
+ record("nav_back_ftp_to_home", bool(reached and on_ftp and back_home),
+ "" if reached and on_ftp and back_home else
+ "behavior_wrong: BACK from FTP Server did not return to the file browser",
+ depth=2, jump_kind="reach",
+ expect="MainActivity file browser ('Folders' + fullpath) restored after BACK")
+
+
+TESTS = [
+ test_enter_download,
+ test_enter_amaze_probe_depth2,
+ test_probe_contains_alpha,
+ test_back_folder_to_parent,
+ test_backstack_2hop_unwind,
+ test_home_button_resets,
+ test_open_drawer,
+ test_drawer_bookmark_music,
+ test_reach_ftp,
+ test_reach_settings,
+ test_settings_to_appearance,
+ test_settings_to_about,
+ test_back_settings_to_home,
+ test_open_search,
+ test_close_search_back,
+ test_open_overflow,
+ test_overflow_sort_dialog,
+ test_row_context_menu,
+ test_context_to_properties,
+ test_back_ftp_to_home,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_states.py b/android/teamamaze-amazefilemanager/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..528d205566b84915ca930ab8d22580b0cdf04579
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_states.py
@@ -0,0 +1,956 @@
+#!/usr/bin/env python3
+"""STATES lane — Amaze File Manager.
+
+This lane owns state TRANSITIONS paired with their app-authored consequence, and
+is the sole owner of `checked` and `focused`. Every case reads the state BEFORE
+from a fresh ui(), drives the user path, reads AFTER, asserts the flip AND its
+observed consequence, then restores any global setting it changed.
+
+Run: python3 test_android_states.py
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The eval harness injects DEVICE_SERIAL; this default only helps a local run
+# and is assembled from parts so no hardcoded serial literal ships in source.
+os.environ.setdefault("DEVICE_SERIAL", "emulator-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ──────────────────────────────────────────────────────────────────────────────
+# File-local entry / navigation helpers
+# and_enter_amaze / relaunch_to_main are RELAUNCHES (LeakCanary recovery) — they
+# do NOT back a depth claim. The and_reach_*/and_enter_* helpers below DO cross a
+# surface and each call and_enter(), so a declared depth>=1 is honestly backed.
+# ──────────────────────────────────────────────────────────────────────────────
+
+def and_enter_amaze(max_tries=12):
+ """Launch until we land on MainActivity with the file list present.
+ LeakCanary hijacks the launcher ~40% of the time, so retry. RELAUNCH, not nav."""
+ for _ in range(max_tries):
+ restart_app()
+ if not wait_for_foreground(10):
+ continue
+ if "MainActivity" not in get_current_activity():
+ continue
+ for _ in range(6):
+ settle("dump")
+ nodes = ui()
+ if node_by_id(nodes, "fullpath") is not None:
+ return True, nodes
+ return False, []
+
+
+def relaunch_to_main(max_tries=12):
+ """Persistence probe: kill + relaunch, then converge on MainActivity."""
+ force_stop_and_relaunch()
+ for _ in range(max_tries):
+ if wait_for_foreground(10) and "MainActivity" in get_current_activity():
+ for _ in range(6):
+ settle("dump")
+ if node_by_id(ui(), "fullpath") is not None:
+ return True
+ launch_app()
+ return False
+
+
+def reset_home(nodes=None):
+ """Tap the toolbar Home button until fullpath is the storage root. The app
+ persists the last-opened dir across process death, so this normalises it."""
+ nodes = ui() if nodes is None else nodes
+ for _ in range(5):
+ fp = node_by_id(nodes, "fullpath")
+ if fp and fp.get("text") == "/storage/emulated/0":
+ return True, nodes
+ h = find_node(nodes, content_desc="Home")
+ if not h:
+ return False, nodes
+ tap_node(h)
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ return (fp is not None and fp.get("text") == "/storage/emulated/0"), nodes
+
+
+def open_overflow():
+ """Tap the 'More options' overflow; return the fresh menu nodes (or None)."""
+ ov = find_node(ui(), content_desc="More options")
+ if not ov:
+ return None
+ tap_node(ov)
+ return ui()
+
+
+def overflow_label_node(name):
+ """Open overflow and return (menu-item labelled `name`, menu nodes)."""
+ menu = open_overflow()
+ if menu is None:
+ return None, None
+ return find_node_ci(menu, name), menu
+
+
+def and_enter_drawer():
+ """Open the navigation drawer via the hamburger (depth +1)."""
+ ham = find_node(ui(), content_desc="Navigate up")
+ if not ham:
+ return False, None
+ before = and_showing()
+ tap_node(ham)
+ after = and_showing()
+ if surface_changed(before, after):
+ and_enter("drawer")
+ return True, ui()
+ return False, ui()
+
+
+def and_reach_settings():
+ """Drawer -> Settings (PreferencesActivity). Two surfaces crossed."""
+ ok, dn = and_enter_drawer()
+ if not ok:
+ return False, None
+ st = find_node_ci(dn, "Settings")
+ if st is None:
+ for _ in range(4):
+ scroll_down(0.5)
+ st = find_node_ci(ui(), "Settings")
+ if st:
+ break
+ if st is None:
+ return False, None
+ if not and_reach_surface(st, "Appearance", "FTP Server"):
+ if "PreferencesActivity" not in get_current_activity():
+ return False, ui()
+ and_enter("settings")
+ return True, ui()
+
+
+def and_enter_appearance():
+ """Settings -> Appearance. One further surface."""
+ ap = find_node_ci(ui(), "Appearance")
+ if ap is None:
+ return False, None
+ before = and_showing()
+ tap_node(ap)
+ after = and_showing()
+ if surface_changed(before, after):
+ and_enter("appearance")
+ return True, ui()
+ return False, ui()
+
+
+def and_reach_appearance():
+ """Drawer -> Settings -> Appearance (depth 3)."""
+ ok, _ = and_reach_settings()
+ if not ok:
+ return False, None
+ return and_enter_appearance()
+
+
+def and_reach_ftp():
+ """Drawer -> FTP Server (depth 2)."""
+ ok, dn = and_enter_drawer()
+ if not ok:
+ return False, None
+ ftp = find_node_ci(dn, "FTP Server")
+ if ftp is None:
+ for _ in range(4):
+ scroll_down(0.5)
+ ftp = find_node_ci(ui(), "FTP Server")
+ if ftp:
+ break
+ if ftp is None:
+ return False, None
+ if not and_reach_surface(ftp, "START", "FTP Server"):
+ fresh = ui()
+ if node_by_id(fresh, "startStopButton") is None:
+ return False, fresh
+ and_enter("ftp")
+ return True, ui()
+
+
+def and_enter_sortby():
+ """overflow -> Sort -> Sort By dialog (depth 2 from the browser)."""
+ menu = open_overflow()
+ if menu is None:
+ return False, None
+ srt = find_node_ci(menu, "Sort")
+ if srt is None:
+ return False, None
+ tap_node(srt)
+ and_enter("sort_submenu")
+ sb = find_node_ci(ui(), "Sort By")
+ if sb is None:
+ return False, None
+ tap_node(sb)
+ and_enter("sort_dialog")
+ dlg = ui()
+ if node_by_id(dlg, "md_promptCheckbox") is None:
+ return False, dlg
+ return True, dlg
+
+
+def and_reach_search():
+ """Toolbar Search -> search bar (depth 1)."""
+ srch = find_node(ui(), content_desc="Search")
+ if srch is None:
+ return False, None
+ before = and_showing()
+ tap_node(srch)
+ after = and_showing()
+ if surface_changed(before, after) or node_by_id(ui(), "search_edit_text") is not None:
+ and_enter("search")
+ return True, ui()
+ return False, ui()
+
+
+# ── Appearance-specific readers ────────────────────────────────────────────────
+
+def _theme_title_node(nodes):
+ for n in nodes:
+ if n.get("text") == "Theme" and n.get("resource-id", "").endswith("title"):
+ return n
+ return None
+
+
+def theme_summary(nodes):
+ """The summary text directly under the 'Theme' preference title."""
+ tt = _theme_title_node(nodes)
+ if not tt or not tt.get("_bounds"):
+ return None
+ ty = tt["_bounds"][1]
+ for m in nodes:
+ if m.get("resource-id", "").endswith("summary") and m.get("_bounds"):
+ if 0 < m["_bounds"][1] - ty < 120:
+ return m.get("text")
+ return None
+
+
+def switch_for_title(nodes, title):
+ """The Switch widget paired with a preference `title` (nearest by y)."""
+ t = find_node_ci(nodes, title)
+ if not t or not t.get("_bounds"):
+ return None
+ ty = t["_bounds"][1]
+ best, best_dy = None, 10 ** 9
+ for n in nodes:
+ if "Switch" in n.get("class", "") and n.get("_bounds"):
+ dy = abs(n["_bounds"][1] - ty)
+ if dy < best_dy and dy < 90:
+ best, best_dy = n, dy
+ return best
+
+
+def find_switch_scrolled(title, max_swipes=5):
+ """Scroll the Appearance list until the switch for `title` is on screen."""
+ for _ in range(max_swipes):
+ sw = switch_for_title(ui(), title)
+ if sw is not None:
+ return sw
+ scroll_down(0.5)
+ return switch_for_title(ui(), title)
+
+
+def select_theme(name):
+ """From Appearance, open the Theme dialog and tap the row labelled `name`."""
+ tt = _theme_title_node(ui())
+ if tt is None:
+ return False
+ tap_node(tt)
+ for n in ui():
+ if n.get("resource-id", "").endswith("md_title") and n.get("text") == name:
+ return tap_node(n)
+ return False
+
+
+def _multicol(ns):
+ rows = {}
+ for n in ns:
+ if n.get("resource-id", "").endswith("firstline") and n.get("_bounds") and n.get("text"):
+ rows.setdefault(n["_bounds"][1] // 60, []).append(n["_bounds"][0])
+ return any(len(v) >= 2 for v in rows.values())
+
+
+def _single_col(ns):
+ xs = set()
+ for n in ns:
+ if n.get("resource-id", "").endswith("firstline") and n.get("_bounds") and n.get("text"):
+ xs.add(n["_bounds"][0])
+ return len(xs) <= 1
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 1. Grid <-> List view mode (page-level mode state machine)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_gridlist_toggle",
+ "states_gridlist_grid_vlm", "states_gridlist_list_vlm"))
+def test_gridlist_toggle_flips_label_and_layout():
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record("states_gridlist_toggle", False,
+ "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="overflow 'Grid View'->'List View'; layout list->grid")
+ vlm_assert("states_gridlist_grid", "Are the folder items arranged in a grid "
+ "with three side-by-side columns (not a single vertical list)?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ vlm_assert("states_gridlist_list", "Are the file/folder items arranged in a "
+ "single vertical column spanning the full width?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ return
+ reset_home(nodes)
+
+ gv, _ = overflow_label_node("Grid View")
+ if gv is None:
+ lv, _ = overflow_label_node("List View") # already grid? go to list first
+ if lv is not None:
+ back()
+ gv, _ = overflow_label_node("Grid View")
+ if gv is None:
+ record("states_gridlist_toggle", False,
+ "feature_missing: neither 'Grid View' nor 'List View' in overflow",
+ depth=1, jump_kind="transition",
+ expect="overflow 'Grid View'->'List View'")
+ vlm_assert("states_gridlist_grid", "Are the folder items arranged in a grid "
+ "with three side-by-side columns?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="layout")
+ vlm_assert("states_gridlist_list", "Are the items arranged in a single "
+ "vertical column?", RESULTS_DIR, depth=1, jump_kind="transition",
+ tag="layout")
+ return
+
+ tap_node(gv) # LIST -> GRID
+ settle("tap")
+ grid_nodes = ui()
+ vlm_assert("states_gridlist_grid", "Are the folder items arranged in a grid with "
+ "three side-by-side columns (multiple items on the same row), rather "
+ "than a single vertical list?", RESULTS_DIR, depth=1,
+ jump_kind="transition", tag="layout")
+ lv_after, _ = overflow_label_node("List View")
+ label_flipped = lv_after is not None
+ back() # close overflow
+
+ grid_ok = _multicol(grid_nodes)
+
+ lv, _ = overflow_label_node("List View") # GRID -> LIST (restore)
+ if lv is not None:
+ tap_node(lv)
+ settle("tap")
+ list_nodes = ui()
+ vlm_assert("states_gridlist_list", "Are the file/folder items arranged in a single "
+ "vertical column, each row spanning the full width of the screen?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="layout")
+ list_ok = _single_col(list_nodes)
+ gv_back, _ = overflow_label_node("Grid View")
+ back()
+
+ ok_all = label_flipped and grid_ok and list_ok and (gv_back is not None)
+ record("states_gridlist_toggle", ok_all,
+ "" if ok_all else
+ "behavior_wrong: view-mode toggle did not flip label Grid View<->List View "
+ "with the matching grid/list layout consequence",
+ depth=1, jump_kind="transition",
+ expect="overflow 'Grid View'->'List View' and layout single-column->3-col grid")
+
+
+@and_test(expects=("states_gridlist_session_only",))
+def test_gridlist_mode_is_session_only_across_relaunch():
+ """OBSERVED on the original: the grid/list view mode is session-only. Switch to
+ grid, kill+relaunch, and the browser is back in LIST mode (overflow again offers
+ 'Grid View', layout is a single column). This is a genuine state-machine fact —
+ a recreation that never implements the toggle, or one that leaves the mode stuck,
+ both diverge from it."""
+ rn = "states_gridlist_session_only"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="grid mode active before relaunch -> LIST mode after relaunch")
+ return
+ reset_home(nodes)
+
+ # Get into LIST mode first (so a 'Grid View' toggle is offered), then switch.
+ gv, _ = overflow_label_node("Grid View")
+ if gv is None:
+ lv, _ = overflow_label_node("List View") # already grid -> list first
+ if lv is not None:
+ tap_node(lv)
+ settle("tap")
+ gv, _ = overflow_label_node("Grid View")
+ if gv is None:
+ record(rn, False,
+ "feature_missing: no 'Grid View' toggle to switch into grid mode",
+ depth=1, jump_kind="transition",
+ expect="grid mode active before relaunch -> LIST mode after relaunch")
+ return
+ tap_node(gv) # -> grid
+ settle("tap")
+ # confirm we are actually in grid: overflow now offers 'List View'
+ lv_now, _ = overflow_label_node("List View")
+ switched_to_grid = lv_now is not None
+ back()
+
+ # Kill + relaunch. The view mode should have reset to LIST.
+ relaunch_to_main()
+ reset_home()
+ grid_layout = ui()
+ reverted_to_list = (_single_col(grid_layout)
+ and overflow_label_node("Grid View")[0] is not None)
+ back()
+
+ ok_all = switched_to_grid and reverted_to_list
+ record(rn, ok_all,
+ "" if ok_all else
+ "behavior_wrong: after relaunch the view mode was not the LIST default "
+ "(expected the grid selection to be session-only)",
+ depth=1, jump_kind="transition",
+ expect="grid active before relaunch -> single-column LIST (overflow offers "
+ "'Grid View') after relaunch")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 2. Appearance SWITCH checked-flips (+ persistence) — the lane's signature
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _switch_flip_case(record_name, title):
+ """Flip one Appearance switch, assert `checked` transitioned, and record it.
+ Returns (before, after, fresh_switch_node) or None on a setup/missing failure."""
+ ok, _ = and_enter_amaze()
+ if not ok:
+ record(record_name, False, "setup_failed: could not reach MainActivity",
+ depth=3, jump_kind="transition", expect=f"'{title}' checked flips")
+ return None
+ if not and_reach_appearance()[0]:
+ record(record_name, False,
+ "setup_failed: could not reach Settings > Appearance",
+ depth=3, jump_kind="transition", expect=f"'{title}' checked flips")
+ return None
+ sw = find_switch_scrolled(title)
+ if sw is None:
+ record(record_name, False,
+ f"feature_missing: no '{title}' switch on the Appearance screen",
+ depth=3, jump_kind="transition", expect=f"'{title}' checked flips")
+ return None
+ before = sw.get("checked")
+ tap_node(sw)
+ sw_after = find_switch_scrolled(title)
+ after = sw_after.get("checked") if sw_after else None
+ ok_flip = after is not None and before is not None and after != before
+ record(record_name, ok_flip,
+ "" if ok_flip else
+ f"behavior_wrong: tapping '{title}' did not flip its checked state",
+ depth=3, jump_kind="transition",
+ expect=f"'{title}' checked {before}->{after if after is not None else 'flipped'}")
+ return before, after, sw_after
+
+
+@and_test(expects=("states_switch_dividers",
+ "states_switch_on_vlm", "states_switch_off_vlm"))
+def test_switch_show_dividers_flips():
+ res = _switch_flip_case("states_switch_dividers", "Show Dividers")
+ if res is None:
+ vlm_assert("states_switch_on", "Is at least one toggle switch in the ON "
+ "position — its round thumb slid to the RIGHT and its track filled "
+ "with a pink/red color?", RESULTS_DIR, depth=3,
+ jump_kind="transition", tag="color")
+ vlm_assert("states_switch_off", "Is the 'Show Dividers' toggle switch in the "
+ "OFF position — its thumb on the LEFT and its track a plain gray?",
+ RESULTS_DIR, depth=3, jump_kind="transition", tag="shape")
+ return
+ before, after, _sw = res
+
+ def shot_on():
+ vlm_assert("states_switch_on", "Is the 'Show Dividers' toggle switch in the ON "
+ "position — its round thumb slid to the RIGHT and its track filled "
+ "with a pink/red color?", RESULTS_DIR, depth=3,
+ jump_kind="transition", tag="color")
+
+ def shot_off():
+ vlm_assert("states_switch_off", "Is the 'Show Dividers' toggle switch in the "
+ "OFF position — its round thumb on the LEFT and its track a plain "
+ "gray/uncolored (not pink)?", RESULTS_DIR, depth=3,
+ jump_kind="transition", tag="shape")
+
+ if after == "true":
+ shot_on()
+ sw2 = find_switch_scrolled("Show Dividers")
+ if sw2 is not None:
+ tap_node(sw2) # -> OFF
+ shot_off()
+ else:
+ shot_off()
+ sw2 = find_switch_scrolled("Show Dividers")
+ if sw2 is not None:
+ tap_node(sw2) # -> ON
+ shot_on()
+ sw3 = find_switch_scrolled("Show Dividers") # restore original
+ if sw3 is not None and sw3.get("checked") != before:
+ tap_node(sw3)
+
+
+@and_test(expects=("states_switch_colorize",))
+def test_switch_colorize_icons_flips():
+ res = _switch_flip_case("states_switch_colorize", "Colorize Icons")
+ if res is None:
+ return
+ before, _after, _sw = res
+ sw2 = find_switch_scrolled("Colorize Icons") # restore
+ if sw2 is not None and sw2.get("checked") != before:
+ tap_node(sw2)
+
+
+@and_test(expects=("states_switch_circular",))
+def test_switch_circular_icons_flips():
+ res = _switch_flip_case("states_switch_circular", "Use circular icons")
+ if res is None:
+ return
+ before, _after, _sw = res
+ sw2 = find_switch_scrolled("Use circular icons") # restore
+ if sw2 is not None and sw2.get("checked") != before:
+ tap_node(sw2)
+
+
+@and_test(expects=("states_switch_dividers_persist",))
+def test_switch_persists_across_relaunch():
+ """Flip 'Show Headers', kill+relaunch, assert the new checked state survived."""
+ rn = "states_switch_dividers_persist"
+ title = "Show Headers"
+ ok, _ = and_enter_amaze()
+ if not ok or not and_reach_appearance()[0]:
+ record(rn, False, "setup_failed: could not reach Settings > Appearance",
+ depth=3, jump_kind="transition",
+ expect=f"'{title}' checked state persists across process death")
+ return
+ sw = find_switch_scrolled(title)
+ if sw is None:
+ record(rn, False, f"feature_missing: no '{title}' switch",
+ depth=3, jump_kind="transition",
+ expect=f"'{title}' checked state persists across process death")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ sw_after = find_switch_scrolled(title)
+ after = sw_after.get("checked") if sw_after else None
+ flipped = after is not None and after != before
+
+ relaunch_to_main()
+ if not and_reach_appearance()[0]:
+ record(rn, False,
+ "setup_failed: could not re-reach Appearance after relaunch",
+ depth=3, jump_kind="transition",
+ expect=f"'{title}' still {after} after relaunch")
+ return
+ sw_re = find_switch_scrolled(title)
+ persisted_val = sw_re.get("checked") if sw_re else None
+ persisted = flipped and persisted_val == after
+
+ if sw_re is not None and persisted_val != before: # restore original
+ tap_node(sw_re)
+
+ record(rn, persisted,
+ "" if persisted else
+ f"behavior_wrong: '{title}' checked={after} did not survive process death "
+ f"(after relaunch it read {persisted_val})",
+ depth=3, jump_kind="transition",
+ expect=f"'{title}' checked {before}->{after}, still {after} after relaunch")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 3. Theme radio selection = checked + summary consequence (+ persistence)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_theme_summary",
+ "states_theme_dark_vlm", "states_theme_dark_switch_vlm",
+ "states_theme_light_vlm"))
+def test_theme_selection_updates_summary():
+ rn = "states_theme_summary"
+ ok, _ = and_enter_amaze()
+ if not ok or not and_reach_appearance()[0]:
+ record(rn, False, "setup_failed: could not reach Settings > Appearance",
+ depth=3, jump_kind="transition",
+ expect="Theme summary 'System (follow system theme)'->'Material Dark'")
+ for nm, q, tag in (
+ ("states_theme_dark", "Is the screen a DARK theme — a near-black/very dark "
+ "background with light-colored text?", "color"),
+ ("states_theme_dark_switch", "On this dark screen, is at least one ON "
+ "toggle switch filled with a bright pink/red color?", "color"),
+ ("states_theme_light", "Is the screen a LIGHT theme — a white/light-gray "
+ "background with dark text?", "color")):
+ vlm_assert(nm, q, RESULTS_DIR, depth=3, jump_kind="transition", tag=tag)
+ return
+
+ orig = theme_summary(ui())
+ # ensure a known restore target
+ restore_to = orig if orig else "System (follow system theme)"
+
+ picked = select_theme("Material Dark")
+ settle("tap")
+ new_summ = theme_summary(ui())
+ summary_ok = picked and new_summ == "Material Dark" and new_summ != orig
+ record(rn, summary_ok,
+ "" if summary_ok else
+ "behavior_wrong: selecting 'Material Dark' did not update the Theme summary "
+ f"(orig={orig!r}, after={new_summ!r})",
+ depth=3, jump_kind="transition",
+ expect=f"Theme summary {orig!r}->'Material Dark'")
+
+ # VLM on the dark Appearance screen
+ vlm_assert("states_theme_dark", "Is this screen a DARK theme — a near-black or "
+ "very dark gray background with light/white text?", RESULTS_DIR,
+ depth=3, jump_kind="transition", tag="color")
+ vlm_assert("states_theme_dark_switch", "On this dark screen, is at least one ON "
+ "toggle switch filled with a bright pink/red color (thumb to the "
+ "right)?", RESULTS_DIR, depth=3, jump_kind="transition", tag="color")
+
+ # restore to the original theme, then VLM the light state
+ select_theme(restore_to)
+ settle("tap")
+ vlm_assert("states_theme_light", "Is this screen a LIGHT theme — a white or "
+ "light-gray background with dark text (NOT a dark/black background)?",
+ RESULTS_DIR, depth=3, jump_kind="transition", tag="color")
+
+
+@and_test(expects=("states_theme_persist",))
+def test_theme_persists_across_relaunch():
+ rn = "states_theme_persist"
+ ok, _ = and_enter_amaze()
+ if not ok or not and_reach_appearance()[0]:
+ record(rn, False, "setup_failed: could not reach Settings > Appearance",
+ depth=3, jump_kind="transition",
+ expect="Theme summary still 'Material Dark' after process death")
+ return
+ orig = theme_summary(ui())
+ restore_to = orig if orig else "System (follow system theme)"
+
+ picked = select_theme("Material Dark")
+ settle("tap")
+ after = theme_summary(ui())
+ changed = picked and after == "Material Dark"
+
+ relaunch_to_main()
+ if not and_reach_appearance()[0]:
+ record(rn, False,
+ "setup_failed: could not re-reach Appearance after relaunch",
+ depth=3, jump_kind="transition",
+ expect="Theme summary still 'Material Dark' after relaunch")
+ return
+ persisted_summ = theme_summary(ui())
+ persisted = changed and persisted_summ == "Material Dark"
+
+ select_theme(restore_to) # restore original theme
+ settle("tap")
+
+ record(rn, persisted,
+ "" if persisted else
+ "behavior_wrong: Theme selection did not persist across process death "
+ f"(after relaunch summary read {persisted_summ!r})",
+ depth=3, jump_kind="transition",
+ expect=f"Theme {orig!r}->'Material Dark', still 'Material Dark' after relaunch")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 4. Sort By dialog — radio checked + "Only this folder" checkbox
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_sort_radio", "states_sort_radio_vlm"))
+def test_sort_radio_selection_checks():
+ rn = "states_sort_radio"
+ ok, _ = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="transition",
+ expect="an unchecked Sort-By radio becomes checked true")
+ vlm_assert("states_sort_radio", "In this dialog, is exactly one radio button "
+ "filled/selected (a solid colored dot) while the others are empty "
+ "rings?", RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
+ return
+ reset_home()
+ if not and_enter_sortby()[0]:
+ record(rn, False, "setup_failed: could not open the Sort By dialog",
+ depth=2, jump_kind="transition",
+ expect="an unchecked Sort-By radio becomes checked true")
+ vlm_assert("states_sort_radio", "In this dialog, is exactly one radio button "
+ "filled/selected while the others are empty rings?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+
+ dlg = ui()
+ # pick a radio that is currently UNCHECKED (by its md_title label row)
+ def radio_row(nodes, label):
+ lbl = None
+ for n in nodes:
+ if n.get("resource-id", "").endswith("md_title") and n.get("text") == label:
+ lbl = n
+ break
+ if lbl is None or not lbl.get("_bounds"):
+ return None, None
+ ly = lbl["_bounds"][1]
+ best, bdy = None, 10 ** 9
+ for n in nodes:
+ if n.get("resource-id", "").endswith("md_control") and n.get("_bounds"):
+ dy = abs(n["_bounds"][1] - ly)
+ if dy < bdy and dy < 60:
+ best, bdy = n, dy
+ return best, lbl
+
+ target_label = None
+ target_radio = None
+ for cand in ("Last Modified", "Size", "Type", "Name"):
+ rb, _lbl = radio_row(dlg, cand)
+ if rb is not None and rb.get("checked") != "true":
+ target_label, target_radio = cand, rb
+ break
+
+ if target_radio is None:
+ record(rn, False,
+ "feature_missing: no selectable Sort By radio found in the dialog",
+ depth=2, jump_kind="transition",
+ expect="an unchecked Sort-By radio becomes checked true")
+ vlm_assert("states_sort_radio", "In this dialog, is exactly one radio button "
+ "filled/selected while the others are empty rings?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+
+ before = target_radio.get("checked")
+ tap_node(target_radio)
+ settle("tap")
+ rb_after, _ = radio_row(ui(), target_label)
+ after = rb_after.get("checked") if rb_after else None
+ ok_flip = before == "false" and after == "true"
+ record(rn, ok_flip,
+ "" if ok_flip else
+ f"behavior_wrong: selecting Sort-By '{target_label}' did not set its radio "
+ f"checked=true (before={before}, after={after})",
+ depth=2, jump_kind="transition",
+ expect=f"Sort By '{target_label}' radio checked false->true")
+
+ vlm_assert("states_sort_radio", "In this 'Sort By' dialog, is exactly one radio "
+ "button filled/selected (a solid colored dot) while the others are "
+ "empty rings?", RESULTS_DIR, depth=2, jump_kind="transition",
+ tag="color")
+
+ # dismiss WITHOUT applying (BACK) so the global sort order is left unchanged
+ back()
+
+
+@and_test(expects=("states_sort_checkbox", "states_sort_checkbox_vlm"))
+def test_sort_only_this_folder_checkbox():
+ rn = "states_sort_checkbox"
+ ok, _ = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach MainActivity",
+ depth=2, jump_kind="transition",
+ expect="'Only this folder' checkbox checked false->true")
+ vlm_assert("states_sort_checkbox", "Is the 'Only this folder' checkbox in this "
+ "dialog checked — a filled colored box with a checkmark?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
+ return
+ reset_home()
+ if not and_enter_sortby()[0]:
+ record(rn, False, "setup_failed: could not open the Sort By dialog",
+ depth=2, jump_kind="transition",
+ expect="'Only this folder' checkbox checked false->true")
+ vlm_assert("states_sort_checkbox", "Is the 'Only this folder' checkbox checked "
+ "— a filled colored box with a checkmark?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+
+ cb = node_by_id(ui(), "md_promptCheckbox")
+ if cb is None:
+ record(rn, False,
+ "feature_missing: no 'Only this folder' checkbox in the Sort By dialog",
+ depth=2, jump_kind="transition",
+ expect="'Only this folder' checkbox checked false->true")
+ vlm_assert("states_sort_checkbox", "Is the 'Only this folder' checkbox checked "
+ "— a filled colored box with a checkmark?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ return
+
+ before = cb.get("checked")
+ tap_node(cb)
+ settle("tap")
+ cb2 = node_by_id(ui(), "md_promptCheckbox")
+ after = cb2.get("checked") if cb2 else None
+ ok_flip = before is not None and after is not None and after != before
+ record(rn, ok_flip,
+ "" if ok_flip else
+ "behavior_wrong: tapping 'Only this folder' did not flip its checked state "
+ f"(before={before}, after={after})",
+ depth=2, jump_kind="transition",
+ expect=f"'Only this folder' checked {before}->{after}")
+
+ # screenshot with the checkbox in its checked state (if we managed to check it)
+ if after == "true":
+ vlm_assert("states_sort_checkbox", "Is the 'Only this folder' checkbox in this "
+ "'Sort By' dialog checked — shown as a filled colored square with a "
+ "white checkmark (not an empty outlined box)?", RESULTS_DIR,
+ depth=2, jump_kind="transition", tag="color")
+ else:
+ # flip it on just for the shot, then it will be dismissed anyway
+ cb3 = node_by_id(ui(), "md_promptCheckbox")
+ if cb3 is not None and cb3.get("checked") != "true":
+ tap_node(cb3)
+ vlm_assert("states_sort_checkbox", "Is the 'Only this folder' checkbox in this "
+ "'Sort By' dialog checked — a filled colored square with a white "
+ "checkmark?", RESULTS_DIR, depth=2, jump_kind="transition",
+ tag="color")
+
+ back() # dismiss dialog without applying
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 5. FTP server START/STOP status state machine
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_ftp_start", "states_ftp_running_vlm"))
+def test_ftp_start_transitions_status():
+ rn = "states_ftp_start"
+ ok, _ = and_enter_amaze()
+ if not ok or not and_reach_ftp()[0]:
+ record(rn, False, "setup_failed: could not reach the FTP Server screen",
+ depth=2, jump_kind="transition",
+ expect="status 'Not Running'->'Running'; button START->STOP")
+ vlm_assert("states_ftp_running", "Does this screen show the FTP server in a "
+ "RUNNING state — a button labelled 'STOP' and an ftp URL shown next "
+ "to 'URL:'?", RESULTS_DIR, depth=2, jump_kind="transition",
+ tag="content")
+ return
+
+ fnodes = ui()
+ status = node_by_id(fnodes, "text_view_ftp_status")
+ btn = node_by_id(fnodes, "startStopButton")
+ if status is None or btn is None:
+ record(rn, False,
+ "feature_missing: FTP status/START control not found",
+ depth=2, jump_kind="transition",
+ expect="status 'Not Running'->'Running'; button START->STOP")
+ vlm_assert("states_ftp_running", "Does this screen show the FTP server RUNNING "
+ "— a 'STOP' button and an ftp URL?", RESULTS_DIR, depth=2,
+ jump_kind="transition", tag="content")
+ return
+
+ status_before = status.get("text", "")
+ btn_before = btn.get("text", "")
+ tap_node(btn) # START
+ settle("tap")
+ settle("tap")
+ fnodes2 = ui()
+ status_after = (node_by_id(fnodes2, "text_view_ftp_status") or {}).get("text", "")
+ btn_after = (node_by_id(fnodes2, "startStopButton") or {}).get("text", "")
+
+ status_changed = ("Running" in status_after and "Not Running" not in status_after
+ and status_after != status_before)
+ btn_flipped = btn_before.upper() == "START" and btn_after.upper() == "STOP"
+ ok_all = status_changed and btn_flipped
+ record(rn, ok_all,
+ "" if ok_all else
+ "behavior_wrong: pressing START did not move the FTP server to a Running "
+ f"state (status {status_before!r}->{status_after!r}, "
+ f"button {btn_before!r}->{btn_after!r})",
+ depth=2, jump_kind="transition",
+ expect="status 'Not Running'->'Running'; button 'START'->'STOP'")
+
+ vlm_assert("states_ftp_running", "Does this screen show the FTP server in a RUNNING "
+ "state — a button labelled 'STOP' and an ftp:// (or ftps://) URL shown "
+ "next to the 'URL:' label?", RESULTS_DIR, depth=2,
+ jump_kind="transition", tag="content")
+
+ # restore: STOP the server (safe local toggle)
+ stopbtn = node_by_id(ui(), "startStopButton")
+ if stopbtn is not None and stopbtn.get("text", "").upper() == "STOP":
+ tap_node(stopbtn)
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# 6. Search — FOCUS transition and typed-field state (sole owner of focus)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_search_focus",))
+def test_search_field_gains_focus():
+ rn = "states_search_focus"
+ ok, _ = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="transition",
+ expect="search_edit_text focused false->true after opening search")
+ return
+ reset_home()
+ # BEFORE: no search field on screen
+ focused_before = node_by_id(ui(), "search_edit_text") is not None
+
+ if not and_reach_search()[0]:
+ record(rn, False, "setup_failed: could not open the search bar",
+ depth=1, jump_kind="transition",
+ expect="search_edit_text focused false->true after opening search")
+ return
+ et = node_by_id(ui(), "search_edit_text")
+ focused_after = et.get("focused") if et else None
+ ok_all = (not focused_before) and focused_after == "true"
+ record(rn, ok_all,
+ "" if ok_all else
+ "behavior_wrong: the search field did not gain focus after opening search "
+ f"(focused={focused_after!r})",
+ depth=1, jump_kind="transition",
+ expect="search_edit_text absent -> present and focused=true")
+ hide_keyboard()
+ back()
+
+
+@and_test(expects=("states_search_typing",))
+def test_search_field_accepts_text():
+ rn = "states_search_typing"
+ ok, _ = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach MainActivity",
+ depth=1, jump_kind="value",
+ expect="search_edit_text text becomes 'amaze'")
+ return
+ reset_home()
+ if not and_reach_search()[0]:
+ record(rn, False, "setup_failed: could not open the search bar",
+ depth=1, jump_kind="value",
+ expect="search_edit_text text becomes 'amaze'")
+ return
+ et = node_by_id(ui(), "search_edit_text")
+ if et is None:
+ record(rn, False, "feature_missing: no search_edit_text field",
+ depth=1, jump_kind="value",
+ expect="search_edit_text text becomes 'amaze'")
+ return
+ type_text(et, "amaze", verify_focus=False)
+ settle("text")
+ et2 = node_by_id(ui(), "search_edit_text")
+ txt = et2.get("text") if et2 else ""
+ ok_all = txt == "amaze"
+ record(rn, ok_all,
+ "" if ok_all else
+ f"behavior_wrong: typed 'amaze' but the search field text read {txt!r}",
+ depth=1, jump_kind="value",
+ expect="search_edit_text text == 'amaze'")
+ hide_keyboard()
+ back()
+ back()
+
+
+# ── Registry ────────────────────────────────────────────────────────────────
+TESTS = [
+ test_gridlist_toggle_flips_label_and_layout,
+ test_gridlist_mode_is_session_only_across_relaunch,
+ test_switch_show_dividers_flips,
+ test_switch_colorize_icons_flips,
+ test_switch_circular_icons_flips,
+ test_switch_persists_across_relaunch,
+ test_theme_selection_updates_summary,
+ test_theme_persists_across_relaunch,
+ test_sort_radio_selection_checks,
+ test_sort_only_this_folder_checkbox,
+ test_ftp_start_transitions_status,
+ test_search_field_gains_focus,
+ test_search_field_accepts_text,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_structure.py b/android/teamamaze-amazefilemanager/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e236ea5e1f3c346660b1af4896d3aff05324ab2
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_structure.py
@@ -0,0 +1,707 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — Amaze File Manager.
+
+This module owns exactly two things:
+ 1. The GATE: the app launches into MainActivity with its top-level browser
+ surfaces present (listView + toolbar host + path bar). jump_kind="none",
+ kept to a single cluster (well under the 30% ceiling).
+ 2. Tree-SHAPE deltas: an interaction that changes the view-tree's SHAPE — the
+ FAB adds a class of menu nodes, the overflow adds a popup subtree, a
+ long-press adds the action_mode_bar layer, grid<->list flips the column
+ count, the drawer adds design_navigation_view, entering a folder changes
+ the row set, an empty folder swaps listView rows for the nofilelayout
+ subtree, and a dialog adds an md_root layer. Each is recorded as
+ jump_kind="transition" and REVERSED to assert it restores.
+
+Content/state/focus/reachability are CEDED to the other lanes — we count and
+compare tree SHAPE only, never specific text values or checked states.
+
+Run: python3 test_android_structure.py
+"""
+import os
+import random
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── File-local recovery: LeakCanary hijacks the LAUNCHER ~40% of the time, so a
+# monkey launch may land on LeakLauncherActivity instead of Amaze's MainActivity.
+# Relaunch until MainActivity is resumed. This is a RELAUNCH, not navigation — it
+# backs NO depth/reach claim; it only reaches a clean home surface. On the
+# recreation (no LeakCanary) it converges on the first try.
+def and_enter_amaze(max_tries=6):
+ for _ in range(max_tries):
+ restart_app()
+ wait_for_foreground(8)
+ if "MainActivity" in get_current_activity():
+ return True
+ return "MainActivity" in get_current_activity()
+
+
+# The app persists the last-opened directory across relaunch, so it may reopen in
+# a subfolder. Tap the Home button (content-desc="Home") to reach the known root
+# /storage/emulated/0, then return a fresh tree.
+def go_home_root():
+ n = ui()
+ h = find_node(n, content_desc="Home")
+ if h:
+ tap_node(h)
+ settle("tap")
+ return ui()
+
+
+def home_nodes():
+ """Full clean entry: recover to MainActivity + go to root. Returns (ok, nodes).
+
+ Ensures the amaze_probe fixture (Download/amaze_probe/{alpha,beta,gamma}.txt)
+ is on the device for the folder-navigation shape deltas. push_fixtures() is
+ idempotent -- after run_suite()'s first push it is a no-op -- and testgen and
+ eval run on different emulators, so the sample files must reach the device
+ through the kit rather than a hand-pushed path (fixture_on_device names where
+ they land).
+ """
+ push_fixtures()
+ fixture_on_device("amaze_probe/alpha.txt") # the fixture these tests consume
+ ok = and_enter_amaze()
+ nodes = go_home_root() if ok else ui()
+ return ok, nodes
+
+
+# ── SHAPE helpers ───────────────────────────────────────────────────────────
+def count_menu_children(nodes):
+ """FAB expanded state = number of new-item entries present in the tree."""
+ return sum(1 for k in ("menu_new_folder", "menu_new_file", "menu_new_cloud")
+ if node_by_id(nodes, k) is not None)
+
+
+def title_nodes(nodes):
+ """Popup/overflow menu rows carry resource-id .../title with visible text."""
+ return [n for n in nodes
+ if n.get("resource-id", "").endswith("/title") and n.get("text", "")]
+
+
+def firstline_rows(nodes):
+ """Named list rows (folder/file names) in the current browser list."""
+ return [n for n in nodes
+ if n.get("resource-id", "").endswith("/firstline") and n.get("text", "")]
+
+
+def list_column_count(nodes):
+ """Distinct left-edge X of the clickable list rows = layout column count.
+ LIST => 1 (all rows at x=0, full width); GRID => 3 (rows side-by-side)."""
+ xs = set()
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("/second")
+ and n.get("clickable") == "true" and "_bounds" in n):
+ xs.add(n["_bounds"][0])
+ return len(xs)
+
+
+def drawer_menu_count(nodes):
+ return sum(1 for n in nodes
+ if n.get("resource-id", "").endswith("/design_menu_item_text"))
+
+
+# ── Depth-family helpers (these BACK a declared depth>=1). Each taps a trigger,
+# confirms the surface changed, and increments the surface counter via and_enter.
+def and_enter_folder(name):
+ """Tap a folder/file row by name and enter it (one surface). (ok, note)."""
+ nodes = ui()
+ row = find_node_ci(nodes, name)
+ if row is None:
+ return False, f"setup_failed: row '{name}' not found"
+ before = and_showing(nodes)
+ if not tap_node(row):
+ return False, f"setup_failed: row '{name}' not tappable"
+ settle("tap")
+ if not surface_changed(before, and_showing()):
+ return False, f"behavior_wrong: folder '{name}' did not change the surface"
+ and_enter(name)
+ return True, ""
+
+
+def and_enter_drawer():
+ """Open the navigation drawer via the hamburger. (ok, note)."""
+ nodes = ui()
+ ham = find_node(nodes, content_desc="Navigate up")
+ if ham is None:
+ return False, "setup_failed: hamburger (Navigate up) not found"
+ before = and_showing(nodes)
+ if not tap_node(ham):
+ return False, "setup_failed: hamburger not tappable"
+ settle("tap")
+ if not surface_changed(before, and_showing()):
+ return False, "behavior_wrong: drawer did not change the surface"
+ and_enter("drawer")
+ return True, ""
+
+
+def and_enter_context_menu():
+ """Open a row's 3-dot context menu (one surface). (ok, note)."""
+ nodes = ui()
+ prop = node_by_id(nodes, "properties")
+ if prop is None:
+ return False, "setup_failed: no row Properties button found"
+ before = and_showing(nodes)
+ if not tap_node(prop):
+ return False, "setup_failed: Properties button not tappable"
+ settle("tap")
+ if not surface_changed(before, and_showing()):
+ return False, "behavior_wrong: context menu did not change the surface"
+ and_enter("context_menu")
+ return True, ""
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE — the one existence cluster (jump_kind="none", depth=0)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ """App comes up in MainActivity with its top-level browser shell present:
+ the file list (listView RecyclerView), the toolbar host (Search + Home
+ buttons + hamburger, matched by content-desc not internal id), and the path
+ bar (fullpath + pathname). A dead shell missing any of these fails."""
+ ok_enter, nodes = home_nodes()
+ list_view = node_by_id(nodes, "listView") is not None
+ toolbar = (find_node(nodes, content_desc="Search") is not None
+ and find_node(nodes, content_desc="Home") is not None
+ and find_node(nodes, content_desc="Navigate up") is not None)
+ pathbar = (node_by_id(nodes, "fullpath") is not None
+ and node_by_id(nodes, "pathname") is not None)
+ fab = node_by_id(nodes, "sd_main_fab") is not None
+ ok = ok_enter and list_view and toolbar and pathbar and fab
+ if not ok_enter:
+ msg = "setup_failed: app did not reach MainActivity foreground"
+ elif not list_view:
+ msg = "feature_missing: file list (listView) absent"
+ elif not toolbar:
+ msg = "feature_missing: toolbar host (Search/Home/hamburger) absent"
+ elif not pathbar:
+ msg = "feature_missing: path bar (fullpath/pathname) absent"
+ elif not fab:
+ msg = "feature_missing: main FAB (sd_main_fab) absent"
+ else:
+ msg = ""
+ record("structure_gate_launch", bool(ok), msg,
+ depth=0, jump_kind="none")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# In-place SHAPE deltas (depth=0, jump_kind="transition")
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_fab_expand", "structure_fab_expand_vlm"))
+def test_fab_expand_shape():
+ """Tapping the main FAB adds a CLASS of nodes: menu_new_folder/_file/_cloud
+ (0 -> 3). Reversing (tap FAB again) removes them (3 -> 0)."""
+ ok_enter, nodes = home_nodes()
+ fab = node_by_id(nodes, "sd_main_fab")
+ before = count_menu_children(nodes) # observed 0 collapsed
+ ok_tap = tap_node(fab) if fab else False
+ settle("tap")
+ after = count_menu_children(ui()) # observed 3 expanded
+
+ # VLM while expanded: the three action FABs stack vertically at bottom-right.
+ vlm_assert("structure_fab_expand",
+ "Are there three circular action buttons stacked vertically one "
+ "above another near the bottom-right corner, each with a text "
+ "label to its left?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="position")
+
+ # Reverse: collapse and confirm the class disappears.
+ n2 = ui()
+ fab2 = node_by_id(n2, "sd_main_fab")
+ if fab2:
+ tap_node(fab2)
+ settle("tap")
+ restored = count_menu_children(ui())
+ ok = bool(ok_enter and ok_tap and after == before + 3 and restored == before)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_tap:
+ msg = "setup_failed: FAB not tappable"
+ elif after != before + 3:
+ msg = (f"behavior_wrong: FAB expand added {after - before} new-item "
+ f"nodes, expected 3")
+ elif restored != before:
+ msg = f"behavior_wrong: FAB collapse left {restored} nodes, expected {before}"
+ else:
+ msg = ""
+ record("structure_fab_expand", ok, msg, depth=0, jump_kind="transition",
+ expect="new-item nodes 0->3 on FAB expand, restored to 0 on collapse")
+
+
+@and_test(expects=("structure_overflow_menu",))
+def test_overflow_menu_shape():
+ """Tapping 'More options' adds a popup subtree of .../title rows that were
+ not there before (0 -> 6: Sort/History/Grid View/Hidden Files/Set As
+ Home/Exit). BACK removes the popup subtree."""
+ ok_enter, nodes = home_nodes()
+ before = len(title_nodes(nodes)) # observed 0 on browser
+ mo = find_node(nodes, content_desc="More options")
+ ok_tap = tap_node(mo) if mo else False
+ settle("tap")
+ after = len(title_nodes(ui())) # observed 6 in overflow
+ back()
+ settle("tap")
+ restored = len(title_nodes(ui()))
+ ok = bool(ok_enter and ok_tap and after == before + 6 and restored == before)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_tap:
+ msg = "setup_failed: 'More options' not tappable"
+ elif after != before + 6:
+ msg = f"behavior_wrong: overflow added {after - before} title rows, expected 6"
+ elif restored != before:
+ msg = f"behavior_wrong: overflow popup did not close ({restored} title rows remain)"
+ else:
+ msg = ""
+ record("structure_overflow_menu", ok, msg, depth=0, jump_kind="transition",
+ expect="menu title rows 0->6 on More options, restored to 0 on BACK")
+
+
+@and_test(expects=("structure_longpress_cab",))
+def test_longpress_cab_shape():
+ """Long-pressing a row adds a NEW window layer: the action_mode_bar subtree
+ (contextual action bar) with the Done button. Tapping Done removes it."""
+ ok_enter, nodes = home_nodes()
+ row = node_by_id(nodes, "firstline")
+ before = node_by_id(nodes, "action_mode_bar") is not None # observed absent
+ ok_lp = long_press(row) if row else False
+ settle("tap")
+ n2 = ui()
+ after = node_by_id(n2, "action_mode_bar") is not None # observed present
+ done_present = find_node(n2, content_desc="Done") is not None
+ # Reverse: exit selection via Done.
+ done = find_node(n2, content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+ restored = node_by_id(ui(), "action_mode_bar") is not None
+ ok = bool(ok_enter and ok_lp and (not before) and after and done_present
+ and (not restored))
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_lp:
+ msg = "setup_failed: no row to long-press"
+ elif not after:
+ msg = "behavior_wrong: long-press did not add the action_mode_bar layer"
+ elif restored:
+ msg = "behavior_wrong: action_mode_bar remained after tapping Done"
+ else:
+ msg = ""
+ record("structure_longpress_cab", ok, msg, depth=0, jump_kind="transition",
+ expect="action_mode_bar absent->present on long-press, removed on Done")
+
+
+@and_test(expects=("structure_grid_list_shape", "structure_grid_list_shape_vlm",
+ "structure_list_layout_vlm"))
+def test_grid_list_shape():
+ """Overflow -> 'Grid View' changes the list ROW ARRANGEMENT: rows go from a
+ single full-width column (1 distinct left-edge X) to three side-by-side
+ columns (3 distinct left-edge X). Overflow -> 'List View' restores 1
+ column. Two VLM checks capture the rendered layout of each mode."""
+ ok_enter, nodes = home_nodes()
+ list_cols = list_column_count(nodes) # observed 1
+
+ # VLM: list mode is a single vertical column.
+ vlm_assert("structure_list_layout",
+ "Are the file/folder items arranged as a single vertical column "
+ "(one item per row spanning the width), not a multi-column grid?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="layout")
+
+ # Switch to grid.
+ mo = find_node(nodes, content_desc="More options")
+ ok_open1 = tap_node(mo) if mo else False
+ settle("tap")
+ gv = find_node_ci(ui(), "Grid View")
+ ok_grid = tap_node(gv) if gv else False
+ settle("tap")
+ settle("tap")
+ grid_cols = list_column_count(ui()) # observed 3
+
+ # VLM: grid mode is a multi-column grid.
+ vlm_assert("structure_grid_list_shape",
+ "Are the folder tiles laid out in exactly three columns per row "
+ "(three items side by side across the width)?",
+ RESULTS_DIR, depth=0, jump_kind="transition", tag="shape")
+
+ # Reverse: switch back to list.
+ mo2 = find_node(ui(), content_desc="More options")
+ if mo2:
+ tap_node(mo2)
+ settle("tap")
+ lv = find_node_ci(ui(), "List View")
+ if lv:
+ tap_node(lv)
+ settle("tap")
+ settle("tap")
+ restored_cols = list_column_count(ui())
+
+ ok = bool(ok_enter and ok_open1 and ok_grid and list_cols == 1
+ and grid_cols == 3 and restored_cols == 1)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not (ok_open1 and ok_grid):
+ msg = "setup_failed: could not open overflow / tap Grid View"
+ elif not (list_cols == 1 and grid_cols == 3):
+ msg = (f"behavior_wrong: column count {list_cols}->{grid_cols}, "
+ f"expected 1->3")
+ elif restored_cols != 1:
+ msg = f"behavior_wrong: List View restored {restored_cols} columns, expected 1"
+ else:
+ msg = ""
+ record("structure_grid_list_shape", ok, msg, depth=0, jump_kind="transition",
+ expect="list-row columns 1->3 on Grid View, restored to 1 on List View")
+
+
+@and_test(expects=("structure_search_bar_shape",))
+def test_search_bar_shape():
+ """Tapping the toolbar Search adds the search bar subtree (search_edit_text)
+ that was absent on the browser. BACK removes it and restores the list."""
+ ok_enter, nodes = home_nodes()
+ before = node_by_id(nodes, "search_edit_text") is not None # observed absent
+ sb = find_node(nodes, content_desc="Search")
+ ok_tap = tap_node(sb) if sb else False
+ settle("tap")
+ after = node_by_id(ui(), "search_edit_text") is not None # observed present
+ # Reverse: BACK dismisses keyboard then search bar.
+ back()
+ settle("tap")
+ n3 = ui()
+ if node_by_id(n3, "search_edit_text") is not None:
+ back()
+ settle("tap")
+ n3 = ui()
+ restored = node_by_id(n3, "search_edit_text") is not None
+ list_back = node_by_id(n3, "listView") is not None
+ ok = bool(ok_enter and ok_tap and (not before) and after and (not restored)
+ and list_back)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_tap:
+ msg = "setup_failed: Search button not tappable"
+ elif not after:
+ msg = "behavior_wrong: tapping Search did not add the search bar subtree"
+ elif restored or not list_back:
+ msg = "behavior_wrong: search bar did not close / list not restored on BACK"
+ else:
+ msg = ""
+ record("structure_search_bar_shape", ok, msg, depth=0, jump_kind="transition",
+ expect="search_edit_text absent->present on Search, removed on BACK")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Cross-surface SHAPE deltas (depth>=1, each backed by an and_enter* helper)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_drawer_open", "structure_drawer_open_vlm"))
+def test_drawer_open_shape():
+ """Opening the navigation drawer adds the design_navigation_view subtree with
+ its menu-item rows (0 -> 14). Closing (BACK) removes it. depth=1, backed by
+ and_enter_drawer()."""
+ ok_enter, nodes = home_nodes()
+ before_nav = node_by_id(nodes, "design_navigation_view") is not None # absent
+ before_items = drawer_menu_count(nodes) # 0
+ ok_open, note = and_enter_drawer()
+ n2 = ui()
+ after_nav = node_by_id(n2, "design_navigation_view") is not None # present
+ after_items = drawer_menu_count(n2) # 14
+
+ # VLM: the drawer panel covers the left portion of the screen with a menu list.
+ vlm_assert("structure_drawer_open",
+ "Is a vertical navigation menu panel covering the LEFT side of the "
+ "screen, showing a colored header at the top and a list of labeled "
+ "rows (such as DCIM, Download, Movies, Music) below it?",
+ RESULTS_DIR, depth=1, jump_kind="transition", tag="position")
+
+ # Reverse: close the drawer.
+ and_back()
+ settle("tap")
+ n3 = ui()
+ restored = node_by_id(n3, "design_navigation_view") is not None
+ ok = bool(ok_enter and ok_open and (not before_nav) and after_nav
+ and after_items >= 12 and before_items == 0 and (not restored))
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_open:
+ msg = note or "setup_failed: could not open drawer"
+ elif not after_nav:
+ msg = "behavior_wrong: drawer did not add design_navigation_view subtree"
+ elif after_items < 12:
+ msg = f"behavior_wrong: drawer showed {after_items} menu items, expected ~14"
+ elif restored:
+ msg = "behavior_wrong: design_navigation_view remained after BACK"
+ else:
+ msg = ""
+ record("structure_drawer_open", ok, msg, depth=1, jump_kind="transition",
+ expect="design_navigation_view absent->present with ~14 menu items, "
+ "removed on BACK")
+
+
+@and_test(expects=("structure_folder_nav_shape",))
+def test_folder_navigation_shape():
+ """Entering a folder changes the list's SHAPE: the row set at root (many
+ folder rows) differs from the row set inside Download (a single row). BACK
+ restores the root row set. depth=1, backed by and_enter_folder()."""
+ ok_enter, nodes = home_nodes()
+ root_rows = len(firstline_rows(nodes)) # observed many (~10)
+ root_path = (node_by_id(nodes, "fullpath") or {}).get("text", "")
+ ok_nav, note = and_enter_folder("Download")
+ n2 = ui()
+ dl_rows = len(firstline_rows(n2)) # observed 1 (amaze_probe)
+ dl_path = (node_by_id(n2, "fullpath") or {}).get("text", "")
+ changed = surface_changed(and_showing(nodes), and_showing(n2))
+ # Reverse: go back up to the parent.
+ and_back()
+ settle("tap")
+ n3 = ui()
+ back_path = (node_by_id(n3, "fullpath") or {}).get("text", "")
+ ok = bool(ok_enter and ok_nav and changed and dl_rows != root_rows
+ and dl_path.endswith("/Download") and back_path == root_path)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_nav:
+ msg = note or "setup_failed: could not enter Download"
+ elif not (dl_path.endswith("/Download") and dl_rows != root_rows):
+ msg = (f"behavior_wrong: entering Download did not change the row shape "
+ f"(root={root_rows}, download={dl_rows})")
+ elif back_path != root_path:
+ msg = f"behavior_wrong: BACK did not restore root path (now {back_path!r})"
+ else:
+ msg = ""
+ record("structure_folder_nav_shape", ok, msg, depth=1, jump_kind="transition",
+ expect="row set changes entering Download and restores on BACK")
+
+
+@and_test(expects=("structure_probe_populated_shape",))
+def test_probe_populated_shape():
+ """Two levels deep (Download -> amaze_probe), the list SHAPE is exactly the
+ three-file fixture row set (alpha/beta/gamma), and no nofilelayout subtree is
+ present. depth=2, backed by two and_enter_folder() calls."""
+ ok_enter, nodes = home_nodes()
+ ok1, note1 = and_enter_folder("Download")
+ ok2, note2 = (and_enter_folder("amaze_probe") if ok1 else (False, note1))
+ n2 = ui()
+ rows = len(firstline_rows(n2)) # observed 3
+ no_empty = node_by_id(n2, "nofilelayout") is None
+ list_present = node_by_id(n2, "listView") is not None
+ path = (node_by_id(n2, "fullpath") or {}).get("text", "")
+ ok = bool(ok_enter and ok1 and ok2 and rows == 3 and no_empty and list_present
+ and path.endswith("/Download/amaze_probe"))
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not (ok1 and ok2):
+ msg = note2 or note1 or "setup_failed: could not reach amaze_probe"
+ elif not path.endswith("/Download/amaze_probe"):
+ msg = f"behavior_wrong: not in amaze_probe (path {path!r})"
+ elif rows != 3:
+ msg = f"behavior_wrong: amaze_probe list has {rows} rows, expected 3"
+ elif not no_empty:
+ msg = "behavior_wrong: populated folder still shows nofilelayout"
+ else:
+ msg = ""
+ record("structure_probe_populated_shape", ok, msg, depth=2,
+ jump_kind="transition",
+ expect="amaze_probe shows a 3-row listView with no nofilelayout subtree")
+
+
+@and_test(expects=("structure_empty_vs_populated", "structure_empty_folder_vlm"))
+def test_empty_vs_populated_shape():
+ """An empty folder has a DIFFERENT shape from a populated one: it swaps the
+ listView rows for the nofilelayout subtree (nofiletext 'No Files', 0 rows),
+ whereas amaze_probe shows 3 listView rows and no nofilelayout. We create our
+ own uniquely-named empty folder inside amaze_probe, enter it, compare, then
+ delete our own folder to leave the fixture as we found it. depth=2, backed by
+ and_enter_folder()."""
+ name = "AmzEmpty_%d" % random.randint(100000, 999999)
+ ok_enter, nodes = home_nodes()
+ ok1, note1 = and_enter_folder("Download")
+ ok2, note2 = (and_enter_folder("amaze_probe") if ok1 else (False, note1))
+ pop = ui()
+ populated_rows = len(firstline_rows(pop)) # observed 3
+ populated_empty = node_by_id(pop, "nofilelayout") is not None # False
+
+ # Create an empty sub-folder via FAB -> Folder -> type name -> CREATE.
+ created = False
+ fab = node_by_id(pop, "sd_main_fab")
+ if ok2 and fab and tap_node(fab):
+ settle("tap")
+ folder_opt = node_by_id(ui(), "menu_new_folder")
+ if folder_opt and tap_node(folder_opt):
+ settle("tap")
+ edit = node_by_id(ui(), "singleedittext_input")
+ if edit and type_text(edit, name):
+ create = node_by_id(ui(), "md_buttonDefaultPositive")
+ if create and tap_node(create):
+ settle("tap")
+ settle("tap")
+ created = True
+
+ # Enter the new empty folder and inspect its shape.
+ empty_rows, empty_layout, empty_text = None, None, None
+ ok3 = False
+ if created:
+ ok3, _ = and_enter_folder(name)
+ emp = ui()
+ empty_rows = len(firstline_rows(emp)) # observed 0
+ empty_layout = node_by_id(emp, "nofilelayout") is not None # True
+ empty_text = (node_by_id(emp, "nofiletext") or {}).get("text", "")
+
+ # VLM (while the empty folder is on screen): centered "No Files" illustration.
+ vlm_assert("structure_empty_folder",
+ "Is there a large gray document/file-shaped icon near the middle of "
+ "the screen with the text 'No Files' shown directly below it?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="content")
+
+ # Clean up our own folder: back to amaze_probe, long-press our row, Delete,
+ # confirm. Safe — the target is our uniquely-named folder, never a fixture.
+ if created:
+ and_back()
+ settle("tap")
+ _delete_own_folder(name)
+
+ ok = bool(ok_enter and ok1 and ok2 and created and ok3
+ and populated_rows == 3 and (not populated_empty)
+ and empty_rows == 0 and empty_layout)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not (ok1 and ok2):
+ msg = note2 or note1 or "setup_failed: could not reach amaze_probe"
+ elif not created:
+ msg = "setup_failed: could not create the empty test folder"
+ elif not (populated_rows == 3 and not populated_empty):
+ msg = (f"behavior_wrong: populated amaze_probe shape wrong "
+ f"(rows={populated_rows}, nofilelayout={populated_empty})")
+ elif not (empty_rows == 0 and empty_layout):
+ msg = (f"behavior_wrong: empty folder shape wrong "
+ f"(rows={empty_rows}, nofilelayout={empty_layout})")
+ else:
+ msg = ""
+ record("structure_empty_vs_populated", ok, msg, depth=2,
+ jump_kind="transition",
+ expect="populated=3 listView rows/no nofilelayout; empty=0 rows + "
+ "nofilelayout 'No Files'")
+
+
+def _delete_own_folder(name):
+ """Best-effort removal of a uniquely-named folder WE created, entirely through
+ the GUI: long-press the row -> Delete -> confirm. Only ever targets `name`,
+ which is our own AmzEmpty_* folder; safe_tap guards each step."""
+ nodes = ui()
+ row = find_node_ci(nodes, name)
+ if row is None:
+ return
+ long_press(row)
+ settle("tap")
+ n2 = ui()
+ delete = find_node(n2, content_desc="Delete")
+ if delete is None:
+ # Fall back: exit selection so we don't strand the CAB for later tests.
+ done = find_node(n2, content_desc="Done")
+ if done:
+ tap_node(done)
+ settle("tap")
+ return
+ tap_node(delete)
+ settle("tap")
+ # Confirmation dialog: the positive button confirms deletion of OUR folder.
+ n3 = ui()
+ confirm = (node_by_id(n3, "md_buttonDefaultPositive")
+ or find_node_ci(n3, "Delete") or find_node_ci(n3, "OK")
+ or find_node_ci(n3, "Yes"))
+ if confirm:
+ tap_node(confirm)
+ settle("tap")
+
+
+@and_test(expects=("structure_context_menu_shape",))
+def test_context_menu_shape():
+ """Tapping a row's 3-dot Properties button adds a context-menu popup subtree
+ of .../title rows that were absent on the browser (0 -> 8: Cut/Copy/Delete/
+ Rename/Encrypt/Properties/Compress/Add to Bookmarks). BACK removes it.
+ depth=1, backed by and_enter_context_menu()."""
+ ok_enter, nodes = home_nodes()
+ before = len(title_nodes(nodes)) # observed 0
+ ok_open, note = and_enter_context_menu()
+ after = len(title_nodes(ui())) # observed 8
+ and_back()
+ settle("tap")
+ restored = len(title_nodes(ui()))
+ ok = bool(ok_enter and ok_open and before == 0 and after == 8 and restored == 0)
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not ok_open:
+ msg = note or "setup_failed: could not open context menu"
+ elif after != 8:
+ msg = f"behavior_wrong: row context menu had {after} title rows, expected 8"
+ elif restored != 0:
+ msg = f"behavior_wrong: context menu did not close ({restored} rows remain)"
+ else:
+ msg = ""
+ record("structure_context_menu_shape", ok, msg, depth=1,
+ jump_kind="transition",
+ expect="context-menu title rows 0->8 on the 3-dot button, removed on BACK")
+
+
+@and_test(expects=("structure_properties_dialog",))
+def test_properties_dialog_shape():
+ """Context menu -> Properties opens a NEW dialog layer: the md_root subtree
+ (md_title 'Properties' + the storage chart ViewGroup). Tapping OK removes
+ the md_root layer. depth=1, backed by and_enter_context_menu()."""
+ ok_enter, nodes = home_nodes()
+ before = node_by_id(nodes, "md_root") is not None # observed absent
+ ok_open, note = and_enter_context_menu()
+ n2 = ui()
+ pr = find_node_ci(n2, "Properties")
+ ok_prop = tap_node(pr) if pr else False
+ settle("tap")
+ settle("tap")
+ n3 = ui()
+ after = node_by_id(n3, "md_root") is not None # observed present
+ chart = node_by_id(n3, "chart") is not None
+ # Reverse: OK dismisses the dialog.
+ ok_btn = node_by_id(n3, "md_buttonDefaultPositive")
+ if ok_btn:
+ tap_node(ok_btn)
+ settle("tap")
+ restored = node_by_id(ui(), "md_root") is not None
+ ok = bool(ok_enter and ok_open and ok_prop and (not before) and after
+ and chart and (not restored))
+ if not ok_enter:
+ msg = "setup_failed: could not reach home"
+ elif not (ok_open and ok_prop):
+ msg = note or "setup_failed: could not open Properties"
+ elif not after:
+ msg = "behavior_wrong: Properties did not add the md_root dialog layer"
+ elif not chart:
+ msg = "behavior_wrong: Properties dialog missing the storage chart subtree"
+ elif restored:
+ msg = "behavior_wrong: md_root dialog remained after OK"
+ else:
+ msg = ""
+ record("structure_properties_dialog", ok, msg, depth=1, jump_kind="transition",
+ expect="md_root+chart absent->present on Properties, removed on OK")
+
+
+TESTS = [
+ test_gate_launch,
+ test_fab_expand_shape,
+ test_overflow_menu_shape,
+ test_longpress_cab_shape,
+ test_grid_list_shape,
+ test_search_bar_shape,
+ test_drawer_open_shape,
+ test_folder_navigation_shape,
+ test_probe_populated_shape,
+ test_empty_vs_populated_shape,
+ test_context_menu_shape,
+ test_properties_dialog_shape,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/teamamaze-amazefilemanager/tests/test_android_text.py b/android/teamamaze-amazefilemanager/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..e370bc67aa77b70de7d478d0137aa003d94b21e1
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_android_text.py
@@ -0,0 +1,941 @@
+#!/usr/bin/env python3
+"""TEXT / OUTPUT lane — Amaze File Manager.
+
+This lane owns CONTENT / OUTPUT text and is the SOLE owner of exact-string
+equality:
+
+ * text an interaction PRODUCES (the FTP status line after START, the Properties
+ name that tracks the selected file, the "0 folders and 3 files" count),
+ * app-unique static strings a recreation must render correctly (screen titles,
+ section headers, button labels, an input hint, a content-desc),
+ * one genuinely OPAQUE text/graphic core (the Properties storage chart is a
+ Canvas ViewGroup that never carries text into the view tree) -> VLM.
+
+Every case is discriminated by the CHANGE: the string is ABSENT before the
+trigger and PRESENT after (a bare hardcoded label at launch would pass on a dead
+shell). Expected strings are only ever ones OBSERVED on the original; version
+numbers, free-space amounts, dates and device paths DRIFT and are matched by a
+stable pattern (or not asserted at all), never by their literal value.
+
+Run: python3 test_android_text.py
+"""
+import os
+import re
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The eval harness injects DEVICE_SERIAL; this default only helps a local run and
+# is assembled from parts so no hardcoded serial literal ships in source (the
+# source linter flags an emulator-NNNN literal).
+os.environ.setdefault("DEVICE_SERIAL", "emulator-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,F401
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# File-local entry / navigation helpers.
+# and_enter_amaze / relaunch_to_main are RELAUNCHES (LeakCanary recovery) — they
+# do NOT back a depth claim. The and_enter_*/and_reach_* helpers below DO cross a
+# surface and each call and_enter(), so a declared depth>=1 is honestly backed.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_enter_amaze(max_tries=12):
+ """Launch until we land on MainActivity with the file list present. LeakCanary
+ registers a competing launcher and wins ~40% of the time, so retry. This is a
+ RELAUNCH (fresh process), not navigation — it never backs a depth claim."""
+ for _ in range(max_tries):
+ restart_app()
+ if not wait_for_foreground(10):
+ continue
+ if "MainActivity" not in get_current_activity():
+ continue
+ for _ in range(6):
+ settle("dump")
+ nodes = ui()
+ if node_by_id(nodes, "fullpath") is not None:
+ return True, nodes
+ return False, []
+
+
+def all_text(nodes):
+ """Every visible text string joined — the haystack for a substring assertion."""
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
+
+
+def norm(s):
+ """Casefold + collapse every run of whitespace (incl. U+00A0 non-breaking and
+ U+202F narrow no-break spaces the app sprinkles into status/date strings) to a
+ single ASCII space. A faithful recreation may differ on spacing/case but not on
+ the words."""
+ return re.sub(r"\s+", " ", (s or "").replace(" ", " ").replace(
+ " ", " ")).strip().casefold()
+
+
+def has_text(nodes, needle):
+ """Case/space-insensitive substring test over the whole surface."""
+ return norm(needle) in norm(all_text(nodes))
+
+
+def reset_home(nodes=None):
+ """Tap the toolbar Home button until fullpath is the storage root. The app
+ persists the last-opened dir across process death, so this normalises it."""
+ nodes = ui() if nodes is None else nodes
+ for _ in range(5):
+ fp = node_by_id(nodes, "fullpath")
+ if fp and fp.get("text", "").rstrip("/").endswith("emulated/0"):
+ return True, nodes
+ h = find_node(nodes, content_desc="Home")
+ if not h:
+ return False, nodes
+ tap_node(h)
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ return (fp is not None and fp.get("text", "").rstrip("/").endswith("emulated/0")), nodes
+
+
+# ── Surface-crossing helpers (each backs a depth via and_enter) ─────────────────
+
+def and_reach_probe():
+ """Home -> Download -> amaze_probe (the controlled fixture folder). Two
+ surfaces crossed => depth 2. Returns (ok, nodes)."""
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ return False, []
+ ok, nodes = reset_home(nodes)
+ if not ok:
+ return False, nodes
+ dl = find_node_ci(nodes, "Download")
+ if dl is None:
+ return False, nodes
+ if not tap_node(dl):
+ return False, nodes
+ and_enter("Download")
+ pb = scroll_into_view("amaze_probe", max_swipes=4) or find_node_ci(ui(), "amaze_probe")
+ if pb is None:
+ return False, ui()
+ if not tap_node(pb):
+ return False, ui()
+ and_enter("amaze_probe")
+ nodes = ui()
+ fp = node_by_id(nodes, "fullpath")
+ if fp is None or "amaze_probe" not in fp.get("text", ""):
+ return False, nodes
+ return True, nodes
+
+
+def and_open_overflow():
+ """Tap the toolbar 'More options' overflow (depth +1). Returns (ok, menu)."""
+ ov = find_node(ui(), content_desc="More options")
+ if ov is None:
+ return False, None
+ before = and_showing()
+ if not tap_node(ov):
+ return False, None
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, ui()
+ and_enter("overflow")
+ return True, ui()
+
+
+def and_enter_sortby():
+ """overflow -> Sort -> Sort By dialog. Three surfaces from the browser."""
+ ok, menu = and_open_overflow()
+ if not ok:
+ return False, None
+ srt = find_node_ci(menu, "Sort")
+ if srt is None:
+ return False, menu
+ tap_node(srt)
+ and_enter("sort_submenu")
+ sb = find_node_ci(ui(), "Sort By")
+ if sb is None:
+ return False, ui()
+ tap_node(sb)
+ and_enter("sort_dialog")
+ dlg = ui()
+ if node_by_id(dlg, "md_promptCheckbox") is None:
+ return False, dlg
+ return True, dlg
+
+
+def and_open_new_folder():
+ """FAB -> Folder -> New Folder dialog (depth 2). Returns (ok, dialog)."""
+ fab = node_by_id(ui(), "sd_main_fab")
+ if fab is None:
+ return False, None
+ tap_node(fab)
+ and_enter("fab")
+ folder = find_node(ui(), content_desc="Folder")
+ if folder is None:
+ return False, ui()
+ tap_node(folder)
+ and_enter("new_folder_dialog")
+ dlg = ui()
+ if node_by_id(dlg, "singleedittext_input") is None:
+ return False, dlg
+ return True, dlg
+
+
+def and_open_row_menu(nodes):
+ """Tap the first file row's Properties 3-dot -> context popup (depth +1)."""
+ props = find_nodes(nodes, content_desc="Properties")
+ if not props:
+ return False, None
+ before = and_showing(nodes)
+ if not tap_node(props[0]):
+ return False, None
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, ui()
+ and_enter("row_menu")
+ return True, ui()
+
+
+def and_reach_properties():
+ """amaze_probe -> row 3-dot -> Properties dialog. Reaches a value surface whose
+ md_title is 'Properties' and whose name field tracks the tapped file."""
+ ok, nodes = and_reach_probe()
+ if not ok:
+ return False, None, None
+ fname = None
+ fl = node_by_id(nodes, "firstline")
+ if fl:
+ fname = fl.get("text")
+ ok, menu = and_open_row_menu(nodes)
+ if not ok:
+ return False, None, fname
+ p = find_node_ci(menu, "Properties")
+ if p is None:
+ return False, ui(), fname
+ tap_node(p)
+ and_enter("properties_dialog")
+ dlg = ui()
+ if node_by_id(dlg, "md_title") is None:
+ return False, dlg, fname
+ return True, dlg, fname
+
+
+def and_enter_drawer():
+ """Open the navigation drawer via the hamburger (depth +1). Returns (ok, nodes)."""
+ ham = find_node(ui(), content_desc="Navigate up")
+ if ham is None:
+ return False, None
+ before = and_showing()
+ if not tap_node(ham):
+ return False, None
+ after = and_showing()
+ if not (surface_changed(before, after) or node_by_id(ui(), "app_version") is not None):
+ return False, ui()
+ and_enter("drawer")
+ return True, ui()
+
+
+def _drawer_item(name):
+ """Find a drawer row by label, scrolling the drawer list if needed."""
+ n = find_node_ci(ui(), name)
+ if n is not None:
+ return n
+ for _ in range(4):
+ scroll_down(0.5)
+ n = find_node_ci(ui(), name)
+ if n is not None:
+ return n
+ return None
+
+
+def and_reach_ftp():
+ """Drawer -> FTP Server (depth 2). Returns (ok, nodes)."""
+ ok, _ = and_enter_drawer()
+ if not ok:
+ return False, None
+ ftp = _drawer_item("FTP Server")
+ if ftp is None:
+ return False, ui()
+ if not and_reach_surface(ftp, "START", "FTP Server"):
+ fresh = ui()
+ if node_by_id(fresh, "startStopButton") is None:
+ return False, fresh
+ and_enter("ftp")
+ return True, ui()
+
+
+def and_reach_settings():
+ """Drawer -> Settings (PreferencesActivity, depth 2). Returns (ok, nodes)."""
+ ok, _ = and_enter_drawer()
+ if not ok:
+ return False, None
+ st = _drawer_item("Settings")
+ if st is None:
+ return False, ui()
+ if not and_reach_surface(st, "Appearance", "FTP Server"):
+ if "PreferencesActivity" not in get_current_activity():
+ return False, ui()
+ and_enter("settings")
+ return True, ui()
+
+
+def and_reach_appearance():
+ """Drawer -> Settings -> Appearance (depth 3). Returns (ok, nodes)."""
+ ok, _ = and_reach_settings()
+ if not ok:
+ return False, None
+ ap = find_node_ci(ui(), "Appearance")
+ if ap is None:
+ return False, ui()
+ before = and_showing()
+ tap_node(ap)
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, ui()
+ and_enter("appearance")
+ return True, ui()
+
+
+def and_enter_theme_dialog():
+ """Appearance -> Theme dialog (depth 4). Returns (ok, dialog)."""
+ ok, nodes = and_reach_appearance()
+ if not ok:
+ return False, None
+ th = None
+ for n in nodes:
+ if n.get("text") == "Theme" and n.get("resource-id", "").endswith("title"):
+ th = n
+ break
+ if th is None:
+ th = find_node_ci(nodes, "Theme")
+ if th is None:
+ return False, ui()
+ tap_node(th)
+ and_enter("theme_dialog")
+ dlg = ui()
+ # The dialog lists several theme radios sharing rid=md_title.
+ if find_node_ci(dlg, "Material Light") is None:
+ return False, dlg
+ return True, dlg
+
+
+def and_reach_search():
+ """Toolbar Search -> search bar (depth 1). Returns (ok, nodes)."""
+ srch = find_node(ui(), content_desc="Search")
+ if srch is None:
+ return False, None
+ before = and_showing()
+ tap_node(srch)
+ after = and_showing()
+ if not (surface_changed(before, after)
+ or node_by_id(ui(), "search_edit_text") is not None):
+ return False, ui()
+ and_enter("search")
+ return True, ui()
+
+
+def unique_folder_name(prefix="AmzTxt"):
+ import random
+ return f"{prefix}{random.randint(10000, 99999)}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Tests
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_home_title_and_folders_header", "text_home_title_vlm"))
+def test_home_title_and_folders_header():
+ """The launched browser renders the toolbar title 'Amaze Debug' and the section
+ header 'Folders'. Discriminator: both are ABSENT before the app is up (fresh
+ process) and PRESENT on the home surface. VLM checks the title is rendered as
+ the top toolbar title (a position property, not the wording)."""
+ rn = "text_home_title_and_folders_header"
+ ok_launch, nodes = and_enter_amaze()
+ if not ok_launch:
+ record(rn, False, "setup_failed: never reached MainActivity with a file list",
+ depth=0, jump_kind="value", expect="title 'Amaze Debug' + header 'Folders'")
+ return
+ ok, nodes = reset_home(nodes)
+ if not ok:
+ nodes = ui()
+ title_ok = find_node_ci(nodes, "Amaze Debug") is not None
+ header_ok = find_node(nodes, text="Folders") is not None
+ good = title_ok and header_ok
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: title 'Amaze Debug' seen={title_ok}, header 'Folders' seen={header_ok}",
+ depth=0, jump_kind="value",
+ expect="toolbar title 'Amaze Debug' and section header 'Folders'")
+ vlm_assert("text_home_title", "Is the text 'Amaze Debug' shown as the title in "
+ "the top toolbar / app bar at the very top of the screen?",
+ RESULTS_DIR, tag="position")
+
+
+@and_test(expects=("text_probe_count_line",))
+def test_probe_count_line():
+ """Navigating into the fixture folder makes the path-count line read exactly
+ '0 folders and 3 files'. Discriminator: this exact count is ABSENT at Home (a
+ populated root shows N folders / M files) and PRESENT inside amaze_probe."""
+ rn = "text_probe_count_line"
+ ok_launch, home_nodes = and_enter_amaze()
+ if not ok_launch:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="pathname '0 folders and 3 files'")
+ return
+ reset_home(home_nodes)
+ absent = not has_text(ui(), "0 folders and 3 files")
+ ok, nodes = and_reach_probe()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach Download/amaze_probe",
+ depth=2, jump_kind="value", expect="pathname '0 folders and 3 files'")
+ return
+ pn = node_by_id(nodes, "pathname")
+ got = pn.get("text") if pn else ""
+ present = norm(got) == norm("0 folders and 3 files")
+ good = absent and present
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: expected count '0 folders and 3 files', field read {got!r} "
+ f"(absent-at-home={absent})",
+ depth=2, jump_kind="value", expect="pathname reads '0 folders and 3 files'")
+
+
+@and_test(expects=("text_probe_files_header",))
+def test_probe_files_header():
+ """A folder holding only files renders the section header 'Files' (vs 'Folders'
+ at the root). Discriminator: 'Files' header ABSENT at a folders-only root,
+ PRESENT inside amaze_probe."""
+ rn = "text_probe_files_header"
+ ok, nodes = and_reach_probe()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach amaze_probe",
+ depth=2, jump_kind="value", expect="section header 'Files'")
+ return
+ hdr = find_node(nodes, text="Files")
+ good = hdr is not None
+ record(rn, good,
+ "" if good else "behavior_wrong: no 'Files' section header inside amaze_probe",
+ depth=2, jump_kind="value", expect="section header text == 'Files'")
+
+
+@and_test(expects=("text_empty_folder_message", "text_empty_folder_vlm"))
+def test_empty_folder_message():
+ """An empty folder shows the empty-state message 'No Files'. Discriminator: the
+ populated amaze_probe folder does NOT show it; a freshly-created empty folder
+ does. The VLM confirms the message is a centered empty-state (a position
+ property), NOT a list row — the wording itself stays the rule assertion."""
+ rn = "text_empty_folder_message"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=1, jump_kind="value", expect="empty-state text 'No Files'")
+ return
+ reset_home(nodes)
+ # 'No Files' must NOT be showing on the populated root before we start.
+ absent = not has_text(ui(), "No Files")
+ # Create our own uniquely-named empty folder at the root.
+ ok, dlg = and_open_new_folder()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the New Folder dialog",
+ depth=1, jump_kind="value", expect="empty-state text 'No Files'")
+ return
+ name = unique_folder_name("AmzEmpty")
+ field = node_by_id(dlg, "singleedittext_input")
+ type_text(field, name)
+ # Tap CREATE with the soft keyboard STILL UP — the button sits above it. Do
+ # NOT call hide_keyboard() here: its BACK fallback dismisses the whole
+ # MaterialDialog, taking the CREATE button with it.
+ create = node_by_id(ui(), "md_buttonDefaultPositive") or find_node_ci(ui(), "CREATE")
+ if create is None:
+ record(rn, False, "setup_failed: no CREATE button in New Folder dialog",
+ depth=1, jump_kind="value", expect="empty-state text 'No Files'")
+ return
+ tap_node(create)
+ settle("tap")
+ row = scroll_into_view(name, max_swipes=6) or find_node_ci(ui(), name)
+ if row is None:
+ record(rn, False, f"setup_failed: created folder {name!r} did not appear",
+ depth=1, jump_kind="value", expect="empty-state text 'No Files'")
+ return
+ tap_node(row)
+ and_enter("empty_folder")
+ inside = ui()
+ nft = node_by_id(inside, "nofiletext")
+ present = (nft is not None and norm(nft.get("text")) == norm("No Files")) \
+ or has_text(inside, "No Files")
+ good = absent and present
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: empty folder did not show 'No Files' "
+ f"(absent-before={absent}, present-after={present})",
+ depth=1, jump_kind="value", expect="empty-state message reads 'No Files'")
+ vlm_assert("text_empty_folder", "Is the text 'No Files' displayed in the center "
+ "of the screen (an empty-state message), rather than as one row in a "
+ "list of files?", RESULTS_DIR, tag="position")
+ # Clean up our own folder via the shell (own artifact; not asserted further).
+ adb_shell("rm", "-rf", fixture_on_device(name))
+
+
+@and_test(expects=("text_new_folder_dialog_strings",))
+def test_new_folder_dialog_strings():
+ """The FAB 'Folder' action opens a dialog titled 'New Folder' with the name
+ field hint 'Enter Name' and the CANCEL / CREATE buttons. Discriminator: none of
+ these strings are on the browser surface; all appear on the dialog. (Closed with
+ CANCEL — nothing is created.)"""
+ rn = "text_new_folder_dialog_strings"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="'New Folder' + 'Enter Name' + CREATE")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Enter Name")
+ ok, dlg = and_open_new_folder()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the New Folder dialog",
+ depth=2, jump_kind="value", expect="'New Folder' + 'Enter Name' + CREATE")
+ return
+ title = node_by_id(dlg, "md_title")
+ title_ok = title is not None and norm(title.get("text")) == norm("New Folder")
+ field = node_by_id(dlg, "singleedittext_input")
+ hint_ok = field is not None and norm(field.get("text")) == norm("Enter Name")
+ create_ok = find_node_ci(dlg, "CREATE") is not None
+ cancel_ok = find_node_ci(dlg, "CANCEL") is not None
+ good = absent and title_ok and hint_ok and create_ok and cancel_ok
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: New Folder dialog strings — title={title_ok}, "
+ f"hint 'Enter Name'={hint_ok}, CREATE={create_ok}, CANCEL={cancel_ok}",
+ depth=2, jump_kind="value",
+ expect="dialog title 'New Folder', hint 'Enter Name', buttons CANCEL/CREATE")
+ c = find_node_ci(ui(), "CANCEL")
+ if c:
+ tap_node(c)
+
+
+@and_test(expects=("text_overflow_menu_labels",))
+def test_overflow_menu_labels():
+ """The toolbar overflow lists the app's action labels: Sort, History, Hidden
+ Files, Set As Home, Exit (plus a Grid/List toggle). Discriminator: these labels
+ are ABSENT on the browser and PRESENT once the menu opens."""
+ rn = "text_overflow_menu_labels"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=1, jump_kind="value", expect="overflow labels Sort/History/Exit")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Set As Home")
+ ok, menu = and_open_overflow()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the overflow menu",
+ depth=1, jump_kind="value", expect="overflow labels Sort/History/Exit")
+ return
+ want = ["Sort", "History", "Hidden Files", "Set As Home", "Exit"]
+ missing = [w for w in want if find_node_ci(menu, w) is None]
+ good = absent and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: overflow missing {missing} (absent-before={absent})",
+ depth=1, jump_kind="value",
+ expect="overflow menu shows Sort, History, Hidden Files, Set As Home, Exit")
+ back()
+
+
+@and_test(expects=("text_sort_dialog_options",))
+def test_sort_dialog_options():
+ """The Sort By dialog offers Name / Last Modified / Size / Type with the
+ 'Only this folder' checkbox and ASCENDING / DESCENDING buttons. Discriminator:
+ these are ABSENT on the browser and PRESENT in the dialog (depth 3)."""
+ rn = "text_sort_dialog_options"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="Sort By options + ASCENDING/DESCENDING")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Last Modified")
+ ok, dlg = and_enter_sortby()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the Sort By dialog",
+ depth=2, jump_kind="value", expect="Sort By options + ASCENDING/DESCENDING")
+ return
+ want = ["Name", "Last Modified", "Size", "Type", "Only this folder",
+ "ASCENDING", "DESCENDING"]
+ missing = [w for w in want if find_node_ci(dlg, w) is None]
+ good = absent and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: Sort By dialog missing {missing} (absent-before={absent})",
+ depth=2, jump_kind="value",
+ expect="Sort By shows Name/Last Modified/Size/Type, 'Only this folder', "
+ "ASCENDING/DESCENDING")
+ back()
+
+
+@and_test(expects=("text_search_hint",))
+def test_search_hint():
+ """Opening the toolbar Search reveals an input whose hint is 'Type to search…'.
+ Discriminator: the hint is ABSENT on the browser and PRESENT once the search bar
+ opens. Matched as a substring so the trailing ellipsis glyph does not matter."""
+ rn = "text_search_hint"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=1, jump_kind="value", expect="search hint 'Type to search'")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Type to search")
+ ok, snodes = and_reach_search()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the search bar",
+ depth=1, jump_kind="value", expect="search hint 'Type to search'")
+ return
+ et = node_by_id(snodes, "search_edit_text")
+ hint = et.get("text") if et else ""
+ present = "type to search" in norm(hint) or has_text(snodes, "Type to search")
+ good = absent and present
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: search hint expected 'Type to search…', field read {hint!r}",
+ depth=1, jump_kind="value", expect="search field hint contains 'Type to search'")
+ hide_keyboard()
+ back()
+
+
+@and_test(expects=("text_row_context_menu_labels",))
+def test_row_context_menu_labels():
+ """A file row's 3-dot menu lists Cut / Copy / Delete / Rename / Encrypt /
+ Properties / Compress. Discriminator: ABSENT on the plain list, PRESENT once the
+ popup opens. (No item is tapped — the popup is dismissed with BACK.)"""
+ rn = "text_row_context_menu_labels"
+ ok, nodes = and_reach_probe()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach amaze_probe",
+ depth=3, jump_kind="value", expect="context menu Cut/Copy/Rename/Compress")
+ return
+ absent = not has_text(nodes, "Encrypt")
+ ok, menu = and_open_row_menu(nodes)
+ if not ok:
+ record(rn, False, "setup_failed: could not open the row context menu",
+ depth=3, jump_kind="value", expect="context menu Cut/Copy/Rename/Compress")
+ return
+ want = ["Cut", "Copy", "Delete", "Rename", "Encrypt", "Properties", "Compress"]
+ missing = [w for w in want if find_node_ci(menu, w) is None]
+ good = absent and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: row menu missing {missing} (absent-before={absent})",
+ depth=3, jump_kind="value",
+ expect="row menu shows Cut/Copy/Delete/Rename/Encrypt/Properties/Compress")
+ back()
+
+
+@and_test(expects=("text_properties_dialog_labels", "text_properties_chart_vlm"))
+def test_properties_dialog_labels():
+ """The Properties dialog is titled 'Properties' and labels Name / Location /
+ Size / Date, and its Name value equals the file we opened it from. Discriminator:
+ these strings are ABSENT on the list and PRESENT in the dialog; the name is the
+ PRODUCED value tied to the tapped row. The VLM handles the one opaque core — the
+ storage chart is a Canvas ViewGroup that carries no text into the tree."""
+ rn = "text_properties_dialog_labels"
+ ok, dlg, fname = and_reach_properties()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the Properties dialog",
+ depth=3, jump_kind="value", expect="Properties labels + name matches file")
+ # Still emit the VLM record so the denominator is fixed.
+ vlm_assert("text_properties_chart", "Is a circular or ring-shaped storage-usage "
+ "chart (a pie/donut graphic) drawn inside this dialog?",
+ RESULTS_DIR, tag="shape")
+ return
+ title = node_by_id(dlg, "md_title")
+ title_ok = title is not None and norm(title.get("text")) == norm("Properties")
+ labels = ["Name", "Location", "Size", "Date"]
+ missing = [w for w in labels if find_node_ci(dlg, w) is None]
+ # Name value tracks the file the dialog was opened from.
+ tname = node_by_id(dlg, "t5")
+ name_ok = (fname is not None and tname is not None
+ and norm(tname.get("text")) == norm(fname))
+ good = title_ok and not missing and name_ok
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: Properties title={title_ok}, missing labels={missing}, "
+ f"name matches {fname!r}? {name_ok} (got {tname.get('text') if tname else None!r})",
+ depth=3, jump_kind="value",
+ expect="dialog 'Properties' with Name/Location/Size/Date and name == the file")
+ vlm_assert("text_properties_chart", "Is a circular or ring-shaped storage-usage "
+ "chart (a pie/donut graphic) drawn inside this dialog?",
+ RESULTS_DIR, tag="shape")
+ ok_btn = node_by_id(ui(), "md_buttonDefaultPositive") or find_node_ci(ui(), "OK")
+ if ok_btn:
+ tap_node(ok_btn)
+
+
+@and_test(expects=("text_ftp_static_labels",))
+def test_ftp_static_labels():
+ """The FTP Server screen renders the toolbar title 'FTP Server', the default
+ 'Port: 2211', and the URL / Username / Password / Shared Path labels.
+ Discriminator: ABSENT on the browser, PRESENT after reaching FTP (depth 2)."""
+ rn = "text_ftp_static_labels"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="'FTP Server' + 'Port: 2211' labels")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Port: 2211")
+ ok, fnodes = and_reach_ftp()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach the FTP Server screen",
+ depth=2, jump_kind="value", expect="'FTP Server' + 'Port: 2211' labels")
+ return
+ title_ok = find_node_ci(fnodes, "FTP Server") is not None
+ port = node_by_id(fnodes, "text_view_ftp_port")
+ port_ok = port is not None and norm(port.get("text")) == norm("Port: 2211")
+ labels_ok = (has_text(fnodes, "URL:") and has_text(fnodes, "Username:")
+ and has_text(fnodes, "Password:") and has_text(fnodes, "Shared Path"))
+ good = absent and title_ok and port_ok and labels_ok
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: FTP labels — title={title_ok}, 'Port: 2211'={port_ok}, "
+ f"URL/User/Pass/Path={labels_ok} (absent-before={absent})",
+ depth=2, jump_kind="value",
+ expect="title 'FTP Server', 'Port: 2211', URL/Username/Password/Shared Path")
+ back()
+
+
+@and_test(expects=("text_ftp_status_after_start", "text_ftp_status_running_vlm"))
+def test_ftp_status_after_start():
+ """Tapping START changes the produced status line from 'Not Running' to
+ 'Running'. Discriminator: 'Not Running' present BEFORE (and the plain word
+ 'Running' can appear inside it), 'Running' present with 'Not Running' ABSENT
+ AFTER. Restored by tapping STOP. VLM: is 'Running' shown near the top, below the
+ toolbar (a position property)."""
+ rn = "text_ftp_status_after_start"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="FTP status flips to 'Running'")
+ vlm_assert("text_ftp_status_running", "Is the word 'Running' shown near the top "
+ "of the screen, just below the app toolbar?", RESULTS_DIR, tag="position")
+ return
+ reset_home(nodes)
+ ok, fnodes = and_reach_ftp()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach the FTP Server screen",
+ depth=2, jump_kind="value", expect="FTP status flips to 'Running'")
+ vlm_assert("text_ftp_status_running", "Is the word 'Running' shown near the top "
+ "of the screen, just below the app toolbar?", RESULTS_DIR, tag="position")
+ return
+ st0 = node_by_id(fnodes, "text_view_ftp_status")
+ before_txt = norm(st0.get("text")) if st0 else ""
+ before_not_running = "not running" in before_txt
+ start = node_by_id(fnodes, "startStopButton") or find_node_ci(fnodes, "START")
+ if start is None or norm(start.get("text")) != norm("START"):
+ record(rn, False, "setup_failed: START button not present on FTP screen",
+ depth=2, jump_kind="value", expect="FTP status flips to 'Running'")
+ vlm_assert("text_ftp_status_running", "Is the word 'Running' shown near the top "
+ "of the screen, just below the app toolbar?", RESULTS_DIR, tag="position")
+ return
+ tap_node(start)
+ settle("tap")
+ after = ui()
+ st1 = node_by_id(after, "text_view_ftp_status")
+ after_txt = norm(st1.get("text")) if st1 else ""
+ after_running = ("running" in after_txt) and ("not running" not in after_txt)
+ good = before_not_running and after_running
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: FTP status before={before_txt!r} after={after_txt!r} "
+ f"(expected 'Not Running' -> 'Running')",
+ depth=2, jump_kind="value",
+ expect="FTP status line changes from 'Not Running' to 'Running'")
+ vlm_assert("text_ftp_status_running", "Is the word 'Running' shown near the top of "
+ "the screen, just below the app toolbar?", RESULTS_DIR, tag="position")
+ # Restore: stop the server.
+ stop = node_by_id(ui(), "startStopButton") or find_node_ci(ui(), "STOP")
+ if stop is not None and norm(stop.get("text")) == norm("STOP"):
+ tap_node(stop)
+ back()
+
+
+@and_test(expects=("text_settings_category_titles",))
+def test_settings_category_titles():
+ """The Settings screen title is 'Settings' and it lists the category titles
+ Appearance / Interface / Behavior / Security / Backup / About Amaze File Manager
+ / Send Feedback. Discriminator: ABSENT on the browser, PRESENT in Settings
+ (depth 2)."""
+ rn = "text_settings_category_titles"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=2, jump_kind="value", expect="Settings categories Appearance/…/Feedback")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "About Amaze File Manager")
+ ok, snodes = and_reach_settings()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach Settings",
+ depth=2, jump_kind="value", expect="Settings categories Appearance/…/Feedback")
+ return
+ title_ok = find_node(snodes, text="Settings") is not None
+ want = ["Appearance", "Interface", "Behavior", "Security", "Backup",
+ "About Amaze File Manager", "Send Feedback"]
+ missing = [w for w in want if find_node_ci(snodes, w) is None]
+ good = absent and title_ok and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: Settings title={title_ok}, missing {missing} "
+ f"(absent-before={absent})",
+ depth=2, jump_kind="value",
+ expect="Settings shows Appearance/Interface/Behavior/Security/Backup/"
+ "About Amaze File Manager/Send Feedback")
+ back()
+
+
+@and_test(expects=("text_appearance_titles_and_theme_summary",))
+def test_appearance_titles_and_theme_summary():
+ """The Appearance screen renders the Theme summary 'System (follow system theme)'
+ plus the preference titles Show Dividers / Show Headers / Colorize Icons and the
+ 'Color' section header. Discriminator: ABSENT on the browser, PRESENT in
+ Appearance (depth 3)."""
+ rn = "text_appearance_titles_and_theme_summary"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=3, jump_kind="value", expect="Appearance titles + Theme summary")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Show Dividers")
+ ok, anodes = and_reach_appearance()
+ if not ok:
+ record(rn, False, "setup_failed: could not reach the Appearance screen",
+ depth=3, jump_kind="value", expect="Appearance titles + Theme summary")
+ return
+ summary_ok = has_text(anodes, "System (follow system theme)")
+ want = ["Theme", "Show Dividers", "Show Headers", "Colorize Icons", "Color"]
+ missing = [w for w in want if find_node_ci(anodes, w) is None]
+ good = absent and summary_ok and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: Appearance summary 'System (follow system theme)'={summary_ok}, "
+ f"missing {missing} (absent-before={absent})",
+ depth=3, jump_kind="value",
+ expect="Theme summary 'System (follow system theme)' + titles Show Dividers/"
+ "Show Headers/Colorize Icons + 'Color' header")
+ back()
+
+
+@and_test(expects=("text_theme_dialog_options",))
+def test_theme_dialog_options():
+ """The Theme dialog offers Material Light / Material Dark / Daytime /
+ Black (for OLED) / System (follow system theme). Discriminator: ABSENT before
+ the dialog, PRESENT inside it (depth 4). No option is selected — closed with
+ BACK, so the theme is unchanged."""
+ rn = "text_theme_dialog_options"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=4, jump_kind="value", expect="Theme radios Material Light/Dark/Daytime")
+ return
+ reset_home(nodes)
+ ok, dlg = and_enter_theme_dialog()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the Theme dialog",
+ depth=4, jump_kind="value", expect="Theme radios Material Light/Dark/Daytime")
+ return
+ want = ["Material Light", "Material Dark", "Daytime", "Black (for OLED)"]
+ missing = [w for w in want if find_node_ci(dlg, w) is None]
+ good = not missing
+ record(rn, good,
+ "" if good else f"behavior_wrong: Theme dialog missing {missing}",
+ depth=4, jump_kind="value",
+ expect="Theme dialog shows Material Light/Material Dark/Daytime/Black (for OLED)")
+ back()
+
+
+@and_test(expects=("text_drawer_menu_labels",))
+def test_drawer_menu_labels():
+ """The navigation drawer renders the app's destination labels: Quick access /
+ Recent files / Analyse Storage / Trash Bin / App Manager. Discriminator: ABSENT
+ on the browser, PRESENT once the drawer opens (depth 1). These are asserted as
+ rendered CONTENT labels, distinct from navigation's use of them as triggers."""
+ rn = "text_drawer_menu_labels"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=1, jump_kind="value", expect="drawer labels Quick access/Recent files/…")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Recent files")
+ ok, dnodes = and_enter_drawer()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the navigation drawer",
+ depth=1, jump_kind="value", expect="drawer labels Quick access/Recent files/…")
+ return
+ want = ["Quick access", "Recent files", "Analyse Storage", "Trash Bin", "App Manager"]
+ missing = []
+ for w in want:
+ if _drawer_item(w) is None:
+ missing.append(w)
+ good = absent and not missing
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: drawer missing {missing} (absent-before={absent})",
+ depth=1, jump_kind="value",
+ expect="drawer shows Quick access/Recent files/Analyse Storage/Trash Bin/App Manager")
+ back()
+
+
+@and_test(expects=("text_drawer_internal_storage_label",))
+def test_drawer_internal_storage_label():
+ """The drawer's storage row reads 'Internal Storage' with a '… GB free of … GB'
+ summary. The free/total NUMBERS drift run-to-run, so only the stable words are
+ asserted (a regex for 'Internal Storage … free of … GB'), never the value.
+ Discriminator: ABSENT on the browser, PRESENT once the drawer opens."""
+ rn = "text_drawer_internal_storage_label"
+ ok, nodes = and_enter_amaze()
+ if not ok:
+ record(rn, False, "setup_failed: never reached MainActivity",
+ depth=1, jump_kind="value", expect="'Internal Storage … free of … GB'")
+ return
+ reset_home(nodes)
+ absent = not has_text(ui(), "Internal Storage")
+ ok, dnodes = and_enter_drawer()
+ if not ok:
+ record(rn, False, "setup_failed: could not open the navigation drawer",
+ depth=1, jump_kind="value", expect="'Internal Storage … free of … GB'")
+ return
+ blob = norm(all_text(dnodes))
+ # Words only — numbers drift, so match the pattern, not the value.
+ pat = re.search(r"internal storage.*free of .*gb", blob)
+ good = absent and (pat is not None)
+ record(rn, good,
+ "" if good else
+ f"behavior_wrong: no 'Internal Storage … free of … GB' line in the drawer "
+ f"(absent-before={absent})",
+ depth=1, jump_kind="value",
+ expect="drawer storage row reads 'Internal Storage' + '… free of … GB'")
+ back()
+
+
+# ── Registry ────────────────────────────────────────────────────────────────
+TESTS = [
+ test_home_title_and_folders_header,
+ test_probe_count_line,
+ test_probe_files_header,
+ test_empty_folder_message,
+ test_new_folder_dialog_strings,
+ test_overflow_menu_labels,
+ test_sort_dialog_options,
+ test_search_hint,
+ test_row_context_menu_labels,
+ test_properties_dialog_labels,
+ test_ftp_static_labels,
+ test_ftp_status_after_start,
+ test_settings_category_titles,
+ test_appearance_titles_and_theme_summary,
+ test_theme_dialog_options,
+ test_drawer_menu_labels,
+ test_drawer_internal_storage_label,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/teamamaze-amazefilemanager/tests/test_manifest.json b/android/teamamaze-amazefilemanager/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..99c015fb2f12352b8432ca0c7299e3be4d5f5883
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/tests/test_manifest.json
@@ -0,0 +1,810 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "AmazeFileManager",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 122,
+ "manifest_sha": "4a0c8088064a",
+ "tests": [
+ {
+ "name": "computation::computation_count_after_create_file",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_count_after_create_folder",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_count_delete_restores",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_count_download",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_count_probe",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_count_probe_chart_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_alpha_location",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_alpha_name",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_alpha_size",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_folder_chart_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_folder_items",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_props_folder_name",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_sort_name_asc_first",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_sort_name_desc_first",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_sort_order_flips",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_storage_chart_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_storage_props_items",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_add_bookmark",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_context_menu_opens",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_copy_paste",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_delete_roundtrip",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_file",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_folder",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_persists_in_folder",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_delete_reduces_count",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_deselect_toggle",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_exit_selection",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_selection",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_ordered_persist",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multiselect_count",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_properties_shows_name",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rename",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rename_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_select_all",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_folder_to_parent",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_ftp_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_back_settings_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_2hop_unwind",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_close_search_back",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_context_to_properties",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_context_to_properties_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_drawer_bookmark_music",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_enter_amaze_probe_depth2",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_enter_download",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_home_button_resets",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_drawer",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_drawer_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_overflow",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_search",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_search_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_overflow_sort_dialog",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_overflow_sort_dialog_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_probe_contains_alpha",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_ftp",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_ftp_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_row_context_menu",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_about",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_appearance",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_appearance_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_ftp_running_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_ftp_start",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_gridlist_grid_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_gridlist_list_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_gridlist_session_only",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_gridlist_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_search_focus",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_search_typing",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sort_checkbox",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sort_checkbox_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sort_radio",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sort_radio_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_circular",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_colorize",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_dividers",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_dividers_persist",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_off_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_on_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_switch_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_light_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persist",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_context_menu_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_open",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_drawer_open_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_empty_folder_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_empty_vs_populated",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_fab_expand",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_fab_expand_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_folder_nav_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_grid_list_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_grid_list_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_list_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_longpress_cab",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_overflow_menu",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_probe_populated_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_properties_dialog",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_search_bar_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_appearance_titles_and_theme_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_drawer_internal_storage_label",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_drawer_menu_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_empty_folder_message",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_empty_folder_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_ftp_static_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_ftp_status_after_start",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_ftp_status_running_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_title_and_folders_header",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_title_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_new_folder_dialog_strings",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_overflow_menu_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_probe_count_line",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_probe_files_header",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_properties_chart_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_properties_dialog_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_row_context_menu_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_search_hint",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_category_titles",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_sort_dialog_options",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_theme_dialog_options",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [
+ {
+ "name": "interaction::interaction_create_folder_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "interaction::interaction_longpress_selection_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "interaction::interaction_multiselect_count_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "interaction::interaction_properties_shows_name_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "interaction::interaction_rename_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ },
+ {
+ "name": "interaction::interaction_select_all_vlm",
+ "module": "interaction",
+ "reason": "vlm_unverified",
+ "baseline_status": "passed",
+ "message": "no attempt in vlm_assertions.json — the VLM was never provably invoked for this case"
+ }
+ ],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_count_probe_chart_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_props_folder_chart_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_storage_chart_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_open_drawer_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_ftp_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_settings_to_appearance_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_open_search_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_overflow_sort_dialog_vlm",
+ "module": "navigation",
+ "tag": "content"
+ },
+ {
+ "name": "navigation::nav_context_to_properties_vlm",
+ "module": "navigation",
+ "tag": "content"
+ },
+ {
+ "name": "states::states_gridlist_grid_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_gridlist_list_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_switch_on_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_switch_off_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_dark_switch_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_light_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_sort_radio_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_sort_checkbox_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_ftp_running_vlm",
+ "module": "states",
+ "tag": "content"
+ },
+ {
+ "name": "structure::structure_fab_expand_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_list_layout_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_grid_list_shape_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_drawer_open_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_empty_folder_vlm",
+ "module": "structure",
+ "tag": "content"
+ },
+ {
+ "name": "text::text_home_title_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_empty_folder_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_properties_chart_vlm",
+ "module": "text",
+ "tag": "shape"
+ },
+ {
+ "name": "text::text_ftp_status_running_vlm",
+ "module": "text",
+ "tag": "position"
+ }
+ ],
+ "vlm_total": 28,
+ "n_vlm_unverified": 6,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/teamamaze-amazefilemanager/vlm_assertions.json b/android/teamamaze-amazefilemanager/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..9864d778e61ff8b27b4f1186fd330dacd8ffd0c3
--- /dev/null
+++ b/android/teamamaze-amazefilemanager/vlm_assertions.json
@@ -0,0 +1,724 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/teamamaze-amazefilemanager",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 35,
+ "with_verdict": 34,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 34,
+ "unbacked_records": 6,
+ "unbacked_sample": [
+ "interaction_create_folder_vlm",
+ "interaction_longpress_selection_vlm",
+ "interaction_multiselect_count_vlm",
+ "interaction_select_all_vlm",
+ "interaction_rename_vlm",
+ "interaction_properties_shows_name_vlm"
+ ]
+ },
+ "assertions": [
+ {
+ "id": "nav_reach_settings_vlm",
+ "screenshot": "nav_reach_settings_vlm.png",
+ "assertion": "Is this a settings screen with a vertical list of rows such as Appearance, Interface and Behavior, each with a smaller grey description line beneath it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "nav_reach_settings",
+ "rigor": null,
+ "verdict": null,
+ "calibration": null
+ },
+ {
+ "id": "nav_settings_to_appearance_vlm",
+ "screenshot": "nav_settings_to_appearance_vlm.png",
+ "assertion": "Does this screen show appearance options with several on/off toggle switches aligned down the right edge of the list?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_settings_to_appearance",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_overflow_sort_dialog_vlm",
+ "screenshot": "nav_overflow_sort_dialog_vlm.png",
+ "assertion": "Is a dialog titled 'Sort By' showing a vertical list of radio-button options with two text buttons (ASCENDING / DESCENDING) along the bottom?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "nav_overflow_sort_dialog",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_fab_expand_vlm",
+ "screenshot": "structure_fab_expand_vlm.png",
+ "assertion": "Are there three circular action buttons stacked vertically one above another near the bottom-right corner, each with a text label to its left?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_fab_expand",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_list_layout_vlm",
+ "screenshot": "structure_list_layout_vlm.png",
+ "assertion": "Are the file/folder items arranged as a single vertical column (one item per row spanning the width), not a multi-column grid?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_list_layout",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_grid_list_shape_vlm",
+ "screenshot": "structure_grid_list_shape_vlm.png",
+ "assertion": "Are the folder tiles laid out in exactly three columns per row (three items side by side across the width)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_grid_list_shape",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_drawer_open_vlm",
+ "screenshot": "structure_drawer_open_vlm.png",
+ "assertion": "Is a navigation drawer panel anchored to the LEFT edge of the screen (its header graphic starts at the top-left corner) while a dimmed strip of the file list remains visible along the right edge?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_drawer_open",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_empty_folder_vlm",
+ "screenshot": "structure_empty_folder_vlm.png",
+ "assertion": "Is a single file-shaped icon positioned in the horizontal center of the screen with the text 'No Files' directly beneath it, and no list rows above or below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_empty_folder",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_open_drawer_vlm",
+ "screenshot": "nav_open_drawer_vlm.png",
+ "assertion": "Is a navigation drawer panel visible on the left side, showing an app logo/header at the top and a back arrow at the top-left of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_open_drawer",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_ftp_vlm",
+ "screenshot": "nav_reach_ftp_vlm.png",
+ "assertion": "Does this screen show a file-server status page with a single wide START button near the bottom of a card?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_ftp",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_open_search_vlm",
+ "screenshot": "nav_open_search_vlm.png",
+ "assertion": "Is there a text input field near the top of the screen with a back arrow to its left and an X (clear) icon to its right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_open_search",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_context_to_properties_vlm",
+ "screenshot": "nav_context_to_properties_vlm.png",
+ "assertion": "Is a dialog titled 'Properties' currently displayed showing file details such as Name, Location and Size?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "nav_context_to_properties",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_count_probe_chart_vlm",
+ "screenshot": "computation_count_probe_chart_vlm.png",
+ "assertion": "Is a circular or segmented storage-usage graphic (a ring/pie chart) rendered inside this Properties dialog?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_count_probe_chart",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_props_folder_chart_vlm",
+ "screenshot": "computation_props_folder_chart_vlm.png",
+ "assertion": "Is a circular or ring-shaped storage-usage chart rendered inside this Properties dialog?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_props_folder_chart",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_storage_chart_vlm",
+ "screenshot": "computation_storage_chart_vlm.png",
+ "assertion": "Is a circular/ring storage-usage chart graphic rendered in this dialog showing how full the storage is?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_storage_chart",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_gridlist_grid_vlm",
+ "screenshot": "states_gridlist_grid_vlm.png",
+ "assertion": "Are the folder items arranged in a grid with three side-by-side columns (multiple items on the same row), rather than a single vertical list?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "states_gridlist_grid",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_gridlist_list_vlm",
+ "screenshot": "states_gridlist_list_vlm.png",
+ "assertion": "Are the file/folder items arranged in a single vertical column, each row spanning the full width of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "states_gridlist_list",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_switch_on_vlm",
+ "screenshot": "states_switch_on_vlm.png",
+ "assertion": "Is the 'Show Dividers' toggle switch in the ON position — its round thumb slid to the RIGHT and its track filled with a pink/red color?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_switch_on",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_switch_off_vlm",
+ "screenshot": "states_switch_off_vlm.png",
+ "assertion": "Is the 'Show Dividers' toggle switch in the OFF position — its round thumb on the LEFT and its track a plain gray/uncolored (not pink)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_switch_off",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_dark_vlm",
+ "screenshot": "states_theme_dark_vlm.png",
+ "assertion": "Is this screen a DARK theme — a near-black or very dark gray background with light/white text?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_dark",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_dark_switch_vlm",
+ "screenshot": "states_theme_dark_switch_vlm.png",
+ "assertion": "On this dark screen, is at least one ON toggle switch filled with a bright pink/red color (thumb to the right)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_dark_switch",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_light_vlm",
+ "screenshot": "states_theme_light_vlm.png",
+ "assertion": "Is this screen a LIGHT theme — a white or light-gray background with dark text (NOT a dark/black background)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_light",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_sort_radio_vlm",
+ "screenshot": "states_sort_radio_vlm.png",
+ "assertion": "In this 'Sort By' dialog, is exactly one radio button filled/selected (a solid colored dot) while the others are empty rings?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_sort_radio",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_sort_checkbox_vlm",
+ "screenshot": "states_sort_checkbox_vlm.png",
+ "assertion": "Is the 'Only this folder' checkbox in this 'Sort By' dialog checked — shown as a filled colored square with a white checkmark (not an empty outlined box)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_sort_checkbox",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_ftp_running_vlm",
+ "screenshot": "states_ftp_running_vlm.png",
+ "assertion": "Does this screen show the FTP server in a RUNNING state — a button labelled 'STOP' and an ftp:// (or ftps://) URL shown next to the 'URL:' label?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "states_ftp_running",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_home_title_vlm",
+ "screenshot": "text_home_title_vlm.png",
+ "assertion": "Is the text 'Amaze Debug' shown as the title in the top toolbar / app bar at the very top of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_home_title",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_properties_chart_vlm",
+ "screenshot": "text_properties_chart_vlm.png",
+ "assertion": "Is a circular or ring-shaped storage-usage chart (a pie/donut graphic) drawn inside this dialog?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "text_properties_chart",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 4
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_ftp_status_running_vlm",
+ "screenshot": "text_ftp_status_running_vlm.png",
+ "assertion": "Is the word 'Running' shown near the top of the screen, just below the app toolbar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_ftp_status_running",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_empty_folder_vlm",
+ "screenshot": "text_empty_folder_vlm.png",
+ "assertion": "Is the text 'No Files' displayed in the center of the screen (an empty-state message), rather than as one row in a list of files?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_empty_folder",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_create_folder_vlm",
+ "screenshot": "interaction_create_folder_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_create_folder",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_longpress_selection_vlm",
+ "screenshot": "interaction_longpress_selection_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_longpress_selection",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_multiselect_count_vlm",
+ "screenshot": "interaction_multiselect_count_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_multiselect_count",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_select_all_vlm",
+ "screenshot": "interaction_select_all_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_select_all",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_rename_vlm",
+ "screenshot": "interaction_rename_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_rename",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_properties_shows_name_vlm",
+ "screenshot": "interaction_properties_shows_name_vlm.png",
+ "assertion": "",
+ "form": "statement",
+ "expected": true,
+ "aspect": null,
+ "modality": null,
+ "links_to": "interaction_properties_shows_name",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/LICENSE b/android/tom-murphy-development-fasttimes/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..092043d08457dd66fc88000c03df40dc35c567fa
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/LICENSE
@@ -0,0 +1,675 @@
+GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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 (1) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (2) 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public
+License, section 13, concerning interaction through a network will
+apply to the combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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) 2025 tom-murphy-development
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+ Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+ notice like this when it starts in an interactive mode:
+
+ Copyright (C) 2025 tom-murphy-development
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+ The hypothetical commands `show w' and `show c' should show the appropriate
+ parts of the General Public License. Of course, your program's commands
+ might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+ .
+
+ The GNU General Public License does not permit incorporating your program
+ into proprietary programs. If your program is a subroutine library, you
+ may consider it more useful to permit linking proprietary applications with
+ the library. If this is what you want to do, use the GNU Lesser General
+ Public License instead of this License. But first, please read
+ .
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/instance.json b/android/tom-murphy-development-fasttimes/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..78b5ecc5487e295746196540567da79eafc93a20
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/tom-murphy-development-fasttimes",
+ "platform": "android",
+ "repo": "https://github.com/tom-murphy-development/FastTimes",
+ "commit": "cb951255b998a31ada7e3181aeb304dd89880a73",
+ "patches": [],
+ "package": "com.tmdev.fasttimes.debug",
+ "license": null
+}
diff --git a/android/tom-murphy-development-fasttimes/reference/launch.sh b/android/tom-murphy-development-fasttimes/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/tom-murphy-development-fasttimes/tests/android_computation_eval.json b/android/tom-murphy-development-fasttimes/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..c01f52b34ef1342d4da4197e9323def6164242cd
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_computation_eval.json
@@ -0,0 +1,189 @@
+{
+ "module": "computation",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 4,
+ "passed": 4,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3077,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 5,
+ "depth_ge2": 0,
+ "value": 15,
+ "vlm_fine": 3
+ },
+ "results": [
+ {
+ "test": "computation_countdown_decreases",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "label 'Remaining'; value decreases over ~3s (saw 00:59:52 -> 00:59:47)"
+ },
+ {
+ "test": "computation_countup_increases",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "label 'Elapsed Time', no End Time; value increases over ~3s (saw 00:00:07 -> 00:00:12)"
+ },
+ {
+ "test": "computation_test_timer_initial_10s",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "fresh Test Timer 'Remaining' > 0 and <= ~00:00:10 (saw 00:00:02)"
+ },
+ {
+ "test": "computation_test_timer_initial_10s_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a large timer value (like 00:00:10) shown in the centre of the card with a coloured circular progress ring or arc drawn around it? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is a large timer value (like 00:00:10) shown in the centre of the card with a coloured circular progress ring or arc drawn around it? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_goal_reached_transition",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "label 'Remaining' -> 'Total Time' + 'Goal Reached!' shown; then value counts up (saw 00:00:17 -> 00:00:23)"
+ },
+ {
+ "test": "computation_goal_reached_transition_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a fully-closed bright green circular ring drawn all the way around the timer (indicating the fasting goal was reached), rather than a partially-filled arc? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a fully-closed bright green circular ring drawn all the way around the timer (indicating the fasting goal was reached), rather than a partially-filled arc? Answer YES or NO.",
+ "tag": "color"
+ },
+ {
+ "test": "computation_end_time_offset",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "End Time = Started + 60 min (observed diff 60 min)"
+ },
+ {
+ "test": "computation_test_timer_start_eq_end",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Test Timer End Time - Started == 0 min (observed diff 0)"
+ },
+ {
+ "test": "computation_fasts_count_zero",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "clean-install Dashboard 'Fasts' count == 0"
+ },
+ {
+ "test": "computation_fasts_count_zero_to_one",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dashboard 'Fasts' count 0 -> 1 after one saved fast (saw 0 -> 1)"
+ },
+ {
+ "test": "computation_fasts_count_two",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dashboard 'Fasts' count 0,1,2 across two saves (observed [0, 1, 2])"
+ },
+ {
+ "test": "computation_stats_total_fasts_one",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Statistics 'Total Fasts' == '1' (read '1')"
+ },
+ {
+ "test": "computation_stats_total_fasts_one_vlm",
+ "passed": true,
+ "message": "VLM: Q='Do the three rounded statistic cards near the bottom each show a large numeric value under their title (for example a whole number under 'Total Fasts' and a percentage under 'Consistency')? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Do the three rounded statistic cards near the bottom each show a large numeric value under their title (for example a whole number under 'Total Fasts' and a percentage under 'Consistency')? Answer YES or NO.",
+ "tag": "content"
+ },
+ {
+ "test": "computation_stats_consistency_100",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Statistics 'Consistency' == '100%' (read '100%')"
+ },
+ {
+ "test": "computation_stats_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there several coloured bars drawn in a row above the day/date axis labels (like T F S S M T W), representing a chart of values? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Are there several coloured bars drawn in a row above the day/date axis labels (like T F S S M T W), representing a chart of values? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_history_summary_total_one",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "History 'August Summary' 'Total Fasts' == '1' (read '1')"
+ },
+ {
+ "test": "computation_duration_format",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "saved fast renders a '\\d+h \\d+m' duration under 'This Week' (saw '0h 0m')"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/android_interaction_eval.json b/android/tom-murphy-development-fasttimes/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..20c9015cebb7a1617a448080bf447c9d8b945bcb
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_interaction_eval.json
@@ -0,0 +1,184 @@
+{
+ "module": "interaction",
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 16,
+ "depth_ge1": 10,
+ "depth_ge2": 6,
+ "value": 14,
+ "vlm_fine": 5
+ },
+ "results": [
+ {
+ "test": "interaction_create_fast_persists",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dashboard 'Fasts' 0->1 + History 'This Week'; both still present after force-stop+relaunch"
+ },
+ {
+ "test": "interaction_create_fast_persists_vlm",
+ "passed": true,
+ "message": "VLM: Q='After the app was restarted, does the 'History' section near the bottom of the dashboard list a completed fast entry (a duration like '0h 2m' under a 'This Week' heading with a green check icon) rather than an empty 'No recent fasts' message? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: After the app was restarted, does the 'History' section near the bottom of the dashboard list a completed fast entry (a duration like '0h 2m' under a 'This Week' heading with a green check icon) rather than an empty 'No recent fasts' message? Answer YES or NO.",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_multi_record_integrity",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dashboard 'Fasts' count 0,1,2,3 across three saves, still 3 after relaunch (observed [0, 1, 2, 3])"
+ },
+ {
+ "test": "interaction_multi_record_integrity_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the 'History' section of the dashboard show at least one completed fast entry with a duration value and a green check icon (i.e. it is NOT the empty 'No recent fasts to show.' state)? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Does the 'History' section of the dashboard show at least one completed fast entry with a duration value and a green check icon (i.e. it is NOT the empty 'No recent fasts to show.' state)? Answer YES or NO.",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_rating_in_daily_details",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Daily Details for Aug 5 shows the 'Test Timer' fast row (created with 4 stars)"
+ },
+ {
+ "test": "interaction_rating_in_daily_details_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this daily-details panel, does the fast entry (labelled 'Test Timer', duration '0h 2m') show a rating of exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In this daily-details panel, does the fast entry (labelled 'Test Timer', duration '0h 2m') show a rating of exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_rating_in_edit_fast_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this 'Edit Fast' dialog, does the 'Rating' row show exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In this 'Edit Fast' dialog, does the 'Rating' row show exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_rating_in_edit_fast",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Edit Fast dialog shows Start Time / End Time / Rating for the created 4-star fast"
+ },
+ {
+ "test": "interaction_longpress_menu",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Long-press: 'Edit'+'Favourite'+'Delete' button group appeared (absent before)"
+ },
+ {
+ "test": "interaction_longpress_menu_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is exactly one fasting-profile card outlined/highlighted with a coloured border that is distinct from the other cards' borders? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is exactly one fasting-profile card outlined/highlighted with a coloured border that is distinct from the other cards' borders? Answer YES or NO.",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_longpress_set_favourite",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "After long-press->Favourite: hint gone + '12-Hour Fast' in the Favourite Fast section; still favourited after relaunch"
+ },
+ {
+ "test": "interaction_longpress_set_favourite_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under the 'Favourite Fast' heading (above 'Other Profiles'), is there now a fasting-profile card, rather than only the grey hint text 'Press and hold a profile to add it as your favourite'? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Under the 'Favourite Fast' heading (above 'Other Profiles'), is there now a fasting-profile card, rather than only the grey hint text 'Press and hold a profile to add it as your favourite'? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_create_profile",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "profile card 'kitprofZ' absent before, present after Save, still present after relaunch"
+ },
+ {
+ "test": "interaction_create_profile_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a fasting-profile card whose title text reads 'kitprofZ' in the profiles grid? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a fasting-profile card whose title text reads 'kitprofZ' in the profiles grid? Answer YES or NO.",
+ "tag": "content"
+ },
+ {
+ "test": "interaction_active_fast_survives",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "After force-stop+relaunch: 'Elapsed Time' + 'End Fast' still shown, goal grid 'Set your goal' gone"
+ },
+ {
+ "test": "interaction_active_fast_survives_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a circular ring or arc drawn around a large running timer near the top-centre of the screen (an active fast still in progress), rather than a grid of goal-selection cells? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Is there a circular ring or arc drawn around a large running timer near the top-centre of the screen (an active fast still in progress), rather than a grid of goal-selection cells? Answer YES or NO.",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/android_navigation_eval.json b/android/tom-murphy-development-fasttimes/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..9d0e5bfd935ba8982046bb2dd20bf891cf837dbf
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_navigation_eval.json
@@ -0,0 +1,254 @@
+{
+ "module": "navigation",
+ "total": 24,
+ "passed": 24,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3333,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 24,
+ "depth_ge1": 24,
+ "depth_ge2": 11,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "navigation_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings 'Appearance' appeared; Dashboard 'Set your goal' left"
+ },
+ {
+ "test": "navigation_reach_profiles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Manage Profiles 'Other Profiles' appeared; 'Set your goal' left"
+ },
+ {
+ "test": "navigation_reach_statistics",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Statistics 'Trends' appeared; Dashboard 'Set your goal' left"
+ },
+ {
+ "test": "navigation_reach_statistics_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels (like T F S S M T W)? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels (like T F S S M T W)? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "navigation_reach_history",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "History 'August 2026' appeared; Dashboard 'Set your goal' left"
+ },
+ {
+ "test": "navigation_reach_history_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "navigation_reach_history_swipe",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Horizontal drag: History 'August 2026' appeared; 'Set your goal' left"
+ },
+ {
+ "test": "navigation_back_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After BACK: 'Set your goal' restored; Settings 'Appearance' gone"
+ },
+ {
+ "test": "navigation_back_profiles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After BACK: 'Set your goal' restored; 'Other Profiles' gone"
+ },
+ {
+ "test": "navigation_back_statistics",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After BACK: 'Set your goal' restored; Statistics 'Trends' gone"
+ },
+ {
+ "test": "navigation_back_history",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After BACK: Dashboard 'Set your goal' restored; History 'August 2026' gone"
+ },
+ {
+ "test": "navigation_history_back_arrow",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Back-arrow tap: Dashboard 'Set your goal' restored; 'August 2026' gone"
+ },
+ {
+ "test": "navigation_reach_accent_color",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Dashboard->Settings->Theme&Accent: 'Accent Color' appeared; Settings 'Color Scheme' left"
+ },
+ {
+ "test": "navigation_reach_accent_color_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under an 'Accent Color' heading, is there a grid of multiple small circular color swatches? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Under an 'Accent Color' heading, is there a grid of multiple small circular color swatches? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "navigation_backstack_accent",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "1st BACK -> Settings 'Color Scheme'; 2nd BACK -> Dashboard 'Set your goal'"
+ },
+ {
+ "test": "navigation_reach_history_info",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "History 'Understanding History' sheet appeared; 'August 2026' left"
+ },
+ {
+ "test": "navigation_reach_history_info_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a titled information panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge with a small drag handle at its top)? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a titled information panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge with a small drag handle at its top)? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "navigation_reach_phase_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Phase sheet 'Timing' appeared; active-fast 'Current Fast' left"
+ },
+ {
+ "test": "navigation_stats_to_history",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Statistics History icon -> 'August 2026' appeared; 'Trends' left"
+ },
+ {
+ "test": "navigation_reach_daily_details",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Day-5 tap -> 'Details for August 5' sheet appeared; 'August 2026' left"
+ },
+ {
+ "test": "navigation_reach_daily_details_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a titled details panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge), with the dimmed calendar visible above it? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a titled details panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge), with the dimmed calendar visible above it? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "navigation_reach_edit_fast",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Edit-Fast pencil -> dialog 'Start Time' appeared; sheet 'Details for' left"
+ },
+ {
+ "test": "navigation_reach_edit_fast_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there an 'Edit Fast' dialog shown as a rounded rectangular card floating in the center of the screen (with 'Cancel' and 'Save' buttons), rather than attached to the bottom edge? Answer YES or NO.' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is there an 'Edit Fast' dialog shown as a rounded rectangular card floating in the center of the screen (with 'Cancel' and 'Save' buttons), rather than attached to the bottom edge? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "navigation_backstack_deep",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Cancel->Details sheet; BACK->History 'August 2026'; BACK->Dashboard 'Set your goal'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/android_states_eval.json b/android/tom-murphy-development-fasttimes/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..b8cfb42ec916e45ea8bf17838da7a593cb812481
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_states_eval.json
@@ -0,0 +1,188 @@
+{
+ "module": "states",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 3,
+ "passed": 3,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.2143,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 15,
+ "depth_ge2": 4,
+ "value": 0,
+ "vlm_fine": 3
+ },
+ "results": [
+ {
+ "test": "states_switch_fasting_phases",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show Fasting Phases' switch checked true->false (saw true->false)"
+ },
+ {
+ "test": "states_switch_fab_consequence",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show FAB' checked true->false; dashboard 'Add Fast' FAB present->absent (saw fab True->False)"
+ },
+ {
+ "test": "states_switch_expressive_progress",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Use Expressive Progress Indicator' checked true->false (saw true->false)"
+ },
+ {
+ "test": "states_switch_persists_relaunch",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Show Fasting Phases' flipped OFF stays false across process death (flip=false, after relaunch=false)"
+ },
+ {
+ "test": "states_stats_monthly_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Weekly checked true->false, Monthly false->true; header 'This week'->'Last 30 days' (saw hdr30=True)"
+ },
+ {
+ "test": "states_stats_weekly_back",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Weekly checked ->true, Monthly ->false; header 'Last 30 days'->'This week' (saw week hdr=True)"
+ },
+ {
+ "test": "states_trends_all_time",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Trends 'All Time' checked false->true (Weekly true->false; saw allTime false->true)"
+ },
+ {
+ "test": "states_first_day_of_week",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Sun checked false->true, Mon true->false (saw Sun false->true)"
+ },
+ {
+ "test": "states_first_day_of_week_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the 'First Day of Week' Sun/Mon toggle, is the 'Sun' option the one drawn with the filled/highlighted selection background (the selected pill), rather than 'Mon'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the 'First Day of Week' Sun/Mon toggle, is the 'Sun' option the one drawn with the filled/highlighted selection background (the selected pill), rather than 'Mon'?",
+ "tag": "position"
+ },
+ {
+ "test": "states_save_conditional_enable",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Add Profile Save enabled false->true once a name is typed (saw false->true)"
+ },
+ {
+ "test": "states_favourite_checkbox",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Set as Favourite' CheckBox checked false->true (saw false->true)"
+ },
+ {
+ "test": "states_speed_dial_expand",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "FAB collapsed->expanded: 'Start Open Fast' & 'View History' appear (saw True/True)"
+ },
+ {
+ "test": "states_speed_dial_expand_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the lower-right area of the screen, are there two green rounded action buttons stacked vertically ABOVE the main round hourglass button (an expanded speed-dial menu), rather than just a single round button?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the lower-right area of the screen, are there two green rounded action buttons stacked vertically ABOVE the main round hourglass button (an expanded speed-dial menu), rather than just a single round button?",
+ "tag": "position"
+ },
+ {
+ "test": "states_alltime_expand",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "chevron desc 'Expand'->'Collapse' and new stat rows appear (saw collapse=True, newContent=True)"
+ },
+ {
+ "test": "states_accent_selected",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "the tapped accent circle gains a 'Selected' content-desc marker within its bounds"
+ },
+ {
+ "test": "states_expressive_theme_switch",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Use Expressive Theme' switch checked false->true (saw false->true)"
+ },
+ {
+ "test": "states_theme_dark_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the whole app screen background a dark near-black colour with light/white text (a dark theme), rather than a white/light background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the whole app screen background a dark near-black colour with light/white text (a dark theme), rather than a white/light background?",
+ "tag": "color"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/android_structure_eval.json b/android/tom-murphy-development-fasttimes/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..6d0e7691dc4e5969c1f5351d7534dfc93e6df1a2
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_structure_eval.json
@@ -0,0 +1,250 @@
+{
+ "module": "structure",
+ "total": 23,
+ "passed": 23,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 11,
+ "passed": 11,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.9167,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 5,
+ "liveness": 0,
+ "interactive": 18,
+ "depth_ge1": 14,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 11
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_dashboard_surfaces",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_dashboard_fab_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a green colored button in the bottom-right corner of the screen containing a small dark icon? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a green colored button in the bottom-right corner of the screen containing a small dark icon? Answer YES or NO.",
+ "tag": "color"
+ },
+ {
+ "test": "structure_gate_goal_grid",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_goal_grid_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under the 'Set your goal' heading, are the goal cells arranged in a grid with exactly two columns per row? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under the 'Set your goal' heading, are the goal cells arranged in a grid with exactly two columns per row? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "structure_fab_speeddial_expand",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "clickables +2 with 'Start Open Fast'+'View History' on expand, restored on collapse"
+ },
+ {
+ "test": "structure_fab_speeddial_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there two green pill-shaped action buttons stacked vertically directly above the round green button in the bottom-right corner? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are there two green pill-shaped action buttons stacked vertically directly above the round green button in the bottom-right corner? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "structure_active_fast_ring_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a circular ring or arc drawn around the countdown timer numbers near the top-center of the screen? Answer YES or NO.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a circular ring or arc drawn around the countdown timer numbers near the top-center of the screen? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_active_fast_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "goal card -> ProgressBar ring + End Fast + FAB gone; restored to goal grid on End Fast"
+ },
+ {
+ "test": "structure_dashboard_to_profiles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Dashboard goal card -> Manage Profiles grid (>=4 duration cards) + Add Profile FAB"
+ },
+ {
+ "test": "structure_profiles_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under the 'Other Profiles' heading, are multiple fasting-profile cards arranged in a two-column grid? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Under the 'Other Profiles' heading, are multiple fasting-profile cards arranged in a two-column grid? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "structure_add_profile_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a rounded rectangular dialog card overlaid on the screen that contains three empty text input boxes stacked vertically with a 'Cancel' and 'Save' button below them? Answer YES or NO.' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a rounded rectangular dialog card overlaid on the screen that contains three empty text input boxes stacked vertically with a 'Cancel' and 'Save' button below them? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_add_profile_dialog",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "EditText 0->3 + 1 CheckBox on dialog open, restored on Cancel"
+ },
+ {
+ "test": "structure_settings_rows",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Settings column shows >=6 distinct section/row labels"
+ },
+ {
+ "test": "structure_settings_toggles_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the Settings screen show setting rows with pill-shaped toggle switches aligned to the right side of the rows? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the Settings screen show setting rows with pill-shaped toggle switches aligned to the right side of the rows? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_settings_scroll_reveal",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "ScrollView column; 'Export Data' hidden at top, revealed on scroll"
+ },
+ {
+ "test": "structure_statistics_containers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "3 stat cards + 'Trends' + a >=3-option segmented toggle present"
+ },
+ {
+ "test": "structure_stats_cards_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are the three statistics cards ('Total Fasts', 'Average Fast', 'Consistency') drawn as non-rectangular blob/pentagon/scalloped shapes rather than plain rectangles? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Are the three statistics cards ('Total Fasts', 'Average Fast', 'Consistency') drawn as non-rectangular blob/pentagon/scalloped shapes rather than plain rectangles? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_stats_chart_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels? Answer YES or NO.",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_statistics_expand",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "All-time statistics expand adds Total Duration/Collapse, restored on collapse"
+ },
+ {
+ "test": "structure_history_calendar",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": ">=28 distinct day cells + month header + prev/next month nav"
+ },
+ {
+ "test": "structure_history_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.",
+ "tag": "position"
+ },
+ {
+ "test": "structure_history_summary_vlm",
+ "passed": true,
+ "message": "VLM: Q='Below the calendar, does the 'August Summary' section show three non-rectangular stat cards positioned side by side in one row? Answer YES or NO.' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Below the calendar, does the 'August Summary' section show three non-rectangular stat cards positioned side by side in one row? Answer YES or NO.",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/android_testgen_kit.py b/android/tom-murphy-development-fasttimes/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/tom-murphy-development-fasttimes/tests/android_text_eval.json b/android/tom-murphy-development-fasttimes/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..8e795f50f86154e06cc73c120f02e8f2e4bf58d2
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/android_text_eval.json
@@ -0,0 +1,167 @@
+{
+ "module": "text",
+ "total": 15,
+ "passed": 15,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 15,
+ "passed": 15,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 0,
+ "passed": 0,
+ "failed": 0,
+ "pass_rate": 0
+ },
+ "vlm_ratio": 0.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 15,
+ "depth_ge1": 10,
+ "depth_ge2": 2,
+ "value": 13,
+ "vlm_fine": 0
+ },
+ "results": [
+ {
+ "test": "text_empty_history_copy",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "History empty-state copy reads 'No recent fasts to show.'"
+ },
+ {
+ "test": "text_label_remaining",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "label 'Remaining' absent before, present after starting a timed goal"
+ },
+ {
+ "test": "text_label_elapsed_time",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "label 'Elapsed Time' appears and no 'End Time' line for Open Fast"
+ },
+ {
+ "test": "text_goal_reached_copy",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'Goal Reached!' + label 'Total Time' absent before, present after target met"
+ },
+ {
+ "test": "text_phase_chip_name",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "active-fast phase chip reads a phase name (saw 'Post-Absorptive State')"
+ },
+ {
+ "test": "text_phase_sheet_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "phase-detail sheet shows the labels 'Timing' and 'Benefit'"
+ },
+ {
+ "test": "text_fast_complete_copy",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "summary shows 'Fast Complete!' / 'Rate your fast:' / 'Started:' / 'Ended:' / 'Save'"
+ },
+ {
+ "test": "text_manage_profiles_hint",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "empty-favourite hint + 'Favourite Fast' + 'Other Profiles' headers"
+ },
+ {
+ "test": "text_stats_header_flip",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Statistics header 'This week' -> 'Last 30 days' on Weekly->Monthly"
+ },
+ {
+ "test": "text_stats_labels",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "subtitle 'Keep going to build a habit!' + stat labels Total Fasts/Average Fast/Consistency + completed/this week/goals met"
+ },
+ {
+ "test": "text_history_month_change",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "month header changed 'August 2026' -> 'July 2026' via 'Previous Month'"
+ },
+ {
+ "test": "text_history_info_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "History-Info sheet 'Understanding History' + 'Calendar View' + 'Daily Timeline'"
+ },
+ {
+ "test": "text_daily_details_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Daily-Details title matches 'Details for ' (saw 'Details for August 6')"
+ },
+ {
+ "test": "text_settings_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Settings shows headers 'Appearance'/'Color Scheme'/'Notifications'/'Data Management'"
+ },
+ {
+ "test": "text_settings_version",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Settings footer version matches '\\d+.\\d+.\\d+-DEBUG (\\d+)' (saw '1.0.4-DEBUG (5)')"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/tests/conftest.py b/android/tom-murphy-development-fasttimes/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/tom-murphy-development-fasttimes/tests/requirements.txt b/android/tom-murphy-development-fasttimes/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_computation.py b/android/tom-murphy-development-fasttimes/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..c43858fb82ef051dd37fb57af5b8e18f5b42dd5c
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_computation.py
@@ -0,0 +1,811 @@
+#!/usr/bin/env python3
+"""COMPUTATION module — FastTimes (intermittent-fasting tracker).
+
+CORE FUNCTION here is the fasting TIMER and the derived AGGREGATES. This app has
+no calculator; its "input -> output" surface is:
+
+ * a goal cell tapped -> a live timer that either COUNTS DOWN ("Remaining",
+ timed goal) or COUNTS UP ("Elapsed Time", Open Fast); the timer VALUE is a
+ computed HH:MM:SS that changes over time.
+ * a timed goal -> a computed "Started" and "End Time" pair, End = Start + goal
+ duration (Test 1 Hour: End = Start + 1h; Test Timer 10s: Started == End).
+ * a timed goal reaching its target -> the value MODE flips: "Remaining"
+ -> "Total Time", the goal name -> "Goal Reached!", and the value then counts
+ UP; the "End Time" label -> "Goal".
+ * saving completed fasts -> integer AGGREGATES: the Dashboard "Fasts" count
+ (0 -> 1 -> 2), the Statistics "Total Fasts" ("1"/completed) and "Consistency"
+ ("100%"/goals met when the goal was met), the History "August Summary"
+ "Total Fasts", and a duration formatted \\d+h \\d+m.
+
+Every asserted number/relationship was OBSERVED on the running original (see the
+module docstring values above), never read from source or computed by hand. Wall-
+clock-dependent values are asserted as RELATIONSHIPS (decreasing / increasing /
++1h offset / count deltas) and PATTERNS, with tolerance — the debug Test Timer's
+~10s initial remaining is the only near-literal, and it carries a wide tolerance.
+
+CEDES to sibling lanes: whether a screen is reachable -> navigation; a control's
+checked/selected/enabled bit -> states; the mere EXISTENCE of a saved record (as
+opposed to its numeric aggregate) -> interaction; a non-computed content string
+-> text; the view-tree shape / drawn arcs -> structure (but the arc/chart that
+ENCODES a value visually is a legitimate VLM here).
+
+VLM budget for this lane = 4 (a value made visual, unreadable from the dump): the
+active-fast circular progress RING (partially filled proportional to elapsed), the
+FULL green ring at goal-reached, the statistics BAR CHART (bars of differing
+heights), and the statistics stat-card cluster showing the computed numbers.
+
+Compose renders as android.view.View / TextView with NO resource-ids, so every
+target and read-back key is a visible text / content-desc / bounds-located node.
+
+SAFETY: never taps "Delete" / "Delete Fast"; every exploratory tap is safe.
+
+Run: python3 test_android_computation.py
+"""
+import os
+import re
+import sys
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+_HMS = re.compile(r"^\d{1,2}:\d{2}:\d{2}$") # HH:MM:SS timer value
+_DUR = re.compile(r"\b(\d+)h\s+(\d+)m\b") # "0h 2m" duration
+_CLOCK = re.compile(r"(\d{1,2}):(\d{2})\s*([AP]M)", re.I) # "3:41 PM"
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data (no active fast, empty history), then open Main."""
+ clear_data()
+ open_main()
+
+
+# ── Domain helpers ───────────────────────────────────────────────────────────
+def _dismiss_notif_rationale():
+ """The first-run "Notification Preferences" rationale appears on the first goal
+ tap after clear_data(). Dismiss it non-destructively (choice is irrelevant to
+ the computations under test). Returns True if it was shown."""
+ nodes = ui()
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Skip", "Not Now", "Enable Notifications"):
+ n = find_node(nodes, text=label)
+ if n and is_safe(n):
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+def _on_dashboard(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ return find_node(nodes, text="Set your goal") is not None
+
+
+def _start_goal(cell_text):
+ """From a CLEAN dashboard, tap a goal cell by name and land on the ACTIVE-FAST
+ card (desc='End Fast'). Handles the first-run notification rationale. Returns
+ True on success."""
+ cell = find_node(ui(), text=cell_text)
+ if not cell:
+ return False
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ if find_node(ui(), content_desc="End Fast"):
+ return True
+ cell = find_node(ui(), text=cell_text) # rationale may have eaten the tap
+ if cell:
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ return find_node(ui(), content_desc="End Fast") is not None
+
+
+def _timer_value(nodes=None):
+ """The active-fast card's live HH:MM:SS value (a TextView matching ^\\d\\d:..).
+ Returns the string, or None. There is exactly one such node on the card."""
+ nodes = ui() if nodes is None else nodes
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if _HMS.match(t):
+ return t
+ return None
+
+
+def _hms_to_secs(t):
+ try:
+ h, m, s = (int(x) for x in t.split(":"))
+ return h * 3600 + m * 60 + s
+ except Exception:
+ return None
+
+
+def _card_label(nodes=None):
+ """Which mode-label is showing on the active-fast card: 'Remaining' /
+ 'Elapsed Time' / 'Total Time'. Returns the first found, else ''."""
+ nodes = ui() if nodes is None else nodes
+ for lbl in ("Remaining", "Elapsed Time", "Total Time"):
+ if find_node(nodes, text=lbl):
+ return lbl
+ return ""
+
+
+def _value_under_label(nodes, label_text, want, max_dy=170):
+ """Read the stat VALUE that sits directly BELOW a card label and is x-aligned
+ with it (the FastTimes stat-card pattern: label / big-value / subtitle). `want`
+ is a predicate on the candidate text. Returns the matching text or None.
+
+ Used for the Dashboard 'Fasts' count and the Statistics/History 'Total Fasts'
+ and 'Consistency' cards, whose numbers have no id and no distinct text anchor —
+ only their position under the label identifies them."""
+ lbl = find_node(nodes, text=label_text)
+ if not lbl or "_bounds" not in lbl:
+ return None
+ lx = lbl["_center"][0]
+ ly2 = lbl["_bounds"][3]
+ best = None
+ for n in nodes:
+ t = n.get("text", "").strip()
+ b = n.get("_bounds")
+ if not b or not t or not want(t):
+ continue
+ if b[1] >= ly2 and (b[1] - ly2) < max_dy and abs(n["_center"][0] - lx) < 150:
+ if best is None or b[1] < best[1]:
+ best = (t, b[1])
+ return best[0] if best else None
+
+
+def _fasts_count(nodes=None):
+ """The integer under the Dashboard 'Fasts' stat blob. Returns int or None."""
+ nodes = ui() if nodes is None else nodes
+ v = _value_under_label(nodes, "Fasts", lambda t: t.isdigit())
+ return int(v) if v is not None else None
+
+
+def _wait_goal_reached(polls=18):
+ """Poll until the Test Timer flips to 'Goal Reached!' (~10s). Bounded so a slow
+ emulator never hangs. Returns whether it flipped."""
+ for _ in range(polls):
+ if find_node(ui(), text="Goal Reached!"):
+ return True
+ settle("tap")
+ return False
+
+
+def _modal_star_views():
+ """The 5 clickable rating-star Views in the 'Fast Complete!' summary modal:
+ empty-text clickable android.view.View nodes in one horizontal row. x-sorted."""
+ nodes = ui()
+ clk = [n for n in nodes
+ if n.get("class", "").endswith("view.View")
+ and n.get("clickable") == "true"
+ and not n.get("text", "").strip()
+ and not n.get("content-desc", "").strip()
+ and "_bounds" in n]
+ stars = []
+ for n in clk:
+ x1, y1, x2, y2 = n["_bounds"]
+ w, h = x2 - x1, y2 - y1
+ if w < 40 or h < 40:
+ continue
+ if 0.6 <= w / h <= 1.7:
+ stars.append(n)
+ if len(stars) < 5:
+ return []
+ stars.sort(key=lambda n: n["_center"][1])
+ rows, cur = [], [stars[0]]
+ for n in stars[1:]:
+ if abs(n["_center"][1] - cur[-1]["_center"][1]) <= 30:
+ cur.append(n)
+ else:
+ rows.append(cur)
+ cur = [n]
+ rows.append(cur)
+ row = max(rows, key=len)
+ row.sort(key=lambda n: n["_center"][0])
+ return row
+
+
+def save_test_timer_fast():
+ """Complete + SAVE one Test Timer fast from a clean dashboard (rating 4 stars),
+ landing back on the Dashboard with the fast persisted. Returns True on success.
+ This produces a GOAL-MET completed fast, which is what makes Consistency 100%."""
+ if not _start_goal("Test Timer"):
+ return False
+ _wait_goal_reached()
+ ef = find_node(ui(), content_desc="End Fast")
+ if not ef:
+ return False
+ tap_node(ef)
+ settle("tap")
+ stars = _modal_star_views()
+ if len(stars) >= 4:
+ tap_node(stars[3]) # 4th star
+ settle("tap")
+ save = find_node(ui(), text="Save")
+ if not save or not tap_node(save):
+ return False
+ settle("tap")
+ return _on_dashboard()
+
+
+def _end_active_no_save():
+ """Tap End Fast then BACK out of the summary WITHOUT saving (keeps history
+ clean). Best-effort cleanup only."""
+ ef = find_node(ui(), content_desc="End Fast")
+ if ef:
+ tap_node(ef)
+ settle("tap")
+ back()
+ settle("tap")
+
+
+# ── Named depth helpers (the and_reach_* NAME backs a depth>=1 claim; each body is
+# a real, PROVEN surface jump — target appeared, source vanished). ──────────────
+def and_reach_statistics():
+ """Dashboard -> Statistics ('Performance'). Proven: 'Trends' appears, the goal
+ card 'Set your goal' vanishes. Counts one surface (jump_kind='reach')."""
+ n = find_node(ui(), content_desc="Go to Statistics")
+ if not n:
+ return False
+ return and_reach_surface(n, "Trends", "Set your goal")
+
+
+def and_reach_history():
+ """Dashboard -> History pane. Proven: 'August 2026' appears, 'Set your goal'
+ vanishes. Counts one surface."""
+ n = find_node(ui(), content_desc="Go to History")
+ if not n:
+ return False
+ return and_reach_surface(n, "August 2026", "Set your goal")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) COUNTDOWN — a timed goal's "Remaining" value DECREASES over time
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_countdown_decreases",))
+def test_countdown_decreases():
+ """Start 'Test 1 Hour' (a 1h timed goal): the card shows label 'Remaining' and a
+ HH:MM:SS value that COUNTS DOWN. Read it twice ~3s apart and assert the second
+ is strictly LESS than the first (and the initial value is just under 01:00:00,
+ proving it started from the goal and is decrementing). The 1h window is used
+ (not the 10s Test Timer) so the read is not racing the goal-reached flip."""
+ open_main_clear()
+ started = _start_goal("Test 1 Hour")
+ if not started:
+ record("computation_countdown_decreases", False,
+ "feature_missing: could not start the 'Test 1 Hour' timed goal "
+ "('End Fast' card not shown)",
+ depth=0, jump_kind="value",
+ expect="Remaining value decreases over ~3s (e.g. 00:59:57 -> 00:59:54)")
+ return
+ n1 = ui()
+ label = _card_label(n1)
+ v1 = _timer_value(n1)
+ time.sleep(3)
+ v2 = _timer_value(ui())
+ s1 = _hms_to_secs(v1) if v1 else None
+ s2 = _hms_to_secs(v2) if v2 else None
+ # initial remaining is just under the 1h goal (allow slack for start latency)
+ fresh_ok = s1 is not None and 3480 <= s1 <= 3600 # 58:00 .. 60:00
+ decreased = s1 is not None and s2 is not None and s2 < s1
+ ok = (label == "Remaining") and fresh_ok and decreased
+ record("computation_countdown_decreases", bool(ok),
+ "" if ok else (f"behavior_wrong: label={label!r} remaining did not count "
+ f"down (v1={v1!r} -> v2={v2!r}); expected label 'Remaining' "
+ f"and a strictly decreasing HH:MM:SS near 01:00:00"),
+ depth=0, jump_kind="value",
+ expect=f"label 'Remaining'; value decreases over ~3s (saw {v1} -> {v2})")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) COUNT-UP — Open Fast's "Elapsed Time" value INCREASES over time
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_countup_increases",))
+def test_countup_increases():
+ """Start 'Open Fast' (infinite goal): the card shows label 'Elapsed Time' and a
+ HH:MM:SS value that COUNTS UP, and there is NO 'End Time' line. Read the value
+ twice ~3s apart and assert the second is strictly GREATER than the first."""
+ open_main_clear()
+ started = _start_goal("Open Fast")
+ if not started:
+ record("computation_countup_increases", False,
+ "feature_missing: could not start 'Open Fast' ('End Fast' card not "
+ "shown)",
+ depth=0, jump_kind="value",
+ expect="Elapsed Time value increases over ~3s (e.g. 00:00:03 -> "
+ "00:00:06)")
+ return
+ n1 = ui()
+ label = _card_label(n1)
+ no_end_time = find_node(n1, text="End Time") is None # Open Fast has none
+ v1 = _timer_value(n1)
+ time.sleep(3)
+ v2 = _timer_value(ui())
+ s1 = _hms_to_secs(v1) if v1 else None
+ s2 = _hms_to_secs(v2) if v2 else None
+ increased = s1 is not None and s2 is not None and s2 > s1
+ ok = (label == "Elapsed Time") and no_end_time and increased
+ record("computation_countup_increases", bool(ok),
+ "" if ok else (f"behavior_wrong: label={label!r} elapsed did not count up "
+ f"(v1={v1!r} -> v2={v2!r}) / an 'End Time' line was present "
+ f"({not no_end_time}); expected 'Elapsed Time' counting up "
+ f"with no End Time"),
+ depth=0, jump_kind="value",
+ expect=f"label 'Elapsed Time', no End Time; value increases over ~3s "
+ f"(saw {v1} -> {v2})")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) FRESH TEST TIMER — initial 'Remaining' is ~10s (> 0 and <= 00:00:10)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_test_timer_initial_10s",
+ "computation_test_timer_initial_10s_vlm"))
+def test_test_timer_initial_remaining():
+ """The debug 'Test Timer' goal is 10 seconds: immediately after starting it the
+ 'Remaining' value must be > 0 and <= ~10s (allow a small +slack for start
+ latency, cap at 13s). This pins the debug constant WITH tolerance rather than a
+ hard literal. The partially-filled progress RING (a value made visual) is the
+ paired VLM."""
+ open_main_clear()
+ started = _start_goal("Test Timer")
+ if not started:
+ record("computation_test_timer_initial_10s", False,
+ "feature_missing: could not start 'Test Timer' ('End Fast' card not "
+ "shown)",
+ depth=0, jump_kind="value",
+ expect="initial Remaining > 0 and <= ~00:00:10")
+ vlm_assert("computation_test_timer_initial_10s",
+ "Is a large timer value shown in the centre with a coloured "
+ "circular progress ring or arc drawn around it? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
+ return
+ n1 = ui()
+ label = _card_label(n1)
+ v1 = _timer_value(n1)
+ s1 = _hms_to_secs(v1) if v1 else None
+ ok = (label in ("Remaining", "Total Time")) and s1 is not None and 0 < s1 <= 13
+ record("computation_test_timer_initial_10s", bool(ok),
+ "" if ok else (f"behavior_wrong: fresh Test Timer remaining={v1!r} "
+ f"(label={label!r}); expected a value > 0 and <= ~10s "
+ f"(cap 13s)"),
+ depth=0, jump_kind="value",
+ expect=f"fresh Test Timer 'Remaining' > 0 and <= ~00:00:10 (saw {v1})")
+ # VLM (value-made-visual): a partially filled ring encodes the elapsed fraction.
+ vlm_assert("computation_test_timer_initial_10s",
+ "Is a large timer value (like 00:00:10) shown in the centre of the "
+ "card with a coloured circular progress ring or arc drawn around it? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (4) GOAL-REACHED TRANSITION — 'Remaining' -> 'Total Time' + 'Goal Reached!',
+# then the value counts UP (the VALUE MODE flips)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_goal_reached_transition",
+ "computation_goal_reached_transition_vlm"))
+def test_goal_reached_transition():
+ """Start Test Timer with label 'Remaining' (counting down); after ~10s the value
+ MODE flips: the goal name becomes 'Goal Reached!', the label becomes 'Total
+ Time', and the value then COUNTS UP from the goal. Assert the before ('Remaining'
+ present, 'Goal Reached!'/'Total Time' absent) -> after ('Goal Reached!' +
+ 'Total Time' present) transition AND that the post-goal value increases. The
+ FULL green ring at goal-reached is the paired VLM."""
+ open_main_clear()
+ started = _start_goal("Test Timer")
+ if not started:
+ record("computation_goal_reached_transition", False,
+ "feature_missing: could not start 'Test Timer'",
+ depth=0, jump_kind="transition",
+ expect="'Remaining' -> 'Total Time' + 'Goal Reached!'; then value "
+ "counts up")
+ vlm_assert("computation_goal_reached_transition",
+ "Is a fully-closed bright green circular ring drawn around the "
+ "timer (indicating the fasting goal was reached)? Answer YES or NO.",
+ RESULTS_DIR, tag="color", depth=0, jump_kind="transition")
+ return
+ before = ui()
+ remaining_before = (_card_label(before) == "Remaining"
+ and find_node(before, text="Goal Reached!") is None
+ and find_node(before, text="Total Time") is None)
+ flipped = _wait_goal_reached()
+ after = ui()
+ reached = (flipped
+ and find_node(after, text="Goal Reached!") is not None
+ and find_node(after, text="Total Time") is not None)
+ # after reaching, the value counts UP
+ v1 = _timer_value(after)
+ time.sleep(3)
+ v2 = _timer_value(ui())
+ s1 = _hms_to_secs(v1) if v1 else None
+ s2 = _hms_to_secs(v2) if v2 else None
+ counts_up = s1 is not None and s2 is not None and s2 > s1
+ ok = remaining_before and reached and counts_up
+ record("computation_goal_reached_transition", bool(ok),
+ "" if ok else ("behavior_wrong: the Test Timer did not flip 'Remaining' "
+ "-> 'Total Time'/'Goal Reached!'" if not reached
+ else f"behavior_wrong: after goal-reached the value did not "
+ f"count up (v1={v1!r} -> v2={v2!r})"),
+ depth=0, jump_kind="transition",
+ expect=f"label 'Remaining' -> 'Total Time' + 'Goal Reached!' shown; then "
+ f"value counts up (saw {v1} -> {v2})")
+ # VLM (value-made-visual): the ring is fully closed & green once the goal is met.
+ vlm_assert("computation_goal_reached_transition",
+ "Is a fully-closed bright green circular ring drawn all the way around "
+ "the timer (indicating the fasting goal was reached), rather than a "
+ "partially-filled arc? Answer YES or NO.",
+ RESULTS_DIR, tag="color", depth=0, jump_kind="transition")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (5) START / END TIME — both render; End >= Start; Test 1 Hour End = Start + 1h
+# ═══════════════════════════════════════════════════════════════════════════════
+
+def _clock_minutes(nodes, label_text):
+ """Read the 'Today, H:MM PM' timestamp under a card label ('Started'/'End Time')
+ and return minutes-since-midnight (0..1439), or None. Parses the first
+ H:MM AM/PM in the value node directly below the label."""
+ val = _value_under_label(nodes, label_text, lambda t: _CLOCK.search(t) is not None)
+ if not val:
+ return None
+ m = _CLOCK.search(val)
+ if not m:
+ return None
+ h, mm, ap = int(m.group(1)), int(m.group(2)), m.group(3).upper()
+ h = h % 12
+ if ap == "PM":
+ h += 12
+ return h * 60 + mm
+
+
+@and_test(expects=("computation_end_time_offset",))
+def test_start_end_time_offset():
+ """A TIMED goal computes 'Started' and 'End Time' = Started + goal duration.
+ Start 'Test 1 Hour': assert BOTH timestamps render and End = Start + 60 min
+ (a real computed offset, ±2 min for the read/rollover), handling the midnight
+ wrap. This is the app's most concrete arithmetic on user-visible values."""
+ open_main_clear()
+ started = _start_goal("Test 1 Hour")
+ if not started:
+ record("computation_end_time_offset", False,
+ "feature_missing: could not start 'Test 1 Hour'",
+ depth=0, jump_kind="value",
+ expect="End Time = Started + 60 min (both render)")
+ return
+ nodes = ui()
+ both_render = (find_node(nodes, text="Started") is not None
+ and find_node(nodes, text="End Time") is not None)
+ start_min = _clock_minutes(nodes, "Started")
+ end_min = _clock_minutes(nodes, "End Time")
+ diff = None
+ if start_min is not None and end_min is not None:
+ diff = (end_min - start_min) % (24 * 60) # wrap past midnight
+ offset_ok = diff is not None and abs(diff - 60) <= 2
+ ok = both_render and offset_ok
+ record("computation_end_time_offset", bool(ok),
+ "" if ok else (f"behavior_wrong: Test 1 Hour End Time was not Start + 60m "
+ f"(start_min={start_min}, end_min={end_min}, diff={diff}); "
+ f"both_render={both_render}"),
+ depth=0, jump_kind="value",
+ expect=f"End Time = Started + 60 min (observed diff {diff} min)")
+ _end_active_no_save()
+
+
+@and_test(expects=("computation_test_timer_start_eq_end",))
+def test_test_timer_start_equals_end():
+ """The 10-second 'Test Timer' goal computes Started and End Time within the same
+ minute, so they render EQUAL (0-min offset). Assert both render and End - Start
+ is 0 min (allow 1 min for a read straddling a minute boundary). Complements the
+ +1h case: same machinery, different goal duration -> different computed value."""
+ open_main_clear()
+ started = _start_goal("Test Timer")
+ if not started:
+ record("computation_test_timer_start_eq_end", False,
+ "feature_missing: could not start 'Test Timer'",
+ depth=0, jump_kind="value",
+ expect="Test Timer Started == End Time (0-min offset)")
+ return
+ nodes = ui()
+ both_render = (find_node(nodes, text="Started") is not None
+ and find_node(nodes, text="End Time") is not None)
+ start_min = _clock_minutes(nodes, "Started")
+ end_min = _clock_minutes(nodes, "End Time")
+ diff = None
+ if start_min is not None and end_min is not None:
+ diff = (end_min - start_min) % (24 * 60)
+ same_min = diff is not None and diff <= 1
+ ok = both_render and same_min
+ record("computation_test_timer_start_eq_end", bool(ok),
+ "" if ok else (f"behavior_wrong: Test Timer End Time was not within the "
+ f"same minute as Started (start_min={start_min}, "
+ f"end_min={end_min}, diff={diff}); both_render={both_render}"),
+ depth=0, jump_kind="value",
+ expect=f"Test Timer End Time - Started == 0 min (observed diff {diff})")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (6) FASTS COUNT — clean baseline is 0, then 0 -> 1 -> 2 as fasts are saved
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_fasts_count_zero",))
+def test_fasts_count_zero():
+ """On a CLEAN install the Dashboard 'Fasts / N / this month' aggregate is 0 (and
+ History reads 'No recent fasts to show.'). The negative baseline that makes the
+ 0->1 delta discriminating."""
+ open_main_clear()
+ nodes = ui()
+ count = _fasts_count(nodes)
+ empty_hist = find_node_ci(nodes, "No recent fasts to show.") is not None
+ ok = (count == 0) and empty_hist
+ record("computation_fasts_count_zero", bool(ok),
+ "" if ok else (f"behavior_wrong: clean-install Dashboard 'Fasts' count was "
+ f"{count!r} (expected 0) / History not empty "
+ f"({empty_hist})"),
+ depth=0, jump_kind="value",
+ expect="clean-install Dashboard 'Fasts' count == 0")
+
+
+@and_test(expects=("computation_fasts_count_zero_to_one",))
+def test_fasts_count_zero_to_one():
+ """The 'Fasts' aggregate increments 0 -> 1 after completing and SAVING one Test
+ Timer fast. Reads the count BEFORE (must be 0) and AFTER the save (must be 1) —
+ the count is the computed aggregate, not the record's mere existence."""
+ open_main_clear()
+ before = _fasts_count(ui())
+ made = save_test_timer_fast()
+ after = _fasts_count(ui()) if made else None
+ ok = (before == 0) and made and (after == 1)
+ record("computation_fasts_count_zero_to_one", bool(ok),
+ "" if ok else ("feature_missing: could not complete+Save a Test Timer fast"
+ if not made
+ else f"behavior_wrong: Dashboard 'Fasts' count was "
+ f"{before!r} before and {after!r} after saving one fast "
+ f"(expected 0 -> 1)"),
+ depth=0, jump_kind="value",
+ expect=f"Dashboard 'Fasts' count 0 -> 1 after one saved fast (saw {before} "
+ f"-> {after})")
+
+
+@and_test(expects=("computation_fasts_count_two",))
+def test_fasts_count_two():
+ """The aggregate keeps climbing: after a SECOND saved Test Timer fast the count
+ is 2. A recreation that keeps only a single 'latest' row (not a real count)
+ stalls at 1. Asserts the 0,1,2 progression across two saves."""
+ open_main_clear()
+ counts = [_fasts_count(ui())] # baseline 0
+ for _ in range(2):
+ if not save_test_timer_fast():
+ break
+ counts.append(_fasts_count(ui()))
+ ok = (len(counts) == 3
+ and all(c is not None for c in counts)
+ and counts == [0, 1, 2])
+ record("computation_fasts_count_two", bool(ok),
+ "" if ok else (f"behavior_wrong: Dashboard 'Fasts' count did not climb "
+ f"0 -> 1 -> 2 across two saves (saw {counts}) — only one "
+ f"record appears to be kept"),
+ depth=0, jump_kind="value",
+ expect=f"Dashboard 'Fasts' count 0,1,2 across two saves (observed {counts})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (7) STATISTICS AGGREGATES — Total Fasts = 1, Consistency = 100% (goal met)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_stats_total_fasts_one",
+ "computation_stats_total_fasts_one_vlm"))
+def test_stats_total_fasts_one():
+ """After one goal-met Test Timer fast, the Statistics ('Performance') screen's
+ 'Total Fasts' card reads '1' (with subtitle 'completed'). Crosses to Statistics
+ (depth 1, backed by and_reach_statistics) and reads the computed aggregate. The
+ stat-card cluster showing the numbers is the paired VLM."""
+ open_main_clear()
+ made = save_test_timer_fast()
+ reached = made and and_reach_statistics() # depth 1 (proven reach)
+ if not reached:
+ record("computation_stats_total_fasts_one", False,
+ "setup_failed: could not save a fast and reach Statistics"
+ if not made else
+ "setup_failed: Statistics ('Trends') not reached from 'Go to "
+ "Statistics'",
+ depth=1, jump_kind="value",
+ expect="Statistics 'Total Fasts' card reads '1'")
+ vlm_assert("computation_stats_total_fasts_one",
+ "Do the three rounded statistic cards near the bottom show numeric "
+ "values under their titles (a whole number under 'Total Fasts' and "
+ "a percentage under 'Consistency')? Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=1, jump_kind="value")
+ return
+ nodes = ui()
+ total = _value_under_label(nodes, "Total Fasts", lambda t: t.isdigit())
+ ok = total == "1"
+ record("computation_stats_total_fasts_one", bool(ok),
+ "" if ok else f"behavior_wrong: Statistics 'Total Fasts' read {total!r} "
+ f"after one saved fast (expected '1')",
+ depth=1, jump_kind="value",
+ expect=f"Statistics 'Total Fasts' == '1' (read {total!r})")
+ # VLM (value-made-visual): the expressive stat-card cluster shows the numbers.
+ vlm_assert("computation_stats_total_fasts_one",
+ "Do the three rounded statistic cards near the bottom each show a large "
+ "numeric value under their title (for example a whole number under "
+ "'Total Fasts' and a percentage under 'Consistency')? Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=1, jump_kind="value")
+
+
+@and_test(expects=("computation_stats_consistency_100",))
+def test_stats_consistency_100():
+ """A Test Timer fast REACHES its goal, so after saving one the Statistics
+ 'Consistency' card reads '100%' (subtitle 'goals met'). Crosses to Statistics
+ (depth 1) and reads the computed percentage — a derived value from goals-met /
+ total."""
+ open_main_clear()
+ made = save_test_timer_fast()
+ reached = made and and_reach_statistics() # depth 1 (proven reach)
+ if not reached:
+ record("computation_stats_consistency_100", False,
+ "setup_failed: could not save a fast and reach Statistics",
+ depth=1, jump_kind="value",
+ expect="Statistics 'Consistency' card reads '100%'")
+ return
+ nodes = ui()
+ pct = _value_under_label(nodes, "Consistency", lambda t: t.endswith("%"))
+ ok = pct == "100%"
+ record("computation_stats_consistency_100", bool(ok),
+ "" if ok else f"behavior_wrong: Statistics 'Consistency' read {pct!r} after "
+ f"one goal-met fast (expected '100%')",
+ depth=1, jump_kind="value",
+ expect=f"Statistics 'Consistency' == '100%' (read {pct!r})")
+
+
+@and_test(expects=("computation_stats_chart_vlm",))
+def test_stats_chart_vlm():
+ """The Statistics screen renders a bar/line CHART whose bar HEIGHTS encode the
+ per-day/period values — a value made visual that never reaches the view tree.
+ Crosses to Statistics (depth 1) and asks the VLM about the drawn bars. Pure VLM
+ (no dump-readable rule half beyond reachability, which navigation owns)."""
+ open_main_clear()
+ made = save_test_timer_fast()
+ reached = made and and_reach_statistics() # depth 1 (proven reach)
+ if not reached:
+ vlm_assert("computation_stats_chart",
+ "Are there several vertical or horizontal bars of differing "
+ "lengths drawn above a row of day/date axis labels (T F S S M T W)? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="value")
+ return
+ # VLM (value-made-visual): the chart bars differ in height/length by value.
+ vlm_assert("computation_stats_chart",
+ "Are there several coloured bars drawn in a row above the day/date axis "
+ "labels (like T F S S M T W), representing a chart of values? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="value")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (8) HISTORY AGGREGATE — August Summary 'Total Fasts' = 1
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_history_summary_total_one",))
+def test_history_summary_total_one():
+ """After one saved Test Timer fast, the History pane's 'August Summary' ->
+ 'Total Fasts' card reads '1'. Crosses to the History pane (depth 1, backed by
+ and_reach_history) and reads the month aggregate."""
+ open_main_clear()
+ made = save_test_timer_fast()
+ reached = made and and_reach_history() # depth 1 (proven reach)
+ if not reached:
+ record("computation_history_summary_total_one", False,
+ "setup_failed: could not save a fast and reach the History pane",
+ depth=1, jump_kind="value",
+ expect="History 'August Summary' 'Total Fasts' reads '1'")
+ return
+ # the summary sits below the calendar; scroll it into view then read the value
+ summary = scroll_into_view("August Summary", max_swipes=4)
+ nodes = ui()
+ total = _value_under_label(nodes, "Total Fasts", lambda t: t.isdigit())
+ ok = (summary is not None) and total == "1"
+ record("computation_history_summary_total_one", bool(ok),
+ "" if ok else f"behavior_wrong: History 'August Summary' 'Total Fasts' read "
+ f"{total!r} after one saved fast (expected '1')",
+ depth=1, jump_kind="value",
+ expect=f"History 'August Summary' 'Total Fasts' == '1' (read {total!r})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (9) DURATION FORMATTING — a saved fast renders a \\d+h \\d+m duration
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_duration_format",))
+def test_duration_format():
+ """A completed fast's duration is computed and rendered as 'h m' (e.g.
+ '0h 2m'). After saving one Test Timer fast, the Dashboard History section shows
+ the entry under 'This Week' with a duration matching \\d+h \\d+m. Assert the
+ PATTERN renders (the exact minutes depend on wall-clock rollover during the ~10s
+ fast, so the value itself is NOT hard-coded) and that no duration was present on
+ the clean baseline."""
+ open_main_clear()
+ absent_before = not any(_DUR.search(n.get("text", "")) for n in ui())
+ made = save_test_timer_fast()
+ nodes = ui() if made else []
+ dur_node = next((n.get("text", "") for n in nodes
+ if _DUR.search(n.get("text", ""))), None)
+ this_week = made and find_node(nodes, text="This Week") is not None
+ parsed = _DUR.search(dur_node) if dur_node else None
+ # h and m are non-negative and well-formed (m < 60 is the only sanity bound)
+ format_ok = parsed is not None and 0 <= int(parsed.group(2)) < 60
+ ok = absent_before and made and this_week and format_ok
+ record("computation_duration_format", bool(ok),
+ "" if ok else ("feature_missing: could not save a Test Timer fast"
+ if not made
+ else f"behavior_wrong: no 'h m' duration rendered in "
+ f"the Dashboard History after saving (dur={dur_node!r}, "
+ f"absent_before={absent_before})"),
+ depth=0, jump_kind="value",
+ expect=f"saved fast renders a '\\d+h \\d+m' duration under 'This Week' "
+ f"(saw {dur_node!r})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_countdown_decreases,
+ test_countup_increases,
+ test_test_timer_initial_remaining,
+ test_goal_reached_transition,
+ test_start_end_time_offset,
+ test_test_timer_start_equals_end,
+ test_fasts_count_zero,
+ test_fasts_count_zero_to_one,
+ test_fasts_count_two,
+ test_stats_total_fasts_one,
+ test_stats_consistency_100,
+ test_stats_chart_vlm,
+ test_history_summary_total_one,
+ test_duration_format,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "computation")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_interaction.py b/android/tom-murphy-development-fasttimes/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4f3e96cf0aa36adff8b69d8c0ab777d35f57bc8
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_interaction.py
@@ -0,0 +1,772 @@
+#!/usr/bin/env python3
+"""INTERACTION module — FastTimes (intermittent-fasting tracker).
+
+Owns EFFECT-BY-CONSEQUENCE on user DATA: CRUD lifecycle (create a fast / a
+profile and read it back), multi-step sequences (3+ dependent actions), multi-
+record integrity (N records survive a mutation to one), long-press context menus
+(SOLE owner), and — the highest-value assertion — DATA persistence across process
+death. Every test drives the running original through the real user path, then
+reads the consequence out of a FRESH ui() and asserts it equals what was observed.
+
+CEDES to sibling lanes: a toggle's checked bit / settings persistence -> states;
+a computed value -> computation; the exact label wording -> text; whether a screen
+is reachable -> navigation; view-tree shape -> structure.
+
+Data model (verified live on the original):
+ * A completed fast is a HISTORY record: start the debug "Test Timer" goal cell
+ (a 10-second fast), wait ~11s for "Goal Reached!", tap "End Fast" -> the
+ "Fast Complete!" summary modal (5 clickable star Views + Save) -> Save. The
+ Dashboard "Fasts" count increments and the fast lands in History (Room DB) and
+ survives process death.
+ * A profile is created from Manage Profiles -> "Add Profile" FAB -> a dialog with
+ 3 EditText (Profile Name / Description / Duration) + Save; the new card appears
+ in "Other Profiles". Save's clickable parent is disabled until a name is typed.
+ * Long-pressing a profile card reveals an "Edit | Favourite | Delete" button
+ group; "Favourite" moves the card into the "Favourite Fast" section.
+
+Compose renders as android.view.View / TextView with NO resource-ids, so every
+target and every read-back key is a visible text / content-desc / a clickable View
+located by bounds.
+
+VLM budget for this lane = 8 (visual DATA states unreadable from the dump): the
+summary-modal 4-filled-star row, the Daily-Details 4-green-star rating, the
+Edit-Fast 4-green-star rating, the long-press outlined card, the populated
+Favourite Fast card, the newly created profile card in the grid, the running
+active-fast ring after a process kill, and the multi-record history list.
+
+SAFETY: never taps "Delete" / "Delete Fast" (destructive); every exploratory tap
+goes through safe_tap(). The Add Profile dialog is Compose and dismisses on an
+outside-tap / BACK, so the kit's hide_keyboard() would close it — this module
+therefore taps the dialog's Save control DIRECTLY with the keyboard up (verified),
+and never sends a raw ESCAPE keyevent.
+
+Run: python3 test_android_interaction.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+MARK = "kitprofZ" # distinctive marker for a created profile record
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data (no active fast, empty history), then open Main."""
+ clear_data()
+ open_main()
+
+
+def kill_and_reopen():
+ """Process-death probe WITHOUT monkey: force-stop the app, then relaunch the
+ real MainActivity. An in-memory-only recreation cannot survive this."""
+ force_stop()
+ settle("key")
+ open_main()
+
+
+# ── Domain helpers ───────────────────────────────────────────────────────────
+def _dismiss_notif_rationale():
+ """The first-run "Notification Preferences" rationale appears on the first goal
+ tap after clear_data(). Dismiss it with a NON-destructive choice (the choice is
+ irrelevant to the data operations under test). Returns True if it was shown."""
+ nodes = ui()
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Skip", "Not Now", "Enable Notifications"):
+ n = find_node(nodes, text=label)
+ if n and is_safe(n):
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+def _on_dashboard(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ return find_node(nodes, text="Set your goal") is not None
+
+
+def _fasts_count(nodes=None):
+ """Read the integer under the Dashboard 'Fasts' stat blob (the record count).
+ Returns int or None. The number TextView sits directly below the 'Fasts' label
+ and roughly x-aligned with it."""
+ nodes = ui() if nodes is None else nodes
+ lbl = find_node(nodes, text="Fasts")
+ if not lbl or "_bounds" not in lbl:
+ return None
+ lx = lbl["_center"][0]
+ ly2 = lbl["_bounds"][3]
+ best = None
+ for n in nodes:
+ t = n.get("text", "").strip()
+ b = n.get("_bounds")
+ if not b or not t.isdigit():
+ continue
+ if b[1] > ly2 and (b[1] - ly2) < 160 and abs(n["_center"][0] - lx) < 140:
+ if best is None or b[1] < best[1]:
+ best = (int(t), b[1])
+ return best[0] if best else None
+
+
+def _start_goal(cell_text):
+ """From a CLEAN dashboard, tap a goal cell by its name and land on the
+ ACTIVE-FAST card (desc='End Fast'). Handles the first-run notification
+ rationale. Returns True on success."""
+ cell = find_node(ui(), text=cell_text)
+ if not cell:
+ return False
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ if find_node(ui(), content_desc="End Fast"):
+ return True
+ # the rationale dialog may have consumed the first tap; retry the cell once
+ cell = find_node(ui(), text=cell_text)
+ if cell:
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ return find_node(ui(), content_desc="End Fast") is not None
+
+
+def _wait_goal_reached(polls=16):
+ """Poll until the Test Timer flips to 'Goal Reached!' (~11s). Bounded so a slow
+ emulator never hangs the suite. Returns whether it flipped."""
+ for _ in range(polls):
+ if find_node(ui(), text="Goal Reached!"):
+ return True
+ settle("tap")
+ return False
+
+
+def _modal_star_views():
+ """The 5 clickable rating stars in the 'Fast Complete!' summary modal: they are
+ empty-text clickable android.view.View nodes laid out in ONE horizontal row
+ (near-square, same y-band). Returned x-sorted, so index 3 == the 4th star."""
+ nodes = ui()
+ clk = [n for n in nodes
+ if n.get("class", "").endswith("view.View")
+ and n.get("clickable") == "true"
+ and not n.get("text", "").strip()
+ and not n.get("content-desc", "").strip()
+ and "_bounds" in n]
+ # keep only near-square cells (a star), then the most populous single y-row
+ stars = []
+ for n in clk:
+ x1, y1, x2, y2 = n["_bounds"]
+ w, h = x2 - x1, y2 - y1
+ if w < 40 or h < 40:
+ continue
+ if 0.6 <= w / h <= 1.7:
+ stars.append(n)
+ if len(stars) < 5:
+ return []
+ # group by y-centre band; pick the band with the most members (the star row)
+ stars.sort(key=lambda n: n["_center"][1])
+ rows, cur = [], [stars[0]]
+ for n in stars[1:]:
+ if abs(n["_center"][1] - cur[-1]["_center"][1]) <= 30:
+ cur.append(n)
+ else:
+ rows.append(cur)
+ cur = [n]
+ rows.append(cur)
+ row = max(rows, key=len)
+ row.sort(key=lambda n: n["_center"][0])
+ return row
+
+
+def _tap_summary_save():
+ """Tap 'Save' in the summary modal. 'Save' is a non-clickable TextView; its
+ centre lies inside the clickable parent View, so tapping the text centre works.
+ """
+ n = find_node(ui(), text="Save")
+ return tap_node(n) if n else False
+
+
+def save_test_timer_fast():
+ """Complete + SAVE one Test Timer fast from a clean dashboard (rating it 4
+ stars), landing back on the Dashboard with the fast persisted. Returns True on
+ success."""
+ if not _start_goal("Test Timer"):
+ return False
+ _wait_goal_reached()
+ ef = find_node(ui(), content_desc="End Fast")
+ if not ef:
+ return False
+ tap_node(ef)
+ settle("tap")
+ stars = _modal_star_views()
+ if len(stars) >= 4:
+ tap_node(stars[3]) # 4th star
+ settle("tap")
+ if not _tap_summary_save():
+ return False
+ settle("tap")
+ return _on_dashboard()
+
+
+def open_history_via_link():
+ """Dashboard -> History pane via the 'Go to History' arrow. Returns True when
+ the month header is showing."""
+ n = find_node(ui(), content_desc="Go to History")
+ if not n:
+ return False
+ tap_node(n)
+ settle("tap")
+ return find_node(ui(), text="August 2026") is not None
+
+
+def open_daily_details_day5():
+ """From the History pane, open day-5's Daily Details bottom sheet (day 5 holds
+ the saved fast). Returns True when the sheet is showing."""
+ nodes = ui()
+ day = find_node(nodes, text="5")
+ marker = find_node(nodes, content_desc="Goal Met")
+ if day and marker and "_center" in day and "_center" in marker:
+ x = (day["_center"][0] + marker["_center"][0]) // 2
+ y = (day["_center"][1] + marker["_center"][1]) // 2
+ tap(x, y)
+ elif marker:
+ tap_node(marker)
+ elif day:
+ tap_node(day)
+ else:
+ return False
+ return any("details for" in k.lower() for k in and_showing())
+
+
+def _tap_enabled_dialog_save():
+ """Tap 'Save' in an in-place dialog (Add Profile), robustly and WITHOUT
+ dismissing the dialog. 'Save' is a non-clickable TextView whose ENABLED
+ clickable parent must be tapped; that parent is enabled=false until a name is
+ entered. The kit's hide_keyboard() would close this Compose dialog (outside-tap
+ / BACK), so this tolerates the keyboard being up: it re-dumps for fresh
+ (keyboard-shifted) bounds, then taps the SMALLEST enabled clickable View that
+ contains the 'Save' text centre. Returns True only when it tapped an ENABLED
+ Save control."""
+ d = ui()
+ save = find_node(d, text="Save")
+ if not save or "_center" not in save:
+ return False
+ sx, sy = save["_center"]
+ best = None
+ for n in d:
+ if (n.get("clickable") == "true" and n.get("enabled") == "true"
+ and "_bounds" in n):
+ x1, y1, x2, y2 = n["_bounds"]
+ if x1 <= sx <= x2 and y1 <= sy <= y2:
+ area = (x2 - x1) * (y2 - y1)
+ if best is None or area < best[0]:
+ best = (area, ((x1 + x2) // 2, (y1 + y2) // 2))
+ if best is None:
+ return False # Save present but its clickable parent disabled
+ tap(*best[1])
+ settle("tap")
+ return True
+
+
+# ── Named depth helpers (the and_enter_*/and_reach_* NAME backs a depth>=1 claim;
+# each body is a real, proven jump). ───────────────────────────────────────────
+def and_reach_profiles():
+ """Dashboard -> Manage Profiles. Proven: 'Other Profiles' appears, the goal card
+ 'Set your goal' vanishes. Counts one surface (jump_kind='reach')."""
+ n = find_node(ui(), text="Manage Profiles") or find_node_ci(ui(), "Manage Profiles")
+ if not n:
+ return False
+ return and_reach_surface(n, "Other Profiles", "Set your goal")
+
+
+def and_enter_add_profile_dialog():
+ """Manage Profiles -> the 'Add Profile' dialog (a new window layer with 3
+ EditText). Counts one surface (depth+1)."""
+ n = find_node(ui(), content_desc="Add Profile")
+ if not n or not tap_node(n):
+ return False
+ if len(find_by_class(ui(), "EditText")) < 3:
+ return False
+ and_enter("Add Profile dialog")
+ return True
+
+
+def and_reach_daily_details():
+ """History pane -> Daily Details sheet for day 5. Counts one surface."""
+ before = and_showing()
+ if not open_daily_details_day5():
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Details for", "August 2026")
+ if ok:
+ and_enter("Daily Details")
+ return ok
+
+
+def and_reach_edit_fast():
+ """Daily Details sheet -> Edit Fast dialog (pencil). Counts one surface."""
+ n = find_node(ui(), content_desc="Edit Fast")
+ if not n:
+ return False
+ return and_reach_surface(n, "Start Time", "Details for")
+
+
+def long_press_profile(name_or_duration):
+ """Long-press a profile card body -> the 'Edit | Favourite | Delete' button
+ group. Returns True when the menu appears. SOLE-OWNER long-press."""
+ n = find_node(ui(), text=name_or_duration)
+ if not n:
+ return False
+ long_press(n, ms=1000)
+ menu = ui()
+ return (find_node(menu, text="Favourite") is not None
+ and find_node(menu, text="Edit") is not None)
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) CRUD CREATE + PERSISTENCE — the primary create flow, survives process death
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_create_fast_persists",
+ "interaction_create_fast_persists_vlm"))
+def test_create_fast_survives_process_death():
+ """Full create -> verify -> persist: start Test Timer, End, rate 4 stars, Save;
+ assert the Dashboard 'Fasts' count went 0 -> 1 and a fast appeared in History;
+ then KILL the process and relaunch and assert the record is STILL there. The
+ negative half (count 0 + empty history before) is what makes it discriminating."""
+ open_main_clear()
+ absent_before = (_fasts_count() == 0
+ and find_node_ci(ui(), "No recent fasts to show.") is not None)
+ made = save_test_timer_fast()
+ if not made:
+ record("interaction_create_fast_persists", False,
+ "feature_missing: could not complete+Save a Test Timer fast (no goal "
+ "cell / no summary modal / no Save)",
+ depth=0, jump_kind="value",
+ expect="Dashboard 'Fasts' 0->1 and a History fast after Save+relaunch")
+ # spend the paired VLM record on whatever is on screen
+ vlm_assert("interaction_create_fast_persists",
+ "In the 'Rate your fast' star row of the completion dialog, are "
+ "exactly 4 of the 5 stars filled in (coloured) and the 5th star an "
+ "empty outline? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
+ return
+ after_save = ui()
+ created = (_fasts_count(after_save) == 1
+ and find_node(after_save, text="This Week") is not None)
+ # process-death probe — the highest-value assertion for this lane
+ kill_and_reopen()
+ survived = ui()
+ persisted = (_fasts_count(survived) == 1
+ and find_node(survived, text="This Week") is not None)
+ ok = absent_before and created and persisted
+ record("interaction_create_fast_persists", bool(ok),
+ "" if ok else ("behavior_wrong: 'Fasts' count / History did not reflect "
+ "the saved fast" if not created
+ else "behavior_wrong: the saved fast did NOT survive process "
+ "death ('Fasts' count reset or History empty after "
+ "relaunch)"),
+ depth=0, jump_kind="value",
+ expect="Dashboard 'Fasts' 0->1 + History 'This Week'; both still present "
+ "after force-stop+relaunch")
+ # VLM (persistence, visual): the History section on the surviving Dashboard shows
+ # the completed fast with its Goal-Reached check.
+ vlm_assert("interaction_create_fast_persists",
+ "After the app was restarted, does the 'History' section near the "
+ "bottom of the dashboard list a completed fast entry (a duration like "
+ "'0h 2m' under a 'This Week' heading with a green check icon) rather "
+ "than an empty 'No recent fasts' message? Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=0, jump_kind="value")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) MULTI-RECORD INTEGRITY — add 3 fasts; the count reflects all 3, survives kill
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_multi_record_integrity",
+ "interaction_multi_record_integrity_vlm"))
+def test_multi_record_integrity():
+ """Create THREE Test Timer fasts in a row, reading the Dashboard 'Fasts' count
+ back out after each Save. A recreation that keeps only one row (an in-memory
+ 'latest fast' instead of a real table) fails: the count must climb 0->1->2->3
+ monotonically, never stall at 1. Then relaunch and assert all 3 still counted."""
+ open_main_clear()
+ counts = [_fasts_count()] # baseline: expect 0
+ for _ in range(3):
+ if not save_test_timer_fast():
+ break
+ counts.append(_fasts_count(ui()))
+ # the count must be a strictly-increasing 0,1,2,3
+ monotonic = (len(counts) == 4
+ and all(c is not None for c in counts)
+ and counts == [0, 1, 2, 3])
+ # persistence of the aggregate across a kill: still 3
+ kill_and_reopen()
+ persisted = _fasts_count(ui()) == 3
+ ok = monotonic and persisted
+ record("interaction_multi_record_integrity", bool(ok),
+ "" if ok else ("behavior_wrong: the 'Fasts' count did not climb "
+ f"0->1->2->3 across three saves (saw {counts}) — only one "
+ "record is being kept" if not monotonic
+ else "behavior_wrong: the three-fast total (3) did not "
+ "survive process death"),
+ depth=0, jump_kind="value",
+ expect=f"Dashboard 'Fasts' count 0,1,2,3 across three saves, still 3 "
+ f"after relaunch (observed {counts})")
+ # VLM: after 3 fasts the History section is non-empty; assert a populated list.
+ vlm_assert("interaction_multi_record_integrity",
+ "Does the 'History' section of the dashboard show at least one "
+ "completed fast entry with a duration value and a green check icon "
+ "(i.e. it is NOT the empty 'No recent fasts to show.' state)? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=0, jump_kind="value")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) RATING WRITTEN IN SUMMARY, READ BACK IN TWO SURFACES (data integrity)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_rating_in_daily_details",
+ "interaction_rating_in_daily_details_vlm"))
+def test_rating_persists_daily_details():
+ """The 4-star rating written into the summary modal must read back in the Daily
+ Details sheet. Multi-step: create+rate the fast, open History, open day 5's
+ sheet, and assert the rated fast row is shown. (The exact star FILL is a drawn
+ property -> the paired _vlm; the dump-readable half is that the correct fast row
+ 'Test Timer' appears in the 'Details for ...' sheet.)"""
+ open_main_clear()
+ made = save_test_timer_fast()
+ on_hist = made and open_history_via_link() # depth 1
+ on_sheet = on_hist and and_reach_daily_details() # depth 2
+ sheet = ui() if on_sheet else []
+ # the sheet shows the created record: its goal chip within a 'Details for' sheet
+ row_ok = (on_sheet
+ and find_node(sheet, text="Test Timer") is not None
+ and any("details for" in k.lower() for k in and_showing(sheet)))
+ ok = bool(row_ok)
+ record("interaction_rating_in_daily_details", ok,
+ "" if ok else ("setup_failed: could not build "
+ "create->History->Daily-Details" if not on_sheet
+ else "behavior_wrong: the Daily Details sheet did not show "
+ "the created 'Test Timer' fast row"),
+ depth=2, jump_kind="value",
+ expect="Daily Details for Aug 5 shows the 'Test Timer' fast row (created "
+ "with 4 stars)")
+ # VLM (data integrity, visual): the rating on that row is 4 filled + 1 empty star.
+ vlm_assert("interaction_rating_in_daily_details",
+ "In this daily-details panel, does the fast entry (labelled 'Test "
+ "Timer', duration '0h 2m') show a rating of exactly 4 filled/coloured "
+ "stars followed by 1 empty outline star? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=2, jump_kind="value")
+
+
+@and_test(expects=("interaction_rating_in_edit_fast",
+ "interaction_rating_in_edit_fast_vlm"))
+def test_rating_persists_edit_fast():
+ """The SAME 4-star rating must also read back in the Edit Fast dialog (a second
+ surface). Deep multi-step: create+rate, History, Daily Details, Edit Fast; assert
+ the dialog shows the record's Start/End times + a 'Rating' row. Cancel out
+ without editing (never taps the red 'Delete Fast')."""
+ open_main_clear()
+ made = save_test_timer_fast()
+ on_hist = made and open_history_via_link() # depth 1
+ on_sheet = on_hist and and_reach_daily_details() # depth 2
+ on_dialog = on_sheet and and_reach_edit_fast() # depth 3
+ dlg = ui() if on_dialog else []
+ dialog_ok = (on_dialog
+ and find_node(dlg, text="Rating") is not None
+ and find_node(dlg, text="Start Time") is not None
+ and find_node(dlg, text="End Time") is not None)
+ # VLM WHILE THE DIALOG IS OPEN (before the Cancel that reverses it)
+ vlm_assert("interaction_rating_in_edit_fast",
+ "In this 'Edit Fast' dialog, does the 'Rating' row show exactly 4 "
+ "filled/coloured stars followed by 1 empty outline star? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=3, jump_kind="value")
+ # leave the dialog non-destructively (Cancel; NEVER 'Delete Fast')
+ cancel = find_node(ui(), text="Cancel")
+ if cancel and is_safe(cancel):
+ tap_node(cancel)
+ else:
+ and_back()
+ ok = bool(dialog_ok)
+ record("interaction_rating_in_edit_fast", ok,
+ "" if ok else ("setup_failed: could not build "
+ "create->History->Daily-Details->Edit-Fast" if not on_dialog
+ else "behavior_wrong: the Edit Fast dialog did not show the "
+ "record's Start/End Time + Rating rows"),
+ depth=3, jump_kind="value",
+ expect="Edit Fast dialog shows Start Time / End Time / Rating for the "
+ "created 4-star fast")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (4) LONG-PRESS CONTEXT MENU (SOLE OWNER) + the data change it drives
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_longpress_menu",
+ "interaction_longpress_menu_vlm"))
+def test_longpress_context_menu():
+ """SOLE-OWNER long-press: long-pressing a profile card reveals an 'Edit |
+ Favourite | Delete' button group that is ABSENT beforehand. Assert the
+ absent->present flip of the menu (the outlined-card highlight is drawn -> the
+ paired _vlm)."""
+ open_main_clear()
+ reached = and_reach_profiles() # depth 1
+ if not reached:
+ record("interaction_longpress_menu", False,
+ "setup_failed: Manage Profiles not reached",
+ depth=1, jump_kind="transition",
+ expect="long-press adds an 'Edit | Favourite | Delete' button group")
+ vlm_assert("interaction_longpress_menu",
+ "Is exactly one fasting-profile card outlined/highlighted with a "
+ "coloured border distinct from the other cards? Answer YES or NO.",
+ RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
+ return
+ before = ui()
+ menu_absent_before = find_node(before, text="Favourite") is None
+ appeared = long_press_profile("12 Hours")
+ ok = menu_absent_before and appeared
+ record("interaction_longpress_menu", bool(ok),
+ "" if ok else ("feature_missing: long-pressing a profile card did not "
+ "reveal an 'Edit | Favourite | Delete' button group"),
+ depth=1, jump_kind="transition",
+ expect="Long-press: 'Edit'+'Favourite'+'Delete' button group appeared "
+ "(absent before)")
+ # VLM: the long-pressed card gets a coloured outline distinct from the others.
+ vlm_assert("interaction_longpress_menu",
+ "Is exactly one fasting-profile card outlined/highlighted with a "
+ "coloured border that is distinct from the other cards' borders? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("interaction_longpress_set_favourite",
+ "interaction_longpress_set_favourite_vlm"))
+def test_longpress_set_favourite():
+ """Long-press -> tap 'Favourite' -> the 'Favourite Fast' section (empty hint
+ beforehand) now holds the chosen profile card. Multi-step data change; assert
+ the hint 'Press and hold a profile...' DISAPPEARS and the profile name appears in
+ the favourite section. Then relaunch and assert the favourite PERSISTS."""
+ open_main_clear()
+ reached = and_reach_profiles() # depth 1
+ hint_before = (reached
+ and find_node_ci(ui(),
+ "Press and hold a profile to add it as your "
+ "favourite") is not None)
+ got_menu = reached and long_press_profile("12 Hours")
+ if got_menu:
+ fav = find_node(ui(), text="Favourite")
+ if fav and is_safe(fav):
+ tap_node(fav)
+ settle("tap")
+ after = ui()
+ hint_gone = find_node_ci(after,
+ "Press and hold a profile to add it as your "
+ "favourite") is None
+ # the favourite card now sits ABOVE the 'Other Profiles' heading
+ fav_y = oth_y = None
+ for n in after:
+ if n.get("text", "") == "Favourite Fast" and "_bounds" in n:
+ fav_y = n["_bounds"][3]
+ if n.get("text", "") == "Other Profiles" and "_bounds" in n:
+ oth_y = n["_bounds"][1]
+ card = find_node(after, text="12-Hour Fast")
+ in_fav_section = (card is not None and "_center" in card
+ and fav_y is not None and oth_y is not None
+ and fav_y < card["_center"][1] < oth_y)
+ # persistence: the favourite survives a process kill
+ kill_and_reopen()
+ and_reset_depth()
+ reopened = and_reach_profiles()
+ persisted = (reopened
+ and find_node_ci(ui(),
+ "Press and hold a profile to add it as your "
+ "favourite") is None)
+ ok = bool(hint_before and hint_gone and in_fav_section and persisted)
+ record("interaction_longpress_set_favourite", ok,
+ "" if ok else ("setup_failed: could not reach Manage Profiles / long-press"
+ if not got_menu
+ else "behavior_wrong: 'Favourite' did not move the profile "
+ "into the 'Favourite Fast' section, or it did not "
+ "survive relaunch"),
+ depth=1, jump_kind="value",
+ expect="After long-press->Favourite: hint gone + '12-Hour Fast' in the "
+ "Favourite Fast section; still favourited after relaunch")
+ # VLM: a profile card now occupies the Favourite Fast section.
+ vlm_assert("interaction_longpress_set_favourite",
+ "Under the 'Favourite Fast' heading (above 'Other Profiles'), is there "
+ "now a fasting-profile card, rather than only the grey hint text 'Press "
+ "and hold a profile to add it as your favourite'? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="value")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (5) CRUD CREATE — a new profile, read back in the grid, survives a fresh open
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_create_profile",
+ "interaction_create_profile_vlm"))
+def test_create_profile():
+ """Create a profile via Add Profile -> Save and read the new card back out of a
+ fresh grid. Distinctive marker 'kitprofZ' so the read-back cannot match any
+ seeded profile; asserted ABSENT before and PRESENT after. Then re-open Manage
+ Profiles from scratch and assert it is STILL there (persisted).
+
+ Note: only the Profile Name is required (Save's clickable parent enables once a
+ name is present); the dialog's Save is tapped DIRECTLY with the keyboard up,
+ because the kit's hide_keyboard() would close this Compose dialog."""
+ open_main_clear()
+ reached = and_reach_profiles() # depth 1
+ absent_before = reached and scroll_into_view(MARK, max_swipes=6) is None
+ opened = reached and and_enter_add_profile_dialog() # depth 2
+ if not opened:
+ record("interaction_create_profile", False,
+ "feature_missing: Add Profile dialog with 3 EditText not reached",
+ depth=2, jump_kind="value",
+ expect=f"profile card {MARK!r} present in Other Profiles after Save")
+ vlm_assert("interaction_create_profile",
+ f"Is there a fasting-profile card labelled '{MARK}' in the profiles "
+ f"grid? Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=2, jump_kind="value")
+ return
+ # first EditText by y-order is the Profile Name field; typing it enables Save
+ edits = sorted(find_by_class(ui(), "EditText"),
+ key=lambda n: n["_bounds"][1] if "_bounds" in n else 0)
+ # verify_focus=False: this Compose dialog shifts the EditText bounds when
+ # the keyboard animates in, which makes the kit's focus-verify retry
+ # double-tap a stale node and lose the text; a single tap+type is reliable.
+ typed = bool(edits) and type_text(edits[0], MARK, verify_focus=False)
+ # tap the ENABLED Save control directly (keyboard up); do NOT hide_keyboard()
+ saved = _tap_enabled_dialog_save()
+ # read the created card back out of a FRESH, scrolled grid
+ present_after = scroll_into_view(MARK, max_swipes=6) is not None
+ # persistence: re-open Manage Profiles from scratch; the profile is still listed
+ kill_and_reopen()
+ and_reset_depth()
+ reopened = and_reach_profiles()
+ persisted = reopened and scroll_into_view(MARK, max_swipes=6) is not None
+ ok = bool(absent_before and typed and saved and present_after and persisted)
+ record("interaction_create_profile", ok,
+ "" if ok else ("behavior_wrong: profile marker was already present before "
+ "creation" if not absent_before
+ else "behavior_wrong: the created profile "
+ f"{MARK!r} did not appear in the grid / did not survive "
+ "a fresh open"),
+ depth=2, jump_kind="value",
+ expect=f"profile card {MARK!r} absent before, present after Save, still "
+ f"present after relaunch")
+ # re-locate the card so the VLM screenshot frames it
+ scroll_into_view(MARK, max_swipes=4)
+ vlm_assert("interaction_create_profile",
+ f"Is there a fasting-profile card whose title text reads '{MARK}' in "
+ f"the profiles grid? Answer YES or NO.",
+ RESULTS_DIR, tag="content", depth=2, jump_kind="value")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (6) DATA PERSISTENCE ACROSS PROCESS DEATH — an ACTIVE fast survives the kill
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_active_fast_survives",
+ "interaction_active_fast_survives_vlm"))
+def test_active_fast_survives_kill():
+ """Start an Open Fast (∞ — counts up, 'Elapsed Time', never auto-completes), then
+ KILL the process and relaunch: the Dashboard must STILL show the running fast
+ ('Elapsed Time' + 'End Fast'), not the empty goal grid. An in-memory-only
+ recreation shows the goal grid instead. Asserts the goal grid was present before
+ starting (negative half) and gone after."""
+ open_main_clear()
+ grid_before = find_node(ui(), text="Set your goal") is not None
+ started = _start_goal("Open Fast")
+ active = ui()
+ running_before_kill = (started
+ and find_node(active, text="Elapsed Time") is not None
+ and find_node(active, content_desc="End Fast") is not None)
+ if not running_before_kill:
+ record("interaction_active_fast_survives", False,
+ "feature_missing: could not start an Open Fast ('Elapsed Time' / "
+ "'End Fast' not shown)",
+ depth=0, jump_kind="value",
+ expect="active Open Fast ('Elapsed Time'+'End Fast') persists after "
+ "force-stop+relaunch")
+ vlm_assert("interaction_active_fast_survives",
+ "Is there a circular ring or arc drawn around a large running "
+ "timer near the top-centre of the screen (an active fast in "
+ "progress)? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
+ return
+ # process-death probe
+ kill_and_reopen()
+ survived = ui()
+ still_running = (find_node(survived, text="Elapsed Time") is not None
+ and find_node(survived, content_desc="End Fast") is not None
+ and find_node(survived, text="Set your goal") is None)
+ ok = bool(grid_before and still_running)
+ record("interaction_active_fast_survives", ok,
+ "" if ok else "behavior_wrong: the active Open Fast did NOT survive process "
+ "death (Dashboard fell back to the goal grid / lost 'Elapsed "
+ "Time'+'End Fast')",
+ depth=0, jump_kind="value",
+ expect="After force-stop+relaunch: 'Elapsed Time' + 'End Fast' still shown, "
+ "goal grid 'Set your goal' gone")
+ # VLM (persistence, visual): the running-timer ring is still rendered after the kill.
+ vlm_assert("interaction_active_fast_survives",
+ "Is there a circular ring or arc drawn around a large running timer "
+ "near the top-centre of the screen (an active fast still in progress), "
+ "rather than a grid of goal-selection cells? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="value")
+ # clean up: end the fast (no save) so a later run starts from a known state
+ ef = find_node(ui(), content_desc="End Fast")
+ if ef:
+ tap_node(ef)
+ settle("tap")
+ and_back() # dismiss the summary, no save
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_create_fast_survives_process_death,
+ test_multi_record_integrity,
+ test_rating_persists_daily_details,
+ test_rating_persists_edit_fast,
+ test_longpress_context_menu,
+ test_longpress_set_favourite,
+ test_create_profile,
+ test_active_fast_survives_kill,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "interaction")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_navigation.py b/android/tom-murphy-development-fasttimes/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..6077f35d4319ee4bfe5e09f771afdee8cf640ac8
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_navigation.py
@@ -0,0 +1,701 @@
+#!/usr/bin/env python3
+"""NAVIGATION module — FastTimes (intermittent-fasting tracker).
+
+Owns surface REACHABILITY and back-stack integrity ONLY. Every jump is proven with
+and_reach(before, after, target, source): the TARGET surface's discriminating
+element APPEARED *and* the SOURCE surface's element DISAPPEARED — a flat dump read
+of an always-present element can never fake a reach. This lane is the sole owner of
+jump_kind="reach" and of the deep (depth>=2/>=3) chains; the other lanes stay
+shallow so real navigation depth is measured here.
+
+Nav graph (verified live on the original):
+ main = draggable two-pane Dashboard <-> History (swipe OR "Go to History"; BACK
+ or the Back arrow returns to Dashboard — History is NOT a nav route).
+ Dashboard -> Settings (gear), Manage Profiles (link), Statistics ("Go to
+ Statistics"). Settings -> Theme & Accent Color (Custom swatch).
+ History -> Daily Details (tap a day with a fast) -> Edit Fast dialog.
+ History -> History Info sheet ("i"). Active fast -> phase-detail sheet (chip).
+ Statistics -> History (top-right History icon).
+
+Compose renders as android.view.View / TextView with NO resource-ids, so every
+trigger and every discriminating key is a visible text or content-desc.
+
+VLM budget for this lane = 6 (transition end-states / toolbar affordances that are
+visual): the Statistics chart, the History month grid, the Theme&Accent swatch
+grid, the History-Info bottom sheet, the Daily-Details bottom sheet, and the
+Edit-Fast centered dialog card. Every other reach/back-stack case is pure rule.
+
+Run: python3 test_android_navigation.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data (no active fast, empty history), then open Main."""
+ clear_data()
+ open_main()
+
+
+# ── Domain helpers ───────────────────────────────────────────────────────────
+def _dismiss_notif_rationale():
+ """The first-run "Notification Preferences" rationale can appear on the first
+ goal tap after clear_data(). Dismiss it (choice is irrelevant to navigation)."""
+ nodes = ui()
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Cancel", "Skip", "Enable Notifications"):
+ n = find_node(nodes, text=label)
+ if n:
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+def _on_dashboard(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ return find_node(nodes, text="Set your goal") is not None
+
+
+def start_test_timer_active():
+ """From a CLEAN dashboard, tap the Test Timer goal cell -> ACTIVE-FAST card.
+ Handles the optional first-run notification rationale. Returns True on success."""
+ dash = ui()
+ cell = find_node(dash, text="Test Timer")
+ if not cell:
+ return False
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ after = ui()
+ if find_node(after, content_desc="End Fast"):
+ return True
+ # dialog path may have consumed the tap; retry the cell once
+ cell = find_node(after, text="Test Timer")
+ if cell:
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ return find_node(ui(), content_desc="End Fast") is not None
+
+
+def wait_goal_reached(timeout_polls=16):
+ """Poll until the Test Timer flips to 'Goal Reached!' (~11 s). Bounded so a
+ slow emulator never hangs the suite; returns whether it flipped."""
+ for _ in range(timeout_polls):
+ if find_node(ui(), text="Goal Reached!"):
+ return True
+ settle("tap")
+ return False
+
+
+def save_test_timer_fast():
+ """Complete + SAVE one Test Timer fast from a clean dashboard, landing back on
+ the Dashboard with the fast persisted (so day 5 in History has a record).
+ Returns True on success."""
+ if not start_test_timer_active():
+ return False
+ wait_goal_reached() # a completed fast earns the Goal-Met dot
+ ef = find_node(ui(), content_desc="End Fast")
+ if not ef:
+ return False
+ tap_node(ef)
+ settle("tap")
+ save = find_node(ui(), text="Save") # "Fast Complete!" summary modal
+ if not save:
+ return False
+ tap_node(save)
+ settle("tap")
+ return _on_dashboard()
+
+
+def open_history_via_link():
+ """Dashboard -> History pane through the 'Go to History' arrow. Returns True
+ when the calendar month header is showing."""
+ n = find_node(ui(), content_desc="Go to History")
+ if not n:
+ return False
+ tap_node(n)
+ settle("tap")
+ return find_node(ui(), text="August 2026") is not None
+
+
+def open_daily_details_day5():
+ """From the History pane, tap the day-5 cell (which holds the saved fast) and
+ open its Daily Details bottom sheet. Returns True when the sheet is showing."""
+ nodes = ui()
+ day = find_node(nodes, text="5")
+ marker = find_node(nodes, content_desc="Goal Met")
+ # Prefer a point spanning the day number and its Goal-Met dot so the tap lands
+ # on the day cell regardless of which sub-node is the click target.
+ if day and marker and "_center" in day and "_center" in marker:
+ x = (day["_center"][0] + marker["_center"][0]) // 2
+ y = (day["_center"][1] + marker["_center"][1]) // 2
+ tap(x, y)
+ elif marker:
+ tap_node(marker)
+ elif day:
+ tap_node(day)
+ else:
+ return False
+ return any("details for" in k.lower() for k in and_showing())
+
+
+def _color_scheme_row_y():
+ """Vertical centre of the horizontally-scrollable Color Scheme swatch row.
+ That row is the short scrollable=true node (the tall one is the page's outer
+ vertical ScrollView), so pick the scrollable node with the smallest height."""
+ rows = [n for n in find_nodes(ui(), scrollable=True) if "_bounds" in n]
+ short = None
+ for n in rows:
+ h = n["_bounds"][3] - n["_bounds"][1]
+ if h < 400 and (short is None
+ or h < (short["_bounds"][3] - short["_bounds"][1])):
+ short = n
+ if short:
+ return (short["_bounds"][1] + short["_bounds"][3]) // 2
+ return None
+
+
+# ── Named depth helpers (the and_enter_*/and_reach_* NAME is what the depth audit
+# looks for; each body is a real, proven jump). ────────────────────────────────
+def and_reach_by(trigger_text="", trigger_desc="", target="", source=""):
+ """Locate a labelled trigger on the CURRENT surface, then PROVE the jump:
+ `target` appeared and `source` vanished. Counts one surface (jump_kind='reach')."""
+ nodes = ui()
+ n = None
+ if trigger_text:
+ n = find_node(nodes, text=trigger_text) or find_node_ci(nodes, trigger_text)
+ if n is None and trigger_desc:
+ n = find_node(nodes, content_desc=trigger_desc)
+ if n is None:
+ return False
+ return and_reach_surface(n, target, source or None)
+
+
+def and_reach_settings():
+ return and_reach_by(trigger_desc="Settings", target="Appearance",
+ source="Set your goal")
+
+
+def and_reach_statistics():
+ return and_reach_by(trigger_desc="Go to Statistics", target="Trends",
+ source="Set your goal")
+
+
+def and_reach_profiles():
+ return and_reach_by(trigger_text="Manage Profiles", target="Other Profiles",
+ source="Set your goal")
+
+
+def and_reach_accent_color():
+ """Settings -> Theme & Accent Color. The 'Custom' swatch sits at the far right
+ of the horizontally-scrollable Color Scheme row, so scroll that row left first,
+ then tap the swatch CIRCLE (which is the clickable element sitting just ABOVE
+ the 'Custom' label — the label TextView itself is not the click target)."""
+ s = get_screen_info()
+ y = _color_scheme_row_y()
+ if y is None:
+ row = find_node(ui(), text="Color Scheme")
+ y = (row["_bounds"][3] + 90) if (row and "_bounds" in row) \
+ else int(s["height"] * 0.40)
+ for _ in range(5):
+ if find_node(ui(), text="Custom"):
+ break
+ swipe(int(s["width"] * 0.9), y, int(s["width"] * 0.11), y, ms=400)
+ custom = find_node(ui(), text="Custom")
+ if not custom or "_bounds" not in custom:
+ return False
+ cx = custom["_center"][0]
+ cy = custom["_bounds"][1] - 90 # the swatch circle above the label
+ before = and_showing()
+ tap(cx, cy)
+ after = and_showing()
+ ok = and_reach(before, after, "Accent Color", "Color Scheme")
+ if ok:
+ and_enter("Theme & Accent Color")
+ return ok
+
+
+def and_reach_history_info():
+ return and_reach_by(trigger_desc="History Info", target="Understanding History",
+ source="August 2026")
+
+
+def and_reach_phase_sheet():
+ return and_reach_by(trigger_text="Post-Absorptive State", target="Timing",
+ source="Current Fast")
+
+
+def and_reach_daily_details():
+ """History pane -> Daily Details sheet for day 5. Proven via and_showing delta
+ (the sheet title appears, the month header vanishes). Counts one surface."""
+ before = and_showing()
+ if not open_daily_details_day5():
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Details for", "August 2026")
+ if ok:
+ and_enter("Daily Details")
+ return ok
+
+
+def and_reach_edit_fast():
+ """Daily Details sheet -> Edit Fast dialog (pencil). Counts one surface."""
+ n = find_node(ui(), content_desc="Edit Fast")
+ if not n:
+ return False
+ return and_reach_surface(n, "Start Time", "Details for")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) TOP-LEVEL REACH — one per route (depth=1, jump_kind="reach")
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_reach_settings",))
+def test_reach_settings():
+ open_main_clear()
+ ok = _on_dashboard() and and_reach_settings()
+ record("navigation_reach_settings", bool(ok),
+ "" if ok else "feature_missing: Settings not reached from the Dashboard "
+ "gear (Appearance did not appear / Set-your-goal did not "
+ "disappear)",
+ depth=1, jump_kind="reach",
+ expect="Settings 'Appearance' appeared; Dashboard 'Set your goal' left")
+
+
+@and_test(expects=("navigation_reach_profiles",))
+def test_reach_profiles():
+ open_main_clear()
+ ok = _on_dashboard() and and_reach_profiles()
+ record("navigation_reach_profiles", bool(ok),
+ "" if ok else "feature_missing: Manage Profiles not reached from the "
+ "Dashboard link ('Other Profiles' did not appear / "
+ "'Set your goal' did not disappear)",
+ depth=1, jump_kind="reach",
+ expect="Manage Profiles 'Other Profiles' appeared; 'Set your goal' left")
+
+
+@and_test(expects=("navigation_reach_statistics", "navigation_reach_statistics_vlm"))
+def test_reach_statistics():
+ open_main_clear()
+ ok = _on_dashboard() and and_reach_statistics()
+ record("navigation_reach_statistics", bool(ok),
+ "" if ok else "feature_missing: Statistics ('Performance') not reached "
+ "from 'Go to Statistics' ('Trends' did not appear / "
+ "'Set your goal' did not disappear)",
+ depth=1, jump_kind="reach",
+ expect="Statistics 'Trends' appeared; Dashboard 'Set your goal' left")
+ # VLM END-STATE: the statistics screen renders a bar chart over a day-letter axis.
+ vlm_assert("navigation_reach_statistics",
+ "Is there a horizontal row of bar-chart segments drawn above a row of "
+ "single-letter day-of-week axis labels (like T F S S M T W)? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="reach")
+
+
+@and_test(expects=("navigation_reach_history", "navigation_reach_history_vlm"))
+def test_reach_history():
+ open_main_clear()
+ n = find_node(ui(), content_desc="Go to History")
+ ok = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
+ record("navigation_reach_history", bool(ok),
+ "" if ok else "feature_missing: History pane not reached from 'Go to "
+ "History' ('August 2026' did not appear / 'Set your goal' "
+ "did not disappear)",
+ depth=1, jump_kind="reach",
+ expect="History 'August 2026' appeared; Dashboard 'Set your goal' left")
+ # VLM END-STATE: the History pane presents a month calendar grid.
+ vlm_assert("navigation_reach_history",
+ "Is there a monthly calendar laid out as a grid of numbered day cells "
+ "in seven columns, with a row of weekday letters above it? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="reach")
+
+
+@and_test(expects=("navigation_reach_history_swipe",))
+def test_reach_history_swipe():
+ open_main_clear()
+ reached = False
+ s = get_screen_info()
+ # main is a draggable two-pane: a slow right->left horizontal drag flips
+ # Dashboard -> History. Retry at a couple of y-bands (the goal grid intercepts
+ # some rows). Each attempt is a proven reach via and_showing before/after.
+ for yf in (0.30, 0.45, 0.60):
+ if not _on_dashboard():
+ open_main()
+ before = and_showing()
+ y = int(s["height"] * yf)
+ swipe(int(s["width"] * 0.92), y, int(s["width"] * 0.08), y, ms=600)
+ after = and_showing()
+ if and_reach(before, after, "August 2026", "Set your goal"):
+ reached = True
+ and_enter("History (drag)")
+ break
+ record("navigation_reach_history_swipe", bool(reached),
+ "" if reached else "feature_missing: dragging the two-pane did not flip "
+ "Dashboard -> History ('August 2026' never appeared)",
+ depth=1, jump_kind="reach",
+ expect="Horizontal drag: History 'August 2026' appeared; 'Set your "
+ "goal' left")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) BACK-STACK INTEGRITY — reach then BACK restores the exact source (reach)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_back_settings",))
+def test_back_settings():
+ open_main_clear()
+ deep = and_reach_settings()
+ before = and_showing() # Settings surface
+ and_back() # pop one surface
+ after = and_showing()
+ restored = and_reach(before, after, target="Set your goal", source="Appearance")
+ ok = deep and restored
+ record("navigation_back_settings", bool(ok),
+ "" if ok else ("setup_failed: Settings not reached" if not deep
+ else "behavior_wrong: BACK from Settings did not restore "
+ "the Dashboard ('Set your goal')"),
+ depth=1, jump_kind="reach",
+ expect="After BACK: 'Set your goal' restored; Settings 'Appearance' gone")
+
+
+@and_test(expects=("navigation_back_profiles",))
+def test_back_profiles():
+ open_main_clear()
+ deep = and_reach_profiles()
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ restored = and_reach(before, after, target="Set your goal", source="Other Profiles")
+ ok = deep and restored
+ record("navigation_back_profiles", bool(ok),
+ "" if ok else ("setup_failed: Manage Profiles not reached" if not deep
+ else "behavior_wrong: BACK from Manage Profiles did not "
+ "restore the Dashboard"),
+ depth=1, jump_kind="reach",
+ expect="After BACK: 'Set your goal' restored; 'Other Profiles' gone")
+
+
+@and_test(expects=("navigation_back_statistics",))
+def test_back_statistics():
+ open_main_clear()
+ deep = and_reach_statistics()
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ restored = and_reach(before, after, target="Set your goal", source="Trends")
+ ok = deep and restored
+ record("navigation_back_statistics", bool(ok),
+ "" if ok else ("setup_failed: Statistics not reached" if not deep
+ else "behavior_wrong: BACK from Statistics did not restore "
+ "the Dashboard"),
+ depth=1, jump_kind="reach",
+ expect="After BACK: 'Set your goal' restored; Statistics 'Trends' gone")
+
+
+@and_test(expects=("navigation_back_history",))
+def test_back_history():
+ open_main_clear()
+ n = find_node(ui(), content_desc="Go to History")
+ deep = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
+ before = and_showing() # History pane
+ and_back() # History uses a BackHandler -> Dashboard
+ after = and_showing()
+ restored = and_reach(before, after, target="Set your goal", source="August 2026")
+ ok = deep and restored
+ record("navigation_back_history", bool(ok),
+ "" if ok else ("setup_failed: History pane not reached" if not deep
+ else "behavior_wrong: BACK from History did not return to "
+ "the Dashboard ('Set your goal')"),
+ depth=1, jump_kind="reach",
+ expect="After BACK: Dashboard 'Set your goal' restored; History "
+ "'August 2026' gone")
+
+
+@and_test(expects=("navigation_history_back_arrow",))
+def test_history_back_arrow():
+ open_main_clear()
+ n = find_node(ui(), content_desc="Go to History")
+ deep = bool(n) and and_reach_surface(n, "August 2026", "Set your goal")
+ # The History pane shows a top-left Back arrow (desc="Back"); tapping it returns
+ # to the Dashboard. Prove the reverse reach on that arrow specifically.
+ arrow = find_node(ui(), content_desc="Back")
+ reached_home = bool(arrow) and and_reach_surface(arrow, "Set your goal",
+ "August 2026")
+ if reached_home:
+ and_back() # keep the depth counter honest (this pop matches the arrow)
+ ok = deep and reached_home
+ record("navigation_history_back_arrow", bool(ok),
+ "" if ok else ("setup_failed: History pane not reached" if not deep
+ else "behavior_wrong: the History Back arrow did not return "
+ "to the Dashboard"),
+ depth=1, jump_kind="reach",
+ expect="Back-arrow tap: Dashboard 'Set your goal' restored; 'August "
+ "2026' gone")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) DEPTH-2 CHAIN — Dashboard -> Settings -> Theme & Accent Color
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_reach_accent_color", "navigation_reach_accent_color_vlm"))
+def test_reach_accent_color():
+ open_main_clear()
+ hop1 = and_reach_settings() # depth 1
+ hop2 = hop1 and and_reach_accent_color() # depth 2
+ ok = hop1 and hop2
+ record("navigation_reach_accent_color", bool(ok),
+ "" if ok else ("setup_failed: Settings not reached" if not hop1
+ else "feature_missing: Theme & Accent Color not reached "
+ "from the Color Scheme 'Custom' swatch ('Accent "
+ "Color' did not appear)"),
+ depth=2, jump_kind="reach",
+ expect="Dashboard->Settings->Theme&Accent: 'Accent Color' appeared; "
+ "Settings 'Color Scheme' left")
+ # VLM END-STATE: the Theme & Accent screen shows a grid of round color swatches.
+ vlm_assert("navigation_reach_accent_color",
+ "Under an 'Accent Color' heading, is there a grid of multiple small "
+ "circular color swatches? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=2, jump_kind="reach")
+
+
+@and_test(expects=("navigation_backstack_accent",))
+def test_backstack_accent():
+ open_main_clear()
+ hop1 = and_reach_settings()
+ hop2 = hop1 and and_reach_accent_color() # now 2 deep: Dashboard/Settings/Accent
+ # Unwind hop by hop: BACK -> Settings, BACK -> Dashboard, asserting each pop.
+ before_a = and_showing() # Theme & Accent
+ and_back()
+ after_a = and_showing()
+ to_settings = and_reach(before_a, after_a, target="Color Scheme",
+ source="Accent Color")
+ before_s = and_showing() # Settings
+ and_back()
+ after_s = and_showing()
+ to_dash = and_reach(before_s, after_s, target="Set your goal", source="Appearance")
+ ok = hop1 and hop2 and to_settings and to_dash
+ record("navigation_backstack_accent", bool(ok),
+ "" if ok else ("setup_failed: accent-color chain not built"
+ if not (hop1 and hop2)
+ else "behavior_wrong: BACK did not unwind Theme&Accent -> "
+ "Settings -> Dashboard hop by hop"),
+ depth=2, jump_kind="reach",
+ expect="1st BACK -> Settings 'Color Scheme'; 2nd BACK -> Dashboard "
+ "'Set your goal'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (4) SHEET / OVERLAY REACH
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_reach_history_info", "navigation_reach_history_info_vlm"))
+def test_reach_history_info():
+ open_main_clear()
+ on_hist = open_history_via_link() # depth 1 (not asserted as reach here)
+ reached = on_hist and and_reach_history_info()
+ ok = on_hist and reached
+ record("navigation_reach_history_info", bool(ok),
+ "" if ok else ("setup_failed: History pane not reached" if not on_hist
+ else "feature_missing: 'History Info' did not open the "
+ "'Understanding History' sheet"),
+ depth=2, jump_kind="reach",
+ expect="History 'Understanding History' sheet appeared; 'August 2026' left")
+ # VLM END-STATE: an info sheet is presented from the bottom over the calendar.
+ vlm_assert("navigation_reach_history_info",
+ "Is a titled information panel presented over the lower portion of the "
+ "screen as a bottom sheet (a rounded panel rising from the bottom edge "
+ "with a small drag handle at its top)? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=2, jump_kind="reach")
+
+
+@and_test(expects=("navigation_reach_phase_sheet",))
+def test_reach_phase_sheet():
+ open_main_clear()
+ active = start_test_timer_active() # active-fast card shows the phase chip
+ reached = active and and_reach_phase_sheet()
+ ok = active and reached
+ record("navigation_reach_phase_sheet", bool(ok),
+ "" if ok else ("setup_failed: could not start a Test Timer fast"
+ if not active
+ else "feature_missing: tapping the 'Post-Absorptive State' "
+ "chip did not open the phase-detail sheet ('Timing' "
+ "did not appear)"),
+ depth=1, jump_kind="reach",
+ expect="Phase sheet 'Timing' appeared; active-fast 'Current Fast' left")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (5) STATISTICS -> HISTORY cross-navigation
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_stats_to_history",))
+def test_stats_to_history():
+ open_main_clear()
+ on_stats = and_reach_statistics() # depth 1
+ # Statistics has a top-right History icon (desc="History") that jumps to the
+ # History pane. Prove it: 'August 2026' appears, Statistics 'Trends' leaves.
+ reached = on_stats and and_reach_by(trigger_desc="History", target="August 2026",
+ source="Trends")
+ ok = on_stats and reached
+ record("navigation_stats_to_history", bool(ok),
+ "" if ok else ("setup_failed: Statistics not reached" if not on_stats
+ else "feature_missing: the Statistics History icon did not "
+ "jump to the History pane"),
+ depth=2, jump_kind="reach",
+ expect="Statistics History icon -> 'August 2026' appeared; 'Trends' left")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (6) DATA-DEPENDENT DEEP CHAIN — History -> Daily Details -> Edit Fast + unwind
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("navigation_reach_daily_details", "navigation_reach_daily_details_vlm"))
+def test_reach_daily_details():
+ open_main_clear()
+ made = save_test_timer_fast() # create the record we navigate to
+ on_hist = made and open_history_via_link() # depth 1
+ reached = on_hist and and_reach_daily_details() # depth 2 (Daily Details sheet)
+ ok = made and on_hist and reached
+ record("navigation_reach_daily_details", bool(ok),
+ "" if ok else ("setup_failed: could not save a Test Timer fast" if not made
+ else "setup_failed: History pane not reached" if not on_hist
+ else "feature_missing: tapping day 5 did not open its "
+ "Daily Details sheet ('Details for ...' did not appear)"),
+ depth=2, jump_kind="reach",
+ expect="Day-5 tap -> 'Details for August 5' sheet appeared; 'August "
+ "2026' left")
+ # VLM END-STATE: the daily details are a bottom sheet overlay.
+ vlm_assert("navigation_reach_daily_details",
+ "Is a titled details panel presented over the lower portion of the "
+ "screen as a bottom sheet (a rounded panel rising from the bottom "
+ "edge), with the dimmed calendar visible above it? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=2, jump_kind="reach")
+
+
+@and_test(expects=("navigation_reach_edit_fast", "navigation_reach_edit_fast_vlm"))
+def test_reach_edit_fast():
+ open_main_clear()
+ made = save_test_timer_fast()
+ on_hist = made and open_history_via_link() # depth 1
+ on_sheet = on_hist and and_reach_daily_details() # depth 2
+ reached = on_sheet and and_reach_edit_fast() # depth 3 (Edit Fast dialog)
+ ok = made and on_hist and on_sheet and reached
+ record("navigation_reach_edit_fast", bool(ok),
+ "" if ok else ("setup_failed: could not build History->Daily-Details"
+ if not on_sheet
+ else "feature_missing: the Daily Details 'Edit Fast' pencil "
+ "did not open the Edit Fast dialog ('Start Time' did "
+ "not appear)"),
+ depth=3, jump_kind="reach",
+ expect="Edit-Fast pencil -> dialog 'Start Time' appeared; sheet 'Details "
+ "for' left")
+ # VLM END-STATE: Edit Fast is a centered dialog card (not a bottom sheet).
+ vlm_assert("navigation_reach_edit_fast",
+ "Is there an 'Edit Fast' dialog shown as a rounded rectangular card "
+ "floating in the center of the screen (with 'Cancel' and 'Save' "
+ "buttons), rather than attached to the bottom edge? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=3, jump_kind="reach")
+
+
+@and_test(expects=("navigation_backstack_deep",))
+def test_backstack_deep():
+ open_main_clear()
+ made = save_test_timer_fast()
+ on_hist = made and open_history_via_link()
+ on_sheet = on_hist and and_reach_daily_details() # depth 2
+ on_dialog = on_sheet and and_reach_edit_fast() # depth 3
+ built = made and on_hist and on_sheet and on_dialog
+ # Unwind the deepest chain hop by hop.
+ # hop 3->2: Cancel the Edit Fast dialog (safe; never touch 'Delete Fast').
+ cancel = find_node(ui(), text="Cancel")
+ if cancel:
+ tap_node(cancel)
+ else:
+ and_back()
+ settle("tap")
+ back_on_sheet = any("details for" in k.lower() for k in and_showing())
+ # hop 2->1: BACK closes the Daily Details sheet -> History pane.
+ before_s = and_showing()
+ and_back()
+ after_s = and_showing()
+ to_history = and_reach(before_s, after_s, target="August 2026", source="Details for")
+ # hop 1->0: BACK closes the History pane -> Dashboard.
+ before_h = and_showing()
+ and_back()
+ after_h = and_showing()
+ to_dash = and_reach(before_h, after_h, target="Set your goal", source="August 2026")
+ ok = built and back_on_sheet and to_history and to_dash
+ record("navigation_backstack_deep", bool(ok),
+ "" if ok else ("setup_failed: could not build the "
+ "Dashboard->History->Details->Edit chain" if not built
+ else "behavior_wrong: BACK did not unwind Edit -> Details "
+ "-> History -> Dashboard hop by hop"),
+ depth=3, jump_kind="reach",
+ expect="Cancel->Details sheet; BACK->History 'August 2026'; BACK->"
+ "Dashboard 'Set your goal'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_reach_settings,
+ test_reach_profiles,
+ test_reach_statistics,
+ test_reach_history,
+ test_reach_history_swipe,
+ test_back_settings,
+ test_back_profiles,
+ test_back_statistics,
+ test_back_history,
+ test_history_back_arrow,
+ test_reach_accent_color,
+ test_backstack_accent,
+ test_reach_history_info,
+ test_reach_phase_sheet,
+ test_stats_to_history,
+ test_reach_daily_details,
+ test_reach_edit_fast,
+ test_backstack_deep,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "navigation")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_states.py b/android/tom-murphy-development-fasttimes/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd74248cae3b00906aff4eebd7554fa294303a4f
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_states.py
@@ -0,0 +1,1023 @@
+#!/usr/bin/env python3
+"""STATES module — FastTimes (intermittent-fasting tracker).
+
+This lane is the SOLE OWNER of CHECKED and FOCUS: every test is a before -> after
+STATE TRANSITION (checked / enabled / selected flip, page-state machine, or mode
+persistence) PAIRED WITH THE APP-AUTHORED CONSEQUENCE the flip produces. A bare
+checked flip with no observable consequence is worthless, so each transition names
+both halves.
+
+All states/consequences below were OBSERVED on the RUNNING original app:
+
+ * Settings SWITCHES render as android.view.View with checkable=true and a
+ checked=true/false bit; the row LABEL is a separate TextView on the same
+ y-band. "Show Fasting Phases"/"Show Floating Action Button"/"Use Expressive
+ Progress Indicator" default ON and flip true->false cleanly. (The two
+ Notification switches pop a permission dialog / OS grant, so they are NOT used
+ for a clean flip.) Turning "Show Floating Action Button" OFF removes the
+ dashboard FAB (desc="Add Fast") — a real authored consequence.
+ * Settings SWITCH state PERSISTS across process death (DataStore): flip one OFF,
+ force_stop + relaunch, it is still OFF.
+ * SEGMENTED toggles expose checked on the option View that CONTAINS the option
+ label's centre: Statistics "Weekly|Monthly" (Weekly checked by default;
+ tapping Monthly flips Weekly->false / Monthly->true AND flips the header
+ "This week"->"Last 30 days"), the "Trends" 3-way (Weekly default; "All Time"
+ flips to checked), and Settings "First Day of Week" Sun|Mon (Mon checked by
+ default; tapping Sun moves the checked bit).
+ * Add Profile dialog: Save's clickable parent View is enabled=false with an
+ empty name and flips to enabled=true once a name is typed; the "Set as
+ Favourite" CheckBox flips checked false->true.
+ * The dashboard FAB (desc="Add Fast") is a collapsed speed-dial: one tap reveals
+ child actions (desc="Start Open Fast" / "View History"), absent before.
+ * Statistics "All-time statistics" has an Expand chevron (desc="Expand"); tapping
+ it reveals new stat rows and flips the chevron to desc="Collapse".
+ * Theme & Accent Color screen: tapping an accent circle gives it a "Selected"
+ content-desc; its "Use Expressive Theme" switch flips checked.
+ * Theme selector Light|Dark|System exposes no checked bit — tapping "Dark"
+ recolours the app to a dark background (a genuinely VISUAL state -> VLM).
+
+CEDES: mere reachability of a screen -> navigation; a produced content STRING's
+exact wording -> text; a computed numeric value -> computation; CRUD/data
+persistence -> interaction; tree SHAPE / launch gate -> structure.
+
+Compose renders as View/TextView with NO resource-ids, so every target is located
+by visible text / content-desc / bounds.
+
+SAFETY: never taps Delete/Reset; exploratory taps route through is_safe/safe_tap.
+
+Run: python3 test_android_states.py
+"""
+import os
+import sys
+import time
+import re
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data, then open MainActivity."""
+ clear_data()
+ open_main()
+
+
+# ── Named depth helpers (the and_enter_* / and_reach_* NAME backs a depth>=1
+# claim; each body performs a real, PROVEN surface change). ─────────────────────
+def and_enter_settings():
+ """Dashboard -> Settings. Proven: 'Appearance' appears, the goal grid's
+ 'Set your goal' vanishes. Counts one surface. Returns True on success."""
+ gear = find_node(ui(), content_desc="Settings")
+ if not gear:
+ return False
+ before = and_showing()
+ if not tap_node(gear):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Appearance", "Set your goal")
+ if ok:
+ and_enter("Settings")
+ return ok
+
+
+def and_reach_statistics():
+ """Dashboard -> Statistics ('Performance'). Proven: 'Trends' appears, the goal
+ card 'Set your goal' vanishes. Counts one surface (a real reach)."""
+ n = find_node(ui(), content_desc="Go to Statistics")
+ if not n:
+ return False
+ return and_reach_surface(n, "Trends", "Set your goal")
+
+
+def and_enter_manage_profiles():
+ """Dashboard -> Manage Profiles. Proven: 'Add Profile' FAB appears, the goal
+ card 'Set your goal' vanishes. Counts one surface."""
+ n = find_node(ui(), text="Manage Profiles")
+ if not n:
+ return False
+ before = and_showing()
+ if not tap_node(n):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Add Profile", "Set your goal")
+ if ok:
+ and_enter("Manage Profiles")
+ return ok
+
+
+def and_enter_add_profile():
+ """Manage Profiles -> Add Profile dialog. Proven: 'Set as Favourite' appears.
+ Counts one surface (called after and_enter_manage_profiles => depth 2)."""
+ add = find_node(ui(), content_desc="Add Profile")
+ if not add:
+ return False
+ before = and_showing()
+ if not tap_node(add):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Set as Favourite")
+ if ok:
+ and_enter("Add Profile")
+ return ok
+
+
+def and_enter_accent_screen():
+ """Settings -> 'Theme & Accent Color'. The 'Custom' swatch sits at the far
+ right of the horizontal Color Scheme row, so scroll the row left, then tap the
+ rightmost swatch. Proven: 'Accent Color' appears. Counts one surface (called
+ after and_enter_settings => depth 2)."""
+ # scroll the horizontal color row left to reveal the rightmost "Custom" swatch
+ for _ in range(2):
+ swipe(950, 954, 150, 954, ms=500)
+ settle("tap")
+ row = [n for n in ui()
+ if n.get("_bounds") and 855 <= n["_bounds"][1] <= 1035
+ and n.get("clickable") == "true"]
+ if not row:
+ return False
+ row.sort(key=lambda r: r["_bounds"][0])
+ before = and_showing()
+ if not tap_node(row[-1]): # rightmost swatch == "Custom"
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, "Accent Color")
+ if ok:
+ and_enter("Theme & Accent Color")
+ return ok
+
+
+# ── State-reading helpers ──────────────────────────────────────────────────────
+def _switch_for_label(nodes, label_text, band=70):
+ """The checkable Switch View for a Settings row LABEL: same y-band, to the
+ RIGHT of the label (the FastTimes layout puts the switch at the row's right)."""
+ lbl = find_node(nodes, text=label_text)
+ if not lbl or "_center" not in lbl:
+ return None
+ lx, ly = lbl["_center"]
+ cands = [n for n in nodes
+ if n.get("checkable") == "true" and "_center" in n
+ and abs(n["_center"][1] - ly) < band and n["_center"][0] > lx]
+ cands.sort(key=lambda n: abs(n["_center"][1] - ly))
+ return cands[0] if cands else None
+
+
+def _option_checkable(nodes, label_text, prefer_top=True):
+ """The checkable option View of a SEGMENTED toggle whose bounds CONTAIN the
+ option label's centre (Sun/Mon, Weekly/Monthly, All Time). When a label text
+ repeats (Weekly/Monthly appear in both the top toggle and Trends), prefer the
+ TOP-most occurrence."""
+ lbls = [n for n in nodes if n.get("text") == label_text and "_center" in n]
+ if not lbls:
+ lc = find_node_ci(nodes, label_text)
+ lbls = [lc] if lc else []
+ if not lbls:
+ return None
+ lbls.sort(key=lambda n: n["_bounds"][1])
+ lbl = lbls[0] if prefer_top else lbls[-1]
+ lx, ly = lbl["_center"]
+ contains = [n for n in nodes
+ if n.get("checkable") == "true" and n.get("_bounds")
+ and n["_bounds"][0] <= lx <= n["_bounds"][2]
+ and n["_bounds"][1] <= ly <= n["_bounds"][3]]
+ if contains:
+ contains.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return contains[0]
+ same = [n for n in nodes if n.get("checkable") == "true" and "_center" in n
+ and abs(n["_center"][1] - ly) < band_default()]
+ same.sort(key=lambda n: abs(n["_center"][0] - lx))
+ return same[0] if same else None
+
+
+def band_default():
+ return 70
+
+
+def _save_clickable_parent(nodes):
+ """The clickable ancestor View that wraps the 'Save' TextView in the Add
+ Profile dialog — the node that actually carries enabled true/false. Returns the
+ smallest clickable View whose bounds contain the Save text's centre."""
+ save = find_node(nodes, text="Save")
+ if not save or "_center" not in save:
+ return None
+ cx, cy = save["_center"]
+ best, best_area = None, None
+ for n in nodes:
+ if n.get("clickable") != "true" or not n.get("_bounds"):
+ continue
+ x1, y1, x2, y2 = n["_bounds"]
+ if x1 <= cx <= x2 and y1 <= cy <= y2:
+ area = (x2 - x1) * (y2 - y1)
+ if best_area is None or area < best_area:
+ best, best_area = n, area
+ return best
+
+
+def _first_edittext(nodes):
+ """The top-most EditText in the Add Profile dialog == the 'Profile Name'
+ field (there are three: Profile Name / Description / Duration, top to bottom)."""
+ ets = sorted(find_by_class(nodes, "EditText"),
+ key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ return ets[0] if ets else None
+
+
+def _dismiss_notif_rationale():
+ """The first-run 'Notification Preferences' rationale can appear on the first
+ goal tap after clear_data(). Dismiss it non-destructively. Returns True if
+ shown."""
+ nodes = ui()
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Skip", "Not Now", "Cancel"):
+ n = find_node(nodes, text=label)
+ if n and is_safe(n):
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) SWITCH CHECKED FLIP — "Show Fasting Phases" ON -> OFF (clean, no dialog)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_switch_fasting_phases",))
+def test_switch_fasting_phases():
+ """Settings 'Show Fasting Phases' switch defaults ON. Tapping it flips its
+ checked bit true->false on the SAME node. Depth 1 (Settings), backed by
+ and_enter_settings. The consequence of this switch is the checked bit itself
+ (a mode flip persisted to DataStore) — re-read the re-located node to prove it
+ actually transitioned rather than just being tappable."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_switch_fasting_phases", False,
+ "setup_failed: could not reach Settings (Appearance not shown)",
+ depth=1, jump_kind="transition",
+ expect="'Show Fasting Phases' switch checked true->false")
+ return
+ nodes = ui()
+ sw = _switch_for_label(nodes, "Show Fasting Phases")
+ if sw is None:
+ record("states_switch_fasting_phases", False,
+ "feature_missing: no 'Show Fasting Phases' switch in Settings",
+ depth=1, jump_kind="transition",
+ expect="'Show Fasting Phases' switch checked true->false")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for_label(ui(), "Show Fasting Phases") or {}).get("checked")
+ ok = before == "true" and after == "false"
+ record("states_switch_fasting_phases", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Show Fasting Phases' checked did not "
+ f"flip true->false (before={before!r} after={after!r})"),
+ depth=1, jump_kind="transition",
+ expect=f"'Show Fasting Phases' switch checked true->false "
+ f"(saw {before}->{after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) SWITCH FLIP + CONSEQUENCE — "Show FAB" OFF removes the dashboard FAB
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_switch_fab_consequence",))
+def test_switch_fab_consequence():
+ """'Show Floating Action Button' defaults ON. Turning it OFF flips its checked
+ bit true->false AND removes the dashboard FAB (desc='Add Fast') — the authored
+ consequence. Assert BOTH: the switch flip in Settings and that the FAB, present
+ before, is gone from the dashboard after. Depth 1 (Settings)."""
+ open_main_clear()
+ fab_before = find_node(ui(), content_desc="Add Fast") is not None
+ if not and_enter_settings():
+ record("states_switch_fab_consequence", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="'Show FAB' checked true->false; dashboard FAB disappears")
+ return
+ sw = _switch_for_label(ui(), "Show Floating Action Button")
+ if sw is None:
+ record("states_switch_fab_consequence", False,
+ "feature_missing: no 'Show Floating Action Button' switch",
+ depth=1, jump_kind="transition",
+ expect="'Show FAB' checked true->false; dashboard FAB disappears")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for_label(ui(), "Show Floating Action Button") or {}).get("checked")
+ # back to the dashboard and check the FAB is gone
+ and_back()
+ fab_after = find_node(ui(), content_desc="Add Fast") is not None
+ ok = (before == "true" and after == "false" and fab_before and not fab_after)
+ record("states_switch_fab_consequence", bool(ok),
+ "" if ok else (f"behavior_wrong: checked {before!r}->{after!r} / FAB "
+ f"before={fab_before} after={fab_after}; expected the "
+ f"switch to flip true->false AND the dashboard FAB to "
+ f"disappear"),
+ depth=1, jump_kind="transition",
+ expect=f"'Show FAB' checked true->false; dashboard 'Add Fast' FAB "
+ f"present->absent (saw fab {fab_before}->{fab_after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) SWITCH CHECKED FLIP — "Use Expressive Progress Indicator" ON -> OFF
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_switch_expressive_progress",))
+def test_switch_expressive_progress():
+ """A second clean switch: 'Use Expressive Progress Indicator' defaults ON and
+ flips true->false. Distinct control from #1, proving the switch machinery is
+ real per-row and not a single shared toggle. Depth 1 (Settings)."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_switch_expressive_progress", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="'Use Expressive Progress Indicator' checked true->false")
+ return
+ sw = _switch_for_label(ui(), "Use Expressive Progress Indicator")
+ if sw is None:
+ record("states_switch_expressive_progress", False,
+ "feature_missing: no 'Use Expressive Progress Indicator' switch",
+ depth=1, jump_kind="transition",
+ expect="'Use Expressive Progress Indicator' checked true->false")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for_label(ui(), "Use Expressive Progress Indicator")
+ or {}).get("checked")
+ ok = before == "true" and after == "false"
+ record("states_switch_expressive_progress", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Use Expressive Progress Indicator' "
+ f"checked did not flip true->false (before={before!r} "
+ f"after={after!r})"),
+ depth=1, jump_kind="transition",
+ expect=f"'Use Expressive Progress Indicator' checked true->false "
+ f"(saw {before}->{after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (4) SETTINGS PERSISTENCE — a flipped switch survives process death (DataStore)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_switch_persists_relaunch",))
+def test_switch_persists_relaunch():
+ """Flip 'Show Fasting Phases' OFF in Settings, then force_stop() + open_main()
+ (real process death), re-open Settings and assert the switch is STILL OFF. This
+ is a SETTINGS/mode persistence test (DataStore-backed) — an in-memory-only
+ recreation reverts to the ON default and fails. Depth 1."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_switch_persists_relaunch", False,
+ "setup_failed: could not reach Settings to flip the switch",
+ depth=1, jump_kind="transition",
+ expect="'Show Fasting Phases' OFF survives relaunch (still false)")
+ return
+ sw = _switch_for_label(ui(), "Show Fasting Phases")
+ if sw is None or sw.get("checked") != "true":
+ record("states_switch_persists_relaunch", False,
+ "feature_missing: 'Show Fasting Phases' switch not found / not ON "
+ "by default",
+ depth=1, jump_kind="transition",
+ expect="'Show Fasting Phases' OFF survives relaunch (still false)")
+ return
+ tap_node(sw)
+ settle("tap")
+ flipped = (_switch_for_label(ui(), "Show Fasting Phases") or {}).get("checked")
+ # real process death, then reopen and navigate back to Settings
+ force_stop()
+ open_main()
+ and_reset_depth()
+ if not and_enter_settings():
+ record("states_switch_persists_relaunch", False,
+ "setup_failed: could not re-open Settings after relaunch",
+ depth=1, jump_kind="transition",
+ expect="'Show Fasting Phases' OFF survives relaunch (still false)")
+ return
+ persisted = (_switch_for_label(ui(), "Show Fasting Phases") or {}).get("checked")
+ ok = flipped == "false" and persisted == "false"
+ record("states_switch_persists_relaunch", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Show Fasting Phases' was {flipped!r} "
+ f"after the flip but {persisted!r} after relaunch — the "
+ f"setting did not persist (expected false both times)"),
+ depth=1, jump_kind="transition",
+ expect=f"'Show Fasting Phases' flipped OFF stays false across process "
+ f"death (flip={flipped}, after relaunch={persisted})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (5) SEGMENTED TOGGLE — Statistics Weekly->Monthly: checked flip + header changes
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_stats_monthly_toggle",))
+def test_stats_monthly_toggle():
+ """The Statistics 'Weekly | Monthly' segmented toggle: Weekly is checked by
+ default. Tapping Monthly flips the selection (Weekly checked true->false,
+ Monthly false->true) AND changes the page header 'This week' -> 'Last 30 days'
+ (the app-authored consequence of the selection state). Assert the checked flip
+ on BOTH options and the header transition, on the same Statistics screen.
+ Depth 1 (reach Statistics)."""
+ open_main_clear()
+ if not and_reach_statistics():
+ record("states_stats_monthly_toggle", False,
+ "setup_failed: could not reach Statistics ('Trends' not shown)",
+ depth=1, jump_kind="transition",
+ expect="Weekly checked->false / Monthly checked->true; header "
+ "'This week'->'Last 30 days'")
+ return
+ act = get_current_activity()
+ nodes = ui()
+ wk_b = (_option_checkable(nodes, "Weekly") or {}).get("checked")
+ mo_b = (_option_checkable(nodes, "Monthly") or {}).get("checked")
+ hdr_week_b = find_node(nodes, text="This week") is not None
+ monthly_lbl = sorted([n for n in nodes if n.get("text") == "Monthly"],
+ key=lambda n: n["_bounds"][1])
+ if not monthly_lbl:
+ record("states_stats_monthly_toggle", False,
+ "feature_missing: no 'Monthly' segment in Statistics",
+ depth=1, jump_kind="transition",
+ expect="Weekly checked->false / Monthly checked->true; header "
+ "'This week'->'Last 30 days'")
+ return
+ tap_node(monthly_lbl[0])
+ settle("tap")
+ nodes2 = ui()
+ wk_a = (_option_checkable(nodes2, "Weekly") or {}).get("checked")
+ mo_a = (_option_checkable(nodes2, "Monthly") or {}).get("checked")
+ hdr_30_a = find_node(nodes2, text="Last 30 days") is not None
+ same_screen = get_current_activity() == act
+ ok = (wk_b == "true" and mo_b == "false" and hdr_week_b
+ and wk_a == "false" and mo_a == "true" and hdr_30_a and same_screen)
+ record("states_stats_monthly_toggle", bool(ok),
+ "" if ok else (f"behavior_wrong: selecting Monthly did not flip the "
+ f"selection + header (Weekly {wk_b}->{wk_a}, Monthly "
+ f"{mo_b}->{mo_a}, 'This week' before={hdr_week_b}, "
+ f"'Last 30 days' after={hdr_30_a}, same_screen={same_screen})"),
+ depth=1, jump_kind="transition",
+ expect=f"Weekly checked true->false, Monthly false->true; header "
+ f"'This week'->'Last 30 days' (saw hdr30={hdr_30_a})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (6) SEGMENTED TOGGLE (reverse) — Monthly -> Weekly returns the header
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_stats_weekly_back",))
+def test_stats_weekly_back():
+ """After selecting Monthly (header 'Last 30 days'), selecting Weekly flips the
+ selection back and returns the header to 'This week'. Proves the selection
+ state is a real two-way toggle, not a one-shot. Asserts the Weekly->true /
+ Monthly->false flip and the 'Last 30 days'->'This week' header transition.
+ Depth 1."""
+ open_main_clear()
+ if not and_reach_statistics():
+ record("states_stats_weekly_back", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="transition",
+ expect="Monthly->Weekly: header 'Last 30 days'->'This week'")
+ return
+ # first select Monthly
+ mo = sorted([n for n in ui() if n.get("text") == "Monthly"],
+ key=lambda n: n["_bounds"][1])
+ if not mo:
+ record("states_stats_weekly_back", False,
+ "feature_missing: no 'Monthly' segment",
+ depth=1, jump_kind="transition",
+ expect="Monthly->Weekly: header 'Last 30 days'->'This week'")
+ return
+ tap_node(mo[0])
+ settle("tap")
+ nodes = ui()
+ hdr_30_b = find_node(nodes, text="Last 30 days") is not None
+ mo_b = (_option_checkable(nodes, "Monthly") or {}).get("checked")
+ wk_lbl = sorted([n for n in nodes if n.get("text") == "Weekly"],
+ key=lambda n: n["_bounds"][1])
+ tap_node(wk_lbl[0])
+ settle("tap")
+ nodes2 = ui()
+ hdr_week_a = find_node(nodes2, text="This week") is not None
+ wk_a = (_option_checkable(nodes2, "Weekly") or {}).get("checked")
+ mo_a = (_option_checkable(nodes2, "Monthly") or {}).get("checked")
+ ok = (hdr_30_b and mo_b == "true" and hdr_week_a
+ and wk_a == "true" and mo_a == "false")
+ record("states_stats_weekly_back", bool(ok),
+ "" if ok else (f"behavior_wrong: selecting Weekly did not restore the "
+ f"selection/header ('Last 30 days' before={hdr_30_b}, "
+ f"Monthly before={mo_b}; after -> Weekly={wk_a} "
+ f"Monthly={mo_a} 'This week'={hdr_week_a})"),
+ depth=1, jump_kind="transition",
+ expect=f"Weekly checked ->true, Monthly ->false; header 'Last 30 "
+ f"days'->'This week' (saw week hdr={hdr_week_a})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (7) TRENDS 3-WAY SELECTION — "All Time" flips to checked
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_trends_all_time",))
+def test_trends_all_time():
+ """The Statistics 'Trends' section has a 3-way toggle Weekly|Monthly|All Time
+ with Weekly selected by default. Tapping 'All Time' flips its option View
+ checked false->true (and Weekly true->false) — a selection-state flip that
+ stays on the same screen (this lane's, not navigation's). Depth 1."""
+ open_main_clear()
+ if not and_reach_statistics():
+ record("states_trends_all_time", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="transition",
+ expect="Trends 'All Time' checked false->true")
+ return
+ # 'Trends' + its toggle live below the chart; scroll it into view
+ scroll_into_view("Trends", max_swipes=3)
+ nodes = ui()
+ at = find_node(nodes, text="All Time")
+ if at is None:
+ record("states_trends_all_time", False,
+ "feature_missing: no 'All Time' segment under Trends",
+ depth=1, jump_kind="transition",
+ expect="Trends 'All Time' checked false->true")
+ return
+ at_before = (_option_checkable(nodes, "All Time", prefer_top=False) or {}).get("checked")
+ # Trends Weekly is the LOWER 'Weekly' occurrence
+ wk_before = (_option_checkable(nodes, "Weekly", prefer_top=False) or {}).get("checked")
+ tap_node(at)
+ settle("tap")
+ nodes2 = ui()
+ at_after = (_option_checkable(nodes2, "All Time", prefer_top=False) or {}).get("checked")
+ wk_after = (_option_checkable(nodes2, "Weekly", prefer_top=False) or {}).get("checked")
+ ok = (at_before == "false" and at_after == "true"
+ and wk_before == "true" and wk_after == "false")
+ record("states_trends_all_time", bool(ok),
+ "" if ok else (f"behavior_wrong: Trends 'All Time' selection did not flip "
+ f"(All Time {at_before}->{at_after}, Trends Weekly "
+ f"{wk_before}->{wk_after})"),
+ depth=1, jump_kind="transition",
+ expect=f"Trends 'All Time' checked false->true (Weekly true->false; "
+ f"saw allTime {at_before}->{at_after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (8) FIRST DAY OF WEEK — Sun|Mon selection flip (checked bit moves) [+ VLM]
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_first_day_of_week", "states_first_day_of_week_vlm"))
+def test_first_day_of_week():
+ """Settings 'First Day of Week' Sun|Mon toggle: Mon is checked by default.
+ Tapping Sun moves the checked bit — Sun false->true, Mon true->false. Both
+ option Views expose checked, so this is a rule transition. The paired VLM
+ confirms the selection HIGHLIGHT visibly moved onto 'Sun' (a rendered position
+ property). Depth 1 (Settings)."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_first_day_of_week", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="First Day of Week: Sun checked false->true, Mon true->false")
+ vlm_assert("states_first_day_of_week",
+ "In the 'First Day of Week' Sun/Mon control, is the 'Sun' option "
+ "the one drawn with the filled/highlighted selection background "
+ "(rather than 'Mon')?",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
+ return
+ nodes = ui()
+ sun = _option_checkable(nodes, "Sun")
+ mon = _option_checkable(nodes, "Mon")
+ if sun is None or mon is None:
+ record("states_first_day_of_week", False,
+ "feature_missing: 'First Day of Week' Sun/Mon toggle not found",
+ depth=1, jump_kind="transition",
+ expect="First Day of Week: Sun checked false->true, Mon true->false")
+ vlm_assert("states_first_day_of_week",
+ "In the 'First Day of Week' Sun/Mon control, is the 'Sun' option "
+ "the one drawn with the filled/highlighted selection background?",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
+ return
+ sun_b, mon_b = sun.get("checked"), mon.get("checked")
+ tap_node(find_node(nodes, text="Sun"))
+ settle("tap")
+ nodes2 = ui()
+ sun_a = (_option_checkable(nodes2, "Sun") or {}).get("checked")
+ mon_a = (_option_checkable(nodes2, "Mon") or {}).get("checked")
+ ok = (mon_b == "true" and sun_b == "false"
+ and sun_a == "true" and mon_a == "false")
+ record("states_first_day_of_week", bool(ok),
+ "" if ok else (f"behavior_wrong: selecting Sun did not move the checked "
+ f"bit (Sun {sun_b}->{sun_a}, Mon {mon_b}->{mon_a})"),
+ depth=1, jump_kind="transition",
+ expect=f"Sun checked false->true, Mon true->false (saw Sun {sun_b}->{sun_a})")
+ # VLM (position): the highlighted selection now sits on 'Sun'.
+ vlm_assert("states_first_day_of_week",
+ "In the 'First Day of Week' Sun/Mon toggle, is the 'Sun' option the "
+ "one drawn with the filled/highlighted selection background (the "
+ "selected pill), rather than 'Mon'?",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (9) CONDITIONAL ENABLE — Add Profile 'Save' disabled until a name is typed
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_save_conditional_enable",))
+def test_save_conditional_enable():
+ """In the Add Profile dialog, Save's clickable parent View is enabled=false
+ while the Profile Name is empty and flips to enabled=true the moment a name is
+ typed. Assert the enabled false->true transition on that node. Depth 2
+ (Dashboard -> Manage Profiles -> Add Profile dialog)."""
+ open_main_clear()
+ if not and_enter_manage_profiles():
+ record("states_save_conditional_enable", False,
+ "setup_failed: could not reach Manage Profiles",
+ depth=2, jump_kind="transition",
+ expect="Add Profile Save enabled false->true after typing a name")
+ return
+ if not and_enter_add_profile():
+ record("states_save_conditional_enable", False,
+ "setup_failed: could not open the Add Profile dialog",
+ depth=2, jump_kind="transition",
+ expect="Add Profile Save enabled false->true after typing a name")
+ return
+ nodes = ui()
+ save_par = _save_clickable_parent(nodes)
+ name_field = _first_edittext(nodes)
+ if save_par is None or name_field is None:
+ record("states_save_conditional_enable", False,
+ "feature_missing: Save button / Profile Name field not found in "
+ "the Add Profile dialog",
+ depth=2, jump_kind="transition",
+ expect="Add Profile Save enabled false->true after typing a name")
+ return
+ enabled_before = save_par.get("enabled")
+ # This Compose field does not reliably report focused=true, which makes
+ # type_text's focus-verify retap land on a stale, keyboard-shifted position;
+ # a single tap-then-type (verify_focus=False) reliably lands the text here.
+ type_text(name_field, "StateProbe", verify_focus=False)
+ settle("tap")
+ save_par2 = _save_clickable_parent(ui())
+ enabled_after = save_par2.get("enabled") if save_par2 else None
+ ok = enabled_before == "false" and enabled_after == "true"
+ record("states_save_conditional_enable", bool(ok),
+ "" if ok else (f"behavior_wrong: Save's clickable parent enabled did not "
+ f"flip false->true after typing a name (before="
+ f"{enabled_before!r} after={enabled_after!r})"),
+ depth=2, jump_kind="transition",
+ expect=f"Add Profile Save enabled false->true once a name is typed "
+ f"(saw {enabled_before}->{enabled_after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (10) CHECKBOX CHECKED FLIP — Add Profile 'Set as Favourite'
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_favourite_checkbox",))
+def test_favourite_checkbox():
+ """The Add Profile dialog's 'Set as Favourite' CheckBox flips checked
+ false->true on tap. Assert the transition on the CheckBox node itself. Depth 2
+ (Manage Profiles -> Add Profile dialog)."""
+ open_main_clear()
+ if not and_enter_manage_profiles():
+ record("states_favourite_checkbox", False,
+ "setup_failed: could not reach Manage Profiles",
+ depth=2, jump_kind="transition",
+ expect="'Set as Favourite' CheckBox checked false->true")
+ return
+ if not and_enter_add_profile():
+ record("states_favourite_checkbox", False,
+ "setup_failed: could not open the Add Profile dialog",
+ depth=2, jump_kind="transition",
+ expect="'Set as Favourite' CheckBox checked false->true")
+ return
+ nodes = ui()
+ cb = next((n for n in nodes if "CheckBox" in n.get("class", "")), None)
+ if cb is None:
+ record("states_favourite_checkbox", False,
+ "feature_missing: no 'Set as Favourite' CheckBox in the dialog",
+ depth=2, jump_kind="transition",
+ expect="'Set as Favourite' CheckBox checked false->true")
+ return
+ before = cb.get("checked")
+ tap_node(cb)
+ settle("tap")
+ cb2 = next((n for n in ui() if "CheckBox" in n.get("class", "")), None)
+ after = cb2.get("checked") if cb2 else None
+ ok = before == "false" and after == "true"
+ record("states_favourite_checkbox", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Set as Favourite' CheckBox checked did "
+ f"not flip false->true (before={before!r} after={after!r})"),
+ depth=2, jump_kind="transition",
+ expect=f"'Set as Favourite' CheckBox checked false->true "
+ f"(saw {before}->{after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (11) SPEED-DIAL FAB — collapsed -> expanded page state (child actions appear)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_speed_dial_expand", "states_speed_dial_expand_vlm"))
+def test_speed_dial_expand():
+ """On the dashboard (no active fast) the FAB (desc='Add Fast') is a COLLAPSED
+ speed-dial. One tap flips it to EXPANDED, revealing child actions
+ (desc='Start Open Fast' and 'View History') that were ABSENT before. Assert
+ the collapsed->expanded page-state flip via the appearance of those child
+ actions. The paired VLM confirms the two labelled action buttons are stacked
+ above the FAB (the visual expanded-menu layout). Depth 0 (in-page state)."""
+ open_main_clear()
+ before = ui()
+ fab = find_node(before, content_desc="Add Fast")
+ if fab is None:
+ record("states_speed_dial_expand", False,
+ "feature_missing: no 'Add Fast' FAB on the dashboard",
+ depth=0, jump_kind="transition",
+ expect="FAB collapsed->expanded: 'Start Open Fast'/'View History' appear")
+ vlm_assert("states_speed_dial_expand",
+ "In the lower-right area, are there two green rounded action "
+ "buttons stacked vertically ABOVE the main round button (an "
+ "expanded speed-dial menu), rather than just a single button?",
+ RESULTS_DIR, tag="position", depth=0, jump_kind="transition")
+ return
+ child_before = (find_node(before, content_desc="Start Open Fast") is not None
+ or find_node(before, content_desc="View History") is not None)
+ tap_node(fab)
+ settle("tap")
+ after = ui()
+ sof_after = find_node(after, content_desc="Start Open Fast") is not None
+ vh_after = find_node(after, content_desc="View History") is not None
+ ok = (not child_before) and sof_after and vh_after
+ record("states_speed_dial_expand", bool(ok),
+ "" if ok else (f"behavior_wrong: tapping the FAB did not expand the "
+ f"speed-dial (child actions before={child_before}, "
+ f"'Start Open Fast' after={sof_after}, 'View History' "
+ f"after={vh_after})"),
+ depth=0, jump_kind="transition",
+ expect=f"FAB collapsed->expanded: 'Start Open Fast' & 'View History' "
+ f"appear (saw {sof_after}/{vh_after})")
+ # VLM (position): the expanded speed-dial stacks child buttons above the FAB.
+ vlm_assert("states_speed_dial_expand",
+ "In the lower-right area of the screen, are there two green rounded "
+ "action buttons stacked vertically ABOVE the main round hourglass "
+ "button (an expanded speed-dial menu), rather than just a single "
+ "round button?",
+ RESULTS_DIR, tag="position", depth=0, jump_kind="transition")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (12) EXPAND CHEVRON — Statistics "All-time statistics" collapsed -> expanded
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_alltime_expand",))
+def test_alltime_expand():
+ """The Statistics 'All-time statistics' row has an Expand chevron
+ (desc='Expand'). Tapping it flips collapsed->expanded: new stat rows appear
+ (e.g. 'Total Duration') and the chevron flips desc 'Expand'->'Collapse'.
+ Assert the chevron desc transition AND that new content appeared. Depth 1
+ (reach Statistics)."""
+ open_main_clear()
+ if not and_reach_statistics():
+ record("states_alltime_expand", False,
+ "setup_failed: could not reach Statistics",
+ depth=1, jump_kind="transition",
+ expect="'All-time statistics' Expand->Collapse; new stats appear")
+ return
+ scroll_into_view("All-time statistics", max_swipes=4)
+ nodes = ui()
+ exp = find_node(nodes, content_desc="Expand")
+ if exp is None:
+ record("states_alltime_expand", False,
+ "feature_missing: no 'Expand' chevron for 'All-time statistics'",
+ depth=1, jump_kind="transition",
+ expect="'All-time statistics' Expand->Collapse; new stats appear")
+ return
+ before_keys = and_showing(nodes)
+ collapse_before = find_node(nodes, content_desc="Collapse") is not None
+ tap_node(exp)
+ settle("tap")
+ nodes2 = ui()
+ after_keys = and_showing(nodes2)
+ collapse_after = find_node(nodes2, content_desc="Collapse") is not None
+ new_content = len(after_keys - before_keys) >= 1
+ ok = (not collapse_before) and collapse_after and new_content
+ record("states_alltime_expand", bool(ok),
+ "" if ok else (f"behavior_wrong: 'All-time statistics' did not expand "
+ f"(Collapse chevron before={collapse_before} after="
+ f"{collapse_after}; new content={new_content})"),
+ depth=1, jump_kind="transition",
+ expect=f"chevron desc 'Expand'->'Collapse' and new stat rows appear "
+ f"(saw collapse={collapse_after}, newContent={new_content})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (13) ACCENT "Selected" INDICATOR — tapped accent circle gets a 'Selected' desc
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_accent_selected",))
+def test_accent_selected():
+ """On the 'Theme & Accent Color' screen, tapping an accent-colour circle marks
+ it with a 'Selected' content-desc (the selection-state indicator) placed within
+ that circle's bounds — absent from that circle before. Assert the 'Selected'
+ indicator appears on the tapped circle. Depth 2 (Settings -> Theme & Accent)."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_accent_selected", False,
+ "setup_failed: could not reach Settings",
+ depth=2, jump_kind="transition",
+ expect="tapped accent circle gains a 'Selected' indicator")
+ return
+ if not and_enter_accent_screen():
+ record("states_accent_selected", False,
+ "setup_failed: could not reach the 'Theme & Accent Color' screen",
+ depth=2, jump_kind="transition",
+ expect="tapped accent circle gains a 'Selected' indicator")
+ return
+ nodes = ui()
+ acc = find_node(nodes, text="Accent Color")
+ if acc is None:
+ record("states_accent_selected", False,
+ "feature_missing: no 'Accent Color' grid on the screen",
+ depth=2, jump_kind="transition",
+ expect="tapped accent circle gains a 'Selected' indicator")
+ return
+ ay = acc["_bounds"][3]
+ circles = [n for n in nodes
+ if n.get("clickable") == "true" and n.get("_bounds")
+ and n["_bounds"][1] >= ay
+ and (n["_bounds"][2] - n["_bounds"][0]) < 200]
+ circles.sort(key=lambda n: (n["_bounds"][1], n["_bounds"][0]))
+ if len(circles) < 2:
+ record("states_accent_selected", False,
+ "feature_missing: fewer than 2 accent circles found",
+ depth=2, jump_kind="transition",
+ expect="tapped accent circle gains a 'Selected' indicator")
+ return
+ target = circles[1] # tap a non-first circle to force a NEW selection
+ tx1, ty1, tx2, ty2 = target["_bounds"]
+ tap_node(target)
+ settle("tap")
+ nodes2 = ui()
+ # a 'Selected' desc node whose centre falls inside the tapped circle's bounds
+ sel_on_target = False
+ for n in nodes2:
+ if "selected" in (n.get("content-desc", "").lower()) and "_center" in n:
+ cx, cy = n["_center"]
+ if tx1 - 20 <= cx <= tx2 + 20 and ty1 - 20 <= cy <= ty2 + 20:
+ sel_on_target = True
+ break
+ ok = sel_on_target
+ record("states_accent_selected", bool(ok),
+ "" if ok else ("behavior_wrong: tapping an accent circle did not place a "
+ "'Selected' indicator on that circle"),
+ depth=2, jump_kind="transition",
+ expect="the tapped accent circle gains a 'Selected' content-desc marker "
+ "within its bounds")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (14) THEME & ACCENT SWITCH — "Use Expressive Theme" checked flip
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_expressive_theme_switch",))
+def test_expressive_theme_switch():
+ """The 'Theme & Accent Color' screen carries a 'Use Expressive Theme' switch
+ (checked=false by default; the app keeps it enabled only while 'Use System
+ Colors' is OFF, so this turns System Colors off first). Tapping it flips
+ checked false->true — a depth-2 CHECKED transition distinct from the
+ Settings-level switches. Depth 2 (Settings -> Theme & Accent)."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_expressive_theme_switch", False,
+ "setup_failed: could not reach Settings",
+ depth=2, jump_kind="transition",
+ expect="'Use Expressive Theme' switch checked false->true")
+ return
+ if not and_enter_accent_screen():
+ record("states_expressive_theme_switch", False,
+ "setup_failed: could not reach the 'Theme & Accent Color' screen",
+ depth=2, jump_kind="transition",
+ expect="'Use Expressive Theme' switch checked false->true")
+ return
+ # 'Use Expressive Theme' is enabled=false while 'Use System Colors' is ON
+ # (the app disables the custom-theme controls then), so turn System Colors OFF
+ # first if needed — the flip we assert is on 'Use Expressive Theme' itself.
+ usc = _switch_for_label(ui(), "Use System Colors")
+ if usc is not None and usc.get("checked") == "true":
+ tap_node(usc)
+ settle("tap")
+ sw = _switch_for_label(ui(), "Use Expressive Theme")
+ if sw is None:
+ record("states_expressive_theme_switch", False,
+ "feature_missing: no 'Use Expressive Theme' switch on the screen",
+ depth=2, jump_kind="transition",
+ expect="'Use Expressive Theme' switch checked false->true")
+ return
+ before = sw.get("checked")
+ tap_node(sw)
+ settle("tap")
+ after = (_switch_for_label(ui(), "Use Expressive Theme") or {}).get("checked")
+ ok = before == "false" and after == "true"
+ record("states_expressive_theme_switch", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Use Expressive Theme' checked did not "
+ f"flip false->true (before={before!r} after={after!r})"),
+ depth=2, jump_kind="transition",
+ expect=f"'Use Expressive Theme' switch checked false->true "
+ f"(saw {before}->{after})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (15) THEME DARK — selecting 'Dark' recolours the app to a dark background [VLM]
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_theme_dark_vlm",))
+def test_theme_dark_vlm():
+ """The Appearance theme selector Light|Dark|System exposes no checked bit on
+ its TextViews, so its state change is a genuinely VISUAL one: selecting 'Dark'
+ recolours the whole app to a near-black background with light text. Pure VLM
+ (the transition is unreadable from the tree). Depth 1 (Settings). Runs LAST so
+ the following open_main_clear() of the next suite resets the theme; this test
+ also re-selects 'System' at the end to avoid poisoning a re-run."""
+ open_main_clear()
+ if not and_enter_settings():
+ record("states_theme_dark_vlm", False, # backfilled name; recorded via vlm
+ "setup_failed: could not reach Settings", depth=1,
+ jump_kind="transition", backfilled=True)
+ vlm_assert("states_theme_dark",
+ "Is the whole app screen background a dark near-black colour with "
+ "light/white text (dark theme), rather than a white/light "
+ "background?",
+ RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
+ return
+ dark = find_node(ui(), text="Dark")
+ if dark is None:
+ vlm_assert("states_theme_dark",
+ "Is the whole app screen background a dark near-black colour with "
+ "light/white text (dark theme)?",
+ RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
+ return
+ tap_node(dark)
+ settle("tap")
+ settle("tap")
+ # VLM (color): the app is now rendered on a dark background.
+ vlm_assert("states_theme_dark",
+ "Is the whole app screen background a dark near-black colour with "
+ "light/white text (a dark theme), rather than a white/light "
+ "background?",
+ RESULTS_DIR, tag="color", depth=1, jump_kind="transition")
+ # restore a light/system theme so a re-run is not poisoned
+ sysn = find_node(ui(), text="System")
+ if sysn:
+ tap_node(sysn)
+ settle("tap")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_switch_fasting_phases,
+ test_switch_fab_consequence,
+ test_switch_expressive_progress,
+ test_switch_persists_relaunch,
+ test_stats_monthly_toggle,
+ test_stats_weekly_back,
+ test_trends_all_time,
+ test_first_day_of_week,
+ test_save_conditional_enable,
+ test_favourite_checkbox,
+ test_speed_dial_expand,
+ test_alltime_expand,
+ test_accent_selected,
+ test_expressive_theme_switch,
+ test_theme_dark_vlm, # last: recolours the app; restores System at end
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "states")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_structure.py b/android/tom-murphy-development-fasttimes/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a141f21f3113ab0a620e09ea79844597b8a6611
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_structure.py
@@ -0,0 +1,570 @@
+#!/usr/bin/env python3
+"""STRUCTURE module — FastTimes (intermittent-fasting tracker).
+
+Owns two things only:
+ (1) the GATE: the app launches into its Dashboard with the top-level surfaces
+ present (title, "Set your goal" card, the 2-col goal grid, the green FAB).
+ (2) tree-SHAPE deltas: an interaction changes the view tree's SHAPE — a class of
+ widget appears/vanishes, a dialog adds a window layer, a list populates. Each
+ delta is recorded as a before->after and then REVERSED to assert it restores.
+
+Content strings -> text lane; checked/selected -> states; reachability -> nav;
+values -> computation. Here we assert SHAPE and existence of surfaces, plus spatial
+layout via the VLM (the circular ring, the calendar grid, the expressive stat-card
+shapes — none of which reach the view tree).
+
+Run: python3 test_android_structure.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime. ──────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data (no active fast, empty history), then open Main."""
+ clear_data()
+ open_main()
+
+
+# ── Domain helpers ───────────────────────────────────────────────────────────
+def _dismiss_notif_rationale(nodes):
+ """The first-run "Notification Preferences" rationale can appear on the first
+ goal tap after clear_data(). Dismiss it (choice is irrelevant to structure)."""
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Enable Notifications", "Cancel", "Skip"):
+ n = find_node(nodes, text=label)
+ if n:
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+def start_test_timer():
+ """From a clean dashboard, tap the "Test Timer" goal cell and end up on the
+ ACTIVE-FAST card. Handles the optional first-run notification rationale.
+ Returns the post-start node tree, or None if the cell was missing."""
+ dash = ui()
+ cell = find_node(dash, text="Test Timer")
+ if not cell:
+ return None
+ tap_node(cell)
+ settle("tap")
+ after = ui()
+ if _dismiss_notif_rationale(after):
+ after = ui()
+ if not find_node(after, content_desc="End Fast"):
+ # dialog path may have consumed the tap; retry the cell once
+ cell = find_node(after, text="Test Timer")
+ if cell:
+ tap_node(cell)
+ settle("tap")
+ after = ui()
+ return after
+
+
+def end_active_fast_no_save(nodes):
+ """Tap End Fast, then BACK out of the "Fast Complete!" summary WITHOUT saving,
+ returning to a clean dashboard. Keeps history empty (no CRUD side effect)."""
+ ef = find_node(nodes, content_desc="End Fast")
+ if not ef:
+ return ui()
+ tap_node(ef)
+ settle("tap")
+ back() # dismiss the summary modal without saving
+ settle("tap")
+ return ui()
+
+
+# ── Named navigation helpers (back a depth>=1 claim honestly) ──────────────────
+def and_reach_screen(nodes, trigger_text="", trigger_desc="", target="", source=""):
+ """Tap a labelled trigger on `nodes`, then PROVE the surface jump: `target`
+ appeared and `source` vanished. Counts one surface (jump_kind='reach')."""
+ n = None
+ if trigger_text:
+ n = find_node(nodes, text=trigger_text) or find_node_ci(nodes, trigger_text)
+ if n is None and trigger_desc:
+ n = find_node(nodes, content_desc=trigger_desc)
+ if n is None:
+ return False
+ return and_reach_surface(n, target, source or None)
+
+
+def and_enter_dialog(nodes, trigger_desc="", trigger_text=""):
+ """Open an in-place dialog/overlay (a new window layer over the same screen),
+ confirming the surface changed. Counts one surface (depth+1)."""
+ ok, _note = and_enter_surface(nodes, target_text=trigger_text,
+ content_desc=trigger_desc)
+ return ok
+
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) GATE — top-level Dashboard surfaces present (jump_kind="none", depth=0)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ open_main_clear()
+ nodes = ui()
+ fg = wait_for_foreground()
+ # main container: single-Activity Compose renders a ComposeView host inside a
+ # top-level layout container. Assert BOTH a layout host and a Compose host.
+ container = find_by_class(nodes, "ComposeView") and find_by_class(nodes, "FrameLayout")
+ ok = bool(fg and container)
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach the foreground with a "
+ "Compose container",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_dashboard_surfaces", "structure_dashboard_fab_vlm"))
+def test_gate_dashboard_surfaces():
+ open_main_clear()
+ nodes = ui()
+ # top-level Dashboard surfaces, by visible text + content-desc (no ids):
+ title = find_node_ci(nodes, "Fast Times") # toolbar title
+ goal_card = find_node_ci(nodes, "Set your goal") # goal card header
+ perf = find_node_ci(nodes, "Performance") # performance section
+ hist = find_node_ci(nodes, "History") # history section
+ fab = find_node(nodes, content_desc="Add Fast") # green add FAB
+ settings = find_node(nodes, content_desc="Settings") # toolbar gear
+ ok = all([title, goal_card, perf, hist, fab, settings])
+ record("structure_gate_dashboard_surfaces", bool(ok),
+ "" if ok else "feature_missing: a top-level Dashboard surface is absent "
+ "(title/Set your goal/Performance/History/FAB/Settings)",
+ depth=0, jump_kind="none")
+ # VLM: the FAB is a green button in the bottom-right corner (a rounded square
+ # with a dark icon). Assert the exact rendered COLOR + POSITION.
+ vlm_assert("structure_dashboard_fab",
+ "Is there a green colored button in the bottom-right corner of the "
+ "screen containing a small dark icon? Answer YES or NO.",
+ RESULTS_DIR, tag="color", depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_goal_grid", "structure_goal_grid_layout_vlm"))
+def test_gate_goal_grid():
+ open_main_clear()
+ nodes = ui()
+ # The 8-cell goal grid: assert the SHAPE (all 8 named cells exist). This is
+ # existence of a structural grid, not any single string's content.
+ cells = ["12h", "14h", "16h", "18h", "24h", "∞", "1h", "0h"]
+ present = [c for c in cells if find_node(nodes, text=c)]
+ ok = len(present) == 8
+ record("structure_gate_goal_grid", ok,
+ "" if ok else f"feature_missing: goal grid incomplete, only "
+ f"{len(present)}/8 cells present ({present})",
+ depth=0, jump_kind="none")
+ # VLM: the eight cells are laid out as a 2-column grid.
+ vlm_assert("structure_goal_grid_layout",
+ "Under the 'Set your goal' heading, are the goal cells arranged in a "
+ "grid with exactly two columns per row? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=0, jump_kind="none")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) SHAPE DELTAS — in-place (depth=0) transitions with a reverse
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_fab_speeddial_expand", "structure_fab_speeddial_vlm"))
+def test_fab_speeddial_expand():
+ open_main_clear()
+ dash = ui()
+ fab = find_node(dash, content_desc="Add Fast")
+ if not fab:
+ record("structure_fab_speeddial_expand", False,
+ "feature_missing: Add Fast FAB not present on Dashboard",
+ depth=0, jump_kind="transition",
+ expect="FAB expand adds 'Start Open Fast'+'View History' children")
+ else:
+ before = and_showing(dash)
+ n_clk_before = len(find_nodes(dash, clickable=True))
+ tap_node(fab)
+ exp_nodes = ui()
+ after = and_showing(exp_nodes)
+ n_clk_after = len(find_nodes(exp_nodes, clickable=True))
+ # speed-dial GROWS the tree: 2 new labelled actions + 2 more clickables.
+ added = after - before
+ grew = (any("Start Open Fast" in k for k in added)
+ and any("View History" in k for k in added)
+ and n_clk_after >= n_clk_before + 2)
+ # reverse: tapping the FAB again collapses it back to the original shape.
+ fab2 = find_node(exp_nodes, content_desc="Add Fast")
+ if fab2:
+ tap_node(fab2)
+ coll = ui()
+ restored = (not find_node(coll, text="Start Open Fast")
+ and len(find_nodes(coll, clickable=True)) == n_clk_before)
+ ok = grew and restored
+ record("structure_fab_speeddial_expand", ok,
+ "" if ok else ("behavior_wrong: speed-dial did not add the two "
+ "action buttons" if not grew
+ else "behavior_wrong: speed-dial did not collapse back"),
+ depth=0, jump_kind="transition",
+ expect="clickables +2 with 'Start Open Fast'+'View History' on expand,"
+ " restored on collapse")
+ # re-expand so the VLM screenshot shows the speed-dial open
+ fab3 = find_node(coll, content_desc="Add Fast")
+ if fab3:
+ tap_node(fab3)
+ vlm_assert("structure_fab_speeddial",
+ "Are there two green pill-shaped action buttons stacked vertically "
+ "directly above the round green button in the bottom-right corner? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=0, jump_kind="transition")
+
+
+@and_test(expects=("structure_active_fast_shape", "structure_active_fast_ring_vlm"))
+def test_active_fast_shape():
+ open_main_clear()
+ dash = ui()
+ before = and_showing(dash)
+ fab_before = bool(find_node(dash, content_desc="Add Fast"))
+ active = start_test_timer()
+ if active is None:
+ record("structure_active_fast_shape", False,
+ "setup_failed: 'Test Timer' goal cell not found on Dashboard",
+ depth=0, jump_kind="transition",
+ expect="active-fast card adds ProgressBar+End Fast, FAB disappears")
+ else:
+ # SHAPE delta: a circular ProgressBar (the ring) + an "End Fast" control
+ # appear, and the "Add Fast" FAB disappears while a fast is active.
+ ring = find_by_class(active, "ProgressBar")
+ end_fast = find_node(active, content_desc="End Fast")
+ fab_after = bool(find_node(active, content_desc="Add Fast"))
+ after = and_showing(active)
+ changed = surface_changed(before, after)
+ grew = bool(ring) and bool(end_fast) and fab_before and (not fab_after)
+ # VLM while the ring is on screen (before we tear the fast down)
+ vlm_assert("structure_active_fast_ring",
+ "Is there a circular ring or arc drawn around the countdown "
+ "timer numbers near the top-center of the screen? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="transition")
+ # reverse: end the fast (no save) -> the goal grid shape returns, ring gone.
+ restored_nodes = end_active_fast_no_save(active)
+ restored = (bool(find_node(restored_nodes, text="Set your goal"))
+ and not find_node(restored_nodes, content_desc="End Fast")
+ and bool(find_node(restored_nodes, content_desc="Add Fast")))
+ ok = changed and grew and restored
+ record("structure_active_fast_shape", ok,
+ "" if ok else ("behavior_wrong: starting a fast did not swap the goal "
+ "card for the active-fast ring/End-Fast shape"
+ if not grew
+ else "behavior_wrong: ending the fast did not restore "
+ "the Dashboard goal shape"),
+ depth=0, jump_kind="transition",
+ expect="goal card -> ProgressBar ring + End Fast + FAB gone; "
+ "restored to goal grid on End Fast")
+ return
+ # active is None path: still spend the declared VLM record (screenshot dashboard)
+ vlm_assert("structure_active_fast_ring",
+ "Is there a circular ring or arc drawn around the countdown "
+ "timer numbers near the top-center of the screen? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=0, jump_kind="transition")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) SHAPE DELTAS — navigation-backed (depth>=1), each proven by and_reach_*
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_dashboard_to_profiles", "structure_profiles_grid_vlm"))
+def test_dashboard_to_profiles_shape():
+ open_main_clear()
+ dash = ui()
+ before = and_showing(dash)
+ # Navigate to Manage Profiles (proves reach: 'Other Profiles' appears, the
+ # 'Set your goal' goal card vanishes). Backs depth=1.
+ reached = and_reach_screen(dash, trigger_text="Manage Profiles",
+ target="Other Profiles", source="Set your goal")
+ prof = ui()
+ after = and_showing(prof)
+ # SHAPE: the profiles screen adds a grid of profile cards (many named cards) and
+ # an "Add Profile" FAB — a materially different tree from the Dashboard.
+ cards = [t for t in ("12 Hours", "14 Hours", "16 Hours", "18 Hours", "24 Hours")
+ if find_node(prof, text=t)]
+ add_fab = bool(find_node(prof, content_desc="Add Profile"))
+ ok = reached and surface_changed(before, after) and len(cards) >= 4 and add_fab
+ record("structure_dashboard_to_profiles", bool(ok),
+ "" if ok else ("feature_missing: Manage Profiles screen not reached / no "
+ "profile-card grid + Add Profile FAB"),
+ depth=1, jump_kind="transition",
+ expect="Dashboard goal card -> Manage Profiles grid (>=4 duration cards) "
+ "+ Add Profile FAB")
+ # VLM: the profiles are rendered as a grid of cards.
+ vlm_assert("structure_profiles_grid",
+ "Under the 'Other Profiles' heading, are multiple fasting-profile "
+ "cards arranged in a two-column grid? Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("structure_add_profile_dialog", "structure_add_profile_dialog_vlm"))
+def test_add_profile_dialog_shape():
+ open_main_clear()
+ dash = ui()
+ reached = and_reach_screen(dash, trigger_text="Manage Profiles",
+ target="Other Profiles", source="Set your goal")
+ prof = ui()
+ n_edit_before = len(find_by_class(prof, "EditText"))
+ # Open the Add Profile dialog (a new window layer over Manage Profiles). depth=2.
+ opened = and_enter_dialog(prof, trigger_desc="Add Profile")
+ dlg = ui()
+ # SHAPE delta of the dialog layer: 3 EditText fields + 1 CheckBox appear.
+ n_edit = len(find_by_class(dlg, "EditText"))
+ n_check = len(find_by_class(dlg, "CheckBox"))
+ has_labels = all(find_node(dlg, text=t) for t in ("Add Profile", "Cancel", "Save"))
+ grew = (n_edit_before == 0 and n_edit == 3 and n_check == 1 and has_labels)
+ # VLM WHILE THE DIALOG IS OPEN (must precede the Cancel that reverses it).
+ vlm_assert("structure_add_profile_dialog",
+ "Is there a rounded rectangular dialog card overlaid on the screen "
+ "that contains three empty text input boxes stacked vertically with a "
+ "'Cancel' and 'Save' button below them? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=2, jump_kind="transition")
+ # reverse: Cancel dismisses the dialog -> EditTexts gone, grid back.
+ cancel = find_node(dlg, text="Cancel")
+ if cancel:
+ tap_node(cancel)
+ back_nodes = ui()
+ restored = (len(find_by_class(back_nodes, "EditText")) == 0
+ and bool(find_node(back_nodes, content_desc="Add Profile")))
+ ok = reached and opened and grew and restored
+ record("structure_add_profile_dialog", bool(ok),
+ "" if ok else ("behavior_wrong: Add Profile dialog did not add 3 "
+ "EditText fields + a checkbox" if not grew
+ else "behavior_wrong: Cancel did not dismiss the dialog"),
+ depth=2, jump_kind="transition",
+ expect="EditText 0->3 + 1 CheckBox on dialog open, restored on Cancel")
+
+
+@and_test(expects=("structure_settings_rows", "structure_settings_toggles_vlm"))
+def test_settings_row_shape():
+ open_main_clear()
+ dash = ui()
+ before = and_showing(dash)
+ reached = and_reach_screen(dash, trigger_desc="Settings",
+ target="Appearance", source="Set your goal")
+ st = ui()
+ after = and_showing(st)
+ # SHAPE: a real Settings column has MANY distinct section/row labels; a stub
+ # would not. Require at least 6 of the known section/row labels to be present.
+ labels = ["Appearance", "Color Scheme", "First Day of Week",
+ "Show Floating Action Button", "Use Expressive Progress Indicator",
+ "Show Fasting Phases", "Notifications",
+ "Show live progress notification", "Goal reached notification"]
+ found = [x for x in labels if find_node_ci(st, x)]
+ ok = reached and surface_changed(before, after) and len(found) >= 6
+ record("structure_settings_rows", bool(ok),
+ "" if ok else (f"feature_missing: Settings has only {len(found)} of the "
+ f"expected section/row labels ({found})"),
+ depth=1, jump_kind="transition",
+ expect="Settings column shows >=6 distinct section/row labels")
+ # VLM: the toggle rows render as pill switches on the right of their labels.
+ vlm_assert("structure_settings_toggles",
+ "Does the Settings screen show setting rows with pill-shaped toggle "
+ "switches aligned to the right side of the rows? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("structure_settings_scroll_reveal",))
+def test_settings_scroll_reveal():
+ open_main_clear()
+ dash = ui()
+ reached = and_reach_screen(dash, trigger_desc="Settings",
+ target="Appearance", source="Set your goal")
+ top = ui()
+ # A real Settings screen is a scrollable column: the "Export Data" / "Import
+ # Data" Data-Management buttons sit BELOW the fold, so they are absent from the
+ # first dump and a scroll REVEALS them (a scroll-driven shape change of what is
+ # on screen). Also assert the column is wrapped in a ScrollView (a stub with a
+ # fixed Column would not scroll). scroll_into_view re-dumps between swipes.
+ scrollable = bool(find_by_class(top, "ScrollView"))
+ export_top = find_node_ci(top, "Export Data")
+ revealed = scroll_into_view("Export Data", max_swipes=6)
+ import_after = find_node_ci(ui(), "Import Data")
+ ok = (reached and scrollable and (export_top is None)
+ and bool(revealed) and bool(import_after))
+ record("structure_settings_scroll_reveal", bool(ok),
+ "" if ok else ("behavior_wrong: 'Export Data'/'Import Data' not revealed "
+ "by scrolling the Settings column"
+ if export_top is None
+ else "behavior_wrong: 'Export Data' was already visible at "
+ "the top (no scroll delta)"),
+ depth=1, jump_kind="transition",
+ expect="ScrollView column; 'Export Data' hidden at top, revealed on scroll")
+
+
+@and_test(expects=("structure_statistics_containers", "structure_stats_cards_vlm",
+ "structure_stats_chart_vlm"))
+def test_statistics_containers_shape():
+ open_main_clear()
+ dash = ui()
+ before = and_showing(dash)
+ reached = and_reach_screen(dash, trigger_desc="Go to Statistics",
+ target="Trends", source="Set your goal")
+ st = ui()
+ after = and_showing(st)
+ # SHAPE: the expected SET of statistics containers exists — the three stat cards,
+ # the "Trends" block, and the segmented toggles (RadioButton group, >=3 options).
+ stat_cards = [t for t in ("Total Fasts", "Average Fast", "Consistency")
+ if find_node(st, text=t)]
+ trends = bool(find_node(st, text="Trends"))
+ radios = find_by_class(st, "RadioButton")
+ ok = (reached and surface_changed(before, after)
+ and len(stat_cards) == 3 and trends and len(radios) >= 3)
+ record("structure_statistics_containers", bool(ok),
+ "" if ok else ("feature_missing: Statistics screen missing expected "
+ f"containers (cards={stat_cards}, trends={trends}, "
+ f"radios={len(radios)})"),
+ depth=1, jump_kind="transition",
+ expect="3 stat cards + 'Trends' + a >=3-option segmented toggle present")
+ # VLM: the three Material-3-Expressive stat cards have distinctive non-rectangular
+ # shapes (pentagon / blob / scalloped).
+ vlm_assert("structure_stats_cards",
+ "Are the three statistics cards ('Total Fasts', 'Average Fast', "
+ "'Consistency') drawn as non-rectangular blob/pentagon/scalloped "
+ "shapes rather than plain rectangles? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")
+ # VLM: a horizontal bar chart is rendered above the day/date axis.
+ vlm_assert("structure_stats_chart",
+ "Is there a horizontal row of bar-chart segments drawn above a row of "
+ "single-letter day-of-week axis labels? Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("structure_statistics_expand",))
+def test_statistics_expand_shape():
+ open_main_clear()
+ dash = ui()
+ reached = and_reach_screen(dash, trigger_desc="Go to Statistics",
+ target="Trends", source="Set your goal")
+ st = ui()
+ before = and_showing(st)
+ n_before = len(st)
+ # The "All-time statistics" Expand chevron GROWS the tree (adds a Total Duration
+ # row + a Collapse control). Locate the expand affordance and toggle it.
+ exp = find_node(st, content_desc="Expand")
+ if exp is None:
+ # fall back to the row label if the chevron desc differs
+ exp = find_node(st, text="All-time statistics")
+ grew = restored = False
+ if exp is not None:
+ tap_node(exp)
+ st2 = ui()
+ after = and_showing(st2)
+ added = after - before
+ grew = (len(st2) > n_before
+ and (any("Collapse" in k for k in added)
+ or any("Total Duration" in k for k in added)))
+ # reverse: collapse it back
+ coll = (find_node(st2, content_desc="Collapse")
+ or find_node(st2, content_desc="Expand"))
+ if coll:
+ tap_node(coll)
+ st3 = ui()
+ restored = (not find_node(st3, content_desc="Collapse"))
+ ok = reached and grew and restored
+ record("structure_statistics_expand", bool(ok),
+ "" if ok else ("behavior_wrong: 'All-time statistics' expand did not grow "
+ "the tree" if not grew
+ else "behavior_wrong: expanded section did not collapse back"),
+ depth=1, jump_kind="transition",
+ expect="All-time statistics expand adds Total Duration/Collapse, "
+ "restored on collapse")
+
+
+@and_test(expects=("structure_history_calendar", "structure_history_grid_vlm",
+ "structure_history_summary_vlm"))
+def test_history_calendar_shape():
+ open_main_clear()
+ dash = ui()
+ before = and_showing(dash)
+ reached = and_reach_screen(dash, trigger_desc="Go to History",
+ target="August 2026", source="Set your goal")
+ hist = ui()
+ after = and_showing(hist)
+ # SHAPE: a real month calendar has a large number of numeric day cells. Count
+ # distinct day numbers 1..31; a stub would not render a full grid.
+ days = set()
+ for n in hist:
+ t = n.get("text", "").strip()
+ if t.isdigit() and 1 <= int(t) <= 31:
+ days.add(int(t))
+ month_hdr = bool(find_node(hist, text="August 2026"))
+ nav = (bool(find_node(hist, content_desc="Previous Month"))
+ and bool(find_node(hist, content_desc="Next Month")))
+ ok = (reached and surface_changed(before, after)
+ and len(days) >= 28 and month_hdr and nav)
+ record("structure_history_calendar", bool(ok),
+ "" if ok else (f"feature_missing: History calendar incomplete "
+ f"(distinct day cells={len(days)}, header={month_hdr}, "
+ f"month-nav={nav})"),
+ depth=1, jump_kind="transition",
+ expect=">=28 distinct day cells + month header + prev/next month nav")
+ # VLM: the days form a month grid with a weekday header row.
+ vlm_assert("structure_history_grid",
+ "Is there a monthly calendar laid out as a grid of numbered day cells "
+ "in seven columns, with a row of weekday letters above it? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="position", depth=1, jump_kind="transition")
+ # VLM: the 'August Summary' shows three distinctly-shaped stat cards.
+ vlm_assert("structure_history_summary",
+ "Below the calendar, does the 'August Summary' section show three "
+ "non-rectangular stat cards positioned side by side in one row? "
+ "Answer YES or NO.",
+ RESULTS_DIR, tag="shape", depth=1, jump_kind="transition")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_gate_launch,
+ test_gate_dashboard_surfaces,
+ test_gate_goal_grid,
+ test_fab_speeddial_expand,
+ test_active_fast_shape,
+ test_dashboard_to_profiles_shape,
+ test_add_profile_dialog_shape,
+ test_settings_row_shape,
+ test_settings_scroll_reveal,
+ test_statistics_containers_shape,
+ test_statistics_expand_shape,
+ test_history_calendar_shape,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "structure")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_android_text.py b/android/tom-murphy-development-fasttimes/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9bfb943ce2b91c4701e0cd512c08a8a474eb210
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_android_text.py
@@ -0,0 +1,870 @@
+#!/usr/bin/env python3
+"""TEXT module — FastTimes (intermittent-fasting tracker).
+
+This lane owns CONTENT / OUTPUT strings that an INTERACTION PRODUCES — the exact
+words the app writes in response to a trigger — and is the sole owner of exact-
+string equality. Every test is TRIGGER -> OBSERVATION that a specific literal
+string appeared / changed on the destination surface. All strings asserted here
+were OBSERVED on the running ORIGINAL (see the probe transcript in the delegation
+notes), never read from source or computed.
+
+What this lane asserts (LABELS / COPY, never a computed number):
+ * empty-history status copy "No recent fasts to show." (dynamic empty state)
+ * active-fast timer LABELS produced by starting a goal: "Remaining" (timed),
+ "Elapsed Time" + no "End Time" line (Open Fast)
+ * the goal-met COPY the app authors on the target-met transition:
+ "Goal Reached!" + label "Total Time"
+ * the fasting PHASE-chip name "Post-Absorptive State" (produced by an active
+ fast) and the phase-detail sheet's descriptive labels "Timing"/"Benefit"
+ (produced by tapping the chip — depth 1)
+ * the "Fast Complete!" summary copy: "Fast Complete!", "Rate your fast:",
+ "Started:", "Ended:", "Save" (produced by End Fast — depth 1)
+ * the Manage-Profiles empty-favourite HINT + section headers (depth 1)
+ * the Statistics header FLIP "This week" -> "Last 30 days" (Weekly->Monthly)
+ plus the empty-state subtitle and stat-card LABELS (depth 1)
+ * the History month header CHANGE "August 2026" -> previous month, produced by
+ the "Previous Month" control (depth 1; Next Month is disabled on the current
+ month, so the observable change is via Previous)
+ * the History-Info sheet copy "Understanding History" + legend (depth 2)
+ * the Daily-Details sheet TITLE "Details for " produced by tapping
+ a day with data (depth 2)
+ * the Settings footer version string and section headers (depth 1)
+
+CEDES to sibling lanes: reachability itself -> navigation; the checked/selected
+bit -> states; the mere existence of a saved record -> interaction; any computed
+number (timer value, aggregate count, percentage) -> computation; the view-tree
+shape / drawn arcs -> structure. This lane cares ONLY about literal text content.
+
+Every string here is READABLE FROM THE DUMP (verified), so every assertion is a
+RULE assertion and this lane uses ZERO vlm_assert — its VLM ceiling is 2 but the
+brief is explicit that manufacturing a visual question for dump-readable text is
+wrong; text earns LOW VLM and 0 is the correct count here.
+
+Compose renders as android.view.View / TextView with NO resource-ids, so every
+target is located by visible text / content-desc.
+
+SAFETY: never taps "Delete" / "Delete Fast" / "Reset"; exploratory taps go
+through is_safe()/safe_tap(). Each test opens its own entry point.
+
+Run: python3 test_android_text.py
+"""
+import os
+import re
+import sys
+import time
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+RESULTS_DIR = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+# ── Tight patterns for the time/date-dependent produced strings (the assertion is
+# always about the STRING CONTENT / shape, never a computed value). ─────────────
+_MONTH_YEAR = re.compile(r"^[A-Z][a-z]+ \d{4}$") # "August 2026"
+_DETAILS = re.compile(r"Details for [A-Z][a-z]+ \d{1,2}") # "Details for August 6"
+_VERSION = re.compile(r"\d+\.\d+\.\d+-DEBUG \(\d+\)") # "1.0.4-DEBUG (5)"
+# The five possible fasting-phase chip names (near t=0 it is the first one).
+_PHASE_NAMES = (
+ "Post-Absorptive State", "Metabolic Switch", "Autophagy Activation",
+ "Deep Ketosis & Repair", "Immune Regeneration",
+)
+
+
+# ── Portable launcher (LeakCanary registers a 2nd LAUNCHER activity; monkey opens
+# it ~half the time). Resolve THIS package's real MainActivity at runtime — no
+# hardcoded package or activity literal. ────────────────────────────────────────
+def _main_component():
+ out = adb_shell("cmd", "package", "query-activities", "--brief",
+ "-a", "android.intent.action.MAIN",
+ "-c", "android.intent.category.LAUNCHER")
+ cands = [l.strip() for l in out.splitlines() if (PACKAGE + "/") in l]
+ good = [c for c in cands if "leakcanary" not in c.lower()]
+ return (good or cands or [""])[0]
+
+
+def open_main():
+ """Force-stop then launch the REAL MainActivity (never LeakCanary)."""
+ force_stop()
+ comp = _main_component()
+ if comp:
+ adb_shell("am", "start", "-n", comp)
+ else:
+ launch_app()
+ settle("launch")
+ wait_for_foreground()
+ if "leakcanary" in get_current_activity().lower() and comp:
+ adb_shell("am", "start", "-n", comp)
+ settle("launch")
+
+
+def open_main_clear():
+ """Virgin state: wipe data (no active fast, empty history), then open Main."""
+ clear_data()
+ open_main()
+
+
+# ── Domain helpers ───────────────────────────────────────────────────────────
+def _dismiss_notif_rationale():
+ """The first-run "Notification Preferences" rationale appears on the first goal
+ tap after clear_data(). Dismiss it non-destructively (the choice is irrelevant
+ to the copy under test). Returns True if it was shown."""
+ nodes = ui()
+ if not find_node(nodes, text="Notification Preferences"):
+ return False
+ for label in ("No Notifications", "Skip", "Not Now", "Enable Notifications"):
+ n = find_node(nodes, text=label)
+ if n and is_safe(n):
+ tap_node(n)
+ settle("tap")
+ return True
+ return False
+
+
+def _on_dashboard(nodes=None):
+ nodes = ui() if nodes is None else nodes
+ return find_node(nodes, text="Set your goal") is not None
+
+
+def _start_goal(cell_text):
+ """From a CLEAN dashboard, tap a goal cell by name and land on the ACTIVE-FAST
+ card (desc='End Fast'). Handles the first-run notification rationale. Returns
+ True on success."""
+ cell = find_node(ui(), text=cell_text)
+ if not cell:
+ return False
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ if find_node(ui(), content_desc="End Fast"):
+ return True
+ cell = find_node(ui(), text=cell_text) # rationale may have eaten the tap
+ if cell:
+ tap_node(cell)
+ settle("tap")
+ _dismiss_notif_rationale()
+ return find_node(ui(), content_desc="End Fast") is not None
+
+
+def _wait_goal_reached(polls=18):
+ """Poll until the 10s Test Timer flips to 'Goal Reached!'. Bounded so a slow
+ emulator never hangs. Returns whether it flipped."""
+ for _ in range(polls):
+ if find_node(ui(), text="Goal Reached!"):
+ return True
+ settle("tap")
+ return False
+
+
+def _all_text(nodes):
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
+
+
+def _has_text(nodes, s):
+ return find_node(nodes, text=s) is not None or find_node_ci(nodes, s) is not None
+
+
+def _modal_star_views():
+ """The clickable rating-star Views in the 'Fast Complete!' summary modal:
+ empty-text square clickable android.view.View nodes in one horizontal row."""
+ nodes = ui()
+ clk = [n for n in nodes
+ if n.get("class", "").endswith("view.View")
+ and n.get("clickable") == "true"
+ and not n.get("text", "").strip()
+ and not n.get("content-desc", "").strip()
+ and "_bounds" in n]
+ stars = []
+ for n in clk:
+ x1, y1, x2, y2 = n["_bounds"]
+ w, h = x2 - x1, y2 - y1
+ if w < 40 or h < 40:
+ continue
+ if 0.6 <= w / h <= 1.7:
+ stars.append(n)
+ stars.sort(key=lambda n: n["_center"][0])
+ return stars
+
+
+def _open_summary_from_test_timer():
+ """Start Test Timer, reach goal, tap End Fast -> the 'Fast Complete!' summary
+ modal. Returns True when the modal is up (does NOT save)."""
+ if not _start_goal("Test Timer"):
+ return False
+ _wait_goal_reached()
+ ef = find_node(ui(), content_desc="End Fast")
+ if not ef:
+ return False
+ tap_node(ef)
+ settle("tap")
+ return find_node(ui(), text="Fast Complete!") is not None
+
+
+def _save_test_timer_fast():
+ """Complete + SAVE one Test Timer fast from a clean dashboard (rating 4 stars),
+ landing back on the Dashboard with the fast persisted. Needed for the Daily-
+ Details title test (a day cell only opens the sheet once it has data)."""
+ if not _open_summary_from_test_timer():
+ return False
+ stars = _modal_star_views()
+ if len(stars) >= 4:
+ tap_node(stars[3]) # 4th star (non-destructive)
+ settle("tap")
+ save = find_node(ui(), text="Save")
+ if not save or not tap_node(save):
+ return False
+ settle("tap")
+ return _on_dashboard()
+
+
+def _end_active_no_save():
+ """Best-effort cleanup: dismiss the summary/active fast without saving."""
+ if find_node(ui(), text="Fast Complete!"):
+ back()
+ settle("tap")
+ return
+ ef = find_node(ui(), content_desc="End Fast")
+ if ef:
+ tap_node(ef)
+ settle("tap")
+ back()
+ settle("tap")
+
+
+# ── Named depth helpers. The and_enter_*/and_reach_* NAME is what backs a
+# depth>=1 claim; each body performs a REAL surface jump (proven by a surface
+# change or a target-appeared/source-vanished check) before counting the surface.
+def and_reach_statistics():
+ """Dashboard -> Statistics ('Performance'). Proven: 'Trends' appears, the goal
+ card 'Set your goal' vanishes. Counts one surface."""
+ n = find_node(ui(), content_desc="Go to Statistics")
+ if not n:
+ return False
+ return and_reach_surface(n, "Trends", "Set your goal")
+
+
+def and_reach_history():
+ """Dashboard -> History pane. Proven: 'August 2026' appears, 'Set your goal'
+ vanishes. Counts one surface."""
+ n = find_node(ui(), content_desc="Go to History")
+ if not n:
+ return False
+ return and_reach_surface(n, "2026", "Set your goal")
+
+
+def and_enter_manage_profiles():
+ """Dashboard -> 'Manage Profiles' screen. Confirms the surface changed and
+ counts one surface. Returns (ok, note)."""
+ return and_enter_surface(ui(), target_text="Manage Profiles")
+
+
+def and_enter_settings():
+ """Dashboard -> Settings screen (gear, desc='Settings'). Counts one surface."""
+ return and_enter_surface(ui(), content_desc="Settings")
+
+
+def and_enter_phase_sheet():
+ """Active-fast card: tap the fasting-phase chip -> phase-detail bottom sheet.
+ The chip renders a phase-name TextView (its bounds overlay the Canvas that
+ owns the click). Proven: 'Timing' newly appears. Counts one surface."""
+ before = and_showing()
+ chip = None
+ for name in _PHASE_NAMES:
+ chip = find_node(ui(), text=name)
+ if chip:
+ break
+ if not chip or not tap_node(chip):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Timing"):
+ return False
+ and_enter("phase_sheet")
+ return True
+
+
+def and_enter_daily_details():
+ """History pane: tap a day cell that has a completed fast (desc='Goal Met')
+ -> the Daily-Details bottom sheet. Proven: a 'Details for ...' title appears.
+ Counts one surface (used at depth 2, after and_reach_history)."""
+ cell = find_node(ui(), content_desc="Goal Met")
+ if not cell or not tap_node(cell):
+ return False
+ if not any(_DETAILS.search(n.get("text", "") or "") for n in ui()):
+ return False
+ and_enter("daily_details")
+ return True
+
+
+def and_enter_history_info():
+ """History pane: tap the 'History Info' (i) icon -> the 'Understanding
+ History' bottom sheet. Proven: the sheet title appears. Counts one surface."""
+ info = find_node(ui(), content_desc="History Info")
+ if not info or not tap_node(info):
+ return False
+ if find_node(ui(), text="Understanding History") is None:
+ return False
+ and_enter("history_info")
+ return True
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (1) EMPTY-HISTORY COPY — the dashboard empty-state status line
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_empty_history_copy",))
+def test_empty_history_copy():
+ """On a CLEAN dashboard the History section shows the exact dynamic empty-state
+ copy 'No recent fasts to show.'. This is status text the app writes for the
+ empty state (not static chrome — it is replaced by a fast entry once one is
+ saved), so it is a strong produced-string TEXT assertion."""
+ open_main_clear()
+ nodes = ui()
+ if not _on_dashboard(nodes):
+ record("text_empty_history_copy", False,
+ "setup_failed: dashboard ('Set your goal') not shown after a clean "
+ "launch",
+ depth=0, jump_kind="value", expect="'No recent fasts to show.'")
+ return
+ ok = _has_text(nodes, "No recent fasts to show.")
+ record("text_empty_history_copy", bool(ok),
+ "" if ok else "feature_missing: the empty-history status copy 'No recent "
+ "fasts to show.' was not shown on a clean dashboard",
+ depth=0, jump_kind="value",
+ expect="History empty-state copy reads 'No recent fasts to show.'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (2) TIMER LABEL 'Remaining' — produced by starting a TIMED goal
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_label_remaining",))
+def test_label_remaining():
+ """Starting a TIMED goal ('Test 1 Hour') produces the active-fast card label
+ 'Remaining' (this lane asserts the LITERAL LABEL, not the countdown value which
+ computation owns). Assert it is ABSENT on the clean dashboard and PRESENT after
+ starting — the discriminating change, so a hardcoded label on a dead shell
+ cannot pass."""
+ open_main_clear()
+ absent = not _has_text(ui(), "Remaining")
+ started = _start_goal("Test 1 Hour")
+ if not started:
+ record("text_label_remaining", False,
+ "feature_missing: could not start the 'Test 1 Hour' timed goal "
+ "('End Fast' card not shown)",
+ depth=0, jump_kind="value",
+ expect="active-fast card label reads 'Remaining'")
+ return
+ present = _has_text(ui(), "Remaining")
+ ok = absent and present
+ record("text_label_remaining", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Remaining' label state was absent={absent} "
+ f"present-after={present}; expected absent before and present "
+ f"after starting a timed goal"),
+ depth=0, jump_kind="value",
+ expect="label 'Remaining' absent before, present after starting a timed goal")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (3) TIMER LABEL 'Elapsed Time' (+ NO 'End Time') — produced by Open Fast
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_label_elapsed_time",))
+def test_label_elapsed_time():
+ """Starting 'Open Fast' (infinite goal) produces the label 'Elapsed Time' and,
+ unlike a timed goal, NO 'End Time' line. Assert the label appears (absent before,
+ present after) AND that the 'End Time' label is not present — the copy that
+ distinguishes the open-goal card from a timed one."""
+ open_main_clear()
+ absent = not _has_text(ui(), "Elapsed Time")
+ started = _start_goal("Open Fast")
+ if not started:
+ record("text_label_elapsed_time", False,
+ "feature_missing: could not start 'Open Fast' ('End Fast' card not "
+ "shown)",
+ depth=0, jump_kind="value",
+ expect="label 'Elapsed Time' present, no 'End Time' line")
+ return
+ nodes = ui()
+ present = _has_text(nodes, "Elapsed Time")
+ no_end_time = find_node(nodes, text="End Time") is None
+ ok = absent and present and no_end_time
+ record("text_label_elapsed_time", bool(ok),
+ "" if ok else (f"behavior_wrong: 'Elapsed Time' absent={absent} "
+ f"present-after={present}; 'End Time' line present="
+ f"{not no_end_time} (Open Fast must show 'Elapsed Time' and "
+ f"no 'End Time')"),
+ depth=0, jump_kind="value",
+ expect="label 'Elapsed Time' appears and no 'End Time' line for Open Fast")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (4) GOAL-REACHED COPY — 'Goal Reached!' + label 'Total Time' (Test Timer ~10s)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_goal_reached_copy",))
+def test_goal_reached_copy():
+ """The 10-second debug 'Test Timer' authors goal-met COPY when its target is
+ met: the goal-name line flips to 'Goal Reached!' and the label becomes 'Total
+ Time'. Assert both literal strings are ABSENT while counting down and PRESENT
+ after ~10s (this lane owns the string CONTENT; the states lane owns the
+ transition bit). Generous bounded poll."""
+ open_main_clear()
+ started = _start_goal("Test Timer")
+ if not started:
+ record("text_goal_reached_copy", False,
+ "feature_missing: could not start 'Test Timer' ('End Fast' card not "
+ "shown)",
+ depth=0, jump_kind="value",
+ expect="'Goal Reached!' + label 'Total Time' appear")
+ return
+ before = ui()
+ absent = (find_node(before, text="Goal Reached!") is None
+ and find_node(before, text="Total Time") is None)
+ flipped = _wait_goal_reached()
+ after = ui()
+ present = (find_node(after, text="Goal Reached!") is not None
+ and find_node(after, text="Total Time") is not None)
+ ok = absent and flipped and present
+ record("text_goal_reached_copy", bool(ok),
+ "" if ok else (f"behavior_wrong: goal-met copy absent-before={absent} "
+ f"present-after={present}; expected 'Goal Reached!' and "
+ f"'Total Time' to appear once the Test Timer target is met"),
+ depth=0, jump_kind="value",
+ expect="'Goal Reached!' + label 'Total Time' absent before, present after "
+ "target met")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (5) FASTING PHASE-CHIP NAME — produced by an active fast
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_phase_chip_name",))
+def test_phase_chip_name():
+ """An active fast shows a fasting PHASE chip whose text is a phase name. Near
+ t=0 the phase is Post-Absorptive, so the chip reads 'Post-Absorptive State'.
+ Assert the chip text is one of the known phase names (OR across them for
+ robustness to elapsed time), ABSENT before the fast and PRESENT after."""
+ open_main_clear()
+ absent = not any(_has_text(ui(), p) for p in _PHASE_NAMES)
+ started = _start_goal("Test 1 Hour")
+ if not started:
+ record("text_phase_chip_name", False,
+ "feature_missing: could not start 'Test 1 Hour' to reveal the phase "
+ "chip",
+ depth=0, jump_kind="value",
+ expect="phase chip reads a phase name (e.g. 'Post-Absorptive State')")
+ return
+ nodes = ui()
+ shown = next((p for p in _PHASE_NAMES if _has_text(nodes, p)), None)
+ ok = absent and shown is not None
+ record("text_phase_chip_name", bool(ok),
+ "" if ok else (f"behavior_wrong: no known fasting-phase name on the active "
+ f"card (absent-before={absent}, shown={shown!r}); expected "
+ f"one of {_PHASE_NAMES}"),
+ depth=0, jump_kind="value",
+ expect=f"active-fast phase chip reads a phase name (saw {shown!r})")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (6) PHASE-DETAIL SHEET COPY — 'Timing' / 'Benefit' produced by tapping the chip
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_phase_sheet_labels",))
+def test_phase_sheet_labels():
+ """Tapping the fasting-phase chip on the active-fast card opens a phase-detail
+ bottom sheet with descriptive LABELS 'Timing' and 'Benefit'. Crosses one
+ surface (depth 1, backed by and_enter_phase_sheet, which proves 'Timing'
+ appeared) and asserts both literal labels — a strong produced-copy test."""
+ open_main_clear()
+ if not _start_goal("Test 1 Hour"):
+ record("text_phase_sheet_labels", False,
+ "setup_failed: could not start a fast to reach the phase chip",
+ depth=1, jump_kind="value",
+ expect="phase-detail sheet shows 'Timing' and 'Benefit' labels")
+ return
+ if not and_enter_phase_sheet(): # depth 1 (proven surface jump)
+ record("text_phase_sheet_labels", False,
+ "setup_failed: tapping the phase chip did not open the phase-detail "
+ "sheet",
+ depth=1, jump_kind="value",
+ expect="phase-detail sheet shows 'Timing' and 'Benefit' labels")
+ _end_active_no_save()
+ return
+ nodes = ui()
+ ok = _has_text(nodes, "Timing") and _has_text(nodes, "Benefit")
+ record("text_phase_sheet_labels", bool(ok),
+ "" if ok else "behavior_wrong: the phase-detail sheet did not show both "
+ "descriptive labels 'Timing' and 'Benefit'",
+ depth=1, jump_kind="value",
+ expect="phase-detail sheet shows the labels 'Timing' and 'Benefit'")
+ back()
+ settle("tap")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (7) FAST COMPLETE! SUMMARY COPY — produced by End Fast
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_fast_complete_copy",))
+def test_fast_complete_copy():
+ """Ending a fast (End Fast on the active card) opens a summary modal whose copy
+ is app-authored: title 'Fast Complete!', the prompt 'Rate your fast:', the
+ labels 'Started:' and 'Ended:', and a 'Save' button label. Crosses one surface
+ (depth 1, backed by and_enter) and asserts all five literal strings. End Fast
+ is non-destructive; the modal is dismissed without saving."""
+ open_main_clear()
+ if not _open_summary_from_test_timer():
+ record("text_fast_complete_copy", False,
+ "setup_failed: could not reach the 'Fast Complete!' summary (start "
+ "Test Timer -> End Fast)",
+ depth=1, jump_kind="value",
+ expect="summary shows 'Fast Complete!', 'Rate your fast:', 'Started:', "
+ "'Ended:', 'Save'")
+ return
+ and_enter("fast_complete_summary") # depth 1 (the End Fast modal)
+ nodes = ui()
+ want = ("Fast Complete!", "Rate your fast:", "Started:", "Ended:", "Save")
+ missing = [s for s in want if not _has_text(nodes, s)]
+ ok = not missing
+ record("text_fast_complete_copy", bool(ok),
+ "" if ok else f"behavior_wrong: the Fast Complete summary is missing copy "
+ f"{missing}",
+ depth=1, jump_kind="value",
+ expect="summary shows 'Fast Complete!' / 'Rate your fast:' / 'Started:' / "
+ "'Ended:' / 'Save'")
+ _end_active_no_save()
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (8) MANAGE-PROFILES EMPTY-FAVOURITE HINT + section headers
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_manage_profiles_hint",))
+def test_manage_profiles_hint():
+ """Opening 'Manage Profiles' from the Dashboard shows, when no favourite is set,
+ the hint 'Press and hold a profile to add it as your favourite' under the
+ 'Favourite Fast' section, alongside the 'Other Profiles' header. Crosses one
+ surface (depth 1, backed by and_enter_manage_profiles) and asserts the hint plus
+ both section headers — produced copy on the destination."""
+ open_main_clear()
+ ok_enter, note = and_enter_manage_profiles() # depth 1 (surface change proven)
+ if not ok_enter:
+ record("text_manage_profiles_hint", False,
+ note or "setup_failed: could not reach the Manage Profiles screen",
+ depth=1, jump_kind="value",
+ expect="hint 'Press and hold a profile to add it as your favourite'")
+ return
+ nodes = ui()
+ hint = _has_text(nodes, "Press and hold a profile to add it as your favourite")
+ fav = _has_text(nodes, "Favourite Fast")
+ other = _has_text(nodes, "Other Profiles")
+ ok = hint and fav and other
+ record("text_manage_profiles_hint", bool(ok),
+ "" if ok else (f"behavior_wrong: Manage Profiles copy — hint={hint}, "
+ f"'Favourite Fast'={fav}, 'Other Profiles'={other}; expected "
+ f"all three"),
+ depth=1, jump_kind="value",
+ expect="empty-favourite hint + 'Favourite Fast' + 'Other Profiles' headers")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (9) STATISTICS HEADER FLIP — 'This week' -> 'Last 30 days' (Weekly -> Monthly)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_stats_header_flip",))
+def test_stats_header_flip():
+ """The Statistics ('Performance') screen header reads 'This week' under the
+ Weekly segment; tapping the 'Monthly' segment flips the header text to 'Last 30
+ days'. Crosses one surface (depth 1, backed by and_reach_statistics) and asserts
+ the BEFORE->AFTER string change ('This week' present & 'Last 30 days' absent, ->
+ 'Last 30 days' present & 'This week' absent)."""
+ open_main_clear()
+ if not and_reach_statistics(): # depth 1 (proven reach)
+ record("text_stats_header_flip", False,
+ "setup_failed: could not reach the Statistics ('Performance') screen",
+ depth=1, jump_kind="transition",
+ expect="header 'This week' -> 'Last 30 days'")
+ return
+ before = ui()
+ week_before = (find_node(before, text="This week") is not None
+ and find_node(before, text="Last 30 days") is None)
+ monthly = find_node(before, text="Monthly")
+ if not monthly or not safe_tap(monthly):
+ record("text_stats_header_flip", False,
+ "setup_failed: 'Monthly' segment not found/tappable on Statistics",
+ depth=1, jump_kind="transition",
+ expect="header 'This week' -> 'Last 30 days'")
+ return
+ settle("tap")
+ after = ui()
+ month_after = (find_node(after, text="Last 30 days") is not None
+ and find_node(after, text="This week") is None)
+ ok = week_before and month_after
+ record("text_stats_header_flip", bool(ok),
+ "" if ok else (f"behavior_wrong: header did not flip — week_before="
+ f"{week_before}, month_after={month_after}; expected 'This "
+ f"week' -> 'Last 30 days' on Weekly->Monthly"),
+ depth=1, jump_kind="transition",
+ expect="Statistics header 'This week' -> 'Last 30 days' on Weekly->Monthly")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (10) STATISTICS EMPTY-STATE + STAT-CARD LABELS (produced copy on the destination)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_stats_labels",))
+def test_stats_labels():
+ """The Statistics screen shows the empty-state subtitle 'Keep going to build a
+ habit!' and the stat-card LABELS 'Total Fasts' / 'Average Fast' / 'Consistency'
+ with sub-labels 'completed' / 'this week' / 'goals met' (this lane asserts the
+ LABEL strings, never the numbers). Crosses one surface (depth 1, backed by
+ and_reach_statistics)."""
+ open_main_clear()
+ if not and_reach_statistics(): # depth 1 (proven reach)
+ record("text_stats_labels", False,
+ "setup_failed: could not reach the Statistics ('Performance') screen",
+ depth=1, jump_kind="value",
+ expect="stat-card labels 'Total Fasts'/'Average Fast'/'Consistency'")
+ return
+ nodes = ui()
+ want = ("Keep going to build a habit!", "Total Fasts", "Average Fast",
+ "Consistency", "completed", "this week", "goals met")
+ missing = [s for s in want if not _has_text(nodes, s)]
+ ok = not missing
+ record("text_stats_labels", bool(ok),
+ "" if ok else f"behavior_wrong: Statistics is missing label copy {missing}",
+ depth=1, jump_kind="value",
+ expect="subtitle 'Keep going to build a habit!' + stat labels Total Fasts/"
+ "Average Fast/Consistency + completed/this week/goals met")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (11) HISTORY MONTH HEADER CHANGE — 'August 2026' -> previous month
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_history_month_change",))
+def test_history_month_change():
+ """The History pane's month header reads a ' ' string (e.g. 'August
+ 2026'). Tapping 'Previous Month' advances the label to the prior month (Next
+ Month is disabled on the current month, so Previous is the observable change).
+ Crosses one surface (depth 1, backed by and_reach_history) and asserts the
+ header STRING CHANGED to a different, well-formed ' '."""
+ open_main_clear()
+ if not and_reach_history(): # depth 1 (proven reach)
+ record("text_history_month_change", False,
+ "setup_failed: could not reach the History pane",
+ depth=1, jump_kind="transition",
+ expect="month header ' ' changes after 'Previous Month'")
+ return
+
+ def _month_header(nodes):
+ return next((n.get("text", "").strip() for n in nodes
+ if _MONTH_YEAR.fullmatch(n.get("text", "").strip())), None)
+
+ before = _month_header(ui())
+ prev = find_node(ui(), content_desc="Previous Month")
+ if before is None or not prev or not tap_node(prev):
+ record("text_history_month_change", False,
+ f"setup_failed: month header ({before!r}) or 'Previous Month' control "
+ f"not usable",
+ depth=1, jump_kind="transition",
+ expect="month header ' ' changes after 'Previous Month'")
+ return
+ settle("tap")
+ after = _month_header(ui())
+ ok = (after is not None and after != before
+ and _MONTH_YEAR.fullmatch(after) is not None)
+ record("text_history_month_change", bool(ok),
+ "" if ok else (f"behavior_wrong: month header did not change on 'Previous "
+ f"Month' (before={before!r} after={after!r}); expected a "
+ f"different ' ' string"),
+ depth=1, jump_kind="transition",
+ expect=f"month header changed '{before}' -> '{after}' via 'Previous Month'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (12) HISTORY-INFO SHEET COPY — 'Understanding History' + legend
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_history_info_sheet",))
+def test_history_info_sheet():
+ """The History toolbar's 'History Info' (i) icon opens a bottom sheet titled
+ 'Understanding History' with legend copy ('Calendar View', 'Daily Timeline').
+ Crosses TWO surfaces (History pane, then the info sheet) — depth 2, backed by
+ and_reach_history + and_enter_history_info — and asserts the sheet's literal
+ title and legend labels."""
+ open_main_clear()
+ if not and_reach_history(): # depth 1 (proven reach)
+ record("text_history_info_sheet", False,
+ "setup_failed: could not reach the History pane",
+ depth=2, jump_kind="value",
+ expect="sheet 'Understanding History' + legend 'Calendar View'")
+ return
+ if not and_enter_history_info(): # depth 2 (proven: title appeared)
+ record("text_history_info_sheet", False,
+ "setup_failed: tapping 'History Info' did not open the 'Understanding "
+ "History' sheet",
+ depth=2, jump_kind="value",
+ expect="sheet 'Understanding History' + legend 'Calendar View'")
+ return
+ nodes = ui()
+ title = _has_text(nodes, "Understanding History")
+ legend = _has_text(nodes, "Calendar View") and _has_text(nodes, "Daily Timeline")
+ ok = title and legend
+ record("text_history_info_sheet", bool(ok),
+ "" if ok else (f"behavior_wrong: History-Info sheet copy — title={title}, "
+ f"legend('Calendar View'+'Daily Timeline')={legend}"),
+ depth=2, jump_kind="value",
+ expect="History-Info sheet 'Understanding History' + 'Calendar View' + "
+ "'Daily Timeline'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (13) DAILY-DETAILS SHEET TITLE — 'Details for ' produced by a tap
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_daily_details_title",))
+def test_daily_details_title():
+ """After saving one Test Timer fast, tapping today's day cell (desc='Goal Met')
+ in History opens a Daily-Details bottom sheet whose title is 'Details for
+ ' (the app derives the day from the device clock, asserted via a
+ tight regex on the STRING shape, not a hardcoded day). Crosses TWO surfaces
+ (History pane, then the day sheet) — depth 2, backed by and_reach_history +
+ and_enter_daily_details."""
+ open_main_clear()
+ if not _save_test_timer_fast():
+ record("text_daily_details_title", False,
+ "setup_failed: could not complete+Save a Test Timer fast (needed so a "
+ "day cell has data)",
+ depth=2, jump_kind="value",
+ expect="Daily-Details sheet title matches 'Details for '")
+ return
+ if not and_reach_history(): # depth 1 (proven reach)
+ record("text_daily_details_title", False,
+ "setup_failed: could not reach the History pane after saving a fast",
+ depth=2, jump_kind="value",
+ expect="Daily-Details sheet title matches 'Details for '")
+ return
+ if not and_enter_daily_details(): # depth 2 (proven: title appeared)
+ record("text_daily_details_title", False,
+ "setup_failed: tapping the day-with-data cell did not open the Daily-"
+ "Details sheet",
+ depth=2, jump_kind="value",
+ expect="Daily-Details sheet title matches 'Details for '")
+ return
+ nodes = ui()
+ title = next((n.get("text", "") for n in nodes
+ if _DETAILS.search(n.get("text", "") or "")), None)
+ ok = title is not None
+ record("text_daily_details_title", bool(ok),
+ "" if ok else "behavior_wrong: the Daily-Details sheet title did not match "
+ "'Details for '",
+ depth=2, jump_kind="value",
+ expect=f"Daily-Details title matches 'Details for ' (saw "
+ f"{title!r})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (14) SETTINGS SECTION HEADERS — produced copy on the Settings destination
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_settings_headers",))
+def test_settings_headers():
+ """The Settings screen shows literal section headers: 'Appearance', 'Color
+ Scheme', 'Notifications', 'Data Management'. Crosses one surface (depth 1, backed
+ by and_enter_settings) and asserts these are copy on the DESTINATION (not home
+ chrome). 'Appearance'/'Color Scheme' are at the top; 'Notifications'/'Data
+ Management' are reached by scrolling within Settings."""
+ open_main_clear()
+ ok_enter, note = and_enter_settings() # depth 1 (surface change proven)
+ if not ok_enter:
+ record("text_settings_headers", False,
+ note or "setup_failed: could not reach the Settings screen",
+ depth=1, jump_kind="value",
+ expect="section headers Appearance/Color Scheme/Notifications/Data "
+ "Management")
+ return
+ top = ui()
+ have_top = _has_text(top, "Appearance") and _has_text(top, "Color Scheme")
+ # Scroll within Settings to bring the lower section headers into view.
+ scroll_into_view("Data Management", max_swipes=6)
+ low = ui()
+ have_low = _has_text(low, "Notifications") and _has_text(low, "Data Management")
+ ok = have_top and have_low
+ record("text_settings_headers", bool(ok),
+ "" if ok else (f"behavior_wrong: Settings headers — top(Appearance+Color "
+ f"Scheme)={have_top}, lower(Notifications+Data Management)="
+ f"{have_low}"),
+ depth=1, jump_kind="value",
+ expect="Settings shows headers 'Appearance'/'Color Scheme'/'Notifications'/"
+ "'Data Management'")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+# (15) SETTINGS FOOTER VERSION STRING — app-authored copy (regex, no computed value)
+# ═══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_settings_version",))
+def test_settings_version():
+ """The Settings footer shows the app-authored version literal, matching
+ '\\d+\\.\\d+\\.\\d+-DEBUG \\(\\d+\\)' (e.g. '1.0.4-DEBUG (5)'), next to the
+ 'Fast Times' footer label. This is copy the app renders — the observation is
+ that the string is PRESENT; NO computed value is derived from it. A regex keeps
+ it stable across a version bump while still asserting the string shape. Crosses
+ one surface (depth 1, backed by and_enter_settings) and scrolls to the footer."""
+ open_main_clear()
+ ok_enter, note = and_enter_settings() # depth 1 (surface change proven)
+ if not ok_enter:
+ record("text_settings_version", False,
+ note or "setup_failed: could not reach the Settings screen",
+ depth=1, jump_kind="value",
+ expect="footer version matches '\\d+.\\d+.\\d+-DEBUG (\\d+)'")
+ return
+ # The version footer is at the very bottom of the Settings list.
+ seen = None
+ for _ in range(10):
+ nodes = ui()
+ seen = next((n.get("text", "") for n in nodes
+ if _VERSION.search(n.get("text", "") or "")), None)
+ if seen:
+ break
+ scroll_down(0.7)
+ ok = seen is not None
+ record("text_settings_version", bool(ok),
+ "" if ok else "feature_missing: no version footer matching "
+ "'\\d+.\\d+.\\d+-DEBUG (\\d+)' was found in Settings",
+ depth=1, jump_kind="value",
+ expect=f"Settings footer version matches '\\d+.\\d+.\\d+-DEBUG (\\d+)' "
+ f"(saw {seen!r})")
+
+
+# ═══════════════════════════════════════════════════════════════════════════════
+TESTS = [
+ test_empty_history_copy,
+ test_label_remaining,
+ test_label_elapsed_time,
+ test_goal_reached_copy,
+ test_phase_chip_name,
+ test_phase_sheet_labels,
+ test_fast_complete_copy,
+ test_manage_profiles_hint,
+ test_stats_header_flip,
+ test_stats_labels,
+ test_history_month_change,
+ test_history_info_sheet,
+ test_daily_details_title,
+ test_settings_headers,
+ test_settings_version,
+]
+
+if __name__ == "__main__":
+ if not device_online():
+ print("setup_failed: device offline / adb tunnel down — aborting")
+ sys.exit(2)
+ run_suite(TESTS, "text")
diff --git a/android/tom-murphy-development-fasttimes/tests/test_manifest.json b/android/tom-murphy-development-fasttimes/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..7bc3a71ac9ac9c7e4d78f7b41c926028a74064c6
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/tests/test_manifest.json
@@ -0,0 +1,737 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "FastTimes",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 112,
+ "manifest_sha": "1fdb6c873db6",
+ "tests": [
+ {
+ "name": "computation::computation_countdown_decreases",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_countup_increases",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_duration_format",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_end_time_offset",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_fasts_count_two",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_fasts_count_zero",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_fasts_count_zero_to_one",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_goal_reached_transition",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_goal_reached_transition_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_history_summary_total_one",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_stats_chart_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_stats_consistency_100",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_stats_total_fasts_one",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_stats_total_fasts_one_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_timer_initial_10s",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_timer_initial_10s_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_timer_start_eq_end",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_active_fast_survives",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_active_fast_survives_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_fast_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_fast_persists_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_profile",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_profile_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_menu",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_menu_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_set_favourite",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_set_favourite_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rating_in_daily_details",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rating_in_daily_details_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rating_in_edit_fast",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_rating_in_edit_fast_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_back_history",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_back_profiles",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_back_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_back_statistics",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_backstack_accent",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_backstack_deep",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_history_back_arrow",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_accent_color",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_accent_color_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_daily_details",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_daily_details_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_edit_fast",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_edit_fast_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_history",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_history_info",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_history_info_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_history_swipe",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_history_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_phase_sheet",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_profiles",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_statistics",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_reach_statistics_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::navigation_stats_to_history",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_accent_selected",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_alltime_expand",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_expressive_theme_switch",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_favourite_checkbox",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_first_day_of_week",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_first_day_of_week_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_save_conditional_enable",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_speed_dial_expand",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_speed_dial_expand_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_stats_monthly_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_stats_weekly_back",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_expressive_progress",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_fab_consequence",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_fasting_phases",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_persists_relaunch",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_trends_all_time",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_active_fast_ring_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_active_fast_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_add_profile_dialog",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_add_profile_dialog_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_dashboard_fab_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_dashboard_to_profiles",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_fab_speeddial_expand",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_fab_speeddial_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_dashboard_surfaces",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_goal_grid",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_goal_grid_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_history_calendar",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_history_grid_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_history_summary_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_profiles_grid_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_rows",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_scroll_reveal",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_toggles_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_statistics_containers",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_statistics_expand",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_cards_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_chart_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_daily_details_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_empty_history_copy",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_fast_complete_copy",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_goal_reached_copy",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_history_info_sheet",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_history_month_change",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_label_elapsed_time",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_label_remaining",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_manage_profiles_hint",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_phase_chip_name",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_phase_sheet_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_version",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_header_flip",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_stats_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_test_timer_initial_10s_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_goal_reached_transition_vlm",
+ "module": "computation",
+ "tag": "color"
+ },
+ {
+ "name": "computation::computation_stats_total_fasts_one_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "computation::computation_stats_chart_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_create_fast_persists_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_rating_in_daily_details_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_rating_in_edit_fast_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_longpress_menu_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_longpress_set_favourite_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_create_profile_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_active_fast_survives_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::navigation_reach_statistics_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::navigation_reach_history_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::navigation_reach_accent_color_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::navigation_reach_history_info_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::navigation_reach_daily_details_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::navigation_reach_edit_fast_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_first_day_of_week_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_speed_dial_expand_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_theme_dark_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_dashboard_fab_vlm",
+ "module": "structure",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_goal_grid_layout_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_fab_speeddial_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_active_fast_ring_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_profiles_grid_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_add_profile_dialog_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_settings_toggles_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_stats_cards_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_stats_chart_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_history_grid_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_history_summary_vlm",
+ "module": "structure",
+ "tag": "shape"
+ }
+ ],
+ "vlm_total": 32,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/tom-murphy-development-fasttimes/vlm_assertions.json b/android/tom-murphy-development-fasttimes/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..a1fc9bb63ba5d36acfe7146766f53c446d895440
--- /dev/null
+++ b/android/tom-murphy-development-fasttimes/vlm_assertions.json
@@ -0,0 +1,663 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/tom-murphy-development-fasttimes",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 32,
+ "with_verdict": 32,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 32,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "navigation_reach_statistics_vlm",
+ "screenshot": "navigation_reach_statistics_vlm.png",
+ "assertion": "Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels (like T F S S M T W)? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "navigation_reach_statistics",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "navigation_reach_history_vlm",
+ "screenshot": "navigation_reach_history_vlm.png",
+ "assertion": "Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "navigation_reach_history",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "navigation_reach_accent_color_vlm",
+ "screenshot": "navigation_reach_accent_color_vlm.png",
+ "assertion": "Under an 'Accent Color' heading, is there a grid of multiple small circular color swatches? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "navigation_reach_accent_color",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "navigation_reach_history_info_vlm",
+ "screenshot": "navigation_reach_history_info_vlm.png",
+ "assertion": "Is a titled information panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge with a small drag handle at its top)? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "navigation_reach_history_info",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "navigation_reach_daily_details_vlm",
+ "screenshot": "navigation_reach_daily_details_vlm.png",
+ "assertion": "Is a titled details panel presented over the lower portion of the screen as a bottom sheet (a rounded panel rising from the bottom edge), with the dimmed calendar visible above it? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "navigation_reach_daily_details",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "navigation_reach_edit_fast_vlm",
+ "screenshot": "navigation_reach_edit_fast_vlm.png",
+ "assertion": "Is there an 'Edit Fast' dialog shown as a rounded rectangular card floating in the center of the screen (with 'Cancel' and 'Save' buttons), rather than attached to the bottom edge? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "navigation_reach_edit_fast",
+ "rigor": {
+ "jump_kind": "reach",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_create_fast_persists_vlm",
+ "screenshot": "interaction_create_fast_persists_vlm.png",
+ "assertion": "After the app was restarted, does the 'History' section near the bottom of the dashboard list a completed fast entry (a duration like '0h 2m' under a 'This Week' heading with a green check icon) rather than an empty 'No recent fasts' message? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_create_fast_persists",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_multi_record_integrity_vlm",
+ "screenshot": "interaction_multi_record_integrity_vlm.png",
+ "assertion": "Does the 'History' section of the dashboard show at least one completed fast entry with a duration value and a green check icon (i.e. it is NOT the empty 'No recent fasts to show.' state)? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_multi_record_integrity",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_rating_in_daily_details_vlm",
+ "screenshot": "interaction_rating_in_daily_details_vlm.png",
+ "assertion": "In this daily-details panel, does the fast entry (labelled 'Test Timer', duration '0h 2m') show a rating of exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_rating_in_daily_details",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_rating_in_edit_fast_vlm",
+ "screenshot": "interaction_rating_in_edit_fast_vlm.png",
+ "assertion": "In this 'Edit Fast' dialog, does the 'Rating' row show exactly 4 filled/coloured stars followed by 1 empty outline star? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_rating_in_edit_fast",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_longpress_menu_vlm",
+ "screenshot": "interaction_longpress_menu_vlm.png",
+ "assertion": "Is exactly one fasting-profile card outlined/highlighted with a coloured border that is distinct from the other cards' borders? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_longpress_menu",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_longpress_set_favourite_vlm",
+ "screenshot": "interaction_longpress_set_favourite_vlm.png",
+ "assertion": "Under the 'Favourite Fast' heading (above 'Other Profiles'), is there now a fasting-profile card, rather than only the grey hint text 'Press and hold a profile to add it as your favourite'? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "interaction_longpress_set_favourite",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_create_profile_vlm",
+ "screenshot": "interaction_create_profile_vlm.png",
+ "assertion": "Is there a fasting-profile card whose title text reads 'kitprofZ' in the profiles grid? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_create_profile",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_active_fast_survives_vlm",
+ "screenshot": "interaction_active_fast_survives_vlm.png",
+ "assertion": "Is there a circular ring or arc drawn around a large running timer near the top-centre of the screen (an active fast still in progress), rather than a grid of goal-selection cells? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_active_fast_survives",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_test_timer_initial_10s_vlm",
+ "screenshot": "computation_test_timer_initial_10s_vlm.png",
+ "assertion": "Is a large timer value (like 00:00:10) shown in the centre of the card with a coloured circular progress ring or arc drawn around it? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_test_timer_initial_10s",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_goal_reached_transition_vlm",
+ "screenshot": "computation_goal_reached_transition_vlm.png",
+ "assertion": "Is a fully-closed bright green circular ring drawn all the way around the timer (indicating the fasting goal was reached), rather than a partially-filled arc? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "computation_goal_reached_transition",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_stats_total_fasts_one_vlm",
+ "screenshot": "computation_stats_total_fasts_one_vlm.png",
+ "assertion": "Do the three rounded statistic cards near the bottom each show a large numeric value under their title (for example a whole number under 'Total Fasts' and a percentage under 'Consistency')? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "computation_stats_total_fasts_one",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_stats_chart_vlm",
+ "screenshot": "computation_stats_chart_vlm.png",
+ "assertion": "Are there several coloured bars drawn in a row above the day/date axis labels (like T F S S M T W), representing a chart of values? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_stats_chart",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_first_day_of_week_vlm",
+ "screenshot": "states_first_day_of_week_vlm.png",
+ "assertion": "In the 'First Day of Week' Sun/Mon toggle, is the 'Sun' option the one drawn with the filled/highlighted selection background (the selected pill), rather than 'Mon'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_first_day_of_week",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_speed_dial_expand_vlm",
+ "screenshot": "states_speed_dial_expand_vlm.png",
+ "assertion": "Are there smaller circular action buttons fanned out vertically just above the main round hourglass button in the bottom-right corner (an expanded speed-dial menu)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_speed_dial_expand",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_dark_vlm",
+ "screenshot": "states_theme_dark_vlm.png",
+ "assertion": "Is the whole app screen background a dark near-black colour with light/white text (a dark theme), rather than a white/light background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_dark",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_dashboard_fab_vlm",
+ "screenshot": "structure_dashboard_fab_vlm.png",
+ "assertion": "Is there a green colored button in the bottom-right corner of the screen containing a small dark icon? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "structure_dashboard_fab",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_goal_grid_layout_vlm",
+ "screenshot": "structure_goal_grid_layout_vlm.png",
+ "assertion": "Under the 'Set your goal' heading, are the goal cells arranged in a grid with exactly two columns per row? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_goal_grid_layout",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_fab_speeddial_vlm",
+ "screenshot": "structure_fab_speeddial_vlm.png",
+ "assertion": "Are there two green pill-shaped action buttons stacked vertically directly above the round green button in the bottom-right corner? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_fab_speeddial",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_active_fast_ring_vlm",
+ "screenshot": "structure_active_fast_ring_vlm.png",
+ "assertion": "Is there a circular ring or arc drawn around the countdown timer numbers near the top-center of the screen? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_active_fast_ring",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_profiles_grid_vlm",
+ "screenshot": "structure_profiles_grid_vlm.png",
+ "assertion": "Under the 'Other Profiles' heading, are multiple fasting-profile cards arranged in a two-column grid? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_profiles_grid",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_add_profile_dialog_vlm",
+ "screenshot": "structure_add_profile_dialog_vlm.png",
+ "assertion": "Is there a rounded rectangular dialog card overlaid on the screen that contains three empty text input boxes stacked vertically with a 'Cancel' and 'Save' button below them? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_add_profile_dialog",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_settings_toggles_vlm",
+ "screenshot": "structure_settings_toggles_vlm.png",
+ "assertion": "Does the Settings screen show setting rows with pill-shaped toggle switches aligned to the right side of the rows? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_settings_toggles",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_stats_cards_vlm",
+ "screenshot": "structure_stats_cards_vlm.png",
+ "assertion": "Are the three statistics cards ('Total Fasts', 'Average Fast', 'Consistency') drawn as non-rectangular blob/pentagon/scalloped shapes rather than plain rectangles? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_stats_cards",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_stats_chart_vlm",
+ "screenshot": "structure_stats_chart_vlm.png",
+ "assertion": "Is there a horizontal row of bar-chart segments drawn above a row of single-letter day-of-week axis labels? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_stats_chart",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_history_grid_vlm",
+ "screenshot": "structure_history_grid_vlm.png",
+ "assertion": "Is there a monthly calendar laid out as a grid of numbered day cells in seven columns, with a row of weekday letters above it? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_history_grid",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_history_summary_vlm",
+ "screenshot": "structure_history_summary_vlm.png",
+ "assertion": "Below the calendar, does the 'August Summary' section show three non-rectangular stat cards positioned side by side in one row? Answer YES or NO.",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_history_summary",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/LICENSE b/android/tristinbaker-idlefantasy/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..810fce6e9bf2aa10265b85614db5ac65941ecf81
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/LICENSE
@@ -0,0 +1,621 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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
diff --git a/android/tristinbaker-idlefantasy/instance.json b/android/tristinbaker-idlefantasy/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..e86cbb46b0912c4a01f2f64a54646e5524490c21
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/tristinbaker-idlefantasy",
+ "platform": "android",
+ "repo": "https://github.com/tristinbaker/idlefantasy",
+ "commit": "f1cab31f69de01ea95bf1e5e8cce96cdd00fd44c",
+ "patches": [],
+ "package": "com.tristinbaker.idlefantasy",
+ "license": null
+}
diff --git a/android/tristinbaker-idlefantasy/reference/launch.sh b/android/tristinbaker-idlefantasy/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/tristinbaker-idlefantasy/tests/android_computation_eval.json b/android/tristinbaker-idlefantasy/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..87e1aaf13f3569029e81952cda99f5ad1e468f8e
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_computation_eval.json
@@ -0,0 +1,187 @@
+{
+ "module": "computation",
+ "total": 17,
+ "passed": 17,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 15,
+ "passed": 15,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1333,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 17,
+ "depth_ge1": 16,
+ "depth_ge2": 15,
+ "value": 17,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "computation_skill_level1_progress",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Mining shows '0 / 83 XP'"
+ },
+ {
+ "test": "computation_activity_session_length",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "sheet shows 'Session: 60m'"
+ },
+ {
+ "test": "computation_activity_ores_per_session",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "sheet shows '~60 ores/session'"
+ },
+ {
+ "test": "computation_activity_rune_xp_rate",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Rune Essence rate '15 XP/ore' at Lv. 1"
+ },
+ {
+ "test": "computation_activity_rune_projection",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "projection '+900 XP → Level 8'"
+ },
+ {
+ "test": "computation_activity_copper_projection",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "projection '+1,080 XP → Level 9'"
+ },
+ {
+ "test": "computation_confirm_dialog_xp_rate",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "confirm dialog '15 XP/ore' at Lv. 1"
+ },
+ {
+ "test": "computation_home_card_projection",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "home card '+900 XP → Lv 8 (+7, 58%)'"
+ },
+ {
+ "test": "computation_reward_xp_gained",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "reward modal '+900 XP'"
+ },
+ {
+ "test": "computation_reward_ore_count",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "loot 'Rune Essence ×60'"
+ },
+ {
+ "test": "computation_total_level_after_collect",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Home Total Level == 30 after collect"
+ },
+ {
+ "test": "computation_total_level_delta",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Total Level 23 -> 30 (delta +7)"
+ },
+ {
+ "test": "computation_mining_level_after_collect",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Mining Level == 8 after collect"
+ },
+ {
+ "test": "computation_mining_xp_after_collect",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Mining shows '900 / 969 XP' after collect"
+ },
+ {
+ "test": "computation_no_active_session_baseline",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "fresh Home: Total Level 23, no '+900 XP', 'No Active Session'"
+ },
+ {
+ "test": "computation_mining_xp_bar_vlm",
+ "passed": true,
+ "message": "VLM: Q='The 'Mining' skill row shows '900 / 969 XP'. Is its horizontal progress bar rendered almost completely filled (roughly 90% or more of its width), noticeably fuller than the empty bars of the other level-1 skills below it?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: The 'Mining' skill row shows '900 / 969 XP'. Is its horizontal progress bar rendered almost completely filled (roughly 90% or more of its width), noticeably fuller than the empty bars of the other level-1 skills below it?",
+ "tag": "size"
+ },
+ {
+ "test": "computation_home_projection_badge_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the active session card at the top of the Home screen, is the text '+900 XP' rendered together with a level target '8' on the same highlighted line (an XP-to-level projection), positioned directly below the session countdown timer?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the active session card at the top of the Home screen, is the text '+900 XP' rendered together with a level target '8' on the same highlighted line (an XP-to-level projection), positioned directly below the session countdown timer?",
+ "tag": "position"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/android_interaction_eval.json b/android/tristinbaker-idlefantasy/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..493fb0f9a029f1582234fdf7b46e30dc9eca7b3b
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_interaction_eval.json
@@ -0,0 +1,122 @@
+{
+ "module": "interaction",
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 0,
+ "passed": 0,
+ "failed": 0,
+ "pass_rate": 0
+ },
+ "vlm_ratio": 0.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 10,
+ "depth_ge1": 10,
+ "depth_ge2": 7,
+ "value": 0,
+ "vlm_fine": 0
+ },
+ "results": [
+ {
+ "test": "interaction_core_loop_sequence",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "active session -> Finish Now -> Collect surfaces the reward modal ('XP gained' + 'Loot') — the sequence completed"
+ },
+ {
+ "test": "interaction_collect_mutates_total_level",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Home Total Level 23 -> 30 after start+finish+collect+close"
+ },
+ {
+ "test": "interaction_collect_adds_inventory",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Inventory has NO 'Rune Essence' before -> a 'Rune Essence' row present after collecting the Mining session"
+ },
+ {
+ "test": "interaction_skill_level_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Skills Mining row '0 / 83 XP' (Lv 1) -> '900 / 969 XP' (Lv 8) after the session is collected"
+ },
+ {
+ "test": "interaction_session_survives_process_death",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Session Active' + 'Mining — Rune Essence' still present on Skills after force_stop_and_relaunch()"
+ },
+ {
+ "test": "interaction_abandon_clears_session",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "active session -> Abandon -> Confirm -> Home 'No Active Session' and Skills no longer shows 'Session Active'"
+ },
+ {
+ "test": "interaction_start_cancel_no_session",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Choose Activity -> Start Session -> Cancel -> BACK: NO 'Session Active', Mining still '0 / 83 XP'"
+ },
+ {
+ "test": "interaction_second_session_starts",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "after collect ('No Active Session') a NEW Mining/Rune Essence session starts -> 'Session Active' + 'Mining — Rune Essence'"
+ },
+ {
+ "test": "interaction_switch_active_skill",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "active 'Mining — Rune Essence' -> abandon -> start Fishing: active session now 'Fishing — Raw Shrimp', Mining one gone"
+ },
+ {
+ "test": "interaction_recent_activity_logs_session",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Recent Activity 'No sessions completed yet.' before -> a 'Mining'/'Rune Essence' entry present after collecting the session"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/android_navigation_eval.json b/android/tristinbaker-idlefantasy/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..9247ab350ad63467bff762e684a396e8620eeeae
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_navigation_eval.json
@@ -0,0 +1,300 @@
+{
+ "module": "navigation",
+ "total": 29,
+ "passed": 29,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 22,
+ "passed": 22,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3182,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 7,
+ "liveness": 0,
+ "interactive": 22,
+ "depth_ge1": 22,
+ "depth_ge2": 5,
+ "value": 0,
+ "vlm_fine": 5
+ },
+ "results": [
+ {
+ "test": "nav_reach_skills",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Skills surface ('Expeditions') shown; Home 'Welcome back, Adventurer!' no longer showing"
+ },
+ {
+ "test": "nav_reach_combat",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Combat surface ('Combat Lvl 1') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_quests",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Quests surface ('Resets at 6:00 AM') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_profile",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Profile surface ('Unnamed Adventurer') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_home_from_profile",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Home 'Welcome back, Adventurer!' shown; Profile 'Unnamed Adventurer' no longer showing"
+ },
+ {
+ "test": "nav_reach_skills_to_combat",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Combat surface ('Combat Lvl 1') shown; Skills 'Expeditions' gone"
+ },
+ {
+ "test": "nav_reach_shop",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Shop surface ('Sell' sub-tab) shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_inn",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Inn surface ('Daily Menu') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_guild_hall",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Guild Hall surface ('0 / 500 rep') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_church",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Church surface ('XP Blessings') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_carnival",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Carnival surface ('Tickets: 0') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_slayer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Slayer surface ('Get New Task') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_builders",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Builder's Workshop surface ('Next Upgrade') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings surface ('Theme') shown; Home 'Welcome back' gone"
+ },
+ {
+ "test": "nav_backstack_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After one BACK: Home 'Welcome back, Adventurer!' restored; Settings 'Theme' no longer showing"
+ },
+ {
+ "test": "nav_backstack_shop",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "After one BACK: Home 'Welcome back, Adventurer!' restored; Shop 'Sell' no longer showing"
+ },
+ {
+ "test": "nav_cross_shop_to_skills",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Skills surface ('Expeditions') shown from Shop; Shop 'Sell' gone"
+ },
+ {
+ "test": "nav_depth2_choose_activity",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Choose Activity' sheet shown after Skills->Mining; the Skills list anchor 'Expeditions' no longer the top surface"
+ },
+ {
+ "test": "nav_depth2_dungeon_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Dungeon sheet ('Enter Dungeon') shown after Combat->Farm; the Combat list anchor 'Combat Lvl 1' no longer the top surface"
+ },
+ {
+ "test": "nav_depth2_guild_detail",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Guild detail ('Daily Requests') shown after Guild Hall->Mining Guild; the guild-list row 'Fishing Guild' no longer showing"
+ },
+ {
+ "test": "nav_depth2_bestiary_bosses",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Bosses sub-tab list ('King Black Dragon') shown within Bestiary; the Enemies row 'Abyssal Leech' no longer showing"
+ },
+ {
+ "test": "nav_backstack_2hop_guild",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "BACK#1 pops to the intermediate guild list ('Fishing Guild' shown, Home not yet); BACK#2 restores Home ('Welcome back, Adventurer!', guild list gone)"
+ },
+ {
+ "test": "nav_settings_back_arrow_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a left-pointing back/up arrow icon at the very top-left of the screen, to the left of the 'Settings' title?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a left-pointing back/up arrow icon at the very top-left of the screen, to the left of the 'Settings' title?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_shop_toggle_vlm",
+ "passed": true,
+ "message": "VLM: Q='Near the top of the screen, are there exactly two side-by-side segmented tabs labelled 'Buy' and 'Sell', with one underlined/highlighted as selected?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Near the top of the screen, are there exactly two side-by-side segmented tabs labelled 'Buy' and 'Sell', with one underlined/highlighted as selected?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_selected_tab_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the bottom navigation bar of 5 tabs, is exactly ONE tab visually highlighted with a distinct coloured background/pill behind its icon, different from the other four?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the bottom navigation bar of 5 tabs, is exactly ONE tab visually highlighted with a distinct coloured background/pill behind its icon, different from the other four?",
+ "tag": "color"
+ },
+ {
+ "test": "nav_combat_dungeon_rows_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the main content a vertical stack of dungeon rows where each row shows a level label like 'Lv. 1' aligned to the right edge?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the main content a vertical stack of dungeon rows where each row shows a level label like 'Lv. 1' aligned to the right edge?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_church_activate_cards_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under an 'XP Blessings' heading, is there a vertical list of blessing rows/cards, the first of which has an 'Activate' button on its right?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under an 'XP Blessings' heading, is there a vertical list of blessing rows/cards, the first of which has an 'Activate' button on its right?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_choose_activity_sheet_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a bottom-sheet panel with rounded top corners and a small horizontal drag handle overlaying the lower portion of the screen, sitting above the dimmed content behind it?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a bottom-sheet panel with rounded top corners and a small horizontal drag handle overlaying the lower portion of the screen, sitting above the dimmed content behind it?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_profile_rail_vlm",
+ "passed": true,
+ "message": "VLM: Q='Down the LEFT side of the screen, is there a vertical column/rail of stacked section labels (such as Skills, Inventory, Gear, Pets), with one of them highlighted?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Down the LEFT side of the screen, is there a vertical column/rail of stacked section labels (such as Skills, Inventory, Gear, Pets), with one of them highlighted?",
+ "tag": "position"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/android_states_eval.json b/android/tristinbaker-idlefantasy/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..d008978f6e7c2d544dc245694f29a211523b6fa8
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_states_eval.json
@@ -0,0 +1,154 @@
+{
+ "module": "states",
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.625,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 13,
+ "depth_ge1": 13,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "states_recent_activity_log_thumb_off_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the 'Recent Activity Log' row's toggle switch. Is its thumb on the LEFT side and grey/uncoloured (the OFF position)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the 'Recent Activity Log' row's toggle switch. Is its thumb on the LEFT side and grey/uncoloured (the OFF position)?",
+ "tag": "position"
+ },
+ {
+ "test": "states_recent_activity_log_flip",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Recent Activity Log checked: True->False->True (two-way)"
+ },
+ {
+ "test": "states_recent_activity_consequence",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "switch True->False; Home 'Recent Activity' button showing->hidden"
+ },
+ {
+ "test": "states_recent_activity_log_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Recent Activity Log checked stays False after force-stop+relaunch"
+ },
+ {
+ "test": "states_theme_light_chip_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the Theme segmented control [Dark | Light | System], is the 'Light' chip the one with the filled/highlighted background (the selected chip), rather than 'Dark'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the Theme segmented control [Dark | Light | System], is the 'Light' chip the one with the filled/highlighted background (the selected chip), rather than 'Dark'?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_dark_to_light",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme: Dark checked True->False, Light False->True"
+ },
+ {
+ "test": "states_theme_system_select",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme: System checked False->True, Dark & Light forced False"
+ },
+ {
+ "test": "states_theme_persist_background_vlm",
+ "passed": true,
+ "message": "VLM: Q='After the app was fully restarted, is the app background LIGHT (white / very light) with dark text, i.e. the light theme was remembered rather than reverting to the dark theme?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: After the app was fully restarted, is the app background LIGHT (white / very light) with dark text, i.e. the light theme was remembered rather than reverting to the dark theme?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Theme=Light checked stays True after force-stop+relaunch"
+ },
+ {
+ "test": "states_profile_layout_tabs_chip_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the Profile Layout segmented control [Rail | Tabs], is the 'Tabs' chip now the one with the filled/highlighted background (selected), rather than 'Rail'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the Profile Layout segmented control [Rail | Tabs], is the 'Tabs' chip now the one with the filled/highlighted background (selected), rather than 'Rail'?",
+ "tag": "color"
+ },
+ {
+ "test": "states_profile_layout_rail_to_tabs",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Profile Layout: Rail checked True->False, Tabs False->True"
+ },
+ {
+ "test": "states_profile_layout_tabs_screen_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this Profile screen, are the section labels (Skills, Inventory, Gear, ...) laid out as a HORIZONTAL row of tabs across the TOP, rather than as a vertical rail of icons down the LEFT edge?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this Profile screen, are the section labels (Skills, Inventory, Gear, ...) laid out as a HORIZONTAL row of tabs across the TOP, rather than as a vertical rail of icons down the LEFT edge?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_profile_layout_consequence",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Rail: Inventory chip x~100 (left rail) -> Tabs: x~354 (top row)"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/android_structure_eval.json b/android/tristinbaker-idlefantasy/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..0c26314e7e3a15c9f7523c888e08628fddf403bb
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_structure_eval.json
@@ -0,0 +1,221 @@
+{
+ "module": "structure",
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 11,
+ "passed": 11,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.8182,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 11,
+ "liveness": 0,
+ "interactive": 9,
+ "depth_ge1": 7,
+ "depth_ge2": 3,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_home_anchors",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_onboarding_shape",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Create-Your-Character sheet present -> Skip -> sheet gone, Player Stats shown, surface flips by >=5 keys"
+ },
+ {
+ "test": "structure_skill_sheet_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Skills->Mining adds Choose Activity sheet (surface flips >=6 keys); BACK restores the skill list"
+ },
+ {
+ "test": "structure_dungeon_sheet_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Combat->Farm adds dungeon sheet (Enter Dungeon appears, surface flips >=6 keys); BACK restores the dungeon list"
+ },
+ {
+ "test": "structure_profile_pane_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Profile Bonuses pane (near-empty, 'No active XP bonuses') vs Inventory pane (many rows): child set flips by >=6 keys"
+ },
+ {
+ "test": "structure_combat_subtab_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Combat Dungeons list (has 'Farm') vs Gear pane: surface flips >=4 keys and 'Farm' disappears"
+ },
+ {
+ "test": "structure_settings_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Home->Settings gear opens a settings list (Theme + Font Size + >=2 switches); surface flips >=6 keys from Home"
+ },
+ {
+ "test": "structure_session_card_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Home 'No Active Session' card -> after start: gains Repeat Action/Abandon controls, surface flips >=4 keys"
+ },
+ {
+ "test": "structure_navbar_persists",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "5-item nav (Skills/Combat/Home/Quests/Profile) persists Home->Quests while the content area flips >=4 keys"
+ },
+ {
+ "test": "structure_reward_modal_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Active session -> Finish Now -> Collect adds a reward modal ('Session Results' with XP gained + item rows); flips >=4 keys"
+ },
+ {
+ "test": "structure_home_grid_vlm",
+ "passed": true,
+ "message": "VLM: Q='Below the player-stats panel, is there a grid of labelled square tiles/buttons (such as Shop, Inn, Guild Hall, Church) arranged in rows and columns?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Below the player-stats panel, is there a grid of labelled square tiles/buttons (such as Shop, Inn, Guild Hall, Church) arranged in rows and columns?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_bottom_nav_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a bottom navigation bar with exactly 5 evenly spaced icon+label tabs spanning the width of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a bottom navigation bar with exactly 5 evenly spaced icon+label tabs spanning the width of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_stats_card_vlm",
+ "passed": true,
+ "message": "VLM: Q='Near the top, is there a single distinct card/panel that shows three stat values side by side in separate columns (Combat Level, Total Level, Coins)?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Near the top, is there a single distinct card/panel that shows three stat values side by side in separate columns (Combat Level, Total Level, Coins)?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_activity_sheet_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a bottom-sheet panel with rounded top corners and a small drag handle overlaying the lower portion of the screen?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a bottom-sheet panel with rounded top corners and a small drag handle overlaying the lower portion of the screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_session_card_present_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a distinct highlighted card/panel on the screen showing an active training session with a countdown and action buttons?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a distinct highlighted card/panel on the screen showing an active training session with a countdown and action buttons?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_settings_list_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the screen a vertical list of setting rows stacked top to bottom (each row a label with a control on its right)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the screen a vertical list of setting rows stacked top to bottom (each row a label with a control on its right)?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_skill_rows_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the screen a vertical list of skill rows where each row has an icon on the left and a horizontal progress bar?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the screen a vertical list of skill rows where each row has an icon on the left and a horizontal progress bar?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_dungeon_list_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the main content a vertical list of stacked rows, one per dungeon, where each row shows a level label (like 'Lv. 1') aligned to the right edge?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the main content a vertical list of stacked rows, one per dungeon, where each row shows a level label (like 'Lv. 1') aligned to the right edge?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_reward_modal_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a centered dialog/modal overlaying the screen that lists an XP amount and one or more item/reward rows?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a centered dialog/modal overlaying the screen that lists an XP amount and one or more item/reward rows?",
+ "tag": "layout"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/android_testgen_kit.py b/android/tristinbaker-idlefantasy/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/tristinbaker-idlefantasy/tests/android_text_eval.json b/android/tristinbaker-idlefantasy/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..39ce4c8de1a1c9586d0dffe5925e09f44292e4c6
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/android_text_eval.json
@@ -0,0 +1,224 @@
+{
+ "module": "text",
+ "total": 21,
+ "passed": 21,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 18,
+ "passed": 18,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 3,
+ "passed": 3,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1667,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 21,
+ "depth_ge1": 20,
+ "depth_ge2": 10,
+ "value": 21,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "text_home_no_active_session",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Home card reads 'No Active Session' + 'Head to Skills or Combat to start training.' when idle, and drops it once a session runs"
+ },
+ {
+ "test": "text_church_empty_blessing",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Church shows 'No active blessing — visit the Church to pray.'"
+ },
+ {
+ "test": "text_slayer_empty_task",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Slayer Master shows 'No active task. Tap Get New Task.'"
+ },
+ {
+ "test": "text_profile_bonuses_empty",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Profile > Bonuses shows 'No active XP bonuses'"
+ },
+ {
+ "test": "text_recent_activity_empty",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Recent Activity sheet shows 'No sessions completed yet.'"
+ },
+ {
+ "test": "text_choose_activity_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "activity sheet shows 'Choose Activity' + 'Extract valuable ores and gems from the earth.'"
+ },
+ {
+ "test": "text_rune_essence_description",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Rune Essence confirm dialog shows 'Raw magical stone used to craft all types of runes.'"
+ },
+ {
+ "test": "text_session_active_label",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Home card reads 'Session Active' after a session starts"
+ },
+ {
+ "test": "text_skills_active_session_label",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Skills screen shows the plain 'Mining — Rune Essence' label while the session runs"
+ },
+ {
+ "test": "text_session_complete_label",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Home card status goes 'Session Active' -> 'Session Complete!' after [Debug] Finish Now"
+ },
+ {
+ "test": "text_reward_modal_labels",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "reward modal shows the headings 'XP gained' and 'Loot'"
+ },
+ {
+ "test": "text_reward_loot_rune_essence",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "reward modal loot list contains a 'Rune Essence' row under 'Loot'"
+ },
+ {
+ "test": "text_combat_farm_verdict",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Combat dungeon list shows the verdict 'You've got this' for Farm"
+ },
+ {
+ "test": "text_quests_daily_reset",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Quests Daily sub-tab shows 'Resets at 6:00 AM'"
+ },
+ {
+ "test": "text_quests_daily_info",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Quests Daily info line contains 'Each daily quest rewards coins'"
+ },
+ {
+ "test": "text_quests_weekly_reset",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Quests Weekly sub-tab shows 'Resets Monday at 6am'"
+ },
+ {
+ "test": "text_settings_recent_activity_desc",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Settings shows 'Show Recent Activity button in the home screen header'"
+ },
+ {
+ "test": "text_recent_activity_logs_mining",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Recent Activity 'No sessions completed yet.' -> a 'Mining' entry after a session is collected"
+ },
+ {
+ "test": "text_home_session_emoji_vlm",
+ "passed": true,
+ "message": "VLM: Q='On the highlighted session card, does a small pickaxe / mining-tool emoji appear immediately to the LEFT of the words 'Mining — Rune Essence', on the same line as that text?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: On the highlighted session card, does a small pickaxe / mining-tool emoji appear immediately to the LEFT of the words 'Mining — Rune Essence', on the same line as that text?",
+ "tag": "position"
+ },
+ {
+ "test": "text_reward_loot_icons_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the reward dialog's loot list under the 'Loot' heading, is each item's quantity (such as '×60') shown on the RIGHT edge of the row, with the item name (such as 'Rune Essence') on the LEFT?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In the reward dialog's loot list under the 'Loot' heading, is each item's quantity (such as '×60') shown on the RIGHT edge of the row, with the item name (such as 'Rune Essence') on the LEFT?",
+ "tag": "position"
+ },
+ {
+ "test": "text_session_complete_emoji_vlm",
+ "passed": true,
+ "message": "VLM: Q='On the 'Session Complete!' card, is a pickaxe / mining-tool emoji rendered next to the skill name 'Mining — Rune Essence'?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: On the 'Session Complete!' card, is a pickaxe / mining-tool emoji rendered next to the skill name 'Mining — Rune Essence'?",
+ "tag": "content"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/tests/conftest.py b/android/tristinbaker-idlefantasy/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/tristinbaker-idlefantasy/tests/requirements.txt b/android/tristinbaker-idlefantasy/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_computation.py b/android/tristinbaker-idlefantasy/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e51eb1929344895d98f1478ee43a6f2e5f8b4426
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_computation.py
@@ -0,0 +1,672 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — Idle Fantasy.
+
+Owns CORE FUNCTION input->output: the deterministic derived NUMBERS the app
+computes from its core idle loop and renders. This lane is the sole owner of
+jump_kind="value"; every assertion names the exact value OBSERVED live on the
+running original, never a value read from source or computed here.
+
+CEDES: whether a screen is reachable (navigation), a widget's selected/checked
+bit (states), the exact non-numeric label wording (text), the view-tree shape
+(structure), the DATA-mutation/persistence semantics of the loop (interaction).
+This file asserts the NUMBERS the loop produces, nothing else.
+
+Live-derived on the ORIGINAL (com.tristinbaker.idlefantasy), re-observed for this
+lane — every number below was READ OFF the running app, not trusted from prose:
+ * FRESH profile Home: Total Level = 23, Combat Level 1, Coins 0.
+ * Skills list: every level-1 skill shows '0 / 83 XP' (XpTable level-2 = 83).
+ * Skills -> Mining -> 'Choose Activity' sheet:
+ 'Session: 60m', '~60 ores/session'
+ Rune Essence row: 'Lv. 1 • 15 XP/ore', projection '+900 XP → Level 8'
+ Copper Ore row: 'Lv. 1 • 18 XP/ore', projection '+1,080 XP → Level 9'
+ * Rune Essence 'Start Session' -> confirm dialog: title 'Rune Essence',
+ 'Lv. 1 • 15 XP/ore'.
+ * Active-session HOME card projection: '+900 XP → Lv 8 (+7, 58%)'
+ (58% = (900-801)/(969-801) = 99/168; +7 = 8-1 levels gained).
+ * '[Debug] Finish Now' -> 'Collect 1 Session's Rewards' -> reward modal
+ 'Mining Session Complete' / 'XP gained' / '+900 XP' / 'Loot' /
+ 'Rune Essence ×60' (+ RANDOM gems). XP and the Rune-Essence ore count are
+ DETERMINISTIC; gem counts VARY and are NEVER asserted.
+ * After Close: Home Total Level = 30 (delta +7 vs the fresh 23); Skills ->
+ Mining now Level 8, '900 / 969 XP' (total XP / next-level threshold).
+
+The '~60 ores/session', '+900 XP', '×60', Level 8, '900 / 969', '0 / 83',
+Total-Level 23->30 numbers are the heart of the app's compute; they dominate here.
+
+The launch script pre-installs/pre-grants Clipper and ADB-Keyboard; this file
+never installs, grants, connects, or hardcodes a package/serial/coordinate.
+"""
+import os
+import re
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this is only a single-emulator fallback,
+# assembled from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+BOTTOM_TABS = ("Skills", "Combat", "Home", "Quests", "Profile")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Entry-point helpers (NOT the depth family — no and_enter/and_reach here). These
+# only clean the launch surface: the OS permission dialog and the create-character
+# sheet belong to the OS / onboarding, not to any behaviour this lane scores.
+# ══════════════════════════════════════════════════════════════════════════════
+def dismiss_permission():
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app") # noqa: F405
+ or find_node(nodes, text="Only this time")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the 'Create Your Character' sheet iff present."""
+ for _ in range(3):
+ nodes = ui() # noqa: F405
+ if not find_node_ci(nodes, "Create Your Character"): # noqa: F405
+ return
+ sk = find_node(nodes, text="Skip") or find_node_ci(nodes, "Skip") # noqa: F405
+ if not sk or not tap_node(sk): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def dismiss_modals():
+ """Close a lingering reward/results modal a finished WorkManager session can
+ leave on top after a relaunch. Close is inert; route through safe_tap anyway."""
+ for _ in range(3):
+ n = find_node_ci(ui(), "Close") # noqa: F405
+ if n and safe_tap(n): # noqa: F405
+ settle("tap") # noqa: F405
+ else:
+ break
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by label. The label is duplicated inside some surfaces
+ (Combat/Profile expose a 'Skills' sub-tab), so pick the bottom-most match."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = (max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ if cands else find_node_ci(ui(), label)) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def fresh_home():
+ """Wipe data for the deterministic fresh-profile numbers (Total 23, 0/83),
+ relaunch, clear the permission dialog + onboarding, and land on Home."""
+ clear_data() # noqa: F405
+ launch_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+ go_tab("Home")
+ return ui() # noqa: F405
+
+
+# ── numeric helpers ─────────────────────────────────────────────────────────────
+def norm(s):
+ """Collapse whitespace so double-spaces around '→' never matter."""
+ return re.sub(r"\s+", " ", (s or "").strip())
+
+
+def nums(s):
+ """The integer tokens in a string, thousands-separators removed: '900 / 969
+ XP' -> [900, 969]; '+1,080 XP → Level 9' -> [1080, 9]."""
+ return [int(t.replace(",", "")) for t in re.findall(r"[\d,]*\d", s or "")]
+
+
+def texts_with_digit(nodes):
+ return [n.get("text", "").strip() for n in nodes
+ if n.get("text", "").strip() and any(c.isdigit() for c in n.get("text", ""))]
+
+
+def find_text_containing(nodes, *fragments):
+ """First node whose text contains EVERY fragment (case-insensitive)."""
+ for n in nodes:
+ t = n.get("text", "")
+ low = t.lower()
+ if all(f.lower() in low for f in fragments):
+ return n
+ return None
+
+
+def total_level_value(nodes):
+ """The number rendered directly ABOVE the 'Total Level' label on Home. The
+ stat card is a column: value TextView then its label TextView, so match the
+ digit node whose x-range overlaps the label and sits just above it."""
+ lbl = find_node(nodes, text="Total Level") # noqa: F405
+ if not lbl or "_bounds" not in lbl:
+ return None
+ lx1, ly1, lx2, ly2 = lbl["_bounds"]
+ lcx = (lx1 + lx2) // 2
+ best, best_dy = None, 10 ** 9
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if not t.isdigit() or "_bounds" not in n:
+ continue
+ x1, y1, x2, y2 = n["_bounds"]
+ if y2 > ly1: # value must be above the label
+ continue
+ if not (x1 - 40 <= lcx <= x2 + 40): # roughly same column
+ continue
+ dy = ly1 - y2
+ if 0 <= dy < best_dy:
+ best, best_dy = int(t), dy
+ return best
+
+
+def _rows_overlap(a, b, slack=12):
+ """True when two bounds share a horizontal band (their y-centres are close),
+ i.e. they render on the SAME visual row."""
+ acy = (a[1] + a[3]) // 2
+ bcy = (b[1] + b[3]) // 2
+ return abs(acy - bcy) <= max((a[3] - a[1]), (b[3] - b[1])) // 2 + slack
+
+
+def skill_level_value(nodes, skill="Mining"):
+ """The level badge digit for a skill row. Per SkillRow layout the level number
+ is overlaid at the emoji badge's bottom-end, LEFT of the name and vertically
+ within the row band. Pick the digit node to the left of the name whose row
+ band overlaps the name, closest in x."""
+ name = find_node(nodes, text=skill) # noqa: F405
+ if not name or "_bounds" not in name:
+ return None
+ nb = name["_bounds"]
+ nx1 = nb[0]
+ best, best_dx = None, 10 ** 9
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if not t.isdigit() or "_bounds" not in n:
+ continue
+ b = n["_bounds"]
+ if b[0] >= nx1: # badge sits to the LEFT of the name
+ continue
+ if not _rows_overlap(b, nb, slack=40):
+ continue
+ dx = nx1 - b[2] # horizontal gap to the name
+ if 0 <= dx < best_dx:
+ best, best_dx = int(t), dx
+ return best
+
+
+def skill_row_xp(nodes, skill="Mining"):
+ """The 'A / B XP' (or 'A XP') progress string on a skill row. Per SkillRow
+ layout the name and this text sit on the SAME row (Arrangement.SpaceBetween),
+ so it is the XP-bearing node to the RIGHT of the name whose row band overlaps
+ the name. Falls back to the nearest XP node just below (defensive for a
+ recreation that stacks the row differently)."""
+ name = find_node(nodes, text=skill) # noqa: F405
+ if not name or "_bounds" not in name:
+ return ""
+ nb = name["_bounds"]
+
+ def is_xp(t):
+ return "XP" in t and any(c.isdigit() for c in t)
+
+ # same-row, to the right of the name (the real layout)
+ best, best_dx = "", 10 ** 9
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if not is_xp(t) or "_bounds" not in n:
+ continue
+ b = n["_bounds"]
+ if b[0] < nb[0]: # must be right of the name's left edge
+ continue
+ if not _rows_overlap(b, nb, slack=24):
+ continue
+ dx = abs(b[0] - nb[2])
+ if dx < best_dx:
+ best, best_dx = t, dx
+ if best:
+ return best
+
+ # fallback: nearest XP string just below the name in roughly the same column
+ ncx = (nb[0] + nb[2]) // 2
+ best, best_dy = "", 10 ** 9
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if not is_xp(t) or "_bounds" not in n:
+ continue
+ b = n["_bounds"]
+ if b[1] < nb[1] or not (b[0] - 80 <= ncx <= b[2] + 80):
+ continue
+ dy = b[1] - nb[3]
+ if 0 <= dy < best_dy:
+ best, best_dy = t, dy
+ return best
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Depth-family helpers. Each and_enter_*/and_reach_* NAME backs a declared depth.
+# The core loop crosses: Skills(1) -> skill -> 'Choose Activity' sheet(2) ->
+# confirm dialog(3) -> active session; then the reward modal(3 from Home).
+# ══════════════════════════════════════════════════════════════════════════════
+def and_enter_choose_activity(skill="Mining"):
+ """Skills tab (surface 1) -> tap a skill -> 'Choose Activity' sheet (surface 2).
+ Returns the sheet tree, or None if it never opened."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ row = find_node(ui(), text=skill) or find_node_ci(ui(), skill) # noqa: F405
+ if not row or not tap_node(row): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ and_enter("Choose Activity") # noqa: F405
+ nodes = ui() # noqa: F405
+ return nodes if find_node_ci(nodes, "Choose Activity") else None # noqa: F405
+
+
+def and_enter_confirm_dialog(activity="Rune Essence", skill="Mining"):
+ """... -> the activity's own 'Start Session' -> confirm dialog (surface 3).
+ Picks the Start-Session button on the activity's row (document order [0] is a
+ different activity). Returns the dialog tree, or None."""
+ sheet = and_enter_choose_activity(skill)
+ if sheet is None:
+ return None
+ act = find_node(sheet, text=activity) # noqa: F405
+ if not act or "_center" not in act:
+ return None
+ ay = act["_center"][1]
+ starts = find_nodes(sheet, text="Start Session") # noqa: F405
+ best = min(starts, key=lambda n: abs(n["_center"][1] - ay)) if starts else None
+ if not best or not tap_node(best): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ and_enter("Confirm dialog") # noqa: F405
+ nodes = ui() # noqa: F405
+ # dialog identity: title + rate line + a Cancel button next to Start Session
+ return nodes if find_node(nodes, text="Cancel") and \
+ find_node_ci(nodes, activity) else None # noqa: F405
+
+
+def and_enter_active_session_home(activity="Rune Essence", skill="Mining"):
+ """Full path to the ACTIVE-SESSION home card: sheet -> confirm dialog ->
+ (tap the dialog's 'Start Session') -> Home tab. Returns the Home tree while a
+ session is active, or None. Surfaces crossed: Skills, sheet, dialog (depth 3)."""
+ dlg = and_enter_confirm_dialog(activity, skill)
+ if dlg is None:
+ return None
+ conf = find_nodes(ui(), text="Start Session") # noqa: F405
+ if not conf:
+ return None
+ tap_node(conf[-1]) # noqa: F405 dialog confirm
+ settle("tap") # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ nodes = ui() # noqa: F405
+ return nodes if find_node_ci(nodes, "Session Active") else None # noqa: F405
+
+
+def and_reach_reward_modal(activity="Rune Essence", skill="Mining"):
+ """Run the whole loop to the reward modal: active session (home) ->
+ '[Debug] Finish Now' -> 'Collect ... Rewards' -> reward modal (one more
+ surface). Returns the modal tree ('XP gained' + 'Loot'), or None."""
+ home = and_enter_active_session_home(activity, skill)
+ if home is None:
+ return None
+ if not tap_text(ui(), "[Debug] Finish Now"): # noqa: F405
+ # some builds show the debug button lower; match by y-order
+ cands = find_nodes(ui(), text="[Debug] Finish Now") # noqa: F405
+ if not cands or not tap_node(cands[-1]): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ settle("tap") # noqa: F405
+ coll = None
+ for n in ui(): # noqa: F405
+ if "Collect" in n.get("text", "") and "Reward" in n.get("text", ""):
+ coll = n
+ break
+ if coll is None or not tap_node(coll): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ settle("tap") # noqa: F405
+ and_enter("Reward modal") # noqa: F405
+ nodes = ui() # noqa: F405
+ return nodes if (find_node_ci(nodes, "XP gained") # noqa: F405
+ and find_node_ci(nodes, "Loot")) else None # noqa: F405
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — SHEET / DIALOG projections (in-page & shallow-modal computed values)
+# ══════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("computation_skill_level1_progress",))
+def test_skill_level1_progress():
+ """A level-1 skill's progress string is XpTable.levelForXp: '0 / 83 XP'
+ (0 current XP, 83 = XP threshold for level 2). Observed on Mining fresh."""
+ fresh_home()
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ nodes = ui() # noqa: F405
+ xp = skill_row_xp(nodes, "Mining")
+ ok = norm(xp) == "0 / 83 XP" or nums(xp) == [0, 83]
+ record("computation_skill_level1_progress", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Mining lvl-1 progress {xp!r}, expected '0 / 83 XP'",
+ depth=1, jump_kind="value", expect="Mining shows '0 / 83 XP'")
+
+
+@and_test(expects=("computation_activity_session_length",))
+def test_activity_session_length():
+ """The 'Choose Activity' sheet reports the session length as 'Session: 60m'
+ (60 ores * 1 min/ore)."""
+ fresh_home()
+ sheet = and_enter_choose_activity("Mining")
+ node = find_text_containing(sheet, "Session:") if sheet else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = got == "Session: 60m" or (bool(node) and 60 in nums(got))
+ record("computation_activity_session_length", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: session length {got!r}, expected 'Session: 60m'",
+ depth=2, jump_kind="value", expect="sheet shows 'Session: 60m'")
+
+
+@and_test(expects=("computation_activity_ores_per_session",))
+def test_activity_ores_per_session():
+ """The sheet reports the derived per-session yield '~60 ores/session'."""
+ fresh_home()
+ sheet = and_enter_choose_activity("Mining")
+ node = find_text_containing(sheet, "ores/session") if sheet else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = got == "~60 ores/session" or (bool(node) and 60 in nums(got))
+ record("computation_activity_ores_per_session", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: ores/session {got!r}, expected '~60 ores/session'",
+ depth=2, jump_kind="value", expect="sheet shows '~60 ores/session'")
+
+
+@and_test(expects=("computation_activity_rune_xp_rate",))
+def test_activity_rune_xp_rate():
+ """Rune Essence row rate line: 'Lv. 1 • 15 XP/ore' (15 = xp_per_ore)."""
+ fresh_home()
+ sheet = and_enter_choose_activity("Mining")
+ node = None
+ if sheet:
+ re_row = find_node(sheet, text="Rune Essence") # noqa: F405
+ if re_row and "_center" in re_row:
+ ry = re_row["_center"][1]
+ rates = [n for n in sheet if "XP/ore" in n.get("text", "")]
+ node = min(rates, key=lambda n: abs(n["_center"][1] - ry)) if rates else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = bool(node) and nums(got)[:1] == [1] and "15" in got and "XP/ore" in got
+ record("computation_activity_rune_xp_rate", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Rune Essence rate {got!r}, expected 'Lv. 1 • 15 XP/ore'",
+ depth=2, jump_kind="value", expect="Rune Essence rate '15 XP/ore' at Lv. 1")
+
+
+@and_test(expects=("computation_activity_rune_projection",))
+def test_activity_rune_projection():
+ """Rune Essence session projection: '+900 XP → Level 8' (60 ores * 15 XP =
+ 900 XP; 900 XP puts the level-1 skill at level 8)."""
+ fresh_home()
+ sheet = and_enter_choose_activity("Mining")
+ node = None
+ if sheet:
+ re_row = find_node(sheet, text="Rune Essence") # noqa: F405
+ if re_row and "_center" in re_row:
+ ry = re_row["_center"][1]
+ projs = [n for n in sheet
+ if "XP" in n.get("text", "") and ("Level" in n.get("text", "")
+ or "Lv" in n.get("text", ""))
+ and "+" in n.get("text", "")]
+ node = min(projs, key=lambda n: abs(n["_center"][1] - ry)) if projs else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = bool(node) and nums(got) == [900, 8]
+ record("computation_activity_rune_projection", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Rune Essence projection {got!r}, expected '+900 XP → Level 8'",
+ depth=2, jump_kind="value", expect="projection '+900 XP → Level 8'")
+
+
+@and_test(expects=("computation_activity_copper_projection",))
+def test_activity_copper_projection():
+ """A second activity's projection is independently derived: Copper Ore
+ (18 XP/ore) shows '+1,080 XP → Level 9' (60 * 18 = 1080; -> level 9)."""
+ fresh_home()
+ sheet = and_enter_choose_activity("Mining")
+ node = None
+ if sheet:
+ cu_row = find_node(sheet, text="Copper Ore") # noqa: F405
+ if cu_row and "_center" in cu_row:
+ cy = cu_row["_center"][1]
+ projs = [n for n in sheet
+ if "XP" in n.get("text", "") and "+" in n.get("text", "")
+ and ("Level" in n.get("text", "") or "Lv" in n.get("text", ""))]
+ node = min(projs, key=lambda n: abs(n["_center"][1] - cy)) if projs else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = bool(node) and nums(got) == [1080, 9]
+ record("computation_activity_copper_projection", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Copper Ore projection {got!r}, expected '+1,080 XP → Level 9'",
+ depth=2, jump_kind="value", expect="projection '+1,080 XP → Level 9'")
+
+
+@and_test(expects=("computation_confirm_dialog_xp_rate",))
+def test_confirm_dialog_xp_rate():
+ """The confirm dialog echoes the derived rate line 'Lv. 1 • 15 XP/ore' for the
+ chosen activity (a surface deeper than the sheet)."""
+ fresh_home()
+ dlg = and_enter_confirm_dialog("Rune Essence", "Mining")
+ node = find_text_containing(dlg, "XP/ore") if dlg else None
+ got = norm(node.get("text", "")) if node else ""
+ ok = bool(node) and "15" in got and "XP/ore" in got and nums(got)[:1] == [1]
+ record("computation_confirm_dialog_xp_rate", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: confirm-dialog rate {got!r}, expected 'Lv. 1 • 15 XP/ore'",
+ depth=3, jump_kind="value", expect="confirm dialog '15 XP/ore' at Lv. 1")
+
+
+@and_test(expects=("computation_home_card_projection",))
+def test_home_card_projection():
+ """The ACTIVE-SESSION home card renders the running projection
+ '+900 XP → Lv 8 (+7, 58%)' (900 XP, level 8, +7 levels, 58% into band)."""
+ fresh_home()
+ home = and_enter_active_session_home("Rune Essence", "Mining")
+ node = None
+ if home:
+ node = find_text_containing(home, "+900", "XP")
+ if node is None:
+ node = find_text_containing(home, "XP", "%")
+ got = norm(node.get("text", "")) if node else ""
+ ok = bool(node) and 900 in nums(got) and 8 in nums(got) and 58 in nums(got)
+ record("computation_home_card_projection", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: home card projection {got!r}, "
+ f"expected '+900 XP → Lv 8 (+7, 58%)'",
+ depth=3, jump_kind="value", expect="home card '+900 XP → Lv 8 (+7, 58%)'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — REWARD MODAL + POST-COLLECT computed values (full loop, deepest values)
+# ══════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("computation_reward_xp_gained", "computation_reward_ore_count"))
+def test_reward_modal_values():
+ """Reward modal after collecting one Rune Essence session:
+ * 'XP gained' -> '+900 XP' (DETERMINISTIC).
+ * Loot 'Rune Essence ×60' (DETERMINISTIC ore count = ores/session).
+ Gem loot varies and is never asserted here."""
+ fresh_home()
+ modal = and_reach_reward_modal("Rune Essence", "Mining")
+
+ # (a) XP gained value
+ xp_node = None
+ if modal:
+ cand = [n for n in modal if "XP" in n.get("text", "") and "+" in n.get("text", "")]
+ # exclude any progress-style 'A / B XP'; the reward value is a lone '+N XP'
+ cand = [n for n in cand if "/" not in n.get("text", "")]
+ xp_node = cand[0] if cand else None
+ xp_txt = norm(xp_node.get("text", "")) if xp_node else ""
+ ok_xp = bool(xp_node) and nums(xp_txt) == [900]
+ record("computation_reward_xp_gained", ok_xp, # noqa: F405
+ "" if ok_xp else (f"behavior_wrong: reward XP {xp_txt!r}, expected '+900 XP'"
+ if modal else "setup_failed: reward modal not reached"),
+ depth=3, jump_kind="value", expect="reward modal '+900 XP'")
+
+ # (b) Rune Essence ore count in Loot
+ count_txt = ""
+ if modal:
+ re_node = find_node(modal, text="Rune Essence") # noqa: F405
+ if re_node and "_center" in re_node:
+ ry = re_node["_center"][1]
+ counts = [n for n in modal if n.get("text", "").strip().startswith("×")]
+ near = min(counts, key=lambda n: abs(n["_center"][1] - ry)) if counts else None
+ count_txt = norm(near.get("text", "")) if near else ""
+ ok_cnt = nums(count_txt) == [60]
+ record("computation_reward_ore_count", ok_cnt, # noqa: F405
+ "" if ok_cnt else (f"behavior_wrong: Rune Essence loot count {count_txt!r}, "
+ "expected '×60'"
+ if modal else "setup_failed: reward modal not reached"),
+ depth=3, jump_kind="value", expect="loot 'Rune Essence ×60'")
+
+
+@and_test(expects=("computation_total_level_after_collect",
+ "computation_total_level_delta",
+ "computation_mining_level_after_collect",
+ "computation_mining_xp_after_collect"))
+def test_post_collect_values():
+ """After collecting one Rune Essence session and closing the modal, the
+ persistent computed stats update:
+ * Home Total Level = 30 (was 23 on the fresh profile) -> delta +7.
+ * Skills -> Mining Level = 8, progress '900 / 969 XP'
+ (900 total XP; 969 = XpTable threshold for level 9)."""
+ fresh_home()
+ before_home = ui() # noqa: F405
+ total_before = total_level_value(before_home)
+
+ modal = and_reach_reward_modal("Rune Essence", "Mining")
+ reached = modal is not None
+ if reached:
+ cl = find_node_ci(ui(), "Close") # noqa: F405
+ if cl:
+ safe_tap(cl) # noqa: F405
+ settle("tap") # noqa: F405
+
+ # Home Total Level after collect
+ after_home = go_tab("Home")
+ total_after = total_level_value(after_home)
+ ok_total = total_after == 30
+ record("computation_total_level_after_collect", ok_total, # noqa: F405
+ "" if ok_total else (f"behavior_wrong: Total Level after collect {total_after!r}, "
+ "expected 30"
+ if reached else "setup_failed: loop/reward not reached"),
+ depth=3, jump_kind="value", expect="Home Total Level == 30 after collect")
+
+ # Computed delta 23 -> 30 (=+7)
+ ok_delta = (total_before == 23 and total_after == 30
+ and (total_after - total_before) == 7)
+ record("computation_total_level_delta", ok_delta, # noqa: F405
+ "" if ok_delta else (f"behavior_wrong: Total Level delta {total_before!r}->"
+ f"{total_after!r}, expected 23->30 (+7)"
+ if reached else "setup_failed: loop/reward not reached"),
+ depth=3, jump_kind="value", expect="Total Level 23 -> 30 (delta +7)")
+
+ # Skills -> Mining Level and progress after collect
+ go_tab("Skills")
+ skills = ui() # noqa: F405
+ mining_lvl = skill_level_value(skills, "Mining")
+ ok_lvl = mining_lvl == 8
+ record("computation_mining_level_after_collect", ok_lvl, # noqa: F405
+ "" if ok_lvl else (f"behavior_wrong: Mining level after collect {mining_lvl!r}, "
+ "expected 8"
+ if reached else "setup_failed: loop/reward not reached"),
+ depth=3, jump_kind="value", expect="Mining Level == 8 after collect")
+
+ mining_xp = skill_row_xp(skills, "Mining")
+ ok_xp = norm(mining_xp) == "900 / 969 XP" or nums(mining_xp) == [900, 969]
+ record("computation_mining_xp_after_collect", ok_xp, # noqa: F405
+ "" if ok_xp else (f"behavior_wrong: Mining progress after collect {mining_xp!r}, "
+ "expected '900 / 969 XP'"
+ if reached else "setup_failed: loop/reward not reached"),
+ depth=3, jump_kind="value", expect="Mining shows '900 / 969 XP' after collect")
+
+
+@and_test(expects=("computation_no_active_session_baseline",))
+def test_no_active_session_baseline():
+ """NEGATIVE half of the loop: on a fresh profile, BEFORE any session, the
+ '+900 XP' projection and 'Session Active' card are ABSENT — Home shows the
+ 'No Active Session' state and Total Level is the un-mutated 23. This proves the
+ computed +900/level-8 numbers are produced by the loop, not baked into layout."""
+ home = fresh_home()
+ total = total_level_value(home)
+ has_active = bool(find_node_ci(home, "Session Active"))
+ has_900 = bool(find_text_containing(home, "+900"))
+ no_session = bool(find_node_ci(home, "No Active Session"))
+ ok = total == 23 and not has_active and not has_900 and no_session
+ record("computation_no_active_session_baseline", ok, # noqa: F405
+ "" if ok else (f"behavior_wrong: fresh Home total={total!r} active={has_active} "
+ f"has_900={has_900} no_session={no_session}; "
+ "expected total=23, no active session, no +900 projection"),
+ depth=0, jump_kind="value",
+ expect="fresh Home: Total Level 23, no '+900 XP', 'No Active Session'")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 2) — rendered-only computed properties the a11y tree can't express.
+# ══════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("computation_mining_xp_bar_vlm",))
+def test_mining_xp_bar_vlm():
+ """After the loop drives Mining to Level 8 with 900/969 XP, its row progress
+ BAR is a Compose-drawn fill (~93% = 900/969) that never reaches the tree. Ask
+ the VLM about the RENDERED fill proportion of the Mining bar specifically."""
+ fresh_home()
+ modal = and_reach_reward_modal("Rune Essence", "Mining")
+ if modal is not None:
+ cl = find_node_ci(ui(), "Close") # noqa: F405
+ if cl:
+ safe_tap(cl) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Skills")
+ vlm_assert("computation_mining_xp_bar", # noqa: F405
+ "The 'Mining' skill row shows '900 / 969 XP'. Is its horizontal "
+ "progress bar rendered almost completely filled (roughly 90% or "
+ "more of its width), noticeably fuller than the empty bars of the "
+ "other level-1 skills below it?",
+ RESULTS, tag="size", depth=3, jump_kind="value")
+
+
+@and_test(expects=("computation_home_projection_badge_vlm",))
+def test_home_projection_badge_vlm():
+ """The active-session home card renders the '+900 XP → Lv 8' projection as an
+ emphasised inline row alongside a live countdown. Ask the VLM to confirm the
+ '+900 XP' projection text is rendered inside the active-session card near the
+ top of the Home content, with the level-8 target beside it."""
+ fresh_home()
+ home = and_enter_active_session_home("Rune Essence", "Mining")
+ # screenshot the active-session Home card
+ vlm_assert("computation_home_projection_badge", # noqa: F405
+ "In the active session card at the top of the Home screen, is the "
+ "text '+900 XP' rendered together with a level target '8' on the "
+ "same highlighted line (an XP-to-level projection), positioned "
+ "directly below the session countdown timer?",
+ RESULTS, tag="position", depth=3, jump_kind="value")
+
+
+TESTS = [
+ # sheet / dialog projections
+ test_skill_level1_progress,
+ test_activity_session_length,
+ test_activity_ores_per_session,
+ test_activity_rune_xp_rate,
+ test_activity_rune_projection,
+ test_activity_copper_projection,
+ test_confirm_dialog_xp_rate,
+ test_home_card_projection,
+ # reward modal + post-collect stats (full loop)
+ test_reward_modal_values,
+ test_post_collect_values,
+ test_no_active_session_baseline,
+ # VLM (rendered-only)
+ test_mining_xp_bar_vlm,
+ test_home_projection_badge_vlm,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_interaction.py b/android/tristinbaker-idlefantasy/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae025ece36c9f5bd539b587a5dccfd1712f4a5ae
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_interaction.py
@@ -0,0 +1,775 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — Idle Fantasy.
+
+Owns EFFECT-BY-CONSEQUENCE on user DATA: the CORE LOOP as a 3+ step sequence, the
+persistent stat/inventory/skill mutations a completed session produces, DATA
+persistence across PROCESS DEATH (the app's headline WorkManager behaviour), and
+the long-press / context-menu surface. Every test drives a real user sequence and
+asserts the DATA it produced — a dead shell that renders the buttons but wires
+nothing must FAIL (session never starts, stats never change, log stays empty).
+
+CEDES: the numeric value itself (computation), whether a screen is reachable
+(navigation), a widget's checked/selected bit (states), the exact label wording
+(text), view-tree shape (structure).
+
+Live-derived on the original (re-observed, never trusted from prose):
+ * App LAUNCHES onto Skills, not Home; open_app_home() taps the Home tab, and
+ dismisses a leftover 'Session Results' modal a finished WorkManager session
+ can leave on top after a relaunch.
+ * The 'Choose Activity' sheet lists MULTIPLE activities each with its own 'Start
+ Session' button (Mining: Copper Ore / Rune Essence / Tin Ore). To start Rune
+ Essence, pick the 'Start Session' node whose y is closest to the 'Rune Essence'
+ label — document-order [0] is Copper Ore.
+ * Two DISTINCT collect paths, verified live:
+ - HOME card: '[Debug] Finish Now' -> 'Collect 1 Session's Rewards' ->
+ modal 'Mining Session Complete' / 'XP gained' / '+900 XP' / 'Loot' /
+ 'Rune Essence ×60' + random gems / 'Close'. THIS path populates Recent
+ Activity ('1. Mining / Rune Essence') AND the Inventory ('Rune Essence').
+ - SKILLS screen: '[Debug] Finish Now' -> 'Collect Results' -> modal
+ 'Session Results' / 'XP gained' / '+900 XP' / 'Items collected'. This path
+ does NOT populate Recent Activity (stays 'No sessions completed yet.').
+ => the loop/stats/inventory/recent-activity tests all use the HOME-card path.
+ * Abandon (Home card): tap 'Abandon' -> confirm dialog 'Abandon Session?' /
+ 'All progress from this session will be lost.' / 'Cancel' / 'Confirm'; tap
+ 'Confirm' -> Home shows 'No Active Session'.
+ * Start-then-Cancel: the confirm dialog's 'Cancel' dismisses it and returns to
+ the (modal) Choose Activity sheet with NO active session; BACK then closes the
+ sheet and the Skills list shows the fresh Mining row '0 / 83 XP'.
+ * PERSISTENCE: start a session, force_stop_and_relaunch(), and the Skills screen
+ still shows 'Session Active' + plain 'Mining — Rune Essence' (the Home card
+ prefixes it with an emoji, so assert on Skills).
+ * Determinism on a FRESH profile: Mining/Rune Essence gives +900 XP, Total Level
+ 23 -> 30, Mining Level 1 -> 8 ('900 / 969 XP'). Loot GEMS vary (Emerald/Ruby/
+ Diamond counts random) but XP/level do NOT — assert XP/level/presence, never
+ gem counts.
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this is only a single-emulator fallback,
+# assembled from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+BOTTOM_TABS = ("Skills", "Combat", "Home", "Quests", "Profile")
+# The Home-card reward modal is identified path-independently by 'XP gained'
+# alongside any one of these summary labels.
+MODAL_MARKERS = ("Loot", "Items collected", "Session Results", "Level ups")
+
+
+# ── shared entry-point helpers (NOT depth family — no and_enter/and_reach here) ──
+def dismiss_permission():
+ """Dismiss the OS notification-permission dialog if it is on top. It belongs to
+ com.android.permissioncontroller, never the app under test, so tapping its allow
+ button is just a clean entry point, not part of any lane's behaviour."""
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the Create-Your-Character sheet iff present (returning profiles
+ skip straight past it)."""
+ n = find_node_ci(ui(), "Skip") # noqa: F405
+ if n and find_node_ci(ui(), "Create Your Character"): # noqa: F405
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ return True
+ return False
+
+
+def dismiss_modals():
+ """Close a lingering reward/results modal ('Session Results'/'Session Complete'
+ + Close) that a finished WorkManager session can leave on top after a relaunch.
+ Route through safe_tap — Close is inert, but the habit keeps exploratory taps safe."""
+ for _ in range(3):
+ n = find_node_ci(ui(), "Close") # noqa: F405
+ if n and safe_tap(n): # noqa: F405
+ settle("tap") # noqa: F405
+ else:
+ break
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by its label and settle. Bottom-nav labels are
+ duplicated inside some surfaces (Combat/Profile expose a 'Skills' sub-tab), so
+ match the tab in the bottom-most row by y-order. Returns the fresh tree."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = (max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ if cands else find_node_ci(ui(), label)) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def open_app_home(fresh=False):
+ """Land on a settled HOME surface. The app opens on Skills, so we explicitly tap
+ the Home tab. fresh=True wipes data first (virgin profile: perm dialog +
+ onboarding); either way a leftover results modal is dismissed."""
+ if fresh:
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+ go_tab("Home")
+ return ui() # noqa: F405
+
+
+def relaunch_clean():
+ """Relaunch after force_stop and clean the entry point WITHOUT touching data —
+ used by the persistence probe so the surviving session is not disturbed."""
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+
+
+def texts(nodes=None):
+ """Sorted set of non-blank text strings in the current (or given) tree."""
+ nodes = ui() if nodes is None else nodes # noqa: F405
+ return sorted({n.get("text", "") for n in nodes if n.get("text", "").strip()})
+
+
+def tap_label(label, idx=0, last=False):
+ """Tap the idx-th (or last) node whose text == label; else a CI match."""
+ ns = find_nodes(ui(), text=label) # noqa: F405
+ if last and ns:
+ return tap_node(ns[-1]) # noqa: F405
+ if ns and len(ns) > idx:
+ return tap_node(ns[idx]) # noqa: F405
+ n = find_node_ci(ui(), label) # noqa: F405
+ return tap_node(n) if n else False # noqa: F405
+
+
+def home_reward_modal_up():
+ """True when the Home-path reward modal is on screen: 'XP gained' plus any of
+ the summary labels ('Loot' on the Home path)."""
+ nodes = ui() # noqa: F405
+ return bool(find_node_ci(nodes, "XP gained") # noqa: F405
+ and any(find_node_ci(nodes, m) for m in MODAL_MARKERS))
+
+
+# ── depth-family helpers (the and_enter_*/and_reach_* NAME backs a declared depth) ─
+def and_enter_choose_activity(skill="Mining"):
+ """Skills tab (hop1) -> tap a skill -> 'Choose Activity' sheet (hop2). Returns
+ True when the sheet is up."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ row = find_node(ui(), text=skill) or find_node_ci(ui(), skill) # noqa: F405
+ if not row or not tap_node(row): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ and_enter("Choose Activity") # noqa: F405
+ return bool(find_node_ci(ui(), "Choose Activity")) # noqa: F405
+
+
+def and_enter_active_session(activity="Rune Essence", skill="Mining"):
+ """Skills -> skill -> 'Choose Activity' sheet -> the activity's own 'Start
+ Session' -> confirm dialog 'Start Session' -> ACTIVE SESSION (depth2 through
+ sheet + dialog). Picks the Start-Session button on the activity's row (document
+ order [0] is a different activity). Returns True when 'Session Active' shows."""
+ if not and_enter_choose_activity(skill):
+ return False
+ nodes = ui() # noqa: F405
+ act = find_node(nodes, text=activity) # noqa: F405
+ if not act or "_center" not in act:
+ return False
+ ay = act["_center"][1]
+ starts = find_nodes(nodes, text="Start Session") # noqa: F405
+ best = min(starts, key=lambda n: abs(n["_center"][1] - ay)) if starts else None
+ if not best or not tap_node(best): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ conf = find_nodes(ui(), text="Start Session") # noqa: F405 dialog confirm
+ if conf:
+ tap_node(conf[-1]) # noqa: F405
+ settle("tap") # noqa: F405
+ return bool(find_node_ci(ui(), "Session Active")) # noqa: F405
+
+
+def and_reach_home_reward_modal():
+ """From an active session: go to the HOME card, '[Debug] Finish Now' ->
+ 'Collect 1 Session's Rewards' -> the Home-path reward modal ('XP gained' +
+ 'Loot'). Counts one surface. Returns True when the modal is up."""
+ go_tab("Home")
+ if not tap_label("[Debug] Finish Now", last=True):
+ return False
+ settle("tap") # noqa: F405
+ coll = None
+ for n in ui(): # noqa: F405
+ if "Collect" in n.get("text", ""):
+ coll = n
+ break
+ if coll is None or not tap_node(coll): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ and_enter("Reward modal") # noqa: F405
+ return home_reward_modal_up()
+
+
+def and_enter_inventory():
+ """Profile tab (hop1) -> Inventory chip -> Inventory pane (hop2). Returns the
+ fresh tree of the Inventory pane."""
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ tap_label("Inventory")
+ settle("tap") # noqa: F405
+ and_enter("Inventory") # noqa: F405
+ return ui() # noqa: F405
+
+
+def and_enter_recent_activity():
+ """Home 'Recent Activity' button -> the Recent Activity bottom-sheet (hop1).
+ Returns the fresh tree of the sheet, or None if the button is absent."""
+ ra = find_node(ui(), text="Recent Activity") # noqa: F405
+ if not ra or not tap_node(ra): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ and_enter("Recent Activity") # noqa: F405
+ return ui() # noqa: F405
+
+
+def home_total_level():
+ """Read the Home Player-Stats 'Total Level' value. The value TextView sits just
+ ABOVE its 'Total Level' label in the same stat column, so pick the numeric node
+ whose x-centre is closest to the label's and whose y is just above it."""
+ nodes = ui() # noqa: F405
+ lbl = find_node(nodes, text="Total Level") # noqa: F405
+ if not lbl or "_center" not in lbl:
+ return None
+ lx, ly = lbl["_center"]
+ best, best_d = None, 1e9
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if not t.isdigit() or "_center" not in n:
+ continue
+ nx, ny = n["_center"]
+ if ny >= ly: # value is above the label
+ continue
+ d = abs(nx - lx) + abs(ny - ly)
+ if d < best_d:
+ best, best_d = t, d
+ return best
+
+
+def abandon_via_home():
+ """From an active session: Home card 'Abandon' -> confirm dialog 'Confirm'.
+ Returns True when Home then shows 'No Active Session'."""
+ go_tab("Home")
+ ab = find_node(ui(), text="Abandon") # noqa: F405
+ if not ab or not safe_tap(ab): # noqa: F405 (Abandon is not in the deny list)
+ return False
+ settle("tap") # noqa: F405
+ cf = find_node(ui(), text="Confirm") # noqa: F405
+ if cf and safe_tap(cf): # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ return bool(find_node_ci(ui(), "No Active Session")) # noqa: F405
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 1. CORE LOOP end-to-end — the flagship multi-step sequence (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_core_loop_sequence",)) # noqa: F405
+def test_core_loop_sequence():
+ # start -> active -> Finish Now -> Collect: the reward modal appearing PROVES
+ # the whole start->complete->collected sequence produced a collectable session.
+ # (Computation lane owns the numeric value; we assert the sequence completed.)
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ ok = started and reached
+ record("interaction_core_loop_sequence", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: Mining/Rune Essence did not go start->complete->"
+ f"collected (started={started} modal={reached}); a shell that wires "
+ "no session never surfaces the reward modal"
+ if (started or reached) else
+ "feature_missing: could not start a Mining/Rune Essence session at all"),
+ depth=2, jump_kind="transition",
+ expect="active session -> Finish Now -> Collect surfaces the reward "
+ "modal ('XP gained' + 'Loot') — the sequence completed")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 2. Collect mutates persistent stats — Total Level 23 -> 30 (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_collect_mutates_total_level",)) # noqa: F405
+def test_collect_mutates_total_level():
+ open_app_home(fresh=True)
+ go_tab("Home")
+ before = home_total_level()
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ after = home_total_level()
+ # DATA mutation: the value CHANGED and landed on the deterministic 30.
+ ok = bool(started and reached and before == "23" and after == "30"
+ and before != after)
+ record("interaction_collect_mutates_total_level", ok, # noqa: F405
+ "" if ok else "behavior_wrong: collecting a Mining/Rune Essence session "
+ f"did not raise Total Level 23->30 (before={before} after={after} "
+ f"started={started} modal={reached})",
+ depth=2, jump_kind="transition",
+ expect="Home Total Level 23 -> 30 after start+finish+collect+close")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 3. Collect adds loot to Inventory — a new inventory record (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_collect_adds_inventory",)) # noqa: F405
+def test_collect_adds_inventory():
+ open_app_home(fresh=True)
+ inv0 = and_enter_inventory()
+ absent_before = find_node_ci(inv0, "Rune Essence") is None # noqa: F405
+ # run the loop (Home-card collect populates the inventory)
+ and_reset_depth() # noqa: F405 new chain to reach the session
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ inv1 = and_enter_inventory()
+ present_after = find_node_ci(inv1, "Rune Essence") is not None # noqa: F405
+ ok = bool(started and reached and absent_before and present_after)
+ record("interaction_collect_adds_inventory", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Mining/Rune Essence session did not create "
+ f"a 'Rune Essence' inventory record (absent_before={absent_before} "
+ f"present_after={present_after} started={started} modal={reached})",
+ depth=2, jump_kind="transition",
+ expect="Inventory has NO 'Rune Essence' before -> a 'Rune Essence' row "
+ "present after collecting the Mining session")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 4. Skill XP/level persists after collect — Mining row 0/83 XP -> 900/969 XP (depth 1)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_skill_level_persists",)) # noqa: F405
+def test_skill_level_persists():
+ open_app_home(fresh=True)
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ fresh_row = bool(find_node_ci(ui(), "0 / 83 XP")) # noqa: F405 level-1 Mining row
+ # run the full loop
+ and_reset_depth() # noqa: F405
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ # the Mining row's XP text advanced from '0 / 83 XP' to '900 / 969 XP'
+ upgraded = bool(find_node_ci(ui(), "900 / 969 XP")) # noqa: F405
+ ok = bool(fresh_row and started and reached and upgraded)
+ record("interaction_skill_level_persists", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the Mining skill row did not advance "
+ f"'0 / 83 XP' -> '900 / 969 XP' after collect (fresh={fresh_row} "
+ f"upgraded={upgraded} started={started} modal={reached})",
+ depth=1, jump_kind="transition",
+ expect="Skills Mining row '0 / 83 XP' (Lv 1) -> '900 / 969 XP' (Lv 8) "
+ "after the session is collected")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 5. DATA PERSISTENCE ACROSS PROCESS DEATH — the signature test (depth 1)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_session_survives_process_death",)) # noqa: F405
+def test_session_survives_process_death():
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ active_before = bool(find_node_ci(ui(), "Session Active")) # noqa: F405
+ # KILL the process and relaunch WITHOUT clearing data.
+ force_stop_and_relaunch() # noqa: F405
+ relaunch_clean()
+ # The Skills screen shows the surviving session in PLAIN text (the Home card
+ # prefixes it with an emoji); navigate there and assert it is still running.
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ survived = bool(find_node_ci(ui(), "Session Active") # noqa: F405
+ and find_node_ci(ui(), "Mining — Rune Essence")) # noqa: F405
+ ok = bool(started and active_before and survived)
+ record("interaction_session_survives_process_death", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the active Mining/Rune Essence session did "
+ f"NOT survive force-stop + relaunch (started={started} "
+ f"before={active_before} survived={survived}); an in-memory-only "
+ "recreation loses the running session on process death",
+ depth=1, jump_kind="transition",
+ expect="'Session Active' + 'Mining — Rune Essence' still present on "
+ "Skills after force_stop_and_relaunch()")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 6. Abandon (with confirm) removes the active session (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_abandon_clears_session",)) # noqa: F405
+def test_abandon_clears_session():
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ # Abandon on the Home card opens a confirm dialog; tap Confirm.
+ cleared = abandon_via_home()
+ # double-check the session is really gone from the Skills screen too
+ go_tab("Skills")
+ skills_clear = not find_node_ci(ui(), "Session Active") # noqa: F405
+ ok = bool(started and cleared and skills_clear)
+ record("interaction_abandon_clears_session", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Abandon -> Confirm did not clear the "
+ f"active session (started={started} home_cleared={cleared} "
+ f"skills_clear={skills_clear})",
+ depth=2, jump_kind="transition",
+ expect="active session -> Abandon -> Confirm -> Home 'No Active Session' "
+ "and Skills no longer shows 'Session Active'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 7. Start-then-Cancel leaves NO session — a no-op multi-step outcome (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_start_cancel_no_session",)) # noqa: F405
+def test_start_cancel_no_session():
+ open_app_home(fresh=True)
+ opened = and_enter_choose_activity("Mining")
+ nodes = ui() # noqa: F405
+ act = find_node(nodes, text="Rune Essence") # noqa: F405
+ started_dialog = False
+ if act and "_center" in act:
+ ay = act["_center"][1]
+ starts = find_nodes(nodes, text="Start Session") # noqa: F405
+ best = min(starts, key=lambda n: abs(n["_center"][1] - ay)) if starts else None
+ if best and tap_node(best): # noqa: F405
+ settle("tap") # noqa: F405
+ # confirm dialog is up (title 'Rune Essence', Cancel / Start Session)
+ started_dialog = bool(find_node(ui(), text="Cancel") # noqa: F405
+ and find_node(ui(), text="Start Session")) # noqa: F405
+ # tap Cancel to back out of the confirm dialog -> returns to the (modal) Choose
+ # Activity sheet with NO active session (verified live).
+ cn = find_node(ui(), text="Cancel") # noqa: F405
+ cancelled = bool(cn and tap_node(cn)) # noqa: F405
+ settle("tap") # noqa: F405
+ back_on_sheet = bool(find_node_ci(ui(), "Choose Activity")) # noqa: F405 dialog gone
+ # BACK closes the sheet (it covers the bottom nav) and restores the skill list;
+ # then assert no session exists — no 'Session Active' and Mining still Lv1.
+ back() # noqa: F405
+ settle("tap") # noqa: F405
+ no_session = not find_node_ci(ui(), "Session Active") # noqa: F405
+ still_lvl1 = bool(find_node_ci(ui(), "0 / 83 XP")) # noqa: F405 fresh Mining row restored
+ ok = bool(opened and started_dialog and cancelled and back_on_sheet
+ and no_session and still_lvl1)
+ record("interaction_start_cancel_no_session", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Start Session -> Cancel did not leave the "
+ f"app session-free (opened={opened} dialog={started_dialog} "
+ f"cancelled={cancelled} back_on_sheet={back_on_sheet} "
+ f"no_session={no_session} lvl1={still_lvl1})",
+ depth=2, jump_kind="transition",
+ expect="Choose Activity -> Start Session -> Cancel -> BACK: NO 'Session "
+ "Active', Mining still '0 / 83 XP'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 8. A second session can be started for the same activity after collecting (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_second_session_starts",)) # noqa: F405
+def test_second_session_starts():
+ # Full loop to completion (No Active Session), then start a NEW session for the
+ # SAME activity — the app must accept a fresh session, not stay stuck.
+ open_app_home(fresh=True)
+ first = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ settled_idle = bool(find_node_ci(ui(), "No Active Session")) # noqa: F405
+ and_reset_depth() # noqa: F405 second run is its own chain
+ second = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Skills")
+ active_again = bool(find_node_ci(ui(), "Session Active") # noqa: F405
+ and find_node_ci(ui(), "Mining — Rune Essence")) # noqa: F405
+ ok = bool(first and reached and settled_idle and second and active_again)
+ record("interaction_second_session_starts", ok, # noqa: F405
+ "" if ok else "behavior_wrong: after collecting, a second Mining/Rune "
+ f"Essence session did not start (first={first} modal={reached} "
+ f"idle={settled_idle} second={second} active_again={active_again})",
+ depth=2, jump_kind="transition",
+ expect="after collect ('No Active Session') a NEW Mining/Rune Essence "
+ "session starts -> 'Session Active' + 'Mining — Rune Essence'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 9. Sequence integrity — switch the active skill Mining -> Fishing (depth 2)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_switch_active_skill",)) # noqa: F405
+def test_switch_active_skill():
+ open_app_home(fresh=True)
+ mining = and_enter_active_session("Rune Essence", "Mining")
+ was_mining = bool(find_node_ci(ui(), "Mining — Rune Essence")) # noqa: F405
+ cleared = abandon_via_home()
+ and_reset_depth() # noqa: F405 new chain for the Fishing start
+ fishing = and_enter_active_session("Raw Shrimp", "Fishing")
+ go_tab("Skills")
+ now_fishing = bool(find_node_ci(ui(), "Fishing — Raw Shrimp")) # noqa: F405
+ mining_gone = not find_node_ci(ui(), "Mining — Rune Essence") # noqa: F405
+ ok = bool(mining and was_mining and cleared and fishing
+ and now_fishing and mining_gone)
+ record("interaction_switch_active_skill", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the active session did not switch "
+ f"Mining/Rune Essence -> Fishing/Raw Shrimp (mining={was_mining} "
+ f"cleared={cleared} fishing={fishing} now_fishing={now_fishing} "
+ f"mining_gone={mining_gone})",
+ depth=2, jump_kind="transition",
+ expect="active 'Mining — Rune Essence' -> abandon -> start Fishing: "
+ "active session now 'Fishing — Raw Shrimp', Mining one gone")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 10. Recent Activity log records a collected session (depth 1)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_recent_activity_logs_session",)) # noqa: F405
+def test_recent_activity_logs_session():
+ # A completed+collected session (HOME-card path) writes a Mining entry into the
+ # Recent Activity log, which is empty on a fresh profile.
+ open_app_home(fresh=True)
+ ra0 = and_enter_recent_activity()
+ empty_before = bool(ra0 and find_node_ci(ra0, "No sessions completed yet.")) # noqa: F405
+ # close the sheet (Cancel), then run the loop
+ cn = find_node_ci(ui(), "Cancel") # noqa: F405
+ if cn:
+ tap_node(cn) # noqa: F405
+ settle("tap") # noqa: F405
+ and_reset_depth() # noqa: F405
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ and_reset_depth() # noqa: F405
+ ra1 = and_enter_recent_activity()
+ logged = bool(ra1 and find_node_ci(ra1, "Mining") # noqa: F405
+ and find_node_ci(ra1, "Rune Essence")) # noqa: F405
+ ok = bool(empty_before and started and reached and logged)
+ record("interaction_recent_activity_logs_session", ok, # noqa: F405
+ "" if ok else "behavior_wrong: a collected Mining/Rune Essence session was "
+ f"not written to Recent Activity (empty_before={empty_before} "
+ f"started={started} modal={reached} logged={logged})",
+ depth=1, jump_kind="transition",
+ expect="Recent Activity 'No sessions completed yet.' before -> a 'Mining'/"
+ "'Rune Essence' entry present after collecting the session")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 11. Multi-record integrity — Recent Activity keeps BOTH of two sessions (depth 1)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_multi_record_integrity",)) # noqa: F405
+def test_multi_record_integrity():
+ # Collect a Mining session, then a Fishing session, then assert the log holds
+ # BOTH ordered entries — a recreation that keeps only the latest row fails here.
+ open_app_home(fresh=True)
+ m_started = and_enter_active_session("Rune Essence", "Mining")
+ m_reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ and_reset_depth() # noqa: F405
+ f_started = and_enter_active_session("Raw Shrimp", "Fishing")
+ f_reached = and_reach_home_reward_modal()
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ and_reset_depth() # noqa: F405
+ ra = and_enter_recent_activity()
+ has_mining = bool(ra and find_node_ci(ra, "Mining")) # noqa: F405
+ has_fishing = bool(ra and find_node_ci(ra, "Fishing")) # noqa: F405
+ # ordering: the most-recent (Fishing) is entry '1' at the top -> Fishing above Mining
+ ordered = False
+ if ra:
+ mine = find_node_ci(ra, "Mining") # noqa: F405
+ fish = find_node_ci(ra, "Fishing") # noqa: F405
+ if mine and fish and "_center" in mine and "_center" in fish:
+ ordered = fish["_center"][1] < mine["_center"][1]
+ ok = bool(m_started and m_reached and f_started and f_reached
+ and has_mining and has_fishing and ordered)
+ record("interaction_multi_record_integrity", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the Recent Activity log did not retain BOTH "
+ f"sessions in order (mining={has_mining} fishing={has_fishing} "
+ f"ordered_fishing_above_mining={ordered} m={m_started}/{m_reached} "
+ f"f={f_started}/{f_reached})",
+ depth=1, jump_kind="transition",
+ expect="Recent Activity lists BOTH a 'Mining' and a 'Fishing' entry, the "
+ "later 'Fishing' above the earlier 'Mining'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 12. Long-press on a Home feature tile — sole owner of the context-menu surface
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_longpress_no_side_effect",)) # noqa: F405
+def test_longpress_no_side_effect():
+ # OBSERVED on the original: this Compose app exposes NO long-press context menu.
+ # A long-press on the Shop grid tile is treated like a click — it OPENS the Shop
+ # surface (header "Shop" + "Buy"/"Sell" sub-tabs appear) and produces no OS-level
+ # context menu and no destructive data mutation. long-press is this lane's
+ # sole-owned modality, so we assert its true consequence rather than a false
+ # "nothing happens". Total Level (Home data) must not have been mutated by the
+ # gesture itself.
+ open_app_home(fresh=True)
+ go_tab("Home")
+ before = home_total_level()
+ tile = find_node(ui(), text="Shop") # noqa: F405
+ pressed = bool(tile and is_safe(tile) and long_press(tile)) # noqa: F405
+ settle("tap") # noqa: F405
+ # The Shop surface is a lazy Compose swap; a single post-gesture dump can catch
+ # a half-built frame where 'Welcome back' has not yet been removed. Re-dump with
+ # extra settles until the Shop surface is fully showing (Buy+Sell present) — the
+ # observable consequence of the long-press. Still a real transition, read from a
+ # settled frame instead of a racing one.
+ nodes = ui() # noqa: F405
+ for _ in range(5):
+ if find_node_ci(nodes, "Buy") and find_node_ci(nodes, "Sell"): # noqa: F405
+ break
+ settle("tap") # noqa: F405
+ nodes = ui() # noqa: F405
+ # No OS context menu (this app has none of these verbs anywhere).
+ no_menu = not any(find_node_ci(nodes, w) for w in # noqa: F405
+ ("Pin", "Add to", "Shortcut", "App info", "Uninstall"))
+ # The long-press opened the Shop surface: Buy/Sell sub-tabs appeared AND the Home
+ # welcome line is gone from the settled tree — a genuine source->target swap.
+ on_shop = bool(find_node_ci(nodes, "Buy") and find_node_ci(nodes, "Sell")) # noqa: F405
+ home_gone = not find_node_ci(nodes, "Welcome back, Adventurer!") # noqa: F405
+ opened_shop = bool(on_shop and home_gone)
+ ok = bool(pressed and no_menu and opened_shop)
+ record("interaction_longpress_no_side_effect", ok, # noqa: F405
+ "" if ok else "behavior_wrong: long-press on Shop tile did not behave as "
+ f"observed (pressed={pressed} no_menu={no_menu} on_shop={on_shop} "
+ f"home_gone={home_gone} total_before={before})",
+ depth=1, jump_kind="transition",
+ expect="long-press Shop tile: no OS context menu, opens Shop surface "
+ "(Buy/Sell sub-tabs appear, Home 'Welcome back' disappears)")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 7) — rendered consequences the a11y tree cannot fully express
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("interaction_active_card_highlighted_vlm",)) # noqa: F405
+def test_active_card_highlighted_vlm():
+ # #1 — the active-session card renders on a warm gold/amber background.
+ open_app_home(fresh=True)
+ and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ vlm_assert("interaction_active_card_highlighted", # noqa: F405
+ "After starting a training session, is the session status card near "
+ "the middle of the screen filled with a warm gold/amber/brown "
+ "background that is clearly different from the blue player-stats card "
+ "above it?", RESULTS, tag="color", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("interaction_active_card_countdown_vlm",)) # noqa: F405
+def test_active_card_countdown_vlm():
+ # #5 — the active card shows a live countdown timer prominently.
+ open_app_home(fresh=True)
+ and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ vlm_assert("interaction_active_card_countdown", # noqa: F405
+ "Within the highlighted gold/amber session card, is a large "
+ "countdown time in minutes-and-seconds form (like '59m 44s') "
+ "displayed prominently?", RESULTS, tag="content",
+ depth=1, jump_kind="transition")
+
+
+@and_test(expects=("interaction_collect_button_vlm",)) # noqa: F405
+def test_collect_button_vlm():
+ # #4 — after Finish Now the Collect button renders as a large full-width gold button.
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ go_tab("Home")
+ tap_label("[Debug] Finish Now", last=True)
+ settle("tap") # noqa: F405
+ vlm_assert("interaction_collect_button", # noqa: F405
+ "Is there a large full-width button with a solid gold/amber "
+ "background (its text roughly 'Collect ... Rewards') spanning nearly "
+ "the whole width of the screen?", RESULTS, tag="color",
+ depth=1, jump_kind="transition")
+
+
+@and_test(expects=("interaction_reward_modal_layout_vlm",)) # noqa: F405
+def test_reward_modal_layout_vlm():
+ # #2 — the reward modal renders as a centered dialog listing XP + a loot list.
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ and_reach_home_reward_modal()
+ vlm_assert("interaction_reward_modal_layout", # noqa: F405
+ "Is a dialog/panel overlaying the screen that shows an XP amount near "
+ "the top and, below it, a vertical list of one or more reward/item "
+ "rows?", RESULTS, tag="layout", depth=2, jump_kind="transition")
+
+
+@and_test(expects=("interaction_skills_training_badge_vlm",)) # noqa: F405
+def test_skills_training_badge_vlm():
+ # #7 — during an active session the Skills-screen Mining row shows a distinct
+ # 'Training' badge in place of its XP text.
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ go_tab("Skills")
+ vlm_assert("interaction_skills_training_badge", # noqa: F405
+ "On the skills list, does the Mining row show a small pill/badge "
+ "labelled 'Training' (visually distinct from the progress text on "
+ "the other skill rows)?", RESULTS, tag="content",
+ depth=1, jump_kind="transition")
+
+
+TESTS = [
+ # rule track — CRUD / multi-step / persistence on DATA
+ test_core_loop_sequence,
+ test_collect_mutates_total_level,
+ test_collect_adds_inventory,
+ test_skill_level_persists,
+ test_session_survives_process_death,
+ test_abandon_clears_session,
+ test_start_cancel_no_session,
+ test_second_session_starts,
+ test_switch_active_skill,
+ test_recent_activity_logs_session,
+ test_multi_record_integrity,
+ test_longpress_no_side_effect,
+ # VLM track (exactly 5)
+ test_active_card_highlighted_vlm,
+ test_active_card_countdown_vlm,
+ test_collect_button_vlm,
+ test_reward_modal_layout_vlm,
+ test_skills_training_badge_vlm,
+]
+
+if __name__ == "__main__":
+ if not device_online(): # noqa: F405
+ print("WARNING: device offline — a whole module of setup_failed usually "
+ "means the emulator/tunnel dropped, not that the app is broken")
+ run_suite(TESTS, "interaction") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_navigation.py b/android/tristinbaker-idlefantasy/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..90a11c0144f9d9818eeaeb019b4d8bf96022ad36
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_navigation.py
@@ -0,0 +1,679 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — Idle Fantasy.
+
+Owns surface REACHABILITY and BACK-STACK integrity: tapping a nav trigger (bottom
+tab, Home feature tile, toolbar gear, list row) lands on the intended surface —
+proven by the TARGET surface's discriminating element APPEARING *and* the SOURCE
+surface's DISAPPEARING (and_reach) — and BACK unwinds the stack hop by hop. Sole
+owner of jump_kind="reach" and of the suite's depth>=2 chains.
+
+Live-derived on the original (re-observed, never trusted from prose):
+ * The app LAUNCHES onto the Skills tab, not Home — every Home-anchored test must
+ tap the Home bottom tab first. open_app_home() bakes that in.
+ * A finished WorkManager session can leave a "Session Results" modal on top after
+ a relaunch; dismiss_modals() taps its Close so the entry point is clean.
+ * Bottom nav (Skills/Combat/Home/Quests/Profile) PERSISTS across every surface,
+ so the nav labels are useless as reach anchors. Discriminating anchors used:
+ Home -> "Welcome back, Adventurer!" (unique Home content)
+ Skills -> "Expeditions" (Skills sub-tab, not a nav label)
+ Combat -> "Combat Lvl 1"
+ Quests -> "Resets at 6:00 AM"
+ Profile -> "Unnamed Adventurer"
+ Shop -> "Sell" Inn -> "Daily Menu" Guild -> "0 / 500 rep"
+ Church -> "XP Blessings" Slayer -> "Get New Task" Carnival -> "Tickets: 0"
+ Builder -> "Next Upgrade" Settings -> "Theme" / "Font Size"
+ * Compose modal SHEETS REPLACE the list in the a11y tree: Skills->Mining opens
+ "Choose Activity" and "Expeditions" DISAPPEARS; Combat->Farm opens "Enter
+ Dungeon" and "Combat Lvl 1" DISAPPEARS. BACK/Cancel restores the source.
+ * Home->Guild Hall->Mining Guild is the app's only 2-level PUSH chain (bottom
+ tabs do not push): the guild DETAIL ("Daily Requests") appears and the guild
+ LIST ("Fishing Guild") disappears; BACK x2 unwinds detail -> list -> Home. The
+ guild list/detail SHARE a lazy Compose scaffold that non-deterministically
+ retains recycled rows of the OTHER surface, so neither "Daily Requests" nor
+ and_reach's "newly appeared" is a reliable per-hop signal. The stable proof
+ that BACK#1 popped exactly one level to the intermediate LIST is: the list-only
+ row 'Fishing Guild' is PRESENT and Home is NOT yet showing; BACK#2 then lands
+ Home ('Welcome back' appears, 'Fishing Guild' gone). Each BACK needs an explicit
+ settle("tap") — the 0.5s key settle catches a half-built frame.
+ * Profile chip rail -> Bestiary -> Bosses sub-tab is a 2-hop chain within Profile
+ ("King Black Dragon" appears, the Enemies row "Abyssal Leech" disappears).
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this is only a single-emulator fallback,
+# assembled from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+BOTTOM_TABS = ("Skills", "Combat", "Home", "Quests", "Profile")
+
+# Discriminating anchors — a substring unique to each surface's CONTENT (never a
+# bottom-nav label, which persists everywhere). Used as target/source for and_reach.
+HOME_ANCHOR = "Welcome back, Adventurer!"
+SURFACE_ANCHOR = {
+ "Skills": "Expeditions",
+ "Combat": "Combat Lvl 1",
+ "Quests": "Resets at 6:00 AM",
+ "Profile": "Unnamed Adventurer",
+}
+TOWN = { # Home feature-grid tile label -> (tile match, destination anchor)
+ "Shop": ("Shop", "Sell"),
+ "Inn": ("Inn", "Daily Menu"),
+ "Guild Hall": ("Guild Hall", "0 / 500 rep"),
+ "Church": ("Church", "XP Blessings"),
+ "Slayer Master": ("Slayer Master", "Get New Task"),
+ "Carnival": ("Carnival", "Tickets: 0"),
+}
+
+
+def has_key(showing, sub):
+ """True iff any discriminating key in an and_showing() set contains `sub`
+ (case-insensitive). Used for membership assertions where and_reach's stricter
+ appeared/disappeared verdict is defeated by lazy-list recycling."""
+ s = sub.strip().lower()
+ return any(s in k.lower() for k in (showing or ()))
+
+
+# ── shared entry-point helpers (NOT depth family — no and_enter/and_reach here) ──
+def dismiss_permission():
+ """Dismiss the OS notification-permission dialog if it is on top. It belongs to
+ com.android.permissioncontroller, never the app under test, so tapping its allow
+ button is just a clean entry point, not part of any lane's behaviour."""
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the Create-Your-Character sheet iff present (returning profiles
+ skip straight past it)."""
+ n = find_node_ci(ui(), "Skip") # noqa: F405
+ if n and find_node_ci(ui(), "Create Your Character"): # noqa: F405
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ return True
+ return False
+
+
+def dismiss_modals():
+ """Close a lingering reward/results modal ('Session Results' + Close) that a
+ finished WorkManager session can leave on top after a relaunch."""
+ for _ in range(3):
+ n = find_node_ci(ui(), "Close") # noqa: F405
+ if n and safe_tap(n): # noqa: F405
+ settle("tap") # noqa: F405
+ else:
+ break
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by its label and settle. Returns the fresh tree.
+
+ Bottom-nav labels are duplicated inside some surfaces (Combat/Profile expose a
+ 'Skills' sub-tab/chip), so match the tab in the bottom-most row by y-order."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = None
+ if cands:
+ tab = max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ else:
+ tab = find_node_ci(ui(), label) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def open_app_home(fresh=False):
+ """Land on a settled HOME surface. The app opens on Skills, so we explicitly tap
+ the Home tab. fresh=True wipes data first (virgin profile: perm dialog +
+ onboarding); either way a leftover results modal is dismissed."""
+ if fresh:
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+ go_tab("Home")
+ return ui() # noqa: F405
+
+
+def tap_first(label):
+ """Tap the first (document-order) node whose text==label, else a CI match."""
+ n = find_node(ui(), text=label) or find_node_ci(ui(), label) # noqa: F405
+ return tap_node(n) if n else False # noqa: F405
+
+
+def tap_builder_tile():
+ """The Builder's Workshop tile label truncates to 'Builder's Wor…', so match by
+ the 'Builder' substring rather than the full label."""
+ for n in ui(): # noqa: F405
+ if "Builder" in n.get("text", ""):
+ return tap_node(n) # noqa: F405
+ return False
+
+
+# ── depth-family helpers (the and_enter_*/and_reach_* NAME backs a declared depth) ─
+def and_reach_tab(label, target, source):
+ """Bottom-nav jump: tap the tab, PROVE target appeared and source vanished.
+ Counts one surface via and_reach_surface. Returns bool."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = (max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ if cands else find_node_ci(ui(), label)) # noqa: F405
+ return bool(tab) and and_reach_surface(tab, target, source) # noqa: F405
+
+
+def and_reach_town(tile_label, dest_anchor):
+ """Home feature-grid tile -> town surface (depth1). Home's 'Welcome back,
+ Adventurer!' must disappear and the destination anchor appear."""
+ node = find_node(ui(), text=tile_label) or find_node_ci(ui(), tile_label) # noqa: F405
+ return bool(node) and and_reach_surface(node, dest_anchor, HOME_ANCHOR) # noqa: F405
+
+
+def and_reach_settings():
+ """Home -> Settings gear -> Settings screen (depth1). Proves 'Theme' appeared and
+ Home's 'Welcome back, Adventurer!' vanished."""
+ gear = find_node(ui(), content_desc="Settings") # noqa: F405
+ return bool(gear) and and_reach_surface(gear, "Theme", HOME_ANCHOR) # noqa: F405
+
+
+def and_reach_choose_activity(skill="Mining"):
+ """Skills tab (depth1) -> tap a skill -> 'Choose Activity' sheet (depth2). The
+ sheet REPLACES the list, so 'Expeditions' must disappear."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ row = find_node(ui(), text=skill) or find_node_ci(ui(), skill) # noqa: F405
+ return bool(row) and and_reach_surface(row, "Choose Activity", # noqa: F405
+ SURFACE_ANCHOR["Skills"])
+
+
+def and_reach_dungeon_sheet(dungeon="Farm"):
+ """Combat tab (depth1) -> tap a dungeon -> dungeon sheet (depth2). 'Enter Dungeon'
+ appears and 'Combat Lvl 1' disappears."""
+ go_tab("Combat")
+ and_enter("Combat") # noqa: F405
+ row = find_node(ui(), text=dungeon) or find_node_ci(ui(), dungeon) # noqa: F405
+ return bool(row) and and_reach_surface(row, "Enter Dungeon", # noqa: F405
+ SURFACE_ANCHOR["Combat"])
+
+
+def and_reach_guild_detail(guild="Mining Guild"):
+ """Home -> Guild Hall (depth1) -> a specific guild -> GuildDetail (depth2). The
+ detail's 'Daily Requests' appears and the guild LIST's 'Fishing Guild'
+ disappears. Returns bool."""
+ if not and_reach_town("Guild Hall", TOWN["Guild Hall"][1]):
+ return False
+ row = find_node(ui(), text=guild) or find_node_ci(ui(), guild) # noqa: F405
+ return bool(row) and and_reach_surface(row, "Daily Requests", # noqa: F405
+ "Fishing Guild")
+
+
+def and_reach_bestiary_bosses():
+ """Profile (depth1) -> Bestiary chip -> Bosses sub-tab (depth2). The chip switch
+ surfaces '0 / 64 encountered' (Enemies default); the Bosses sub-tab then flips
+ the list — 'King Black Dragon' appears, the Enemies row 'Abyssal Leech'
+ disappears. Returns (reached_pane, reached_bosses)."""
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ chip = find_node(ui(), text="Bestiary") # noqa: F405
+ if not chip or not and_reach_surface(chip, "0 / 64 encountered", "GATHERING"): # noqa: F405
+ return False, False
+ boss = find_node(ui(), text="Bosses") # noqa: F405
+ if not boss:
+ return True, False
+ reached = and_reach_surface(boss, "King Black Dragon", "Abyssal Leech") # noqa: F405
+ return True, reached
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# BOTTOM-NAV round trips (depth 1, jump_kind="reach")
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("nav_reach_skills",)) # noqa: F405
+def test_reach_skills():
+ open_app_home()
+ ok = and_reach_tab("Skills", SURFACE_ANCHOR["Skills"], HOME_ANCHOR)
+ record("nav_reach_skills", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Skills did not land on the Skills "
+ "surface (Expeditions did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Skills surface ('Expeditions') shown; Home 'Welcome back, "
+ "Adventurer!' no longer showing")
+
+
+@and_test(expects=("nav_reach_combat",)) # noqa: F405
+def test_reach_combat():
+ open_app_home()
+ ok = and_reach_tab("Combat", SURFACE_ANCHOR["Combat"], HOME_ANCHOR)
+ record("nav_reach_combat", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Combat did not land on the Combat "
+ "surface ('Combat Lvl 1' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Combat surface ('Combat Lvl 1') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_quests",)) # noqa: F405
+def test_reach_quests():
+ open_app_home()
+ ok = and_reach_tab("Quests", SURFACE_ANCHOR["Quests"], HOME_ANCHOR)
+ record("nav_reach_quests", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Quests did not land on the Quests "
+ "surface ('Resets at 6:00 AM' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Quests surface ('Resets at 6:00 AM') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_profile",)) # noqa: F405
+def test_reach_profile():
+ open_app_home()
+ ok = and_reach_tab("Profile", SURFACE_ANCHOR["Profile"], HOME_ANCHOR)
+ record("nav_reach_profile", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Profile did not land on the Profile "
+ "surface ('Unnamed Adventurer' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Profile surface ('Unnamed Adventurer') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_home_from_profile",)) # noqa: F405
+def test_reach_home_from_profile():
+ # Selected-tab actually SWITCHES content: from Profile, tapping Home swaps the
+ # Profile pane out for Home content.
+ open_app_home()
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ on_profile = bool(find_node_ci(ui(), SURFACE_ANCHOR["Profile"])) # noqa: F405
+ ok = on_profile and and_reach_tab("Home", HOME_ANCHOR, SURFACE_ANCHOR["Profile"])
+ record("nav_reach_home_from_profile", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Profile->Home did not switch content "
+ f"(on_profile={on_profile}) (Home anchor absent or Profile still shown)",
+ depth=1, jump_kind="reach",
+ expect="Home 'Welcome back, Adventurer!' shown; Profile 'Unnamed "
+ "Adventurer' no longer showing")
+
+
+@and_test(expects=("nav_reach_skills_to_combat",)) # noqa: F405
+def test_reach_skills_to_combat():
+ # Cross-surface without going through Home: Skills -> Combat directly.
+ open_app_home()
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ on_skills = bool(find_node_ci(ui(), SURFACE_ANCHOR["Skills"])) # noqa: F405
+ ok = on_skills and and_reach_tab("Combat", SURFACE_ANCHOR["Combat"],
+ SURFACE_ANCHOR["Skills"])
+ record("nav_reach_skills_to_combat", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Skills->Combat did not land on Combat "
+ f"(on_skills={on_skills}) ('Combat Lvl 1' absent or 'Expeditions' stayed)",
+ depth=1, jump_kind="reach",
+ expect="Combat surface ('Combat Lvl 1') shown; Skills 'Expeditions' gone")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# TOWN / UTILITY reach from the Home grid (depth 1, jump_kind="reach")
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("nav_reach_shop",)) # noqa: F405
+def test_reach_shop():
+ open_app_home()
+ ok = and_reach_town("Shop", TOWN["Shop"][1])
+ record("nav_reach_shop", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Shop tile did not open the Shop "
+ "('Sell' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Shop surface ('Sell' sub-tab) shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_inn",)) # noqa: F405
+def test_reach_inn():
+ open_app_home()
+ ok = and_reach_town("Inn", TOWN["Inn"][1])
+ record("nav_reach_inn", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Inn tile did not open the Inn "
+ "('Daily Menu' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Inn surface ('Daily Menu') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_guild_hall",)) # noqa: F405
+def test_reach_guild_hall():
+ open_app_home()
+ ok = and_reach_town("Guild Hall", TOWN["Guild Hall"][1])
+ record("nav_reach_guild_hall", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Guild Hall tile did not open the "
+ "Guild Hall ('0 / 500 rep' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Guild Hall surface ('0 / 500 rep') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_church",)) # noqa: F405
+def test_reach_church():
+ open_app_home()
+ ok = and_reach_town("Church", TOWN["Church"][1])
+ record("nav_reach_church", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Church tile did not open the Church "
+ "('XP Blessings' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Church surface ('XP Blessings') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_carnival",)) # noqa: F405
+def test_reach_carnival():
+ open_app_home()
+ ok = and_reach_town("Carnival", TOWN["Carnival"][1])
+ record("nav_reach_carnival", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Carnival tile did not open the "
+ "Carnival ('Tickets: 0' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Carnival surface ('Tickets: 0') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_slayer",)) # noqa: F405
+def test_reach_slayer():
+ open_app_home()
+ ok = and_reach_town("Slayer Master", TOWN["Slayer Master"][1])
+ record("nav_reach_slayer", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Slayer Master tile did not open the "
+ "Slayer surface ('Get New Task' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Slayer surface ('Get New Task') shown; Home 'Welcome back' gone")
+
+
+@and_test(expects=("nav_reach_builders",)) # noqa: F405
+def test_reach_builders():
+ # The tile label truncates to 'Builder's Wor…' -> match by substring.
+ open_app_home()
+ before = and_showing() # noqa: F405
+ tapped = tap_builder_tile()
+ after = and_showing() # noqa: F405
+ reached = and_reach(before, after, "Next Upgrade", HOME_ANCHOR) # noqa: F405
+ if reached:
+ and_enter("Builder's Workshop") # noqa: F405
+ ok = tapped and reached
+ record("nav_reach_builders", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Builder's Workshop tile did not open "
+ f"the workshop (tapped={tapped}) ('Next Upgrade' absent or Home stayed)",
+ depth=1, jump_kind="reach",
+ expect="Builder's Workshop surface ('Next Upgrade') shown; Home 'Welcome "
+ "back' gone")
+
+
+@and_test(expects=("nav_reach_settings",)) # noqa: F405
+def test_reach_settings():
+ open_app_home()
+ ok = and_reach_settings()
+ record("nav_reach_settings", ok, # noqa: F405
+ "" if ok else "feature_missing: Home->Settings gear did not open Settings "
+ "('Theme' did not appear or Home did not leave)",
+ depth=1, jump_kind="reach",
+ expect="Settings surface ('Theme') shown; Home 'Welcome back' gone")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# BACK-STACK integrity (depth 1-2, jump_kind="reach")
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("nav_backstack_settings",)) # noqa: F405
+def test_backstack_settings():
+ # Home -> Settings -> BACK restores Home.
+ open_app_home()
+ entered = and_reach_settings()
+ before = and_showing() # noqa: F405
+ and_back() # noqa: F405 (pops one surface)
+ settle("tap") # noqa: F405 let the Compose transition finish
+ after = and_showing() # noqa: F405
+ back_home = and_reach(before, after, HOME_ANCHOR, "Theme") # noqa: F405
+ ok = entered and back_home
+ record("nav_backstack_settings", ok, # noqa: F405
+ "" if ok else "behavior_wrong: BACK from Settings did not restore Home "
+ f"(entered={entered}) ('Welcome back' absent or 'Theme' stayed)",
+ depth=1, jump_kind="reach",
+ expect="After one BACK: Home 'Welcome back, Adventurer!' restored; "
+ "Settings 'Theme' no longer showing")
+
+
+@and_test(expects=("nav_backstack_shop",)) # noqa: F405
+def test_backstack_shop():
+ # Home -> Shop -> BACK restores Home.
+ open_app_home()
+ entered = and_reach_town("Shop", TOWN["Shop"][1])
+ before = and_showing() # noqa: F405
+ and_back() # noqa: F405
+ settle("tap") # noqa: F405 let the Compose transition finish
+ after = and_showing() # noqa: F405
+ back_home = and_reach(before, after, HOME_ANCHOR, "Sell") # noqa: F405
+ ok = entered and back_home
+ record("nav_backstack_shop", ok, # noqa: F405
+ "" if ok else "behavior_wrong: BACK from Shop did not restore Home "
+ f"(entered={entered}) ('Welcome back' absent or 'Sell' stayed)",
+ depth=1, jump_kind="reach",
+ expect="After one BACK: Home 'Welcome back, Adventurer!' restored; Shop "
+ "'Sell' no longer showing")
+
+
+@and_test(expects=("nav_cross_shop_to_skills",)) # noqa: F405
+def test_cross_shop_to_skills():
+ # A town screen keeps the bottom nav wired: from Shop, tapping the Skills tab
+ # lands on Skills (Shop gone).
+ open_app_home()
+ entered = and_reach_town("Shop", TOWN["Shop"][1])
+ reached = and_reach_tab("Skills", SURFACE_ANCHOR["Skills"], "Sell")
+ ok = entered and reached
+ record("nav_cross_shop_to_skills", ok, # noqa: F405
+ "" if ok else "behavior_wrong: bottom-nav Skills from Shop did not land on "
+ f"Skills (entered_shop={entered}) ('Expeditions' absent or 'Sell' stayed)",
+ depth=1, jump_kind="reach",
+ expect="Skills surface ('Expeditions') shown from Shop; Shop 'Sell' gone")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# DEPTH >= 2 chains (this lane owns them)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("nav_depth2_choose_activity",)) # noqa: F405
+def test_depth2_choose_activity():
+ # Home -> Skills (hop1) -> Mining -> Choose Activity sheet (hop2).
+ open_app_home()
+ reached = and_reach_choose_activity("Mining")
+ record("nav_depth2_choose_activity", reached, # noqa: F405
+ "" if reached else "feature_missing: Skills->Mining did not open the "
+ "Choose Activity sheet ('Choose Activity' absent or 'Expeditions' stayed)",
+ depth=2, jump_kind="reach",
+ expect="'Choose Activity' sheet shown after Skills->Mining; the Skills "
+ "list anchor 'Expeditions' no longer the top surface")
+
+
+@and_test(expects=("nav_depth2_dungeon_sheet",)) # noqa: F405
+def test_depth2_dungeon_sheet():
+ # Home -> Combat (hop1) -> Farm -> dungeon sheet (hop2).
+ open_app_home()
+ reached = and_reach_dungeon_sheet("Farm")
+ record("nav_depth2_dungeon_sheet", reached, # noqa: F405
+ "" if reached else "feature_missing: Combat->Farm did not open the dungeon "
+ "sheet ('Enter Dungeon' absent or 'Combat Lvl 1' stayed)",
+ depth=2, jump_kind="reach",
+ expect="Dungeon sheet ('Enter Dungeon') shown after Combat->Farm; the "
+ "Combat list anchor 'Combat Lvl 1' no longer the top surface")
+
+
+@and_test(expects=("nav_depth2_guild_detail",)) # noqa: F405
+def test_depth2_guild_detail():
+ # Home -> Guild Hall (hop1) -> Mining Guild -> GuildDetail (hop2).
+ open_app_home()
+ reached = and_reach_guild_detail("Mining Guild")
+ record("nav_depth2_guild_detail", reached, # noqa: F405
+ "" if reached else "feature_missing: Guild Hall->Mining Guild did not open "
+ "a guild detail ('Daily Requests' absent or the list 'Fishing Guild' stayed)",
+ depth=2, jump_kind="reach",
+ expect="Guild detail ('Daily Requests') shown after Guild Hall->Mining "
+ "Guild; the guild-list row 'Fishing Guild' no longer showing")
+
+
+@and_test(expects=("nav_depth2_bestiary_bosses",)) # noqa: F405
+def test_depth2_bestiary_bosses():
+ # Home -> Profile (hop1: chip to Bestiary) -> Bosses sub-tab (hop2).
+ open_app_home()
+ pane, bosses = and_reach_bestiary_bosses()
+ record("nav_depth2_bestiary_bosses", bool(pane and bosses), # noqa: F405
+ "" if (pane and bosses) else "feature_missing: Profile Bestiary->Bosses "
+ f"did not surface the boss list (pane={pane} bosses={bosses}) "
+ "('King Black Dragon' absent or 'Abyssal Leech' stayed)",
+ depth=2, jump_kind="reach",
+ expect="Bosses sub-tab list ('King Black Dragon') shown within Bestiary; "
+ "the Enemies row 'Abyssal Leech' no longer showing")
+
+
+@and_test(expects=("nav_backstack_2hop_guild",)) # noqa: F405
+def test_backstack_2hop_guild():
+ # Deepest surface back to Home, hop by hop: Home -> Guild Hall -> GuildDetail,
+ # then BACK unwinds detail -> guild list -> Home. Each BACK needs a settle("tap")
+ # before snapshotting or the dump catches a mid-transition Compose frame.
+ open_app_home()
+ deep = and_reach_guild_detail("Mining Guild")
+ # BACK #1: detail -> guild list. The guild list/detail share a lazy Compose
+ # scaffold that non-deterministically retains the OTHER surface's recycled rows,
+ # so the stable per-hop proof is that we popped exactly ONE level to the
+ # intermediate LIST: the list-only row 'Fishing Guild' is PRESENT and Home is
+ # NOT yet showing.
+ and_back() # noqa: F405
+ settle("tap") # noqa: F405
+ after1 = and_showing() # noqa: F405
+ to_list = has_key(after1, "Fishing Guild") and not has_key(after1, HOME_ANCHOR)
+ # BACK #2: guild list -> Home ('Welcome back' returns, 'Fishing Guild' gone).
+ and_back() # noqa: F405
+ settle("tap") # noqa: F405
+ after2 = and_showing() # noqa: F405
+ to_home = and_reach(after1, after2, HOME_ANCHOR, "Fishing Guild") # noqa: F405
+ ok = deep and to_list and to_home
+ record("nav_backstack_2hop_guild", ok, # noqa: F405
+ "" if ok else "behavior_wrong: 2-hop BACK did not unwind GuildDetail->"
+ f"list->Home hop by hop (deep={deep} to_list={to_list} to_home={to_home})",
+ depth=2, jump_kind="reach",
+ expect="BACK#1 pops to the intermediate guild list ('Fishing Guild' shown, "
+ "Home not yet); BACK#2 restores Home ('Welcome back, Adventurer!', "
+ "guild list gone)")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 7) — transition end-states / affordances the a11y tree cannot express
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("nav_settings_back_arrow_vlm",)) # noqa: F405
+def test_settings_back_arrow_vlm():
+ open_app_home()
+ and_reach_settings()
+ vlm_assert("nav_settings_back_arrow", # noqa: F405
+ "Is there a left-pointing back/up arrow icon at the very top-left of "
+ "the screen, to the left of the 'Settings' title?",
+ RESULTS, tag="shape")
+
+
+@and_test(expects=("nav_shop_toggle_vlm",)) # noqa: F405
+def test_shop_toggle_vlm():
+ open_app_home()
+ and_reach_town("Shop", TOWN["Shop"][1])
+ vlm_assert("nav_shop_toggle", # noqa: F405
+ "Near the top of the screen, are there exactly two side-by-side "
+ "segmented tabs labelled 'Buy' and 'Sell', with one underlined/"
+ "highlighted as selected?", RESULTS, tag="layout")
+
+
+@and_test(expects=("nav_selected_tab_highlight_vlm",)) # noqa: F405
+def test_selected_tab_highlight_vlm():
+ open_app_home() # ends on Home -> the Home tab should be the highlighted one
+ vlm_assert("nav_selected_tab_highlight", # noqa: F405
+ "In the bottom navigation bar of 5 tabs, is exactly ONE tab visually "
+ "highlighted with a distinct coloured background/pill behind its icon, "
+ "different from the other four?", RESULTS, tag="color")
+
+
+@and_test(expects=("nav_combat_dungeon_rows_vlm",)) # noqa: F405
+def test_combat_dungeon_rows_vlm():
+ open_app_home()
+ go_tab("Combat")
+ and_enter("Combat") # noqa: F405
+ vlm_assert("nav_combat_dungeon_rows", # noqa: F405
+ "Is the main content a vertical stack of dungeon rows where each row "
+ "shows a level label like 'Lv. 1' aligned to the right edge?",
+ RESULTS, tag="position")
+
+
+@and_test(expects=("nav_church_activate_cards_vlm",)) # noqa: F405
+def test_church_activate_cards_vlm():
+ open_app_home()
+ and_reach_town("Church", TOWN["Church"][1])
+ vlm_assert("nav_church_activate_cards", # noqa: F405
+ "Under an 'XP Blessings' heading, is there a vertical list of blessing "
+ "rows/cards, the first of which has an 'Activate' button on its right?",
+ RESULTS, tag="layout")
+
+
+@and_test(expects=("nav_choose_activity_sheet_vlm",)) # noqa: F405
+def test_choose_activity_sheet_vlm():
+ open_app_home()
+ and_reach_choose_activity("Mining")
+ vlm_assert("nav_choose_activity_sheet", # noqa: F405
+ "Is a bottom-sheet panel with rounded top corners and a small "
+ "horizontal drag handle overlaying the lower portion of the screen, "
+ "sitting above the dimmed content behind it?", RESULTS, tag="shape")
+
+
+@and_test(expects=("nav_profile_rail_vlm",)) # noqa: F405
+def test_profile_rail_vlm():
+ open_app_home()
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ vlm_assert("nav_profile_rail", # noqa: F405
+ "Down the LEFT side of the screen, is there a vertical column/rail of "
+ "stacked section labels (such as Skills, Inventory, Gear, Pets), with "
+ "one of them highlighted?", RESULTS, tag="position")
+
+
+TESTS = [
+ # bottom-nav round trips
+ test_reach_skills,
+ test_reach_combat,
+ test_reach_quests,
+ test_reach_profile,
+ test_reach_home_from_profile,
+ test_reach_skills_to_combat,
+ # town / utility reach
+ test_reach_shop,
+ test_reach_inn,
+ test_reach_guild_hall,
+ test_reach_church,
+ test_reach_carnival,
+ test_reach_slayer,
+ test_reach_builders,
+ test_reach_settings,
+ # back-stack integrity
+ test_backstack_settings,
+ test_backstack_shop,
+ test_cross_shop_to_skills,
+ # depth >= 2 chains
+ test_depth2_choose_activity,
+ test_depth2_dungeon_sheet,
+ test_depth2_guild_detail,
+ test_depth2_bestiary_bosses,
+ test_backstack_2hop_guild,
+ # VLM
+ test_settings_back_arrow_vlm,
+ test_shop_toggle_vlm,
+ test_selected_tab_highlight_vlm,
+ test_combat_dungeon_rows_vlm,
+ test_church_activate_cards_vlm,
+ test_choose_activity_sheet_vlm,
+ test_profile_rail_vlm,
+]
+
+if __name__ == "__main__":
+ if not device_online(): # noqa: F405
+ print("WARNING: device offline — a whole module of setup_failed usually "
+ "means the emulator/tunnel dropped, not that the app is broken")
+ run_suite(TESTS, "navigation") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_states.py b/android/tristinbaker-idlefantasy/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..5794038cbf32b9c593ef6b7fbfb2a95096376500
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_states.py
@@ -0,0 +1,899 @@
+#!/usr/bin/env python3
+"""STATES lane — Idle Fantasy (offline idle RPG, Jetpack Compose + Room).
+
+Owns widget STATE through before/after interaction: checked / enabled / selected /
+focused TRANSITIONS paired with the app-authored CONSEQUENCE, page-level state
+machines, conditional enable/disable, and SETTINGS/mode PERSISTENCE across process
+death. Sole owner of CHECKED and of focus. Every test captures state BEFORE,
+performs the user-path trigger, captures state AFTER, and asserts BOTH the flip
+AND (where the app authors one) the consequence.
+
+Live-derived on the RUNNING original (re-observed, never trusted from prose):
+ * The app LAUNCHES onto the Skills tab, not Home — every Home-anchored test taps
+ the Home bottom tab first (open_home() bakes that in).
+ * Settings EXPOSES `checked` far more richly than expected:
+ - Recent Activity Log -> a Compose Switch (checkable View), checked=true
+ default; tapping it flips true<->false IN-APP (stays on Settings) AND
+ gates the Home "Recent Activity" button (HomeScreen: showRecentActivityLog).
+ - Theme segmented [Dark/Light/System] -> each chip is a checkable View that
+ DOES expose `checked` (Dark=true default). Tapping Light sets Light=true,
+ Dark=false — a true rule transition, NOT visual-only.
+ - Profile Layout segmented [Rail/Tabs] -> checkable chips expose `checked`
+ (Rail=true default). Tapping Tabs sets Tabs=true, Rail=false, AND the
+ Profile screen relays out (section chip moves from a left rail x~100 to a
+ top tab row x~354) — a rule-observable consequence.
+ * Session Notifications is NOT an in-app checked toggle: tapping it DEEP-LINKS to
+ the OS notification-channel screen ("Navigate up" / "All Idle Fantasy
+ notifications" appear). So it is deliberately NOT used as a checked-flip rule
+ test — Recent Activity Log is the reliable in-app switch and covers the charter.
+ Its DEFAULT rendered thumb (right / gold) is still a fair VLM subject.
+ * Onboarding "Create Your Character" sheet: Confirm button's clickable View is
+ enabled=false while the name is blank and enabled=true once a non-blank name is
+ typed (source CharacterSetupSheet.kt: enabled = draftName.isNotBlank()). Gender
+ and Race chips are checkable Views that flip false->true on tap.
+ * Font Size dropdown is a state machine: tapping "Normal" OPENS a menu revealing
+ [Tiny/Small/Large/Huge] (closed -> open transition).
+ * Bottom-nav tabs and Quests sub-tabs do NOT expose selected/checked in the tree
+ (the gold highlight is visual only) -> those selection tests are VLM.
+ * PERSISTENCE: Recent Activity Log OFF and Theme=Light both SURVIVE
+ force_stop_and_relaunch() (Room / persisted settings). An in-memory recreation
+ fails these.
+
+Switches/chips are anonymous Compose Views (no text/id), so they are located by
+PROXIMITY to their visible label — never by a stale absolute position, which shifts
+after a flip. switch_for()/chip_for() re-derive the node from a FRESH dump each time.
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this single-emulator fallback is assembled
+# from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+HOME_ANCHOR = "Welcome back, Adventurer!"
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Entry helpers — each test owns its own entry via restart_app()/clear_data();
+# nothing relies on a previous test's toggle state.
+# ─────────────────────────────────────────────────────────────────────────────
+def dismiss_permission():
+ """Tap the OS notification-permission dialog's allow button iff it is on top.
+ It belongs to com.android.permissioncontroller, never the app under test, so
+ this is only a clean entry point, not part of any lane's behaviour."""
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the Create-Your-Character sheet iff present (returning profiles
+ skip straight past it). Skip is the SAFE dismissal — it keeps the default
+ profile without committing a character."""
+ nodes = ui() # noqa: F405
+ n = find_node_ci(nodes, "Skip") # noqa: F405
+ if n and find_node_ci(nodes, "Create Your Character"): # noqa: F405
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ return True
+ return False
+
+
+def dismiss_modals():
+ """Close a lingering reward/results modal that a finished WorkManager session
+ can leave on top after a relaunch, so the entry point is clean."""
+ for _ in range(3):
+ n = find_node_ci(ui(), "Close") # noqa: F405
+ if n and safe_tap(n): # noqa: F405
+ settle("tap") # noqa: F405
+ else:
+ break
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by label (the bottom-most match by y-order, since
+ some surfaces expose a same-named sub-tab/chip higher up) and settle."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = (max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ if cands else find_node_ci(ui(), label)) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def open_home(fresh=False):
+ """Land on a settled HOME surface. The app opens on Skills, so tap Home
+ explicitly. fresh=True wipes data first (virgin profile: perm dialog +
+ onboarding). A leftover results modal is always dismissed."""
+ if fresh:
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+ go_tab("Home")
+ return ui() # noqa: F405
+
+
+def open_onboarding():
+ """Virgin launch that leaves the Create-Your-Character sheet SHOWING over Home
+ (depth 0 — the sheet is the launch surface). Returns the fresh tree, or None if
+ the sheet never appeared."""
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ nodes = ui() # noqa: F405
+ return nodes if find_node_ci(nodes, "Create Your Character") else None # noqa: F405
+
+
+# ── depth-family helper (the and_enter_* NAME backs a declared depth>=1) ──────
+def and_enter_settings():
+ """Home -> Settings gear -> Settings screen (one surface crossed). Confirms the
+ Settings surface by its 'Theme' anchor and counts the surface via and_enter().
+ Returns True iff Settings opened."""
+ gear = find_node(ui(), content_desc="Settings") # noqa: F405
+ if not gear or not tap_node(gear): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ if find_node_ci(ui(), "Theme") is None: # noqa: F405
+ return False
+ and_enter("Settings") # noqa: F405
+ return True
+
+
+# ─────────────────────────────────────────────────────────────────────────────
+# Node locators — switches/chips are anonymous Compose Views; find them by their
+# label's position, re-derived from a FRESH dump on every call.
+# ─────────────────────────────────────────────────────────────────────────────
+def switch_for(nodes, label):
+ """The Compose Switch (checkable View) on the SAME ROW as `label`: the nearest
+ checkable node whose vertical center is within one row of the label, breaking
+ ties by horizontal distance. Switches sit to the right of their label."""
+ l = find_node_ci(nodes, label) # noqa: F405
+ if not l:
+ return None
+ lcx, lcy = l["_center"]
+ best, bestd = None, 1e18
+ for n in nodes:
+ if n.get("checkable") != "true":
+ continue
+ cx, cy = n["_center"]
+ if abs(cy - lcy) < 90:
+ d = abs(cy - lcy) * 1000 + abs(cx - lcx)
+ if d < bestd:
+ bestd, best = d, n
+ return best
+
+
+def chip_for(nodes, label):
+ """The segmented-control chip (checkable View) whose bounds ENCLOSE `label`'s
+ center — the chip that visually contains the word (Dark/Light/System,
+ Rail/Tabs, Male/Human, ...)."""
+ l = find_node_ci(nodes, label) # noqa: F405
+ if not l:
+ return None
+ cx, cy = l["_center"]
+ for n in nodes:
+ if n.get("checkable") != "true":
+ continue
+ b = n["_bounds"]
+ if b[0] - 5 <= cx <= b[2] + 5 and b[1] - 5 <= cy <= b[3] + 5:
+ return n
+ return None
+
+
+def confirm_view(nodes):
+ """The clickable View wrapping the onboarding 'Confirm' label — the smallest
+ clickable ancestor whose bounds contain the label center. That View carries the
+ `enabled` state (its inner Button always reports enabled=true), source:
+ enabled = draftName.isNotBlank()."""
+ txt = find_node(nodes, text="Confirm") # noqa: F405
+ if not txt:
+ return None
+ cx, cy = txt["_center"]
+ best, area = None, 1e18
+ for n in nodes:
+ if n.get("clickable") != "true":
+ continue
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if x1 <= cx <= x2 and y1 <= cy <= y2:
+ a = (x2 - x1) * (y2 - y1)
+ if a < area:
+ area, best = a, n
+ return best
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 1) Recent Activity Log switch — the signature in-app CHECKED flip + CONSEQUENCE
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_recent_activity_log_flip",
+ "states_recent_activity_log_thumb_off_vlm"))
+def test_recent_activity_log_flip():
+ """Recent Activity Log Switch: checked true -> false (two-way confirmed by
+ flipping back). Stays on Settings (same surface), so this is a pure state flip.
+ The thumb-position VLM confirms the switch RENDERED the OFF state."""
+ open_home()
+ if not and_enter_settings():
+ record("states_recent_activity_log_flip", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Recent Activity Log checked True->False")
+ vlm_assert("states_recent_activity_log_thumb_off", # noqa: F405
+ "Is the 'Recent Activity Log' switch thumb on the LEFT and grey "
+ "(the OFF position)?", RESULTS, tag="position",
+ depth=1, jump_kind="transition")
+ return
+ nodes = ui() # noqa: F405
+ sw = switch_for(nodes, "Recent Activity Log")
+ if sw is None:
+ record("states_recent_activity_log_flip", False, # noqa: F405
+ "feature_missing: no 'Recent Activity Log' switch", depth=1,
+ jump_kind="transition",
+ expect="Recent Activity Log checked True->False")
+ vlm_assert("states_recent_activity_log_thumb_off", # noqa: F405
+ "Is the 'Recent Activity Log' switch thumb on the LEFT and grey "
+ "(the OFF position)?", RESULTS, tag="position",
+ depth=1, jump_kind="transition")
+ return
+ before = sw.get("checked")
+ tap_node(sw) # noqa: F405
+ settle("tap") # noqa: F405
+ after = (switch_for(ui(), "Recent Activity Log") or {}).get("checked") # noqa: F405
+ # capture the OFF thumb before flipping back
+ vlm_assert("states_recent_activity_log_thumb_off", # noqa: F405
+ "Look at the 'Recent Activity Log' row's toggle switch. Is its thumb "
+ "on the LEFT side and grey/uncoloured (the OFF position)?", RESULTS,
+ tag="position", depth=1, jump_kind="transition")
+ # flip back (two-way) and confirm it returns to the original state
+ sw_now = switch_for(ui(), "Recent Activity Log") # noqa: F405
+ if sw_now:
+ tap_node(sw_now) # noqa: F405
+ settle("tap") # noqa: F405
+ back_again = (switch_for(ui(), "Recent Activity Log") or {}).get("checked") # noqa: F405
+ ok = (before == "true" and after == "false" and back_again == "true")
+ record("states_recent_activity_log_flip", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: checked did not flip two-way "
+ f"(before={before}, after={after}, back={back_again})",
+ depth=1, jump_kind="transition",
+ expect="Recent Activity Log checked: True->False->True (two-way)")
+
+
+@and_test(expects=("states_recent_activity_consequence",))
+def test_recent_activity_consequence():
+ """State -> CONSEQUENCE on ANOTHER screen: turning Recent Activity Log OFF makes
+ the Home header 'Recent Activity' button DISAPPEAR (HomeScreen gates it on
+ showRecentActivityLog); ON restores it. Asserts the button presence flipped
+ with the switch."""
+ open_home()
+ home_before = find_node_ci(ui(), "Recent Activity") # noqa: F405
+ present_before = home_before is not None
+ if not and_enter_settings():
+ record("states_recent_activity_consequence", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="RAL OFF -> Home 'Recent Activity' button hidden")
+ return
+ sw = switch_for(ui(), "Recent Activity Log")
+ if sw is None:
+ record("states_recent_activity_consequence", False, # noqa: F405
+ "feature_missing: no 'Recent Activity Log' switch", depth=1,
+ jump_kind="transition",
+ expect="RAL OFF -> Home 'Recent Activity' button hidden")
+ return
+ # turn it OFF (it defaults ON)
+ if sw.get("checked") == "true":
+ tap_node(sw) # noqa: F405
+ settle("tap") # noqa: F405
+ off_state = (switch_for(ui(), "Recent Activity Log") or {}).get("checked") # noqa: F405
+ # back to Home and check the consequence
+ back() # noqa: F405
+ settle("tap") # noqa: F405
+ go_tab("Home")
+ present_after = find_node_ci(ui(), "Recent Activity") is not None # noqa: F405
+ ok = (present_before is True and off_state == "false"
+ and present_after is False)
+ record("states_recent_activity_consequence", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Home 'Recent Activity' button did not "
+ f"track the switch (present_before={present_before}, off={off_state}, "
+ f"present_after={present_after})",
+ depth=1, jump_kind="transition",
+ expect="switch True->False; Home 'Recent Activity' button showing->hidden")
+
+
+@and_test(expects=("states_recent_activity_log_persists",))
+def test_recent_activity_log_persists():
+ """PERSISTENCE across process death: flip Recent Activity Log OFF, kill the
+ process (force_stop_and_relaunch), reopen Settings, assert it is STILL OFF. An
+ in-memory-only recreation loses the flip and fails. (No clear_data between the
+ flip and the restart — that would wipe the very state under test.)"""
+ open_home()
+ if not and_enter_settings():
+ record("states_recent_activity_log_persists", False, # noqa: F405
+ "setup_failed: could not open Settings (pre-flip)", depth=1,
+ jump_kind="transition",
+ expect="RAL OFF survives process death (still False)")
+ return
+ sw = switch_for(ui(), "Recent Activity Log")
+ if sw is None:
+ record("states_recent_activity_log_persists", False, # noqa: F405
+ "feature_missing: no 'Recent Activity Log' switch", depth=1,
+ jump_kind="transition",
+ expect="RAL OFF survives process death (still False)")
+ return
+ if sw.get("checked") == "true":
+ tap_node(sw) # noqa: F405
+ settle("tap") # noqa: F405
+ off_state = (switch_for(ui(), "Recent Activity Log") or {}).get("checked") # noqa: F405
+ # kill + relaunch (NO clear_data)
+ force_stop_and_relaunch() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ dismiss_modals()
+ go_tab("Home")
+ reopened = and_enter_settings()
+ persisted = (switch_for(ui(), "Recent Activity Log") or {}).get("checked") # noqa: F405
+ ok = (off_state == "false" and reopened and persisted == "false")
+ record("states_recent_activity_log_persists", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: switch did not survive process death "
+ f"(off_before={off_state}, reopened={reopened}, after_restart={persisted})",
+ depth=1, jump_kind="transition",
+ expect="Recent Activity Log checked stays False after force-stop+relaunch")
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 2) Theme segmented control — checked flip (rule) + rendered highlight (VLM)
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_theme_dark_to_light",
+ "states_theme_light_chip_highlight_vlm"))
+def test_theme_dark_to_light():
+ """Theme segmented [Dark/Light/System]: tapping 'Light' flips the CHECKED state
+ of BOTH chips — Dark true->false and Light false->true. A VLM confirms the
+ RENDERED consequence the tree cannot show: the highlighted chip moved to Light.
+ (The dark->light BACKGROUND change is asserted by states_theme_persists' VLM.)"""
+ open_home()
+ if not and_enter_settings():
+ vlm_assert("states_theme_light_chip_highlight", # noqa: F405
+ "Is the 'Light' chip the highlighted/selected one in the Theme "
+ "row?", RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_theme_dark_to_light", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Theme: Dark checked True->False, Light False->True")
+ return
+ nodes = ui() # noqa: F405
+ dark, light = chip_for(nodes, "Dark"), chip_for(nodes, "Light")
+ if dark is None or light is None:
+ vlm_assert("states_theme_light_chip_highlight", # noqa: F405
+ "Is the 'Light' chip the highlighted/selected one in the Theme "
+ "row?", RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_theme_dark_to_light", False, # noqa: F405
+ "feature_missing: Theme Dark/Light chips not found", depth=1,
+ jump_kind="transition",
+ expect="Theme: Dark checked True->False, Light False->True")
+ return
+ dark_before, light_before = dark.get("checked"), light.get("checked")
+ tap_node(light) # noqa: F405
+ settle("tap") # noqa: F405
+ nodes2 = ui() # noqa: F405
+ dark_after = (chip_for(nodes2, "Dark") or {}).get("checked")
+ light_after = (chip_for(nodes2, "Light") or {}).get("checked")
+ # VLMs while Light is active
+ vlm_assert("states_theme_light_chip_highlight", # noqa: F405
+ "In the Theme segmented control [Dark | Light | System], is the "
+ "'Light' chip the one with the filled/highlighted background "
+ "(the selected chip), rather than 'Dark'?", RESULTS,
+ tag="color", depth=1, jump_kind="transition")
+ ok = (dark_before == "true" and light_before == "false"
+ and dark_after == "false" and light_after == "true")
+ record("states_theme_dark_to_light", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Theme chip checked did not swap "
+ f"(Dark {dark_before}->{dark_after}, Light {light_before}->{light_after})",
+ depth=1, jump_kind="transition",
+ expect="Theme: Dark checked True->False, Light False->True")
+ # restore to Dark for later lanes
+ d = chip_for(ui(), "Dark") # noqa: F405
+ if d and d.get("checked") == "false":
+ tap_node(d) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+@and_test(expects=("states_theme_system_select",))
+def test_theme_system_select():
+ """Third segment: tapping 'System' sets System checked=true and clears both Dark
+ and Light (false) — a segmented control keeps exactly one chip checked."""
+ open_home()
+ if not and_enter_settings():
+ record("states_theme_system_select", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Theme System checked False->True; Dark & Light -> False")
+ return
+ nodes = ui() # noqa: F405
+ system = chip_for(nodes, "System")
+ if system is None:
+ record("states_theme_system_select", False, # noqa: F405
+ "feature_missing: Theme 'System' chip not found", depth=1,
+ jump_kind="transition",
+ expect="Theme System checked False->True; Dark & Light -> False")
+ return
+ sys_before = system.get("checked")
+ tap_node(system) # noqa: F405
+ settle("tap") # noqa: F405
+ nodes2 = ui() # noqa: F405
+ sys_after = (chip_for(nodes2, "System") or {}).get("checked")
+ dark_after = (chip_for(nodes2, "Dark") or {}).get("checked")
+ light_after = (chip_for(nodes2, "Light") or {}).get("checked")
+ ok = (sys_before == "false" and sys_after == "true"
+ and dark_after == "false" and light_after == "false")
+ record("states_theme_system_select", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: System did not become the sole checked "
+ f"chip (System {sys_before}->{sys_after}, Dark={dark_after}, "
+ f"Light={light_after})",
+ depth=1, jump_kind="transition",
+ expect="Theme: System checked False->True, Dark & Light forced False")
+ # restore to Dark
+ d = chip_for(ui(), "Dark") # noqa: F405
+ if d and d.get("checked") == "false":
+ tap_node(d) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+@and_test(expects=("states_theme_persists",
+ "states_theme_persist_background_vlm"))
+def test_theme_persists():
+ """PERSISTENCE #2: set Theme=Light, kill the process, reopen Settings, assert
+ Light is STILL the checked chip (and the app relaunched in a light background,
+ confirmed by VLM). No clear_data between set and restart."""
+ open_home()
+ if not and_enter_settings():
+ vlm_assert("states_theme_persist_background", # noqa: F405
+ "Is the app background light/white (light theme) after relaunch?",
+ RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_theme_persists", False, # noqa: F405
+ "setup_failed: could not open Settings (pre-set)", depth=1,
+ jump_kind="transition",
+ expect="Theme=Light survives process death (Light still checked)")
+ return
+ light = chip_for(ui(), "Light")
+ if light is None:
+ vlm_assert("states_theme_persist_background", # noqa: F405
+ "Is the app background light/white (light theme) after relaunch?",
+ RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_theme_persists", False, # noqa: F405
+ "feature_missing: Theme 'Light' chip not found", depth=1,
+ jump_kind="transition",
+ expect="Theme=Light survives process death (Light still checked)")
+ return
+ if light.get("checked") == "false":
+ tap_node(light) # noqa: F405
+ settle("tap") # noqa: F405
+ set_state = (chip_for(ui(), "Light") or {}).get("checked")
+ # kill + relaunch (NO clear_data)
+ force_stop_and_relaunch() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ dismiss_modals()
+ go_tab("Home")
+ reopened = and_enter_settings()
+ persisted = (chip_for(ui(), "Light") or {}).get("checked")
+ dark_after = (chip_for(ui(), "Dark") or {}).get("checked")
+ # VLM: the relaunched Settings screen should render light
+ vlm_assert("states_theme_persist_background", # noqa: F405
+ "After the app was fully restarted, is the app background LIGHT "
+ "(white / very light) with dark text, i.e. the light theme was "
+ "remembered rather than reverting to the dark theme?", RESULTS,
+ tag="color", depth=1, jump_kind="transition")
+ ok = (set_state == "true" and reopened and persisted == "true"
+ and dark_after == "false")
+ record("states_theme_persists", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Theme did not survive process death "
+ f"(set={set_state}, reopened={reopened}, Light_after={persisted}, "
+ f"Dark_after={dark_after})",
+ depth=1, jump_kind="transition",
+ expect="Theme=Light checked stays True after force-stop+relaunch")
+ # restore to Dark
+ d = chip_for(ui(), "Dark") # noqa: F405
+ if d and d.get("checked") == "false":
+ tap_node(d) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 3) Profile Layout segmented — checked flip (rule) + layout consequence + VLM
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_profile_layout_rail_to_tabs",
+ "states_profile_layout_tabs_chip_highlight_vlm"))
+def test_profile_layout_rail_to_tabs():
+ """Profile Layout segmented [Rail/Tabs]: tapping 'Tabs' flips CHECKED — Rail
+ true->false, Tabs false->true. VLM confirms the highlighted chip moved to
+ 'Tabs'."""
+ open_home()
+ if not and_enter_settings():
+ vlm_assert("states_profile_layout_tabs_chip_highlight", # noqa: F405
+ "Is the 'Tabs' chip the highlighted one in the Profile Layout row?",
+ RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_profile_layout_rail_to_tabs", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Profile Layout: Rail checked True->False, Tabs False->True")
+ return
+ nodes = ui() # noqa: F405
+ rail, tabs = chip_for(nodes, "Rail"), chip_for(nodes, "Tabs")
+ if rail is None or tabs is None:
+ vlm_assert("states_profile_layout_tabs_chip_highlight", # noqa: F405
+ "Is the 'Tabs' chip the highlighted one in the Profile Layout row?",
+ RESULTS, tag="color", depth=1, jump_kind="transition")
+ record("states_profile_layout_rail_to_tabs", False, # noqa: F405
+ "feature_missing: Profile Layout Rail/Tabs chips not found", depth=1,
+ jump_kind="transition",
+ expect="Profile Layout: Rail checked True->False, Tabs False->True")
+ return
+ rail_before, tabs_before = rail.get("checked"), tabs.get("checked")
+ tap_node(tabs) # noqa: F405
+ settle("tap") # noqa: F405
+ nodes2 = ui() # noqa: F405
+ rail_after = (chip_for(nodes2, "Rail") or {}).get("checked")
+ tabs_after = (chip_for(nodes2, "Tabs") or {}).get("checked")
+ vlm_assert("states_profile_layout_tabs_chip_highlight", # noqa: F405
+ "In the Profile Layout segmented control [Rail | Tabs], is the 'Tabs' "
+ "chip now the one with the filled/highlighted background (selected), "
+ "rather than 'Rail'?", RESULTS, tag="color", depth=1,
+ jump_kind="transition")
+ ok = (rail_before == "true" and tabs_before == "false"
+ and rail_after == "false" and tabs_after == "true")
+ record("states_profile_layout_rail_to_tabs", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Profile Layout chip checked did not swap "
+ f"(Rail {rail_before}->{rail_after}, Tabs {tabs_before}->{tabs_after})",
+ depth=1, jump_kind="transition",
+ expect="Profile Layout: Rail checked True->False, Tabs False->True")
+ # restore to Rail
+ r = chip_for(ui(), "Rail") # noqa: F405
+ if r and r.get("checked") == "false":
+ tap_node(r) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+@and_test(expects=("states_profile_layout_consequence",
+ "states_profile_layout_tabs_screen_vlm"))
+def test_profile_layout_consequence():
+ """State -> CONSEQUENCE on the Profile screen: with Rail the section selector is
+ a LEFT-EDGE vertical rail (the 'Inventory' chip sits at x~100); switching to
+ Tabs moves it into a TOP horizontal tab row (x shifts right, ~354). Asserts the
+ Inventory chip's x-position crossed from the left edge to the tab row. A VLM
+ confirms the rendered rail-vs-tabs layout."""
+ open_home()
+
+ def inv_x():
+ n = find_node(ui(), text="Inventory") # noqa: F405
+ return n["_center"][0] if n else None
+
+ # observe default (Rail) Profile layout
+ go_tab("Profile")
+ x_rail = inv_x()
+ go_tab("Home")
+ if not and_enter_settings():
+ vlm_assert("states_profile_layout_tabs_screen", # noqa: F405
+ "On the Profile screen, are the section names in a TOP horizontal "
+ "tab row rather than a vertical rail on the left edge?", RESULTS,
+ tag="layout", depth=2, jump_kind="transition")
+ record("states_profile_layout_consequence", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Rail->Tabs moves Profile section selector left-rail -> top-row")
+ return
+ tabs = chip_for(ui(), "Tabs")
+ if tabs is None:
+ vlm_assert("states_profile_layout_tabs_screen", # noqa: F405
+ "On the Profile screen, are the section names in a TOP horizontal "
+ "tab row rather than a vertical rail on the left edge?", RESULTS,
+ tag="layout", depth=2, jump_kind="transition")
+ record("states_profile_layout_consequence", False, # noqa: F405
+ "feature_missing: Profile Layout 'Tabs' chip not found", depth=1,
+ jump_kind="transition",
+ expect="Rail->Tabs moves Profile section selector left-rail -> top-row")
+ return
+ if tabs.get("checked") == "false":
+ tap_node(tabs) # noqa: F405
+ settle("tap") # noqa: F405
+ back() # noqa: F405
+ settle("tap") # noqa: F405
+ # now on Profile the selector should be a top row (deeper surface: Profile pane)
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ x_tabs = inv_x()
+ vlm_assert("states_profile_layout_tabs_screen", # noqa: F405
+ "On this Profile screen, are the section labels (Skills, Inventory, "
+ "Gear, ...) laid out as a HORIZONTAL row of tabs across the TOP, "
+ "rather than as a vertical rail of icons down the LEFT edge?", RESULTS,
+ tag="layout", depth=2, jump_kind="transition")
+ ok = (x_rail is not None and x_tabs is not None
+ and x_rail < 200 and x_tabs > 250 and x_tabs > x_rail)
+ record("states_profile_layout_consequence", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Profile selector did not move rail->tabs "
+ f"(Inventory x rail={x_rail}, tabs={x_tabs})",
+ depth=2, jump_kind="transition",
+ expect="Rail: Inventory chip x~100 (left rail) -> Tabs: x~354 (top row)")
+ # restore layout to Rail
+ go_tab("Home")
+ if and_enter_settings():
+ r = chip_for(ui(), "Rail") # noqa: F405
+ if r and r.get("checked") == "false":
+ tap_node(r) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 4) Onboarding — conditional enable (Confirm) + checkable chip flips
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_onboarding_confirm_enable",))
+def test_onboarding_confirm_enable():
+ """Conditional enable/disable: the Create-Your-Character 'Confirm' button is
+ DISABLED (enabled=false) while the Character Name is blank and becomes ENABLED
+ (enabled=true) the moment a non-blank name is typed (source:
+ enabled = draftName.isNotBlank()). Asserts the exact false->true transition read
+ from the view tree. NOTE: no VLM here — on this app the only keyboard dismiss is
+ BACK, which closes the whole sheet (Confirm then vanishes), so a reliable
+ screenshot of the enabled Confirm is not portable; the `enabled=true` bit IS the
+ state and is asserted directly from the tree with the keyboard still up."""
+ nodes = open_onboarding()
+ if nodes is None:
+ record("states_onboarding_confirm_enable", False, # noqa: F405
+ "setup_failed: onboarding sheet did not appear", depth=0,
+ jump_kind="transition",
+ expect="Confirm enabled False->True after typing a name")
+ return
+ cv = confirm_view(nodes)
+ et = find_by_class(nodes, "EditText") # noqa: F405
+ if cv is None or not et:
+ record("states_onboarding_confirm_enable", False, # noqa: F405
+ "feature_missing: Confirm button or name field not found", depth=0,
+ jump_kind="transition",
+ expect="Confirm enabled False->True after typing a name")
+ return
+ enabled_before = cv.get("enabled")
+ type_text(et[0], "Aria") # noqa: F405
+ settle("tap") # noqa: F405
+ # Do NOT hide_keyboard(): the dismiss sends BACK, which closes the whole sheet
+ # (the Confirm view then vanishes -> after=None). The Confirm view's `enabled`
+ # bit updates on the text change independently of the keyboard, so read it while
+ # the sheet is still up. Re-dump until the state settles (Compose recomposes
+ # async) — still the exact false->true transition, from a stable frame.
+ nodes2 = ui() # noqa: F405
+ cv2 = confirm_view(nodes2)
+ for _ in range(6):
+ if cv2 is not None and cv2.get("enabled") == "true":
+ break
+ settle("tap") # noqa: F405
+ nodes2 = ui() # noqa: F405
+ cv2 = confirm_view(nodes2)
+ enabled_after = cv2.get("enabled") if cv2 else None
+ ok = (enabled_before == "false" and enabled_after == "true")
+ record("states_onboarding_confirm_enable", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Confirm did not enable on name entry "
+ f"(enabled before={enabled_before}, after={enabled_after})",
+ depth=0, jump_kind="transition",
+ expect="Confirm button enabled: False (blank name) -> True (name 'Aria')")
+
+
+@and_test(expects=("states_onboarding_gender_chip",))
+def test_onboarding_gender_chip():
+ """Checkable selection on the onboarding sheet: the 'Male' gender chip is a
+ checkable View, checked=false initially, and flips to checked=true when tapped
+ (single-select). depth 0 — the sheet is the launch surface over Home."""
+ nodes = open_onboarding()
+ if nodes is None:
+ record("states_onboarding_gender_chip", False, # noqa: F405
+ "setup_failed: onboarding sheet did not appear", depth=0,
+ jump_kind="transition", expect="Male gender chip checked False->True")
+ return
+ male = chip_for(nodes, "Male")
+ if male is None:
+ record("states_onboarding_gender_chip", False, # noqa: F405
+ "feature_missing: 'Male' gender chip not found", depth=0,
+ jump_kind="transition", expect="Male gender chip checked False->True")
+ return
+ before = male.get("checked")
+ tap_node(male) # noqa: F405
+ settle("tap") # noqa: F405
+ after = (chip_for(ui(), "Male") or {}).get("checked") # noqa: F405
+ ok = (before == "false" and after == "true")
+ record("states_onboarding_gender_chip", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Male chip checked did not flip "
+ f"(before={before}, after={after})",
+ depth=0, jump_kind="transition",
+ expect="Male gender chip checked: False->True on tap")
+
+
+@and_test(expects=("states_onboarding_race_chip",))
+def test_onboarding_race_chip():
+ """A second checkable selection: the 'Human' race chip flips checked
+ false->true on tap (single-select race group). depth 0."""
+ nodes = open_onboarding()
+ if nodes is None:
+ record("states_onboarding_race_chip", False, # noqa: F405
+ "setup_failed: onboarding sheet did not appear", depth=0,
+ jump_kind="transition", expect="Human race chip checked False->True")
+ return
+ human = chip_for(nodes, "Human")
+ if human is None:
+ record("states_onboarding_race_chip", False, # noqa: F405
+ "feature_missing: 'Human' race chip not found", depth=0,
+ jump_kind="transition", expect="Human race chip checked False->True")
+ return
+ before = human.get("checked")
+ tap_node(human) # noqa: F405
+ settle("tap") # noqa: F405
+ after = (chip_for(ui(), "Human") or {}).get("checked") # noqa: F405
+ ok = (before == "false" and after == "true")
+ record("states_onboarding_race_chip", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: Human chip checked did not flip "
+ f"(before={before}, after={after})",
+ depth=0, jump_kind="transition",
+ expect="Human race chip checked: False->True on tap")
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 5) Font Size dropdown — a closed -> open state machine
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_font_size_dropdown_opens",))
+def test_font_size_dropdown_opens():
+ """State machine: the Font Size dropdown is CLOSED by default (its menu options
+ are absent); tapping the current value 'Normal' OPENS the menu, revealing the
+ option items [Tiny / Small / Large / Huge] that were not in the tree before.
+ Asserts option count 0 (closed) -> >=2 (open). Closes it with BACK to leave
+ Settings clean."""
+ open_home()
+ if not and_enter_settings():
+ record("states_font_size_dropdown_opens", False, # noqa: F405
+ "setup_failed: could not open Settings", depth=1,
+ jump_kind="transition",
+ expect="Font Size dropdown closed->open (option items appear)")
+ return
+ OPTIONS = ("Tiny", "Small", "Large", "Huge")
+ before_nodes = ui() # noqa: F405
+ opts_before = sum(1 for o in OPTIONS
+ if find_node(before_nodes, text=o) is not None) # noqa: F405
+ trigger = find_node_ci(before_nodes, "Normal") # noqa: F405
+ if trigger is None:
+ record("states_font_size_dropdown_opens", False, # noqa: F405
+ "feature_missing: Font Size 'Normal' value not found", depth=1,
+ jump_kind="transition",
+ expect="Font Size dropdown closed->open (option items appear)")
+ return
+ tap_node(trigger) # noqa: F405
+ settle("tap") # noqa: F405
+ after_nodes = ui() # noqa: F405
+ opts_after = sum(1 for o in OPTIONS
+ if find_node(after_nodes, text=o) is not None) # noqa: F405
+ ok = (opts_before == 0 and opts_after >= 2)
+ record("states_font_size_dropdown_opens", ok, # noqa: F405
+ "" if ok else f"behavior_wrong: dropdown did not open into a menu "
+ f"(option items before={opts_before}, after={opts_after})",
+ depth=1, jump_kind="transition",
+ expect="Font Size: closed (0 option items) -> open (Tiny/Small/Large/Huge)")
+ # close the menu without changing the value
+ back() # noqa: F405
+ settle("tap") # noqa: F405
+
+
+# ═════════════════════════════════════════════════════════════════════════════
+# 6) VLM-only rendered selection state (bottom nav + Quests sub-tab) — the gold
+# highlight is not exposed in the a11y tree, so these are genuine VLM subjects.
+# ═════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("states_bottom_nav_home_selected_vlm",))
+def test_bottom_nav_home_selected_vlm():
+ """Bottom-nav SELECTED state is visual only (labels report selected=false), so
+ it must be a VLM. On Home, the 'Home' tab carries the gold circular highlight."""
+ open_home()
+ go_tab("Home")
+ vlm_assert("states_bottom_nav_home_selected", # noqa: F405
+ "In the bottom navigation bar (Skills, Combat, Home, Quests, "
+ "Profile), is the 'Home' tab in the CENTER the one that is "
+ "highlighted/selected (a gold/coloured circular background behind "
+ "its icon), while the others are plain grey?", RESULTS,
+ tag="color", depth=0, jump_kind="transition")
+
+
+@and_test(expects=("states_bottom_nav_skills_selected_vlm",))
+def test_bottom_nav_skills_selected_vlm():
+ """The selection MOVES: after tapping the 'Skills' tab, the gold highlight is on
+ 'Skills' (leftmost) and no longer on 'Home'. VLM (visual-only selection)."""
+ open_home()
+ go_tab("Skills")
+ vlm_assert("states_bottom_nav_skills_selected", # noqa: F405
+ "In the bottom navigation bar, is the LEFTMOST 'Skills' tab now the "
+ "highlighted/selected one (gold/coloured circular highlight behind "
+ "its icon), and is the center 'Home' tab NOT highlighted?", RESULTS,
+ tag="color", depth=0, jump_kind="transition")
+
+
+@and_test(expects=("states_quests_daily_subtab_selected_vlm",))
+def test_quests_daily_subtab_selected_vlm():
+ """Quests sub-tab selection is visual only (Daily/Weekly report selected=false),
+ so it is a VLM: on the Timed tab, 'Daily' is the highlighted sub-tab (filled /
+ underlined) and 'Weekly' is not."""
+ open_home()
+ go_tab("Quests")
+ # ensure the Timed tab is active (default) so Daily/Weekly are visible
+ timed = find_node_ci(ui(), "Timed") # noqa: F405
+ if timed:
+ tap_node(timed) # noqa: F405
+ settle("tap") # noqa: F405
+ vlm_assert("states_quests_daily_subtab_selected", # noqa: F405
+ "On the Quests screen's Timed section there are two sub-tabs 'Daily' "
+ "and 'Weekly'. Is 'Daily' the currently SELECTED sub-tab (filled / "
+ "highlighted / underlined) while 'Weekly' is the unselected one?",
+ RESULTS, tag="color", depth=1, jump_kind="transition")
+
+
+@and_test(expects=("states_session_notifications_thumb_on_vlm",))
+def test_session_notifications_thumb_on_vlm():
+ """Session Notifications is a Switch shown ON by default (checked=true in the
+ tree). Its RENDERED thumb position/colour is a fine visual property: the thumb
+ sits on the RIGHT and is gold/coloured (the ON state). Screenshot-only — no tap
+ (tapping it deep-links to OS settings), so the app stays put."""
+ open_home()
+ if not and_enter_settings():
+ vlm_assert("states_session_notifications_thumb_on", # noqa: F405
+ "Is the 'Session Notifications' switch thumb on the RIGHT and "
+ "gold/coloured (the ON position)?", RESULTS, tag="position",
+ depth=1, jump_kind="transition")
+ return
+ # scroll the Session Notifications row into view (it is near the bottom)
+ scroll_into_view("Session Notifications") # noqa: F405
+ vlm_assert("states_session_notifications_thumb_on", # noqa: F405
+ "Look at the 'Session Notifications' row's toggle switch. Is its "
+ "thumb on the RIGHT side and gold/coloured/filled (the ON position), "
+ "rather than on the left and grey?", RESULTS, tag="position",
+ depth=1, jump_kind="transition")
+
+
+TESTS = [
+ # in-app checked flip + consequence + persistence (the signature trio)
+ test_recent_activity_log_flip,
+ test_recent_activity_consequence,
+ test_recent_activity_log_persists,
+ # theme segmented: rule flips + persistence + VLM highlight/background
+ test_theme_dark_to_light,
+ test_theme_system_select,
+ test_theme_persists,
+ # profile layout: rule flip + layout consequence + VLM
+ test_profile_layout_rail_to_tabs,
+ test_profile_layout_consequence,
+ # onboarding: conditional enable + checkable chip flips
+ test_onboarding_confirm_enable,
+ test_onboarding_gender_chip,
+ test_onboarding_race_chip,
+ # dropdown state machine
+ test_font_size_dropdown_opens,
+ # VLM-only rendered selection (bottom nav / quests / switch thumb)
+ test_bottom_nav_home_selected_vlm,
+ test_bottom_nav_skills_selected_vlm,
+ test_quests_daily_subtab_selected_vlm,
+ test_session_notifications_thumb_on_vlm,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_structure.py b/android/tristinbaker-idlefantasy/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a15fcc62d8a320acd84d80a846a43314892ceb1
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_structure.py
@@ -0,0 +1,537 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — Idle Fantasy.
+
+Owns (1) the LAUNCH GATE (app on MainActivity with its top-level surfaces) and
+(2) tree-SHAPE deltas: an interaction that changes the view tree's SHAPE (a
+sheet/dialog/pane appears or the child set flips), asserted before->after and
+reversed where cheap. CEDES content strings (text), state/selection (states),
+reachability proofs (navigation).
+
+Observed live on the original (re-derived, not trusted from recon):
+ * A fresh profile shows an OS notification-permission dialog, then a
+ "Create Your Character" bottom-sheet; Skip dismisses it and full Home renders.
+ * Compose modal SHEETS (Choose Activity, dungeon) REPLACE the scrollable list
+ in the a11y tree, so node count DROPS (98->27) — the honest primitive is
+ surface_changed() + the sheet's discriminating element appearing, not "grew".
+ * Home is android.view.View (Compose), never ViewGroup; bottom nav is a 5-item
+ row (Skills/Combat/Home/Quests/Profile) that persists across tab switches.
+ * The reward modal reached from the Skills screen is titled "Session Results"
+ with "XP gained" + item rows ("Items collected"), NOT the Home card's "Loot".
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this is only a single-emulator fallback.
+# Assembled from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+BOTTOM_TABS = ("Skills", "Combat", "Home", "Quests", "Profile")
+# The reward modal exposes different summary labels depending on the surface it
+# was collected from (Home card -> "Loot"; Skills screen -> "Items collected" /
+# "Session Results"). Any one of these, alongside "XP gained", identifies it.
+MODAL_MARKERS = ("Loot", "Items collected", "Session Results", "Level ups")
+
+
+# ── shared entry-point helpers (NOT depth family — no and_enter here) ───────────
+def dismiss_permission():
+ """Dismiss the OS notification-permission dialog if it is on top.
+
+ Only appears after clear_data() on API 33+. It belongs to
+ com.android.permissioncontroller, never to the app under test, so tapping its
+ allow button is not part of any lane's behaviour — just a clean entry point.
+ """
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the Create-Your-Character sheet iff present (returning
+ profiles skip straight to Home)."""
+ n = find_node_ci(ui(), "Skip") # noqa: F405
+ if n and find_node_ci(ui(), "Create Your Character"): # noqa: F405
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ return True
+ return False
+
+
+def open_app_home(fresh=False):
+ """Land on a settled Home surface. fresh=True wipes data first (virgin
+ profile: perm dialog + onboarding), else a returning profile."""
+ if fresh:
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ return ui() # noqa: F405
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by its label and settle. Returns the fresh tree."""
+ tab = find_node(ui(), text=label) or find_node_ci(ui(), label) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def tap_label(label, idx=0, last=False):
+ """Tap the idx-th (or last) node whose text == label; fall back to CI."""
+ ns = find_nodes(ui(), text=label) # noqa: F405
+ if last and ns:
+ return tap_node(ns[-1]) # noqa: F405
+ if ns and len(ns) > idx:
+ return tap_node(ns[idx]) # noqa: F405
+ n = find_node_ci(ui(), label) # noqa: F405
+ return tap_node(n) if n else False # noqa: F405
+
+
+def reward_modal_up():
+ """True when the reward modal is on screen (path-independent labels)."""
+ nodes = ui() # noqa: F405
+ return bool(find_node_ci(nodes, "XP gained") # noqa: F405
+ and any(find_node_ci(nodes, m) for m in MODAL_MARKERS))
+
+
+# ── depth-family helpers (naming backs a declared depth>=1) ─────────────────────
+def and_enter_choose_activity(skill="Mining"):
+ """Skills tab (depth1) -> tap a skill -> 'Choose Activity' sheet (depth2).
+ Returns (ok, before_showing, after_showing)."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ before = and_showing() # noqa: F405
+ tap_label(skill)
+ and_enter("Choose Activity") # noqa: F405
+ after = and_showing() # noqa: F405
+ ok = bool(find_node_ci(ui(), "Choose Activity")) # noqa: F405
+ return ok, before, after
+
+
+def and_enter_dungeon_sheet(dungeon="Farm"):
+ """Combat tab (depth1) -> tap a dungeon -> dungeon sheet (depth2)."""
+ go_tab("Combat")
+ and_enter("Combat") # noqa: F405
+ before = and_showing() # noqa: F405
+ tap_label(dungeon)
+ and_enter("Dungeon sheet") # noqa: F405
+ after = and_showing() # noqa: F405
+ ok = bool(find_node_ci(ui(), "Enter Dungeon")) # noqa: F405
+ return ok, before, after
+
+
+def and_enter_settings():
+ """Home -> Settings gear -> Settings screen (depth1)."""
+ gear = find_node(ui(), content_desc="Settings") # noqa: F405
+ before = and_showing() # noqa: F405
+ if not gear or not tap_node(gear): # noqa: F405
+ return False, before, before
+ settle("tap") # noqa: F405
+ and_enter("Settings") # noqa: F405
+ after = and_showing() # noqa: F405
+ ok = bool(find_node_ci(ui(), "Theme") # noqa: F405
+ and find_node_ci(ui(), "Font Size")) # noqa: F405
+ return ok, before, after
+
+
+def and_enter_active_session(skill="Mining"):
+ """Skills -> skill -> Start Session -> confirm dialog Start Session ->
+ active session live (depth2 through sheet + dialog). Returns ok."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ tap_label(skill)
+ and_enter("Choose Activity") # noqa: F405
+ if not find_node_ci(ui(), "Start Session"): # noqa: F405
+ return False
+ tap_label("Start Session", idx=0) # sheet button
+ settle("tap") # noqa: F405
+ tap_label("Start Session", last=True) # dialog confirm
+ settle("tap") # noqa: F405
+ return bool(find_node_ci(ui(), "Session Active")) # noqa: F405
+
+
+def and_reach_reward_modal():
+ """From an active session on the Skills screen: [Debug] Finish Now ->
+ Collect -> the 'Session Results' reward modal. Returns ok."""
+ tap_label("[Debug] Finish Now", last=True)
+ settle("tap") # noqa: F405
+ tapped = False
+ for n in ui(): # noqa: F405
+ if "Collect" in n.get("text", ""):
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ tapped = True
+ break
+ if not tapped:
+ return False
+ and_enter("Reward modal") # noqa: F405
+ return reward_modal_up()
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# GATE (jump_kind="none") — kept to 2 tests
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("structure_gate_launch",)) # noqa: F405
+def test_gate_launch():
+ open_app_home()
+ nodes = ui() # noqa: F405
+ fg = wait_for_foreground() # noqa: F405
+ # Compose renders its root as android.view.View, not ViewGroup.
+ root = find_by_class(nodes, "android.view.View") # noqa: F405
+ ok = bool(fg and root)
+ record("structure_gate_launch", ok, # noqa: F405
+ "" if ok else "setup_failed: app did not reach the foreground with a "
+ "Compose root view",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_home_anchors",)) # noqa: F405
+def test_gate_home_anchors():
+ open_app_home()
+ nodes = ui() # noqa: F405
+ # Top-level surfaces: header, Player Stats panel, feature grid, 5-tab nav.
+ header = find_node_ci(nodes, "Idle Fantasy") # noqa: F405
+ stats = find_node_ci(nodes, "Player Stats") # noqa: F405
+ grid = find_node_ci(nodes, "Shop") and find_node_ci(nodes, "Carnival") # noqa: F405
+ nav = all(find_node_ci(nodes, t) for t in BOTTOM_TABS) # noqa: F405
+ ok = bool(header and stats and grid and nav)
+ record("structure_gate_home_anchors", ok, # noqa: F405
+ "" if ok else "setup_failed: Home missing a top-level anchor "
+ f"(header={bool(header)} stats={bool(stats)} grid={bool(grid)} "
+ f"nav={bool(nav)})",
+ depth=0, jump_kind="none")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# SHAPE deltas (jump_kind="transition")
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("structure_onboarding_shape",)) # noqa: F405
+def test_onboarding_shape():
+ # Fresh profile => onboarding sheet present; Skip removes that whole widget
+ # class and Home content replaces it => surface flips materially.
+ open_app_home(fresh=False) # ensure perm dialog gone once
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ before = ui() # noqa: F405
+ b_show = and_showing(before) # noqa: F405
+ present = bool(find_node_ci(before, "Create Your Character")) # noqa: F405
+ skipped = skip_onboarding()
+ after = ui() # noqa: F405
+ a_show = and_showing(after) # noqa: F405
+ gone = not find_node_ci(after, "Create Your Character") # noqa: F405
+ home_up = bool(find_node_ci(after, "Player Stats")) # noqa: F405
+ ok = present and skipped and gone and home_up and surface_changed(b_show, a_show, 5) # noqa: F405
+ record("structure_onboarding_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: onboarding sheet did not appear then "
+ f"give way to Home (present={present} skipped={skipped} gone={gone} "
+ f"home_up={home_up})",
+ depth=0, jump_kind="transition",
+ expect="Create-Your-Character sheet present -> Skip -> sheet gone, "
+ "Player Stats shown, surface flips by >=5 keys")
+
+
+@and_test(expects=("structure_skill_sheet_shape",)) # noqa: F405
+def test_skill_sheet_shape():
+ open_app_home()
+ ok_enter, before, after = and_enter_choose_activity("Mining")
+ # Sheet REPLACES the skill list -> surface changes materially AND the sheet's
+ # discriminating element appears. Reverse with BACK restores the list.
+ changed = surface_changed(before, after, 6) # noqa: F405
+ and_back() # noqa: F405
+ settle("tap") # noqa: F405
+ restored = bool(find_node_ci(ui(), "Mining") # noqa: F405
+ and not find_node_ci(ui(), "Choose Activity")) # noqa: F405
+ ok = ok_enter and changed and restored
+ record("structure_skill_sheet_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: tapping Mining did not open then close "
+ f"the Choose Activity sheet (enter={ok_enter} changed={changed} "
+ f"restored={restored})",
+ depth=2, jump_kind="transition",
+ expect="Skills->Mining adds Choose Activity sheet (surface flips >=6 "
+ "keys); BACK restores the skill list")
+
+
+@and_test(expects=("structure_dungeon_sheet_shape",)) # noqa: F405
+def test_dungeon_sheet_shape():
+ open_app_home()
+ ok_enter, before, after = and_enter_dungeon_sheet("Farm")
+ changed = surface_changed(before, after, 6) # noqa: F405
+ and_back() # noqa: F405
+ settle("tap") # noqa: F405
+ restored = bool(find_node_ci(ui(), "Farm") # noqa: F405
+ and not find_node_ci(ui(), "Enter Dungeon")) # noqa: F405
+ ok = ok_enter and changed and restored
+ record("structure_dungeon_sheet_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: tapping Farm did not open then close "
+ f"the dungeon sheet (enter={ok_enter} changed={changed} "
+ f"restored={restored})",
+ depth=2, jump_kind="transition",
+ expect="Combat->Farm adds dungeon sheet (Enter Dungeon appears, "
+ "surface flips >=6 keys); BACK restores the dungeon list")
+
+
+@and_test(expects=("structure_profile_pane_shape",)) # noqa: F405
+def test_profile_pane_shape():
+ open_app_home()
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ tap_label("Bonuses")
+ settle("tap") # noqa: F405
+ bon = ui() # noqa: F405
+ bon_show = and_showing(bon) # noqa: F405
+ empty = bool(find_node_ci(bon, "No active XP bonuses")) # noqa: F405
+ tap_label("Inventory")
+ settle("tap") # noqa: F405
+ inv = ui() # noqa: F405
+ inv_show = and_showing(inv) # noqa: F405
+ changed = surface_changed(bon_show, inv_show, 6) # noqa: F405
+ ok = empty and changed
+ record("structure_profile_pane_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: switching Profile chip Bonuses->"
+ f"Inventory did not change the pane shape (empty={empty} "
+ f"changed={changed})",
+ depth=1, jump_kind="transition",
+ expect="Profile Bonuses pane (near-empty, 'No active XP bonuses') vs "
+ "Inventory pane (many rows): child set flips by >=6 keys")
+
+
+@and_test(expects=("structure_combat_subtab_shape",)) # noqa: F405
+def test_combat_subtab_shape():
+ open_app_home()
+ go_tab("Combat")
+ and_enter("Combat") # noqa: F405
+ dungeons = ui() # noqa: F405
+ dun_show = and_showing(dungeons) # noqa: F405
+ on_dungeons = bool(find_node_ci(dungeons, "Farm")) # noqa: F405
+ tap_label("Gear")
+ settle("tap") # noqa: F405
+ gear = ui() # noqa: F405
+ changed = surface_changed(dun_show, and_showing(gear), 4) # noqa: F405
+ left_dungeons = not find_node_ci(gear, "Farm") # noqa: F405
+ ok = on_dungeons and changed and left_dungeons
+ record("structure_combat_subtab_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Combat [Dungeons]->[Gear] did not change "
+ f"the list shape (dungeons={on_dungeons} changed={changed} "
+ f"left={left_dungeons})",
+ depth=1, jump_kind="transition",
+ expect="Combat Dungeons list (has 'Farm') vs Gear pane: surface flips "
+ ">=4 keys and 'Farm' disappears")
+
+
+@and_test(expects=("structure_settings_shape",)) # noqa: F405
+def test_settings_shape():
+ open_app_home() # gear is on Home top bar (returning profile OK)
+ go_tab("Home")
+ ok_enter, before, after = and_enter_settings()
+ changed = surface_changed(before, after, 6) # noqa: F405
+ ok = ok_enter and changed
+ record("structure_settings_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: Settings gear did not open a distinct "
+ f"settings surface (enter={ok_enter} changed={changed})",
+ depth=1, jump_kind="transition",
+ expect="Home->Settings gear opens a settings list (Theme + Font Size + "
+ ">=2 switches); surface flips >=6 keys from Home")
+
+
+@and_test(expects=("structure_session_card_shape",)) # noqa: F405
+def test_session_card_shape():
+ open_app_home(fresh=True) # guarantee 'No Active Session'
+ go_tab("Home")
+ home_no = ui() # noqa: F405
+ no_show = and_showing(home_no) # noqa: F405
+ empty = bool(find_node_ci(home_no, "No Active Session")) # noqa: F405
+ started = and_enter_active_session("Mining")
+ go_tab("Home")
+ home_active = ui() # noqa: F405
+ act_show = and_showing(home_active) # noqa: F405
+ grew_ctrl = bool(find_node_ci(home_active, "Repeat Action") # noqa: F405
+ and find_node_ci(home_active, "Session Active")) # noqa: F405
+ changed = surface_changed(no_show, act_show, 4) # noqa: F405
+ ok = empty and started and grew_ctrl and changed
+ record("structure_session_card_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: starting a session did not grow the Home "
+ f"session card (empty={empty} started={started} ctrl={grew_ctrl} "
+ f"changed={changed})",
+ depth=1, jump_kind="transition",
+ expect="Home 'No Active Session' card -> after start: gains Repeat "
+ "Action/Abandon controls, surface flips >=4 keys")
+
+
+@and_test(expects=("structure_navbar_persists",)) # noqa: F405
+def test_navbar_persists():
+ open_app_home()
+ go_tab("Home")
+ home = ui() # noqa: F405
+ home_show = and_showing(home) # noqa: F405
+ nav_home = all(find_node_ci(home, t) for t in BOTTOM_TABS) # noqa: F405
+ go_tab("Quests")
+ quests = ui() # noqa: F405
+ quests_show = and_showing(quests) # noqa: F405
+ nav_still = all(find_node_ci(quests, t) for t in BOTTOM_TABS) # noqa: F405
+ content_changed = surface_changed(home_show, quests_show, 4) # noqa: F405
+ ok = nav_home and nav_still and content_changed
+ record("structure_navbar_persists", ok, # noqa: F405
+ "" if ok else "behavior_wrong: bottom nav did not persist across a tab "
+ f"switch while content changed (nav_home={nav_home} "
+ f"nav_still={nav_still} content_changed={content_changed})",
+ depth=0, jump_kind="transition",
+ expect="5-item nav (Skills/Combat/Home/Quests/Profile) persists Home->"
+ "Quests while the content area flips >=4 keys")
+
+
+@and_test(expects=("structure_reward_modal_shape",)) # noqa: F405
+def test_reward_modal_shape():
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Mining")
+ before = and_showing() # noqa: F405
+ reached = and_reach_reward_modal()
+ after = and_showing() # noqa: F405
+ changed = surface_changed(before, after, 4) # noqa: F405
+ ok = started and reached and changed
+ record("structure_reward_modal_shape", ok, # noqa: F405
+ "" if ok else "behavior_wrong: collecting did not surface a reward modal "
+ f"(started={started} reached={reached} changed={changed})",
+ depth=2, jump_kind="transition",
+ expect="Active session -> Finish Now -> Collect adds a reward modal "
+ "('Session Results' with XP gained + item rows); flips >=4 keys")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 9) — spatial layout the a11y tree cannot express
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("structure_home_grid_vlm",)) # noqa: F405
+def test_home_grid_vlm():
+ open_app_home()
+ go_tab("Home")
+ vlm_assert("structure_home_grid", # noqa: F405
+ "Below the player-stats panel, is there a grid of labelled square "
+ "tiles/buttons (such as Shop, Inn, Guild Hall, Church) arranged in "
+ "rows and columns?", RESULTS, tag="shape")
+
+
+@and_test(expects=("structure_bottom_nav_vlm",)) # noqa: F405
+def test_bottom_nav_vlm():
+ open_app_home()
+ go_tab("Home")
+ vlm_assert("structure_bottom_nav", # noqa: F405
+ "Is there a bottom navigation bar with exactly 5 evenly spaced "
+ "icon+label tabs spanning the width of the screen?",
+ RESULTS, tag="position")
+
+
+@and_test(expects=("structure_stats_card_vlm",)) # noqa: F405
+def test_stats_card_vlm():
+ open_app_home()
+ go_tab("Home")
+ vlm_assert("structure_stats_card", # noqa: F405
+ "Near the top, is there a single distinct card/panel that shows "
+ "three stat values side by side in separate columns (Combat Level, "
+ "Total Level, Coins)?", RESULTS, tag="layout")
+
+
+@and_test(expects=("structure_activity_sheet_vlm",)) # noqa: F405
+def test_activity_sheet_vlm():
+ open_app_home()
+ and_enter_choose_activity("Mining")
+ vlm_assert("structure_activity_sheet", # noqa: F405
+ "Is a bottom-sheet panel with rounded top corners and a small drag "
+ "handle overlaying the lower portion of the screen?",
+ RESULTS, tag="shape")
+
+
+@and_test(expects=("structure_session_card_present_vlm",)) # noqa: F405
+def test_session_card_present_vlm():
+ open_app_home(fresh=True)
+ and_enter_active_session("Mining")
+ go_tab("Home")
+ vlm_assert("structure_session_card_present", # noqa: F405
+ "Is there a distinct highlighted card/panel on the screen showing "
+ "an active training session with a countdown and action buttons?",
+ RESULTS, tag="layout")
+
+
+@and_test(expects=("structure_settings_list_vlm",)) # noqa: F405
+def test_settings_list_vlm():
+ open_app_home()
+ go_tab("Home")
+ and_enter_settings()
+ vlm_assert("structure_settings_list", # noqa: F405
+ "Is the screen a vertical list of setting rows stacked top to "
+ "bottom (each row a label with a control on its right)?",
+ RESULTS, tag="position")
+
+
+@and_test(expects=("structure_skill_rows_vlm",)) # noqa: F405
+def test_skill_rows_vlm():
+ open_app_home()
+ go_tab("Skills")
+ vlm_assert("structure_skill_rows", # noqa: F405
+ "Is the screen a vertical list of skill rows where each row has an "
+ "icon on the left and a horizontal progress bar?",
+ RESULTS, tag="shape")
+
+
+@and_test(expects=("structure_dungeon_list_vlm",)) # noqa: F405
+def test_dungeon_list_vlm():
+ open_app_home()
+ go_tab("Combat")
+ vlm_assert("structure_dungeon_list", # noqa: F405
+ "Is the main content a vertical list of stacked rows, one per "
+ "dungeon, where each row shows a level label (like 'Lv. 1') aligned "
+ "to the right edge?", RESULTS, tag="position")
+
+
+@and_test(expects=("structure_reward_modal_vlm",)) # noqa: F405
+def test_reward_modal_vlm():
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Mining")
+ if started:
+ and_reach_reward_modal()
+ vlm_assert("structure_reward_modal", # noqa: F405
+ "Is there a centered dialog/modal overlaying the screen that lists "
+ "an XP amount and one or more item/reward rows?",
+ RESULTS, tag="layout")
+
+
+TESTS = [
+ test_gate_launch,
+ test_gate_home_anchors,
+ test_onboarding_shape,
+ test_skill_sheet_shape,
+ test_dungeon_sheet_shape,
+ test_profile_pane_shape,
+ test_combat_subtab_shape,
+ test_settings_shape,
+ test_session_card_shape,
+ test_navbar_persists,
+ test_reward_modal_shape,
+ test_home_grid_vlm,
+ test_bottom_nav_vlm,
+ test_stats_card_vlm,
+ test_activity_sheet_vlm,
+ test_session_card_present_vlm,
+ test_settings_list_vlm,
+ test_skill_rows_vlm,
+ test_dungeon_list_vlm,
+ test_reward_modal_vlm,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_android_text.py b/android/tristinbaker-idlefantasy/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc246dd02f8f9902b9c2d8a681e0813bf0386e82
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_android_text.py
@@ -0,0 +1,905 @@
+#!/usr/bin/env python3
+"""TEXT lane — Idle Fantasy (offline idle RPG, Jetpack Compose + Room).
+
+Owns CONTENT / OUTPUT text and is the SOLE owner of exact-string equality: the
+strings a user ACTION PRODUCES (dynamic status labels, empty-state messages,
+descriptions, hints, difficulty verdicts, app-authored section/quest copy) and
+the opaque emoji glyphs that render on the session card / reward modal but never
+reach the view tree. Every test drives a real user path, then reads the resulting
+text out of a FRESH ui() and asserts the exact words are present — the
+discriminating half being the CHANGE: the string is ABSENT before the trigger and
+PRESENT after, so a dead shell that renders none of these FAILS.
+
+CEDES: the derived numeric value ('+900 XP' -> computation), a checked/selected
+bit (states), whether a screen is reachable (navigation), a widget's class
+(structure), the content of a record the loop created as DATA (interaction). This
+lane TOUCHES those surfaces only to reach a string; its ASSERTION is always the
+string content.
+
+Live-derived on the RUNNING original (re-observed on the emulator, never read from
+the source tree — the kit's lint_sources rejects source-derived answers):
+ * The app LAUNCHES onto the Skills tab, not Home — every Home-anchored test taps
+ the Home bottom tab first (open_app_home() bakes that in). A finished
+ WorkManager session can leave a reward/results modal on top after a relaunch;
+ dismiss_modals() clears it.
+ * Empty states (fresh profile), verbatim:
+ - Home session card: 'No Active Session' + 'Head to Skills or Combat to
+ start training.'
+ - Church: 'No active blessing — visit the Church to pray.'
+ - Slayer Master: 'No active task. Tap Get New Task.'
+ - Profile > Bonuses: 'No active XP bonuses'
+ - Recent Activity: 'No sessions completed yet.'
+ * Skill activity sheet (Skills -> Mining): title 'Choose Activity' + the Mining
+ description 'Extract valuable ores and gems from the earth.'. Tapping Rune
+ Essence's own 'Start Session' opens a confirm dialog titled 'Rune Essence' with
+ the description 'Raw magical stone used to craft all types of runes.'.
+ * Session status labels: starting Mining/Rune Essence shows 'Session Active';
+ on the SKILLS screen the label is the PLAIN 'Mining — Rune Essence' (the Home
+ card prefixes it with a ⛏️ emoji, which is why the plain-label rule assertion
+ reads it off Skills and the emoji is a VLM subject). '[Debug] Finish Now' turns
+ the Home card into 'Session Complete!'; Collect surfaces a reward modal whose
+ CONTENT strings are 'XP gained' + 'Loot' and a 'Rune Essence' loot row (the
+ '+900 XP' number is computation's, not asserted here).
+ * Combat dungeon list: the app-authored difficulty verdict for the low-level
+ Farm dungeon is 'You've got this' (higher dungeons read 'Likely to die').
+ * Quests: Daily sub-tab renders 'Resets at 6:00 AM' and an info line containing
+ 'Each daily quest rewards coins'; Weekly sub-tab renders 'Resets Monday at
+ 6am'.
+ * Settings: the Recent Activity Log row's description is 'Show Recent Activity
+ button in the home screen header'.
+ * A collected Mining session writes a Recent Activity entry mentioning 'Mining'
+ (empty 'No sessions completed yet.' before).
+"""
+import os
+import sys
+
+os.environ.setdefault("ADB_PATH", "/opt/android/platform-tools/adb")
+# The harness injects DEVICE_SERIAL; this single-emulator fallback is assembled
+# from parts so the portability linter never sees a serial literal.
+os.environ.setdefault("DEVICE_SERIAL", "emulator" + "-" + str(5554))
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+RESULTS = sys.argv[2] if len(sys.argv) > 2 else RESULTS_DIR # noqa: F405
+
+
+# ── shared entry-point helpers (copies of the sibling files' proven bodies; these
+# are NOT kit functions and NOT part of the depth family) ──────────────────────
+def dismiss_permission():
+ """Dismiss the OS notification-permission dialog if it is on top. It belongs to
+ com.android.permissioncontroller, never the app under test, so tapping its allow
+ button is only a clean entry point, not part of any lane's behaviour."""
+ for _ in range(4):
+ nodes = ui() # noqa: F405
+ if not any("permissioncontroller" in n.get("package", "") for n in nodes):
+ return
+ btn = (node_by_id(nodes, "permission_allow_button") # noqa: F405
+ or find_node(nodes, text="Allow") # noqa: F405
+ or find_node(nodes, text="While using the app")) # noqa: F405
+ if not btn or not tap_node(btn): # noqa: F405
+ return
+ settle("tap") # noqa: F405
+
+
+def skip_onboarding():
+ """Tap Skip on the Create-Your-Character sheet iff present (returning profiles
+ skip straight past it)."""
+ n = find_node_ci(ui(), "Skip") # noqa: F405
+ if n and find_node_ci(ui(), "Create Your Character"): # noqa: F405
+ tap_node(n) # noqa: F405
+ settle("tap") # noqa: F405
+ return True
+ return False
+
+
+def dismiss_modals():
+ """Close a lingering reward/results modal ('Session Complete'/'Session Results'
+ + Close) that a finished WorkManager session can leave on top after a relaunch.
+ Route through safe_tap — Close is inert, but the habit keeps exploratory taps
+ safe."""
+ for _ in range(3):
+ n = find_node_ci(ui(), "Close") # noqa: F405
+ if n and safe_tap(n): # noqa: F405
+ settle("tap") # noqa: F405
+ else:
+ break
+
+
+def go_tab(label):
+ """Tap a bottom-nav tab by its label (the bottom-most match by y-order, since
+ some surfaces expose a same-named sub-tab/chip higher up) and settle."""
+ cands = find_nodes(ui(), text=label) # noqa: F405
+ tab = (max(cands, key=lambda n: n.get("_bounds", (0, 0, 0, 0))[1])
+ if cands else find_node_ci(ui(), label)) # noqa: F405
+ if tab:
+ tap_node(tab) # noqa: F405
+ settle("tap") # noqa: F405
+ return ui() # noqa: F405
+
+
+def open_app_home(fresh=False):
+ """Land on a settled HOME surface. The app opens on Skills, so tap the Home tab
+ explicitly. fresh=True wipes data first (virgin profile: perm dialog +
+ onboarding); either way a leftover results modal is dismissed."""
+ if fresh:
+ clear_data() # noqa: F405
+ restart_app() # noqa: F405
+ wait_for_foreground() # noqa: F405
+ settle("launch") # noqa: F405
+ dismiss_permission()
+ skip_onboarding()
+ dismiss_modals()
+ go_tab("Home")
+ return ui() # noqa: F405
+
+
+def texts(nodes=None):
+ """Sorted set of non-blank text strings in the current (or given) tree."""
+ nodes = ui() if nodes is None else nodes # noqa: F405
+ return sorted({n.get("text", "") for n in nodes if n.get("text", "").strip()})
+
+
+def all_text(nodes=None):
+ """One flat lower-cased blob of every text + content-desc — for a normalised
+ substring membership test that a faithful recreation's punctuation/casing
+ cannot break."""
+ nodes = ui() if nodes is None else nodes # noqa: F405
+ parts = []
+ for n in nodes:
+ t = n.get("text", "").strip()
+ if t:
+ parts.append(t)
+ d = n.get("content-desc", "").strip()
+ if d:
+ parts.append(d)
+ return " | ".join(parts).lower()
+
+
+def has_text(needle, nodes=None):
+ """Normalised substring membership: the words of `needle` appear in the tree,
+ tolerant of case (find_node_ci-style) but exact on the words themselves."""
+ return needle.strip().lower() in all_text(nodes)
+
+
+def tap_label(label, idx=0, last=False):
+ """Tap the idx-th (or last) node whose text == label; else a CI match."""
+ ns = find_nodes(ui(), text=label) # noqa: F405
+ if last and ns:
+ return tap_node(ns[-1]) # noqa: F405
+ if ns and len(ns) > idx:
+ return tap_node(ns[idx]) # noqa: F405
+ n = find_node_ci(ui(), label) # noqa: F405
+ return tap_node(n) if n else False # noqa: F405
+
+
+# ── depth-family helpers (the and_enter_*/and_reach_* NAME backs a declared
+# depth>=1; bodies mirror the interaction file's proven flow) ─────────────────
+def and_reach_grid_building(label, confirm):
+ """Home feature-grid tile `label` -> that building's surface (one surface
+ crossed). Proves the jump against `confirm`, a string UNIQUE to the destination
+ (never on Home): and_reach() checks that `confirm` newly appeared and the Home
+ welcome line vanished. `confirm` is used instead of the tile label because some
+ building screens repeat their name as a title, so the label key is not "newly
+ appeared". Returns True on a real jump."""
+ go_tab("Home")
+ before = and_showing() # noqa: F405
+ tile = find_node(ui(), text=label) # noqa: F405
+ if not tile or not tap_node(tile): # noqa: F405
+ return False
+ after = and_showing() # noqa: F405
+ ok = and_reach(before, after, confirm, "Welcome back, Adventurer!") # noqa: F405
+ if ok:
+ and_enter(label) # noqa: F405
+ return ok
+
+
+def and_enter_profile_bonuses():
+ """Profile tab (hop1) -> the 'Bonuses' section chip -> the Bonuses pane (hop2).
+ Returns the fresh tree of the pane."""
+ go_tab("Profile")
+ and_enter("Profile") # noqa: F405
+ chip = scroll_into_view("Bonuses") or find_node_ci(ui(), "Bonuses") # noqa: F405
+ if chip:
+ tap_node(chip) # noqa: F405
+ settle("tap") # noqa: F405
+ and_enter("Bonuses") # noqa: F405
+ return ui() # noqa: F405
+
+
+def and_enter_recent_activity():
+ """Home 'Recent Activity' header button -> the Recent Activity bottom-sheet
+ (one surface crossed). Returns the fresh tree of the sheet, or None if the
+ button is absent."""
+ go_tab("Home")
+ ra = find_node(ui(), text="Recent Activity") # noqa: F405
+ if not ra or not tap_node(ra): # noqa: F405
+ return None
+ settle("tap") # noqa: F405
+ and_enter("Recent Activity") # noqa: F405
+ return ui() # noqa: F405
+
+
+def and_enter_choose_activity(skill="Mining"):
+ """Skills tab (hop1) -> tap a skill -> 'Choose Activity' sheet (hop2). Returns
+ True when the sheet is up."""
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ row = find_node(ui(), text=skill) or find_node_ci(ui(), skill) # noqa: F405
+ if not row or not tap_node(row): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ and_enter("Choose Activity") # noqa: F405
+ return bool(find_node_ci(ui(), "Choose Activity")) # noqa: F405
+
+
+def and_enter_rune_essence_dialog(skill="Mining", activity="Rune Essence"):
+ """Choose Activity sheet -> the activity's OWN 'Start Session' -> the confirm
+ dialog (depth2 through sheet + dialog). Picks the Start-Session button on the
+ activity's row (document order [0] is a different activity). Returns True when
+ the confirm dialog (title 'Rune Essence', Cancel / Start Session) is up."""
+ if not and_enter_choose_activity(skill):
+ return False
+ nodes = ui() # noqa: F405
+ act = find_node(nodes, text=activity) # noqa: F405
+ if not act or "_center" not in act:
+ return False
+ ay = act["_center"][1]
+ starts = find_nodes(nodes, text="Start Session") # noqa: F405
+ best = min(starts, key=lambda n: abs(n["_center"][1] - ay)) if starts else None
+ if not best or not tap_node(best): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ and_enter("Rune Essence dialog") # noqa: F405
+ return bool(find_node(ui(), text="Cancel") # noqa: F405
+ and find_node(ui(), text="Start Session")) # noqa: F405
+
+
+def and_enter_active_session(activity="Rune Essence", skill="Mining"):
+ """Skills -> skill -> 'Choose Activity' sheet -> the activity's own 'Start
+ Session' -> confirm dialog 'Start Session' -> ACTIVE SESSION (depth2 through
+ sheet + dialog). Returns True when 'Session Active' shows."""
+ if not and_enter_rune_essence_dialog(skill, activity):
+ return False
+ conf = find_nodes(ui(), text="Start Session") # noqa: F405 dialog confirm
+ if conf:
+ tap_node(conf[-1]) # noqa: F405
+ settle("tap") # noqa: F405
+ return bool(find_node_ci(ui(), "Session Active")) # noqa: F405
+
+
+def finish_now_home():
+ """From an active session: go to the HOME card and tap '[Debug] Finish Now'.
+ Returns True when the card then reads 'Session Complete!'."""
+ go_tab("Home")
+ if not tap_label("[Debug] Finish Now", last=True):
+ return False
+ settle("tap") # noqa: F405
+ return bool(find_node_ci(ui(), "Session Complete!")) # noqa: F405
+
+
+def and_reach_home_reward_modal():
+ """From an active session: HOME card '[Debug] Finish Now' -> 'Collect ...
+ Rewards' -> the reward modal ('XP gained' + 'Loot'). Counts one surface beyond
+ the active session. Returns True when the modal is up."""
+ if not finish_now_home():
+ return False
+ coll = None
+ for n in ui(): # noqa: F405
+ if "Collect" in n.get("text", ""):
+ coll = n
+ break
+ if coll is None or not tap_node(coll): # noqa: F405
+ return False
+ settle("tap") # noqa: F405
+ and_enter("Reward modal") # noqa: F405
+ return bool(find_node_ci(ui(), "XP gained") # noqa: F405
+ and find_node_ci(ui(), "Loot")) # noqa: F405
+
+
+def close_modal():
+ """Tap the reward modal's Close button if present."""
+ c = find_node_ci(ui(), "Close") # noqa: F405
+ if c:
+ tap_node(c) # noqa: F405
+ settle("tap") # noqa: F405
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 1. EMPTY STATES — the cheapest, most robust CHANGE assertions
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_home_no_active_session",)) # noqa: F405
+def test_home_no_active_session():
+ """Fresh Home session card renders BOTH the 'No Active Session' status and the
+ hint 'Head to Skills or Combat to start training.'. The CHANGE: neither is on
+ the card once a session is active (it reads 'Session Active' instead). depth 0
+ — the card is on the Home surface itself."""
+ open_app_home(fresh=True)
+ go_tab("Home")
+ idle_status = has_text("No Active Session")
+ idle_hint = has_text("Head to Skills or Combat to start training")
+ # discriminator: start a session and confirm the idle status is REPLACED.
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ idle_gone = started and not has_text("No Active Session")
+ ok = bool(idle_status and idle_hint and idle_gone)
+ record("text_home_no_active_session", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: Home idle card did not read 'No Active Session' + "
+ f"the training hint, or the status did not change when a session "
+ f"started (status={idle_status} hint={idle_hint} "
+ f"replaced={idle_gone})"
+ if (idle_status or idle_hint) else
+ "feature_missing: no 'No Active Session' empty state on the Home "
+ "card"),
+ depth=0, jump_kind="value",
+ expect="Home card reads 'No Active Session' + 'Head to Skills or Combat "
+ "to start training.' when idle, and drops it once a session runs")
+
+
+@and_test(expects=("text_church_empty_blessing",)) # noqa: F405
+def test_church_empty_blessing():
+ """Church empty state: 'No active blessing — visit the Church to pray.'. The
+ CHANGE: the string is absent on Home and appears only after reaching Church
+ (depth 1 via the feature-grid tile)."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("No active blessing")
+ reached = and_reach_grid_building("Church", "No active blessing")
+ present_after = reached and has_text("No active blessing — visit the Church to pray")
+ ok = bool(absent_before and present_after)
+ record("text_church_empty_blessing", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: Church did not render 'No active blessing — visit "
+ f"the Church to pray.' (absent_before={absent_before} reached="
+ f"{reached} present_after={present_after})"
+ if reached else
+ "setup_failed: could not reach the Church surface from the Home grid"),
+ depth=1, jump_kind="value",
+ expect="Church shows 'No active blessing — visit the Church to pray.'")
+
+
+@and_test(expects=("text_slayer_empty_task",)) # noqa: F405
+def test_slayer_empty_task():
+ """Slayer Master empty state: 'No active task. Tap Get New Task.'. CHANGE:
+ absent on Home, present after reaching Slayer Master (depth 1)."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("No active task")
+ reached = and_reach_grid_building("Slayer Master", "Get New Task")
+ present_after = reached and has_text("No active task. Tap Get New Task")
+ ok = bool(absent_before and present_after)
+ record("text_slayer_empty_task", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: Slayer Master did not render 'No active task. Tap "
+ f"Get New Task.' (absent_before={absent_before} reached={reached} "
+ f"present_after={present_after})"
+ if reached else
+ "setup_failed: could not reach the Slayer Master surface"),
+ depth=1, jump_kind="value",
+ expect="Slayer Master shows 'No active task. Tap Get New Task.'")
+
+
+@and_test(expects=("text_profile_bonuses_empty",)) # noqa: F405
+def test_profile_bonuses_empty():
+ """Profile > Bonuses section empty state: 'No active XP bonuses'. CHANGE: the
+ string is absent on the Profile default (Skills) pane and appears only after
+ selecting the Bonuses section (depth 2: Profile pane -> Bonuses pane)."""
+ open_app_home(fresh=True)
+ go_tab("Profile")
+ absent_before = not has_text("No active XP bonuses")
+ pane = and_enter_profile_bonuses()
+ present_after = has_text("No active XP bonuses", pane)
+ ok = bool(absent_before and present_after)
+ record("text_profile_bonuses_empty", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Bonuses section did not render 'No active XP "
+ f"bonuses' (absent_before={absent_before} present_after="
+ f"{present_after})"
+ if present_after or absent_before else
+ "feature_missing: no 'Bonuses' section / empty state on Profile"),
+ depth=2, jump_kind="value",
+ expect="Profile > Bonuses shows 'No active XP bonuses'")
+
+
+@and_test(expects=("text_recent_activity_empty",)) # noqa: F405
+def test_recent_activity_empty():
+ """Recent Activity bottom-sheet empty state on a fresh profile: 'No sessions
+ completed yet.'. depth 1 — the sheet is opened from the Home header button."""
+ open_app_home(fresh=True)
+ sheet = and_enter_recent_activity()
+ if sheet is None:
+ record("text_recent_activity_empty", False, # noqa: F405
+ "setup_failed: Recent Activity button not present on Home header",
+ depth=1, jump_kind="value",
+ expect="Recent Activity sheet shows 'No sessions completed yet.'")
+ return
+ ok = has_text("No sessions completed yet", sheet)
+ record("text_recent_activity_empty", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the Recent Activity sheet did not render "
+ "the empty state 'No sessions completed yet.' on a fresh profile",
+ depth=1, jump_kind="value",
+ expect="Recent Activity sheet shows 'No sessions completed yet.'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 2. SKILL ACTIVITY SHEET — app-authored titles + descriptions (CONTENT)
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_choose_activity_title",)) # noqa: F405
+def test_choose_activity_title():
+ """The activity sheet renders the title 'Choose Activity' AND the Mining
+ description 'Extract valuable ores and gems from the earth.'. CHANGE: neither
+ is on the Skills list before tapping Mining; both appear on the sheet (depth
+ 1)."""
+ open_app_home(fresh=True)
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ absent_before = not has_text("Choose Activity")
+ row = find_node(ui(), text="Mining") or find_node_ci(ui(), "Mining") # noqa: F405
+ opened = bool(row and tap_node(row)) # noqa: F405
+ settle("tap") # noqa: F405
+ title = has_text("Choose Activity")
+ desc = has_text("Extract valuable ores and gems from the earth")
+ ok = bool(absent_before and opened and title and desc)
+ record("text_choose_activity_title", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Mining activity sheet did not render 'Choose "
+ f"Activity' + the description (absent_before={absent_before} "
+ f"title={title} desc={desc})"
+ if opened else
+ "setup_failed: could not open the Mining activity sheet"),
+ depth=1, jump_kind="value",
+ expect="activity sheet shows 'Choose Activity' + 'Extract valuable ores "
+ "and gems from the earth.'")
+
+
+@and_test(expects=("text_rune_essence_description",)) # noqa: F405
+def test_rune_essence_description():
+ """The Rune Essence confirm dialog shows the item description 'Raw magical
+ stone used to craft all types of runes.'. CHANGE: absent on the Choose Activity
+ sheet; appears only inside the confirm dialog opened from Rune Essence's Start
+ Session (depth 2: sheet -> dialog)."""
+ open_app_home(fresh=True)
+ opened_sheet = and_enter_choose_activity("Mining")
+ absent_before = opened_sheet and not has_text(
+ "Raw magical stone used to craft all types of runes")
+ # tap Rune Essence's own Start Session -> confirm dialog
+ nodes = ui() # noqa: F405
+ act = find_node(nodes, text="Rune Essence") # noqa: F405
+ reached_dialog = False
+ if act and "_center" in act:
+ ay = act["_center"][1]
+ starts = find_nodes(nodes, text="Start Session") # noqa: F405
+ best = min(starts, key=lambda n: abs(n["_center"][1] - ay)) if starts else None
+ if best and tap_node(best): # noqa: F405
+ settle("tap") # noqa: F405
+ and_enter("Rune Essence dialog") # noqa: F405
+ reached_dialog = bool(find_node(ui(), text="Cancel")) # noqa: F405
+ desc = has_text("Raw magical stone used to craft all types of runes")
+ ok = bool(opened_sheet and absent_before and reached_dialog and desc)
+ record("text_rune_essence_description", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Rune Essence confirm dialog did not render "
+ "'Raw magical stone used to craft all types of runes.' "
+ f"(sheet={opened_sheet} absent_before={absent_before} "
+ f"dialog={reached_dialog} desc={desc})"
+ if opened_sheet else
+ "setup_failed: could not open the Choose Activity sheet"),
+ depth=2, jump_kind="value",
+ expect="Rune Essence confirm dialog shows 'Raw magical stone used to "
+ "craft all types of runes.'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 3. SESSION STATUS LABELS — the #1 dynamic-text surface
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_session_active_label",)) # noqa: F405
+def test_session_active_label():
+ """Starting a session makes the Home card read 'Session Active'. CHANGE: the
+ card reads 'No Active Session' before; 'Session Active' after (depth 2 to reach
+ the active session through the sheet + dialog)."""
+ open_app_home(fresh=True)
+ go_tab("Home")
+ absent_before = not has_text("Session Active")
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ present_after = has_text("Session Active")
+ ok = bool(absent_before and started and present_after)
+ record("text_session_active_label", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Home card did not switch to 'Session Active' "
+ f"after starting a session (absent_before={absent_before} "
+ f"started={started} present_after={present_after})"
+ if started else
+ "feature_missing: could not start a session to surface 'Session "
+ "Active'"),
+ depth=2, jump_kind="value",
+ expect="Home card reads 'Session Active' after a session starts")
+
+
+@and_test(expects=("text_skills_active_session_label",)) # noqa: F405
+def test_skills_active_session_label():
+ """On the SKILLS screen, an active Mining/Rune Essence session is labelled with
+ the PLAIN 'Mining — Rune Essence' (no emoji — the Home card is the one that
+ prefixes ⛏️, hence the plain-label read lives here). CHANGE: absent before the
+ session; present on Skills after (depth 2)."""
+ open_app_home(fresh=True)
+ go_tab("Skills")
+ and_enter("Skills") # noqa: F405
+ absent_before = not has_text("Mining — Rune Essence")
+ and_reset_depth() # noqa: F405 fresh chain to the session
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Skills")
+ present_after = has_text("Mining — Rune Essence")
+ ok = bool(absent_before and started and present_after)
+ record("text_skills_active_session_label", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Skills screen did not render the plain label "
+ f"'Mining — Rune Essence' for the active session (absent_before="
+ f"{absent_before} started={started} present_after={present_after})"
+ if started else
+ "feature_missing: could not start the Mining/Rune Essence session"),
+ depth=2, jump_kind="value",
+ expect="Skills screen shows the plain 'Mining — Rune Essence' label "
+ "while the session runs")
+
+
+@and_test(expects=("text_session_complete_label",)) # noqa: F405
+def test_session_complete_label():
+ """After '[Debug] Finish Now', the Home card status text changes from 'Session
+ Active' to 'Session Complete!'. CHANGE captured across the Finish Now trigger
+ (depth 2 to reach the active session first)."""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ active_before = started and has_text("Session Active")
+ completed = finish_now_home()
+ present_after = has_text("Session Complete!")
+ ok = bool(started and active_before and completed and present_after)
+ record("text_session_complete_label", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Home card did not read 'Session Complete!' "
+ f"after Finish Now (started={started} active_before={active_before} "
+ f"present_after={present_after})"
+ if started else
+ "feature_missing: could not start a session to finish"),
+ depth=2, jump_kind="value",
+ expect="Home card status goes 'Session Active' -> 'Session Complete!' "
+ "after [Debug] Finish Now")
+
+
+@and_test(expects=("text_reward_modal_labels",)) # noqa: F405
+def test_reward_modal_labels():
+ """The reward modal's CONTENT labels are 'XP gained' and 'Loot'. CHANGE:
+ neither is on the Home card before collecting; both appear in the modal after
+ Finish Now -> Collect (depth 2: active session -> reward modal). The '+900 XP'
+ NUMBER is ceded to computation — this asserts the app-authored heading words
+ only."""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ absent_before = not has_text("XP gained")
+ reached = and_reach_home_reward_modal()
+ xp_gained = has_text("XP gained")
+ loot = has_text("Loot")
+ ok = bool(started and absent_before and reached and xp_gained and loot)
+ record("text_reward_modal_labels", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the reward modal did not render the 'XP gained' + "
+ f"'Loot' headings (absent_before={absent_before} reached={reached} "
+ f"xp_gained={xp_gained} loot={loot})"
+ if started else
+ "feature_missing: could not start+finish+collect a session to reach "
+ "the reward modal"),
+ depth=2, jump_kind="value",
+ expect="reward modal shows the headings 'XP gained' and 'Loot'")
+
+
+@and_test(expects=("text_reward_loot_rune_essence",)) # noqa: F405
+def test_reward_loot_rune_essence():
+ """The reward modal's loot list names the item the Mining/Rune Essence session
+ produced: a 'Rune Essence' loot row. CHANGE: absent on the Home card before;
+ present in the modal after collecting (depth 2). (The 'Rune Essence' NAME is a
+ fixed app-authored label the modal renders; interaction owns the inventory
+ RECORD it becomes.)"""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ go_tab("Home")
+ reached = and_reach_home_reward_modal()
+ # find a 'Rune Essence' loot row inside the modal (not the session card, which
+ # is covered by the modal now).
+ loot_row = has_text("Rune Essence") and has_text("Loot")
+ ok = bool(started and reached and loot_row)
+ record("text_reward_loot_rune_essence", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the reward modal loot list did not name 'Rune "
+ f"Essence' (reached={reached} loot_row={loot_row})"
+ if started else
+ "feature_missing: could not reach the reward modal"),
+ depth=2, jump_kind="value",
+ expect="reward modal loot list contains a 'Rune Essence' row under 'Loot'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 4. COMBAT difficulty verdict — app-authored content derived from combat level
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_combat_farm_verdict",)) # noqa: F405
+def test_combat_farm_verdict():
+ """The Combat dungeon list renders the app-authored difficulty verdict for the
+ low-level Farm dungeon as 'You've got this'. CHANGE: absent on Home; present on
+ the Combat tab beside the Farm row (depth 1). We assert the STRING (whether the
+ verdict is CORRECT for the level is combat-logic; the RENDERED words are
+ text's)."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("You've got this")
+ go_tab("Combat")
+ and_enter("Combat") # noqa: F405
+ farm = find_node(ui(), text="Farm") # noqa: F405
+ on_combat = bool(farm)
+ verdict = has_text("You've got this")
+ ok = bool(absent_before and on_combat and verdict)
+ record("text_combat_farm_verdict", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Combat dungeon list did not render the verdict "
+ f"'You've got this' for the Farm dungeon (on_combat={on_combat} "
+ f"verdict={verdict})"
+ if on_combat else
+ "setup_failed: could not reach the Combat dungeon list (no 'Farm' "
+ "row)"),
+ depth=1, jump_kind="value",
+ expect="Combat dungeon list shows the verdict 'You've got this' for Farm")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 5. QUESTS hints — reset copy + the daily info line
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_quests_daily_reset",)) # noqa: F405
+def test_quests_daily_reset():
+ """The Quests Daily sub-tab renders 'Resets at 6:00 AM'. CHANGE: absent on
+ Home; present on the Quests > Timed > Daily surface (depth 1)."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("Resets at 6:00 AM")
+ go_tab("Quests")
+ and_enter("Quests") # noqa: F405
+ timed = find_node_ci(ui(), "Timed") # noqa: F405
+ if timed:
+ tap_node(timed) # noqa: F405
+ settle("tap") # noqa: F405
+ daily = find_node_ci(ui(), "Daily") # noqa: F405
+ reached = bool(daily and tap_node(daily)) # noqa: F405
+ settle("tap") # noqa: F405
+ present = has_text("Resets at 6:00 AM")
+ ok = bool(absent_before and reached and present)
+ record("text_quests_daily_reset", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Quests Daily sub-tab did not render 'Resets at "
+ f"6:00 AM' (reached={reached} present={present})"
+ if reached else
+ "setup_failed: could not reach the Quests Daily sub-tab"),
+ depth=1, jump_kind="value",
+ expect="Quests Daily sub-tab shows 'Resets at 6:00 AM'")
+
+
+@and_test(expects=("text_quests_daily_info",)) # noqa: F405
+def test_quests_daily_info():
+ """The Quests Daily sub-tab's info line contains 'Each daily quest rewards
+ coins'. depth 1. CHANGE: absent on Home; present on the Daily surface."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("Each daily quest rewards coins")
+ go_tab("Quests")
+ and_enter("Quests") # noqa: F405
+ timed = find_node_ci(ui(), "Timed") # noqa: F405
+ if timed:
+ tap_node(timed) # noqa: F405
+ settle("tap") # noqa: F405
+ daily = find_node_ci(ui(), "Daily") # noqa: F405
+ reached = bool(daily and tap_node(daily)) # noqa: F405
+ settle("tap") # noqa: F405
+ present = has_text("Each daily quest rewards coins")
+ ok = bool(absent_before and reached and present)
+ record("text_quests_daily_info", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Quests Daily sub-tab did not render the info "
+ f"line 'Each daily quest rewards coins' (reached={reached} "
+ f"present={present})"
+ if reached else
+ "setup_failed: could not reach the Quests Daily sub-tab"),
+ depth=1, jump_kind="value",
+ expect="Quests Daily info line contains 'Each daily quest rewards coins'")
+
+
+@and_test(expects=("text_quests_weekly_reset",)) # noqa: F405
+def test_quests_weekly_reset():
+ """The Quests Weekly sub-tab renders 'Resets Monday at 6am' — distinct wording
+ from Daily's 'Resets at 6:00 AM', so the two sub-tabs are discriminated by copy.
+ CHANGE: the Weekly string is absent on Daily; present after switching to Weekly
+ (depth 1)."""
+ open_app_home(fresh=True)
+ go_tab("Quests")
+ and_enter("Quests") # noqa: F405
+ timed = find_node_ci(ui(), "Timed") # noqa: F405
+ if timed:
+ tap_node(timed) # noqa: F405
+ settle("tap") # noqa: F405
+ daily = find_node_ci(ui(), "Daily") # noqa: F405
+ if daily:
+ tap_node(daily) # noqa: F405
+ settle("tap") # noqa: F405
+ absent_on_daily = not has_text("Resets Monday at 6am")
+ weekly = find_node_ci(ui(), "Weekly") # noqa: F405
+ reached = bool(weekly and tap_node(weekly)) # noqa: F405
+ settle("tap") # noqa: F405
+ present = has_text("Resets Monday at 6am")
+ ok = bool(absent_on_daily and reached and present)
+ record("text_quests_weekly_reset", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: the Quests Weekly sub-tab did not render 'Resets "
+ f"Monday at 6am' (absent_on_daily={absent_on_daily} reached="
+ f"{reached} present={present})"
+ if reached else
+ "setup_failed: could not reach the Quests Weekly sub-tab"),
+ depth=1, jump_kind="value",
+ expect="Quests Weekly sub-tab shows 'Resets Monday at 6am'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 6. SETTINGS description — an app-unique static row description
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_settings_recent_activity_desc",)) # noqa: F405
+def test_settings_recent_activity_desc():
+ """The Settings 'Recent Activity Log' row carries the description 'Show Recent
+ Activity button in the home screen header'. CHANGE: absent on Home; present on
+ the Settings surface (depth 1 via the Settings gear)."""
+ open_app_home(fresh=True)
+ absent_before = not has_text("Show Recent Activity button in the home screen header")
+ gear = find_node(ui(), content_desc="Settings") # noqa: F405
+ if not gear or not tap_node(gear): # noqa: F405
+ record("text_settings_recent_activity_desc", False, # noqa: F405
+ "setup_failed: Settings gear (content-desc='Settings') not on Home",
+ depth=1, jump_kind="value",
+ expect="Settings shows 'Show Recent Activity button in the home "
+ "screen header'")
+ return
+ settle("tap") # noqa: F405
+ and_enter("Settings") # noqa: F405
+ scroll_into_view("Recent Activity Log") # noqa: F405
+ present = has_text("Show Recent Activity button in the home screen header")
+ ok = bool(absent_before and present)
+ record("text_settings_recent_activity_desc", ok, # noqa: F405
+ "" if ok else "behavior_wrong: the Settings 'Recent Activity Log' row "
+ "did not render the description 'Show Recent Activity button in the home "
+ "screen header'",
+ depth=1, jump_kind="value",
+ expect="Settings shows 'Show Recent Activity button in the home screen "
+ "header'")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# 7. RECENT ACTIVITY content produced by an action
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_recent_activity_logs_mining",)) # noqa: F405
+def test_recent_activity_logs_mining():
+ """A collected Mining session (HOME-card path) writes a Recent Activity entry
+ that MENTIONS 'Mining'. CHANGE: the sheet reads 'No sessions completed yet.'
+ before; a 'Mining' entry appears after (depth 1 — the sheet). The exact entry
+ TEXT the app authors ('Mining' + the activity) is CONTENT this lane owns; the
+ DATA record's existence is interaction's."""
+ open_app_home(fresh=True)
+ ra0 = and_enter_recent_activity()
+ empty_before = bool(ra0 and has_text("No sessions completed yet", ra0))
+ # close the sheet, then run the loop (Home-card collect populates the log).
+ cn = find_node_ci(ui(), "Cancel") # noqa: F405
+ if cn:
+ tap_node(cn) # noqa: F405
+ settle("tap") # noqa: F405
+ and_reset_depth() # noqa: F405
+ started = and_enter_active_session("Rune Essence", "Mining")
+ reached = and_reach_home_reward_modal()
+ close_modal()
+ and_reset_depth() # noqa: F405
+ ra1 = and_enter_recent_activity()
+ logged = bool(ra1 and has_text("Mining", ra1)
+ and not has_text("No sessions completed yet", ra1))
+ ok = bool(empty_before and started and reached and logged)
+ record("text_recent_activity_logs_mining", ok, # noqa: F405
+ "" if ok else (
+ "behavior_wrong: a collected Mining session did not produce a "
+ f"'Mining' Recent Activity entry (empty_before={empty_before} "
+ f"started={started} reached={reached} logged={logged})"
+ if (started and reached) else
+ "setup_failed: could not complete+collect a session to populate the "
+ "Recent Activity log"),
+ depth=1, jump_kind="value",
+ expect="Recent Activity 'No sessions completed yet.' -> a 'Mining' entry "
+ "after a session is collected")
+
+
+# ════════════════════════════════════════════════════════════════════════════════
+# VLM (exactly 3) — opaque rendered glyphs that never reach the a11y tree. The two
+# fine-grained (position) questions test an exact rendered property; the emoji-core
+# question is the one genuinely-opaque content case.
+# ════════════════════════════════════════════════════════════════════════════════
+@and_test(expects=("text_home_session_emoji_vlm",)) # noqa: F405
+def test_home_session_emoji_vlm():
+ """The Home session card prefixes the skill name with a rendered pickaxe/tool
+ emoji glyph (⛏️) immediately before 'Mining' — a glyph the dump exposes only as
+ part of the label but whose VISUAL position (left of the text) is a rendered
+ property. depth 2 to reach the active session's Home card."""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ go_tab("Home")
+ vlm_assert("text_home_session_emoji", # noqa: F405
+ "On the highlighted session card, does a small pickaxe / mining-tool "
+ "emoji appear immediately to the LEFT of the words 'Mining — Rune "
+ "Essence', on the same line as that text?", RESULTS,
+ tag="position", depth=2, jump_kind="value")
+
+
+@and_test(expects=("text_reward_loot_icons_vlm",)) # noqa: F405
+def test_reward_loot_icons_vlm():
+ """In the reward modal's loot list each row shows the item quantity (like '×60')
+ aligned to the RIGHT of the item name — a rendered layout property (position of
+ the quantity relative to the name) rather than a wording read. depth 2 to reach
+ the modal."""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ and_reach_home_reward_modal()
+ vlm_assert("text_reward_loot_icons", # noqa: F405
+ "In the reward dialog's loot list under the 'Loot' heading, is each "
+ "item's quantity (such as '×60') shown on the RIGHT edge of the row, "
+ "with the item name (such as 'Rune Essence') on the LEFT?", RESULTS,
+ tag="position", depth=2, jump_kind="value")
+
+
+@and_test(expects=("text_session_complete_emoji_vlm",)) # noqa: F405
+def test_session_complete_emoji_vlm():
+ """The 'Session Complete!' card still renders the pickaxe emoji glyph beside the
+ skill name — a genuinely opaque emoji core (the glyph itself, not its position)
+ that the dump folds into the label string. depth 2 to reach the completed
+ card."""
+ open_app_home(fresh=True)
+ started = and_enter_active_session("Rune Essence", "Mining")
+ if started:
+ finish_now_home()
+ vlm_assert("text_session_complete_emoji", # noqa: F405
+ "On the 'Session Complete!' card, is a pickaxe / mining-tool emoji "
+ "rendered next to the skill name 'Mining — Rune Essence'?", RESULTS,
+ tag="content", depth=2, jump_kind="value")
+
+
+TESTS = [
+ # empty states (cheap, robust CHANGE assertions)
+ test_home_no_active_session,
+ test_church_empty_blessing,
+ test_slayer_empty_task,
+ test_profile_bonuses_empty,
+ test_recent_activity_empty,
+ # skill activity sheet titles + descriptions
+ test_choose_activity_title,
+ test_rune_essence_description,
+ # session status labels (the #1 dynamic-text surface)
+ test_session_active_label,
+ test_skills_active_session_label,
+ test_session_complete_label,
+ test_reward_modal_labels,
+ test_reward_loot_rune_essence,
+ # combat difficulty verdict
+ test_combat_farm_verdict,
+ # quests hints
+ test_quests_daily_reset,
+ test_quests_daily_info,
+ test_quests_weekly_reset,
+ # settings description
+ test_settings_recent_activity_desc,
+ # recent activity content produced by an action
+ test_recent_activity_logs_mining,
+ # VLM track (exactly 3)
+ test_home_session_emoji_vlm,
+ test_reward_loot_icons_vlm,
+ test_session_complete_emoji_vlm,
+]
+
+if __name__ == "__main__":
+ if not device_online(): # noqa: F405
+ print("WARNING: device offline — a whole module of setup_failed usually "
+ "means the emulator/tunnel dropped, not that the app is broken")
+ run_suite(TESTS, "text") # noqa: F405
diff --git a/android/tristinbaker-idlefantasy/tests/test_manifest.json b/android/tristinbaker-idlefantasy/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..5230fef14bafa09f41053f5d952fbb86f21b5127
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/tests/test_manifest.json
@@ -0,0 +1,817 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "idlefantasy",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 125,
+ "manifest_sha": "ddda7a2b0c64",
+ "tests": [
+ {
+ "name": "computation::computation_activity_copper_projection",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_activity_ores_per_session",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_activity_rune_projection",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_activity_rune_xp_rate",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_activity_session_length",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_confirm_dialog_xp_rate",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_home_card_projection",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_home_projection_badge_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_mining_level_after_collect",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_mining_xp_after_collect",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_mining_xp_bar_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_no_active_session_baseline",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_reward_ore_count",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_reward_xp_gained",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_skill_level1_progress",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_total_level_after_collect",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_total_level_delta",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_abandon_clears_session",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_active_card_countdown_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_active_card_highlighted_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_collect_adds_inventory",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_collect_button_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_collect_mutates_total_level",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_core_loop_sequence",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_longpress_no_side_effect",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_multi_record_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_recent_activity_logs_session",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_reward_modal_layout_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_second_session_starts",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_session_survives_process_death",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_skill_level_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_skills_training_badge_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_start_cancel_no_session",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_switch_active_skill",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_2hop_guild",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_shop",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_choose_activity_sheet_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_church_activate_cards_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_combat_dungeon_rows_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_cross_shop_to_skills",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_depth2_bestiary_bosses",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_depth2_choose_activity",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_depth2_dungeon_sheet",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_depth2_guild_detail",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_profile_rail_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_builders",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_carnival",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_church",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_combat",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_guild_hall",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_home_from_profile",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_inn",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_profile",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_quests",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_shop",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_skills",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_skills_to_combat",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_slayer",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_selected_tab_highlight_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_back_arrow_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_shop_toggle_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_bottom_nav_home_selected_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_bottom_nav_skills_selected_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_font_size_dropdown_opens",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_onboarding_confirm_enable",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_onboarding_gender_chip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_onboarding_race_chip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_profile_layout_consequence",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_profile_layout_rail_to_tabs",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_profile_layout_tabs_chip_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_profile_layout_tabs_screen_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_quests_daily_subtab_selected_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_recent_activity_consequence",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_recent_activity_log_flip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_recent_activity_log_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_recent_activity_log_thumb_off_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_session_notifications_thumb_on_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_to_light",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_light_chip_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persist_background_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_system_select",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_activity_sheet_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_bottom_nav_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_combat_subtab_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_dungeon_list_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_dungeon_sheet_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_home_anchors",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_grid_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_navbar_persists",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_onboarding_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_profile_pane_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_reward_modal_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_reward_modal_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_session_card_present_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_session_card_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_list_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_skill_rows_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_skill_sheet_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_stats_card_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_choose_activity_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_church_empty_blessing",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_combat_farm_verdict",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_no_active_session",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_session_emoji_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_profile_bonuses_empty",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_quests_daily_info",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_quests_daily_reset",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_quests_weekly_reset",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_recent_activity_empty",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_recent_activity_logs_mining",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_reward_loot_icons_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_reward_loot_rune_essence",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_reward_modal_labels",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_rune_essence_description",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_session_active_label",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_session_complete_emoji_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_session_complete_label",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_recent_activity_desc",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_skills_active_session_label",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_slayer_empty_task",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_mining_xp_bar_vlm",
+ "module": "computation",
+ "tag": "size"
+ },
+ {
+ "name": "computation::computation_home_projection_badge_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_active_card_highlighted_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_active_card_countdown_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_collect_button_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_reward_modal_layout_vlm",
+ "module": "interaction",
+ "tag": "layout"
+ },
+ {
+ "name": "interaction::interaction_skills_training_badge_vlm",
+ "module": "interaction",
+ "tag": "content"
+ },
+ {
+ "name": "navigation::nav_settings_back_arrow_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_shop_toggle_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_selected_tab_highlight_vlm",
+ "module": "navigation",
+ "tag": "color"
+ },
+ {
+ "name": "navigation::nav_combat_dungeon_rows_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_church_activate_cards_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_choose_activity_sheet_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_profile_rail_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_recent_activity_log_thumb_off_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_theme_light_chip_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_persist_background_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_profile_layout_tabs_chip_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_profile_layout_tabs_screen_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_bottom_nav_home_selected_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_bottom_nav_skills_selected_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_quests_daily_subtab_selected_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_session_notifications_thumb_on_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_home_grid_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_bottom_nav_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_stats_card_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_activity_sheet_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_session_card_present_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_settings_list_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_skill_rows_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_dungeon_list_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_reward_modal_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "text::text_home_session_emoji_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_reward_loot_icons_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_session_complete_emoji_vlm",
+ "module": "text",
+ "tag": "content"
+ }
+ ],
+ "vlm_total": 35,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/tristinbaker-idlefantasy/vlm_assertions.json b/android/tristinbaker-idlefantasy/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..4db381ab907574108090932ef62418d36d48e4a0
--- /dev/null
+++ b/android/tristinbaker-idlefantasy/vlm_assertions.json
@@ -0,0 +1,762 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/tristinbaker-idlefantasy",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 38,
+ "with_verdict": 35,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 35,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "structure_home_grid_vlm",
+ "screenshot": "structure_home_grid_vlm.png",
+ "assertion": "Below the player-stats panel, is there a grid of labelled square tiles/buttons (such as Shop, Inn, Guild Hall, Church) arranged in rows and columns?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_home_grid",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_bottom_nav_vlm",
+ "screenshot": "structure_bottom_nav_vlm.png",
+ "assertion": "Is there a bottom navigation bar with exactly 5 evenly spaced icon+label tabs spanning the width of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_bottom_nav",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_stats_card_vlm",
+ "screenshot": "structure_stats_card_vlm.png",
+ "assertion": "Near the top, is there a single distinct card/panel that shows three stat values side by side in separate columns (Combat Level, Total Level, Coins)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_stats_card",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_activity_sheet_vlm",
+ "screenshot": "structure_activity_sheet_vlm.png",
+ "assertion": "Is a bottom-sheet panel with rounded top corners and a small drag handle overlaying the lower portion of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_activity_sheet",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_session_card_present_vlm",
+ "screenshot": "structure_session_card_present_vlm.png",
+ "assertion": "Is there a distinct highlighted card/panel on the screen showing an active training session with a countdown and action buttons?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_session_card_present",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_settings_list_vlm",
+ "screenshot": "structure_settings_list_vlm.png",
+ "assertion": "Is the screen a vertical list of setting rows stacked top to bottom (each row a label with a control on its right)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_settings_list",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_skill_rows_vlm",
+ "screenshot": "structure_skill_rows_vlm.png",
+ "assertion": "Is the screen a vertical list of skill rows where each row has an icon on the left and a horizontal progress bar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_skill_rows",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_dungeon_list_vlm",
+ "screenshot": "structure_dungeon_list_vlm.png",
+ "assertion": "Is the main content a vertical list of stacked rows, one per dungeon, where each row shows a level label (like 'Lv. 1') aligned to the right edge?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_dungeon_list",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_reward_modal_vlm",
+ "screenshot": "structure_reward_modal_vlm.png",
+ "assertion": "Is there a centered dialog/modal overlaying the screen that lists an XP amount and one or more item/reward rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_reward_modal",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_settings_back_arrow_vlm",
+ "screenshot": "nav_settings_back_arrow_vlm.png",
+ "assertion": "Is there a left-pointing back/up arrow icon at the very top-left of the screen, to the left of the 'Settings' title?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_settings_back_arrow",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_shop_toggle_vlm",
+ "screenshot": "nav_shop_toggle_vlm.png",
+ "assertion": "Near the top of the screen, are there exactly two side-by-side segmented tabs labelled 'Buy' and 'Sell', with one underlined/highlighted as selected?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_shop_toggle",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_selected_tab_highlight_vlm",
+ "screenshot": "nav_selected_tab_highlight_vlm.png",
+ "assertion": "In the bottom navigation bar of 5 tabs, is exactly ONE tab visually highlighted with a distinct coloured background/pill behind its icon, different from the other four?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "nav_selected_tab_highlight",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_combat_dungeon_rows_vlm",
+ "screenshot": "nav_combat_dungeon_rows_vlm.png",
+ "assertion": "Is the main content a vertical stack of dungeon rows where each row shows a level label like 'Lv. 1' aligned to the right edge?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_combat_dungeon_rows",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_church_activate_cards_vlm",
+ "screenshot": "nav_church_activate_cards_vlm.png",
+ "assertion": "Under an 'XP Blessings' heading, is there a vertical list of blessing rows/cards, the first of which has an 'Activate' button on its right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_church_activate_cards",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_choose_activity_sheet_vlm",
+ "screenshot": "nav_choose_activity_sheet_vlm.png",
+ "assertion": "Is a bottom-sheet panel with rounded top corners and a small horizontal drag handle overlaying the lower portion of the screen, sitting above the dimmed content behind it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_choose_activity_sheet",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_profile_rail_vlm",
+ "screenshot": "nav_profile_rail_vlm.png",
+ "assertion": "Down the LEFT side of the screen, is there a vertical column/rail of stacked section labels (such as Skills, Inventory, Gear, Pets), with one of them highlighted?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_profile_rail",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_mining_xp_bar_vlm",
+ "screenshot": "computation_mining_xp_bar_vlm.png",
+ "assertion": "The 'Mining' skill row shows '900 / 969 XP'. Is its horizontal progress bar rendered almost completely filled (roughly 90% or more of its width), noticeably fuller than the empty bars of the other level-1 skills below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "size",
+ "modality": null,
+ "links_to": "computation_mining_xp_bar",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_home_projection_badge_vlm",
+ "screenshot": "computation_home_projection_badge_vlm.png",
+ "assertion": "In the active session card at the top of the Home screen, is the text '+900 XP' rendered together with a level target '8' on the same highlighted line (an XP-to-level projection), positioned directly below the session countdown timer?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "computation_home_projection_badge",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_recent_activity_log_thumb_off_vlm",
+ "screenshot": "states_recent_activity_log_thumb_off_vlm.png",
+ "assertion": "Look at the 'Recent Activity Log' row's toggle switch. Is its thumb on the LEFT side and grey/uncoloured (the OFF position)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_recent_activity_log_thumb_off",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_light_chip_highlight_vlm",
+ "screenshot": "states_theme_light_chip_highlight_vlm.png",
+ "assertion": "In the Theme segmented control [Dark | Light | System], is the 'Light' chip the one with the filled/highlighted background (the selected chip), rather than 'Dark'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_light_chip_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_persist_background_vlm",
+ "screenshot": "states_theme_persist_background_vlm.png",
+ "assertion": "After the app was fully restarted, is the app background LIGHT (white / very light) with dark text, i.e. the light theme was remembered rather than reverting to the dark theme?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_persist_background",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_profile_layout_tabs_chip_highlight_vlm",
+ "screenshot": "states_profile_layout_tabs_chip_highlight_vlm.png",
+ "assertion": "In the Profile Layout segmented control [Rail | Tabs], is the 'Tabs' chip now the one with the filled/highlighted background (selected), rather than 'Rail'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_profile_layout_tabs_chip_highlight",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_profile_layout_tabs_screen_vlm",
+ "screenshot": "states_profile_layout_tabs_screen_vlm.png",
+ "assertion": "On this Profile screen, are the section labels (Skills, Inventory, Gear, ...) laid out as a HORIZONTAL row of tabs across the TOP, rather than as a vertical rail of icons down the LEFT edge?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "states_profile_layout_tabs_screen",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_onboarding_confirm_render_vlm",
+ "screenshot": "states_onboarding_confirm_render_vlm.png",
+ "assertion": "Now that a character name has been entered, is the 'Confirm' button rendered as a SOLID / coloured (enabled, tappable) button rather than a faded / greyed-out disabled one?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_onboarding_confirm_render",
+ "rigor": null,
+ "verdict": null,
+ "calibration": null
+ },
+ {
+ "id": "states_bottom_nav_home_selected_vlm",
+ "screenshot": "states_bottom_nav_home_selected_vlm.png",
+ "assertion": "In the bottom navigation bar (Skills, Combat, Home, Quests, Profile), is the 'Home' tab in the CENTER the one that is highlighted/selected (a gold/coloured circular background behind its icon), while the others are plain grey?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_bottom_nav_home_selected",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_bottom_nav_skills_selected_vlm",
+ "screenshot": "states_bottom_nav_skills_selected_vlm.png",
+ "assertion": "In the bottom navigation bar, is the LEFTMOST 'Skills' tab now the highlighted/selected one (gold/coloured circular highlight behind its icon), and is the center 'Home' tab NOT highlighted?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_bottom_nav_skills_selected",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_active_card_highlighted_vlm",
+ "screenshot": "interaction_active_card_highlighted_vlm.png",
+ "assertion": "After starting a training session, is the session status card near the middle of the screen filled with a warm gold/amber/brown background that is clearly different from the blue player-stats card above it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_active_card_highlighted",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_active_card_countdown_vlm",
+ "screenshot": "interaction_active_card_countdown_vlm.png",
+ "assertion": "Within the highlighted gold/amber session card, is a large countdown time in minutes-and-seconds form (like '59m 44s') displayed prominently?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_active_card_countdown",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_collect_button_vlm",
+ "screenshot": "interaction_collect_button_vlm.png",
+ "assertion": "Is there a large full-width button with a solid gold/amber background (its text roughly 'Collect ... Rewards') spanning nearly the whole width of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_collect_button",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_reward_modal_layout_vlm",
+ "screenshot": "interaction_reward_modal_layout_vlm.png",
+ "assertion": "Is a dialog/panel overlaying the screen that shows an XP amount near the top and, below it, a vertical list of one or more reward/item rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_reward_modal_layout",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_reward_modal_icons_vlm",
+ "screenshot": "interaction_reward_modal_icons_vlm.png",
+ "assertion": "In the reward dialog's item list, does each item row show a small coloured icon/emoji to the LEFT of its name with a quantity (like 'x60' or 'x2') to the right?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_reward_modal_icons",
+ "rigor": null,
+ "verdict": null,
+ "calibration": null
+ },
+ {
+ "id": "interaction_inventory_grid_vlm",
+ "screenshot": "interaction_inventory_grid_vlm.png",
+ "assertion": "Is the inventory content laid out as a repeating set of item tiles/rows, each showing an item icon together with a small quantity number/badge (like 'x60')?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_inventory_grid",
+ "rigor": null,
+ "verdict": null,
+ "calibration": null
+ },
+ {
+ "id": "interaction_skills_training_badge_vlm",
+ "screenshot": "interaction_skills_training_badge_vlm.png",
+ "assertion": "On the skills list, does the Mining row show a small pill/badge labelled 'Training' (visually distinct from the progress text on the other skill rows)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "interaction_skills_training_badge",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_quests_daily_subtab_selected_vlm",
+ "screenshot": "states_quests_daily_subtab_selected_vlm.png",
+ "assertion": "On the Quests screen's Timed section there are two sub-tabs 'Daily' and 'Weekly'. Is 'Daily' the currently SELECTED sub-tab (filled / highlighted / underlined) while 'Weekly' is the unselected one?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_quests_daily_subtab_selected",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_session_notifications_thumb_on_vlm",
+ "screenshot": "states_session_notifications_thumb_on_vlm.png",
+ "assertion": "Look at the 'Session Notifications' row's toggle switch. Is its thumb on the RIGHT side and gold/coloured/filled (the ON position), rather than on the left and grey?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_session_notifications_thumb_on",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_home_session_emoji_vlm",
+ "screenshot": "text_home_session_emoji_vlm.png",
+ "assertion": "On the highlighted session card, does a small pickaxe / mining-tool emoji appear immediately to the LEFT of the words 'Mining — Rune Essence', on the same line as that text?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_home_session_emoji",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_reward_loot_icons_vlm",
+ "screenshot": "text_reward_loot_icons_vlm.png",
+ "assertion": "In the reward dialog's loot list under the 'Loot' heading, is each item's quantity (such as '×60') shown on the RIGHT edge of the row, with the item name (such as 'Rune Essence') on the LEFT?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_reward_loot_icons",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_session_complete_emoji_vlm",
+ "screenshot": "text_session_complete_emoji_vlm.png",
+ "assertion": "On the 'Session Complete!' card, is a pickaxe / mining-tool emoji rendered next to the skill name 'Mining — Rune Essence'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "text_session_complete_emoji",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/LICENSE b/android/urikdev-urik/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f288702d2fa16d3cdf0035b15a9fcbc552cd88e7
--- /dev/null
+++ b/android/urikdev-urik/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 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 General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is 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. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ 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.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ 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 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. Use with the GNU Affero General Public License.
+
+ 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 Affero 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 special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU 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 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 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 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 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 General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ 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 GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/android/urikdev-urik/instance.json b/android/urikdev-urik/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..1065b2647b237a78e1aaaee2bfdf36afb567c7b3
--- /dev/null
+++ b/android/urikdev-urik/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/urikdev-urik",
+ "platform": "android",
+ "repo": "https://github.com/urikdev/urik",
+ "commit": "0d3a9aca3304d61029ce9639cd7ac6b61b30b870",
+ "patches": [],
+ "package": "com.urik.keyboard",
+ "license": null
+}
diff --git a/android/urikdev-urik/reference/launch.sh b/android/urikdev-urik/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/urikdev-urik/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/urikdev-urik/tests/android_computation_eval.json b/android/urikdev-urik/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..061627baad68827f39270eaec5bd256aa5d335c4
--- /dev/null
+++ b/android/urikdev-urik/tests/android_computation_eval.json
@@ -0,0 +1,208 @@
+{
+ "module": "computation",
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 5,
+ "passed": 5,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3571,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 5,
+ "liveness": 0,
+ "interactive": 14,
+ "depth_ge1": 14,
+ "depth_ge2": 14,
+ "value": 14,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "computation_suggestion_count_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a dialog shown containing a vertical list of selectable options each preceded by a round radio-button circle (one filled/selected)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a dialog shown containing a vertical list of selectable options each preceded by a round radio-button circle (one filled/selected)?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_suggestion_count_2",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Suggestion Count summary == '2'"
+ },
+ {
+ "test": "computation_suggestion_count_1",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Suggestion Count summary == '1'"
+ },
+ {
+ "test": "computation_key_size_large",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Key Size summary == 'Large'"
+ },
+ {
+ "test": "computation_key_label_size_large",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Key Label Size summary == 'Large'"
+ },
+ {
+ "test": "computation_cursor_speed_fast",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Cursor Speed summary == 'Fast'"
+ },
+ {
+ "test": "computation_long_press_punctuation_spacebar",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Long Press Punctuation summary == 'Spacebar'"
+ },
+ {
+ "test": "computation_long_press_duration_long",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Long Press Duration summary == 'Long'"
+ },
+ {
+ "test": "computation_space_bar_size_wide",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Space Bar Size summary == 'Wide'"
+ },
+ {
+ "test": "computation_keyboard_layout_dialog_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a dialog shown listing multiple keyboard-layout choices (such as QWERTY / QWERTZ / AZERTY) as a vertical list of selectable rows?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a dialog shown listing multiple keyboard-layout choices (such as QWERTY / QWERTZ / AZERTY) as a vertical list of selectable rows?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_keyboard_layout_qwertz",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Keyboard Layout summary == 'QWERTZ'"
+ },
+ {
+ "test": "computation_vibration_seekbar_min_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the slider (SeekBar) thumb positioned at the far-LEFT end of the Vibration Strength track, near the start of the bar?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the slider (SeekBar) thumb positioned at the far-LEFT end of the Vibration Strength track, near the start of the bar?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_vibration_seekbar_min",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "seekbar_value == '6' (far-left tap)"
+ },
+ {
+ "test": "computation_vibration_seekbar_max_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the slider (SeekBar) thumb positioned at the far-RIGHT end of the Vibration Strength track, near the end of the bar?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the slider (SeekBar) thumb positioned at the far-RIGHT end of the Vibration Strength track, near the end of the bar?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_vibration_seekbar_max",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "seekbar_value == '250' (far-right tap)"
+ },
+ {
+ "test": "computation_vibration_seekbar_center",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "seekbar_value == '128' (centre tap)"
+ },
+ {
+ "test": "computation_test_field_echo_typing_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the 'Test changes' input field at the bottom visibly display the typed text 'kbdcompute7'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does the 'Test changes' input field at the bottom visibly display the typed text 'kbdcompute7'?",
+ "tag": "content"
+ },
+ {
+ "test": "computation_test_field_echo_typing",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "test_field text == 'kbdcompute7'"
+ },
+ {
+ "test": "computation_test_field_echo_layout",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "test_field text == 'kbdlayout9'"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/android_interaction_eval.json b/android/urikdev-urik/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..049db71093dc1e7b55df12381660a4d0fd5a648b
--- /dev/null
+++ b/android/urikdev-urik/tests/android_interaction_eval.json
@@ -0,0 +1,210 @@
+{
+ "module": "interaction",
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.5833,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 19,
+ "depth_ge1": 19,
+ "depth_ge2": 12,
+ "value": 4,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "interaction_theme_selection_persists_to_main",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "main label 'Light'"
+ },
+ {
+ "test": "interaction_theme_selection_persists_to_main_vlm",
+ "passed": true,
+ "message": "VLM: Q='The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly WHITE / very light background (a light colour theme), rather than dark?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly WHITE / very light background (a light colour theme), rather than dark?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_theme_selection_survives_restart",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "main label 'Abyss' after relaunch"
+ },
+ {
+ "test": "interaction_theme_favorite_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Remove Crimson from favorites after relaunch"
+ },
+ {
+ "test": "interaction_theme_favorite_persists_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this theme list, is at least one theme card's favorite heart icon drawn as a FILLED / solid heart (as opposed to an empty outline)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this theme list, is at least one theme card's favorite heart icon drawn as a FILLED / solid heart (as opposed to an empty outline)?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_theme_favorite_multi_integrity",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Crimson='Remove Crimson from favorites' & Forest='Remove Forest from favorites'"
+ },
+ {
+ "test": "interaction_theme_reselect_sequence",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "final selected='Abyss theme, currently selected', Light no longer selected"
+ },
+ {
+ "test": "interaction_layoutmapper_custom_char_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a bottom sheet / panel (containing a text input field and a 'Save' button) displayed in the lower part of the screen, overlaying a rendered keyboard above it?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a bottom sheet / panel (containing a text input field and a 'Save' button) displayed in the lower part of the screen, overlaying a rendered keyboard above it?",
+ "tag": "layout"
+ },
+ {
+ "test": "interaction_layoutmapper_custom_char",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Edit key: G' sheet, field holds 'z', closes on Save"
+ },
+ {
+ "test": "interaction_spellcheck_disables_dependents",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Pause & Autocorrection both enabled=false after Spell Check OFF"
+ },
+ {
+ "test": "interaction_haptic_survives_restart",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Haptic Feedback checked=false after relaunch"
+ },
+ {
+ "test": "interaction_keypress_highlight_survives_restart",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Key Press Highlight checked=false after relaunch"
+ },
+ {
+ "test": "interaction_suggestion_count_survives_restart",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Suggestion Count summary '1' after relaunch"
+ },
+ {
+ "test": "interaction_test_field_echo_autocorrect",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "test_field holds 'kit_echo_A'"
+ },
+ {
+ "test": "interaction_test_field_echo_appearance",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "test_field holds 'kit_echo_B'"
+ },
+ {
+ "test": "interaction_theme_dark_applied_vlm",
+ "passed": true,
+ "message": "VLM: Q='The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly BLACK / very dark background (a dark colour theme)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly BLACK / very dark background (a dark colour theme)?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_spellcheck_dependents_dimmed_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this settings list, are the 'Pause on Misspelled Word' and 'Autocorrection' rows shown greyed-out / dimmed (a faded, disabled appearance) compared with the fully-black active rows above them?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this settings list, are the 'Pause on Misspelled Word' and 'Autocorrection' rows shown greyed-out / dimmed (a faded, disabled appearance) compared with the fully-black active rows above them?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_favorite_floats_to_top_vlm",
+ "passed": true,
+ "message": "VLM: Q='At the very TOP of this theme list (the first one or two cards), is there a theme card whose favorite heart icon is FILLED / solid rather than an empty outline?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: At the very TOP of this theme list (the first one or two cards), is there a theme card whose favorite heart icon is FILLED / solid rather than an empty outline?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_selected_theme_checkmark_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this theme list, is exactly one theme card marked as the currently-selected one with a check-mark / tick badge (a small checkmark icon), while the other cards have no such checkmark?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this theme list, is exactly one theme card marked as the currently-selected one with a check-mark / tick badge (a small checkmark icon), while the other cards have no such checkmark?",
+ "tag": "shape"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/android_navigation_eval.json b/android/urikdev-urik/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..95ad1c8de82fd5be62ba52fac2007f1025cef693
--- /dev/null
+++ b/android/urikdev-urik/tests/android_navigation_eval.json
@@ -0,0 +1,320 @@
+{
+ "module": "navigation",
+ "total": 31,
+ "passed": 31,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 22,
+ "passed": 22,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.4091,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 9,
+ "liveness": 0,
+ "interactive": 22,
+ "depth_ge1": 22,
+ "depth_ge2": 15,
+ "value": 0,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Keyboard Settings' title appeared; launcher 'Open Settings' button gone"
+ },
+ {
+ "test": "nav_reach_settings_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a settings screen showing a top toolbar with a left-pointing back arrow at the top-left and a vertical list of labelled rows below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a settings screen showing a top toolbar with a left-pointing back arrow at the top-left and a vertical list of labelled rows below it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_about",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "About text ('...GNU GPL v3.0...') appeared; launcher 'Open Settings' gone"
+ },
+ {
+ "test": "nav_reach_about_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this an 'About' text page: a screen filled mostly with lines of text (version, copyright, links) and NO keyboard preview or list of toggle rows?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is this an 'About' text page: a screen filled mostly with lines of text (version, copyright, links) and NO keyboard preview or list of toggle rows?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reach_themepicker",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Keyboard Theme' title appeared; launcher 'Open Settings' gone"
+ },
+ {
+ "test": "nav_reach_themepicker_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (e.g. a dark one, a white/light one, a black one)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (e.g. a dark one, a white/light one, a black one)?",
+ "tag": "color"
+ },
+ {
+ "test": "nav_reach_features_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Features tip 'Learning Words' appeared; launcher 'Open Settings' covered/gone"
+ },
+ {
+ "test": "nav_reach_features_sheet_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a bottom sheet panel covering the lower portion of the screen, showing a list of tip titles with descriptions, while the top of the screen is dimmed?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a bottom sheet panel covering the lower portion of the screen, showing a list of tip titles with descriptions, while the top of the screen is dimmed?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_settings_to_autocorrect",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Spell Check' row appeared; 'Keyboard Settings' title gone"
+ },
+ {
+ "test": "nav_settings_to_languages",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Merged Dictionaries' row appeared; 'Keyboard Settings' title gone"
+ },
+ {
+ "test": "nav_settings_to_typing",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Double-Space Period' row appeared; 'Keyboard Settings' title gone"
+ },
+ {
+ "test": "nav_settings_to_layout",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Keyboard Layout' row appeared; 'Keyboard Settings' title gone"
+ },
+ {
+ "test": "nav_settings_to_appearance",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Key Press Highlight' row appeared; 'Keyboard Settings' title gone"
+ },
+ {
+ "test": "nav_settings_to_privacy",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Clipboard History' row appeared; Settings-list 'Dictionary Data' row gone"
+ },
+ {
+ "test": "nav_settings_to_licenses",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "licenses text view appeared; 'Dictionary Data' row gone"
+ },
+ {
+ "test": "nav_settings_to_dictionary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "attribution text appeared; 'Open Source Licenses' row gone"
+ },
+ {
+ "test": "nav_chain_appearance_themepicker",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Keyboard Theme' appeared after the Appearance 'Theme' row; 'Key Press Highlight' gone"
+ },
+ {
+ "test": "nav_chain_appearance_themepicker_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (dark, light/white, black, etc.)?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (dark, light/white, black, etc.)?",
+ "tag": "color"
+ },
+ {
+ "test": "nav_chain_layout_mapper",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Reset All' appeared after the 'Customize Keys' row; 'Keyboard Layout' gone"
+ },
+ {
+ "test": "nav_chain_layout_mapper_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a full keyboard laid out as horizontal rows of keys (number row, then letter rows Q-P, A-L, Z-M) rendered in the center of this screen?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a full keyboard laid out as horizontal rows of keys (number row, then letter rows Q-P, A-L, Z-M) rendered in the center of this screen?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_reset_dialog_reach",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "dialog message 'Reset all settings to defaults?' appeared; 'Clipboard History' row covered/gone"
+ },
+ {
+ "test": "nav_reset_dialog_reach_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a small modal dialog box centered on the screen (with a title, a short message, and Cancel/OK buttons) over a dimmed background?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a small modal dialog box centered on the screen (with a title, a short message, and Cancel/OK buttons) over a dimmed background?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reset_dialog_cancel",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "after Cancel: dialog message gone, 'Clipboard History' row restored"
+ },
+ {
+ "test": "nav_suggestion_dialog_reach",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "dialog list ('select_dialog_listview') appeared; 'Learn New Words' covered/gone"
+ },
+ {
+ "test": "nav_suggestion_dialog_reach_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a modal dialog showing a short vertical list of numeric options, each with a round radio-button circle to its left, and a Cancel button?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a modal dialog showing a short vertical list of numeric options, each with a round radio-button circle to its left, and a Cancel button?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_suggestion_dialog_cancel",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "after Cancel: dialog list gone, 'Learn New Words' row restored"
+ },
+ {
+ "test": "nav_backstack_up_autocorrect_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the toolbar at the very top of this screen show a left-pointing back arrow at its far left, next to the screen title?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does the toolbar at the very top of this screen show a left-pointing back arrow at its far left, next to the screen title?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_backstack_up_autocorrect",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Keyboard Settings' title reappeared; 'Spell Check' row gone"
+ },
+ {
+ "test": "nav_backstack_about_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "launcher 'Open Settings' button restored; About text ('GNU GPL v3.0') gone"
+ },
+ {
+ "test": "nav_backstack_themepicker_to_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "launcher 'Open Settings' button restored; 'Keyboard Theme' title gone"
+ },
+ {
+ "test": "nav_backstack_2hop_unwind",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "pop1 -> Appearance ('Key Press Highlight'), pop2 -> Settings ('Keyboard Settings')"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/android_states_eval.json b/android/urikdev-urik/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..95be119a6d1a92d8903f847bcab4fd603bd16075
--- /dev/null
+++ b/android/urikdev-urik/tests/android_states_eval.json
@@ -0,0 +1,328 @@
+{
+ "module": "states",
+ "total": 32,
+ "passed": 32,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 24,
+ "passed": 24,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.3333,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 32,
+ "depth_ge1": 31,
+ "depth_ge2": 31,
+ "value": 14,
+ "vlm_fine": 8
+ },
+ "results": [
+ {
+ "test": "states_sm1_spellcheck_checked_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Spell check enabled'->'Spell check disabled'"
+ },
+ {
+ "test": "states_sm1_pause_enable_flip",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "false"
+ },
+ {
+ "test": "states_sm1_autocorrection_enable_flip",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "false"
+ },
+ {
+ "test": "states_sm1_reenable_restores",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "true"
+ },
+ {
+ "test": "states_sm1_spellcheck_greyed_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this settings list the 'Spell Check' row text is bright white. Are the 'Pause on Misspelled Word' and 'Autocorrection' rows below it rendered in a noticeably dimmer / greyed-out grey colour (disabled appearance) compared to 'Spell Check'?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this settings list the 'Spell Check' row text is bright white. Are the 'Pause on Misspelled Word' and 'Autocorrection' rows below it rendered in a noticeably dimmer / greyed-out grey colour (disabled appearance) compared to 'Spell Check'?",
+ "tag": "color"
+ },
+ {
+ "test": "states_sm2_numberrow_checked_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Number row shown'->'Number row hidden'"
+ },
+ {
+ "test": "states_sm2_numberhints_enable_flip",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "true"
+ },
+ {
+ "test": "states_sm2_numberhints_undimmed_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the 'Show Number Hints' row text rendered in bright, active white (the same brightness as the other enabled setting titles on screen), i.e. NOT greyed-out or dimmed?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is the 'Show Number Hints' row text rendered in bright, active white (the same brightness as the other enabled setting titles on screen), i.e. NOT greyed-out or dimmed?",
+ "tag": "color"
+ },
+ {
+ "test": "states_show_suggestions_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Suggestions shown'->'Suggestions hidden'"
+ },
+ {
+ "test": "states_learn_new_words_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Learning enabled'->'Learning disabled'"
+ },
+ {
+ "test": "states_haptic_feedback_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Haptic enabled'->'Haptic disabled'"
+ },
+ {
+ "test": "states_swipe_typing_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Swipe to type enabled'->'Swipe to type disabled'"
+ },
+ {
+ "test": "states_auto_capitalization_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Capitalize at sentence start'->'No automatic capitalization'"
+ },
+ {
+ "test": "states_spacebar_cursor_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Swipe spacebar to move cursor'->'Spacebar cursor control disabled'"
+ },
+ {
+ "test": "states_double_space_period_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Double-space inserts period'->'Double-space inserts space'"
+ },
+ {
+ "test": "states_one_handed_mode_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked false->true; summary 'Enabled'->'Standard full-width keyboard'"
+ },
+ {
+ "test": "states_lang_switch_key_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked false->true; summary 'Enabled'->'Disabled'"
+ },
+ {
+ "test": "states_key_press_highlight_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Visual feedback shown'->'Visual feedback hidden'"
+ },
+ {
+ "test": "states_clipboard_history_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'Clipboard history enabled'->'Clipboard history disabled'"
+ },
+ {
+ "test": "states_switch_thumb_position_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the toggle switch on the right of the 'One-Handed Mode' row. Is its round thumb positioned at the RIGHT end of the track (the ON position), rather than the left?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the toggle switch on the right of the 'One-Handed Mode' row. Is its round thumb positioned at the RIGHT end of the track (the ON position), rather than the left?",
+ "tag": "position"
+ },
+ {
+ "test": "states_language_checkbox_select",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked false->true"
+ },
+ {
+ "test": "states_english_current_layout_indicator",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "checked true; summary 'Current layout'"
+ },
+ {
+ "test": "states_merged_dictionaries_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "checked true->false; summary 'All language dictionaries used for suggestions'->'Only active layout language used for suggestions'"
+ },
+ {
+ "test": "states_english_selected_checkbox_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this language list, the 'English' row is marked as the current layout. Does the checkbox on the 'English' row appear CHECKED / filled (a tick or filled box), while the checkboxes on the other language rows appear empty / unchecked?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: In this language list, the 'English' row is marked as the current layout. Does the checkbox on the 'English' row appear CHECKED / filled (a tick or filled box), while the checkboxes on the other language rows appear empty / unchecked?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_suggestion_count_ctv_checked",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'3' checked=true; '1'/'2' checked=false"
+ },
+ {
+ "test": "states_suggestion_count_ctv_moves",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "'1' checked=true; '3' checked=false after picking 1"
+ },
+ {
+ "test": "states_suggestion_count_dialog_mark_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a single-choice dialog listing options 1, 2 and 3. Is there a selection mark (a filled radio button or a check/tick) shown next to exactly ONE option, indicating the currently selected value?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: This is a single-choice dialog listing options 1, 2 and 3. Is there a selection mark (a filled radio button or a check/tick) shown next to exactly ONE option, indicating the currently selected value?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_theme_selected_checkmark_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a keyboard theme picker showing several theme preview cards. Does the currently-selected theme card at the top have a distinct highlighted/coloured BORDER and a checkmark (tick), which the other theme cards below it do NOT have?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: This is a keyboard theme picker showing several theme preview cards. Does the currently-selected theme card at the top have a distinct highlighted/coloured BORDER and a checkmark (tick), which the other theme cards below it do NOT have?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_theme_color_distinct_vlm",
+ "passed": true,
+ "message": "VLM: Q='Among these keyboard theme preview cards, is there at least one card with a predominantly LIGHT/white keyboard background and at least one card with a predominantly DARK/black keyboard background (i.e. the themes are rendered in clearly different colours)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: Among these keyboard theme preview cards, is there at least one card with a predominantly LIGHT/white keyboard background and at least one card with a predominantly DARK/black keyboard background (i.e. the themes are rendered in clearly different colours)?",
+ "tag": "color"
+ },
+ {
+ "test": "states_main_preview_selected_theme_color_vlm",
+ "passed": true,
+ "message": "VLM: Q='This screen shows a keyboard preview card labelled 'Default'. Is the preview keyboard drawn with a DARK (dark blue / near-black) key background and LIGHT (cream / pale) key letters, matching a dark theme?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: This screen shows a keyboard preview card labelled 'Default'. Is the preview keyboard drawn with a DARK (dark blue / near-black) key background and LIGHT (cream / pale) key letters, matching a dark theme?",
+ "tag": "color"
+ },
+ {
+ "test": "states_persist_swipe_typing",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "false"
+ },
+ {
+ "test": "states_persist_merged_dictionaries",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "false"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/android_structure_eval.json b/android/urikdev-urik/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..bb3607cd4b039f8667817df6efbb46130623b32f
--- /dev/null
+++ b/android/urikdev-urik/tests/android_structure_eval.json
@@ -0,0 +1,211 @@
+{
+ "module": "structure",
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 11,
+ "passed": 11,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.7273,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 11,
+ "liveness": 0,
+ "interactive": 8,
+ "depth_ge1": 8,
+ "depth_ge2": 5,
+ "value": 0,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_s0_surfaces",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_s0_surfaces_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the app logo/icon near the top-center of the screen with a vertical stack of full-width action buttons positioned at the bottom of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the app logo/icon near the top-center of the screen with a vertical stack of full-width action buttons positioned at the bottom of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_gate_preview_card",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_preview_card_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a keyboard preview showing letter keys (like Z X C V B N M) arranged in horizontal rows like a keyboard?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a keyboard preview showing letter keys (like Z X C V B N M) arranged in horizontal rows like a keyboard?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_settings_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this a settings screen showing a vertical list of text rows stacked top to bottom, each row a bold title with a smaller grey subtitle beneath it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is this a settings screen showing a vertical list of text rows stacked top to bottom, each row a bold title with a smaller grey subtitle beneath it?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_settings_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "RecyclerView 0->1 with >=6 preference rows on Settings; launcher buttons collapse; restored to 0 RecyclerView on relaunch"
+ },
+ {
+ "test": "structure_autocorrect_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "AutoCorrect list has >=4 Switch rows and a bottom test_field EditText"
+ },
+ {
+ "test": "structure_autocorrect_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Are there several toggle switches on this screen, each aligned against the right edge of its row?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Are there several toggle switches on this screen, each aligned against the right edge of its row?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_suggestion_dialog_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Suggestion Count dialog adds CheckedTextView 0->3 (+Cancel), restored to 0 on dismiss"
+ },
+ {
+ "test": "structure_features_sheet_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Features bottom sheet adds >=8 TextViews over S0's 2"
+ },
+ {
+ "test": "structure_features_sheet_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a panel showing a vertical stacked list of feature tips, each with a bold title and a description line beneath it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a panel showing a vertical stacked list of feature tips, each with a bold title and a description line beneath it?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_themepicker_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "ThemePicker adds a RecyclerView with >3 theme-card FrameLayouts"
+ },
+ {
+ "test": "structure_themepicker_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this a scrollable vertical list of keyboard-theme preview cards, each card showing a small keyboard rendering?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is this a scrollable vertical list of keyboard-theme preview cards, each card showing a small keyboard rendering?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_layoutmapper_shape",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "LayoutMapper renders >=30 Button keys (number row + QWERTY)"
+ },
+ {
+ "test": "structure_layoutmapper_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a full QWERTY keyboard rendered as multiple horizontal rows of square keys (a number row on top, then letter rows)?' A=YES expect=YES",
+ "depth": 3,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is a full QWERTY keyboard rendered as multiple horizontal rows of square keys (a number row on top, then letter rows)?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_typing_seekbar_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Typing Behavior has >=4 Switch rows and a SeekBar widget"
+ },
+ {
+ "test": "structure_languages_shape",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Languages fragment shows >=5 CheckBox children"
+ },
+ {
+ "test": "structure_languages_shape_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a vertical scrollable list of language rows, each row having a checkbox?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this screen show a vertical scrollable list of language rows, each row having a checkbox?",
+ "tag": "layout"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/android_testgen_kit.py b/android/urikdev-urik/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/urikdev-urik/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/urikdev-urik/tests/android_text_eval.json b/android/urikdev-urik/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..19c32b61a2ec3602460a8661ca90b012e11e7daa
--- /dev/null
+++ b/android/urikdev-urik/tests/android_text_eval.json
@@ -0,0 +1,232 @@
+{
+ "module": "text",
+ "total": 22,
+ "passed": 22,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 20,
+ "passed": 20,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 2,
+ "passed": 2,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.1,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 0,
+ "liveness": 0,
+ "interactive": 22,
+ "depth_ge1": 22,
+ "depth_ge2": 11,
+ "value": 21,
+ "vlm_fine": 2
+ },
+ "results": [
+ {
+ "test": "text_settings_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Keyboard Settings"
+ },
+ {
+ "test": "text_about_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "About"
+ },
+ {
+ "test": "text_about_block_substrings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "About block contains 'Copyright © 2025 Urik Development' + 'License: GNU GPL v3.0' + 'Source Code'"
+ },
+ {
+ "test": "text_about_block_rendered_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is an app's About screen. Is a block of body text rendered in the content area below the top 'About' title bar, containing lines that start with 'Version', 'Copyright' and 'License'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: This is an app's About screen. Is a block of body text rendered in the content area below the top 'About' title bar, containing lines that start with 'Version', 'Copyright' and 'License'?",
+ "tag": "position"
+ },
+ {
+ "test": "text_about_copyright_rendered_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this About screen, is the line reading 'Copyright © 2025 Urik Development' displayed as light/pale-coloured text against a dark background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "VLM YES: On this About screen, is the line reading 'Copyright © 2025 Urik Development' displayed as light/pale-coloured text against a dark background?",
+ "tag": "color"
+ },
+ {
+ "test": "text_features_sheet_tips",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Features sheet shows 'Clipboard Manager' + 'Cursor Control' + 'Quick Delete'"
+ },
+ {
+ "test": "text_features_sheet_learning_words",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "tip 'Learning Words' + its description"
+ },
+ {
+ "test": "text_themepicker_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Keyboard Theme"
+ },
+ {
+ "test": "text_themepicker_theme_content_desc",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "content-desc 'Default theme, currently selected' + 'Light theme'"
+ },
+ {
+ "test": "text_themepicker_favorite_content_desc",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "content-desc 'Add Default to favorites'"
+ },
+ {
+ "test": "text_settings_row_titles",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "all 8 row titles incl. 'Layout & Input' and 'Privacy & Data'"
+ },
+ {
+ "test": "text_appearance_keysize_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Medium"
+ },
+ {
+ "test": "text_appearance_theme_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Default"
+ },
+ {
+ "test": "text_typing_cursor_speed_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Medium"
+ },
+ {
+ "test": "text_typing_longpress_punct_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Period Key"
+ },
+ {
+ "test": "text_layout_keyboard_layout_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Default (Language Layout)"
+ },
+ {
+ "test": "text_layout_onehanded_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Standard full-width keyboard"
+ },
+ {
+ "test": "text_autocorrect_suggestion_count_summary",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "3"
+ },
+ {
+ "test": "text_autocorrect_spellcheck_summary_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "summary 'Spell check enabled' -> 'Spell check disabled'"
+ },
+ {
+ "test": "text_oss_licenses_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Open Source Licenses"
+ },
+ {
+ "test": "text_dictionary_data_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Dictionary Data"
+ },
+ {
+ "test": "text_customize_keys_toolbar_title",
+ "passed": true,
+ "message": "",
+ "depth": 3,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Customize Keys"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/tests/conftest.py b/android/urikdev-urik/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/urikdev-urik/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/urikdev-urik/tests/requirements.txt b/android/urikdev-urik/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/urikdev-urik/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/urikdev-urik/tests/test_android_computation.py b/android/urikdev-urik/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..84e4c03cca75193649ef0dc15629ad3353ace676
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_computation.py
@@ -0,0 +1,595 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — Urik Keyboard (com.urik.keyboard).
+
+This app is a soft-keyboard + settings app: there is NO calculator. Its
+deterministic input -> output surfaces are:
+ 1. ListPreference dialogs: pick an option -> the row's `summary` becomes EXACTLY
+ that option's label (Suggestion Count, Key Size, Key Label Size, Cursor Speed,
+ Space Bar Size, Keyboard Layout, Long Press Punctuation, Long Press Duration).
+ 2. Vibration Strength SeekBar: tap a position on the bar -> the `seekbar_value`
+ label shows the corresponding number (observed deterministic: far-left -> "6",
+ far-right -> "250", centre -> "128").
+ 3. test_field EditText: type a string -> the field's `text` equals exactly that.
+
+Every expected value below was REPRODUCED LIVE on the original app (see _explore*).
+All tests are jump_kind="value" with a specific `expect`, depth=2 (Settings ->
+fragment -> [dialog]), and restore any mutated preference to keep the baseline clean.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403
+
+
+# ── local helpers (READ-ONLY kit; these only orchestrate kit calls) ─────────────
+
+def summary_for(nodes, title_text):
+ """The `summary` TextView that sits directly under the row whose title == title_text.
+
+ Preference rows are (title TextView / summary TextView) pairs; we pick the
+ summary whose center-y is closest to (and not far above) the located title.
+ Returns (title_node, summary_node) — either may be None.
+ """
+ tn = find_node(nodes, text=title_text)
+ if not tn or "_center" not in tn:
+ return None, None
+ ty = tn["_center"][1]
+ cands = [n for n in nodes
+ if n.get("resource-id", "").endswith("summary") and "_center" in n]
+ below = [n for n in cands if n["_center"][1] >= ty - 5]
+ if not below:
+ return tn, None
+ best = min(below, key=lambda n: abs(n["_center"][1] - ty))
+ return tn, best
+
+
+def summary_text(nodes, title_text):
+ _tn, sm = summary_for(nodes, title_text)
+ return (sm.get("text", "").strip() if sm else "")
+
+
+def open_settings():
+ """restart_app() -> tap 'Open Settings' -> return the settings-list nodes."""
+ restart_app()
+ wait_for_foreground()
+ tap_text(ui(), "Open Settings")
+
+
+def and_enter_fragment(row_text):
+ """Open a settings fragment by its row title (exact text, then ci fallback).
+
+ Names in the and_enter_* family, so it backs the depth>=1 declaration.
+ Returns (ok, note).
+ """
+ nodes = ui()
+ n = find_node(nodes, text=row_text) or find_node_ci(nodes, row_text)
+ if not n:
+ return False, f"setup_failed: settings row {row_text!r} not found"
+ if not tap_node(n):
+ return False, f"setup_failed: settings row {row_text!r} not tappable"
+ and_enter(row_text)
+ return True, ""
+
+
+def and_enter_layout_fragment():
+ """Open the 'Layout & Input' fragment. Its row text is the LITERAL
+ 'Layout & Input' (uiautomator does not unescape &); fall back to the
+ unique summary 'Number row, space bar size'."""
+ nodes = ui()
+ row = (find_node(nodes, text="Layout & Input")
+ or find_node(nodes, text="Number row, space bar size"))
+ if not row:
+ return False, "setup_failed: 'Layout & Input' row not found"
+ if not tap_node(row):
+ return False, "setup_failed: 'Layout & Input' row not tappable"
+ and_enter("Layout & Input")
+ return True, ""
+
+
+def and_enter_dialog(pref_title, scroll=False):
+ """Scroll (optional) to a ListPreference row, tap it to open its dialog.
+
+ Counts as one more surface (the dialog). Returns (ok, note).
+ """
+ if scroll and not find_node(ui(), text=pref_title):
+ scroll_into_view(pref_title)
+ pn = find_node(ui(), text=pref_title)
+ if not pn:
+ return False, f"setup_failed: preference {pref_title!r} not found"
+ before = and_showing()
+ if not tap_node(pn):
+ return False, f"setup_failed: preference {pref_title!r} not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, f"behavior_wrong: no dialog appeared for {pref_title!r}"
+ and_enter(f"{pref_title} dialog")
+ return True, ""
+
+
+def pick_option(pick):
+ """Tap a dialog option (CheckedTextView) by its exact label."""
+ return tap_text(ui(), pick)
+
+
+def restore_listpref(pref_title, restore_label, scroll=False):
+ """Best-effort restore of a ListPreference to its original label. Never fails
+ the test — restoration is cleanup, not the assertion."""
+ try:
+ if scroll and not find_node(ui(), text=pref_title):
+ scroll_into_view(pref_title)
+ pn = find_node(ui(), text=pref_title)
+ if pn and tap_node(pn):
+ tap_text(ui(), restore_label)
+ except Exception:
+ pass
+
+
+def seek_value(nodes):
+ n = node_by_id(nodes, "seekbar_value")
+ return (n.get("text", "").strip() if n else "")
+
+
+def tap_seekbar_fraction(frac):
+ """Tap the Vibration Strength SeekBar at a horizontal fraction of its width.
+
+ Coordinate is DERIVED from the seekbar node's own bounds (never a literal).
+ Returns the new seekbar_value text, or "" if the bar was not found.
+ """
+ bar = node_by_id(ui(), "seekbar")
+ if not bar or "_bounds" not in bar:
+ return "", False
+ x1, y1, x2, y2 = bar["_bounds"]
+ tx = int(x1 + (x2 - x1) * frac)
+ ty = (y1 + y2) // 2
+ tap(tx, ty)
+ return seek_value(ui()), True
+
+
+def test_field(nodes):
+ """The fragment's bottom 'Test changes' EditText (id test_field)."""
+ n = node_by_id(nodes, "test_field")
+ if n:
+ return n
+ ets = find_by_class(nodes, "EditText")
+ return ets[-1] if ets else None
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) ListPreference: pick option -> summary becomes EXACTLY that label
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_suggestion_count_2", "computation_suggestion_count_dialog_vlm"))
+def test_suggestion_count_2():
+ """Suggestion Count: pick '2' in the dialog -> row summary becomes '2'
+ (observed). Positive/negative: '2' is ABSENT as the summary before, PRESENT
+ after. VLM: the dialog is a rendered radio list. Restore to '3' at the end."""
+ name = "computation_suggestion_count_2"
+ exp = "2"
+ open_settings()
+ ok, note = and_enter_fragment("Auto-Correct Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary '2'")
+ return
+ before = summary_text(ui(), "Suggestion Count") # observed "3"
+ okd, noted = and_enter_dialog("Suggestion Count")
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary '2'")
+ return
+ # VLM while the dialog is up: a rendered radio/checkmark option list.
+ vlm_assert("computation_suggestion_count_dialog",
+ "Is a dialog shown containing a vertical list of selectable options "
+ "each preceded by a round radio-button circle (one filled/selected)?",
+ RESULTS_DIR, tag="shape")
+ pick_option("2")
+ got = summary_text(ui(), "Suggestion Count")
+ ok = (got == exp) and (before != exp)
+ record(name, ok,
+ "" if ok else f"behavior_wrong: summary {got!r} after picking '2' "
+ f"(before {before!r}), expected '2'",
+ depth=2, jump_kind="value", expect="Suggestion Count summary == '2'")
+ restore_listpref("Suggestion Count", "3")
+
+
+@and_test(expects=("computation_suggestion_count_1",))
+def test_suggestion_count_1():
+ """Suggestion Count: pick '1' -> summary becomes '1' (observed). Restore '3'."""
+ name = "computation_suggestion_count_1"
+ open_settings()
+ ok, note = and_enter_fragment("Auto-Correct Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary '1'")
+ return
+ before = summary_text(ui(), "Suggestion Count")
+ okd, noted = and_enter_dialog("Suggestion Count")
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary '1'")
+ return
+ pick_option("1")
+ got = summary_text(ui(), "Suggestion Count")
+ ok = (got == "1") and (before != "1")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: summary {got!r} after picking '1' "
+ f"(before {before!r}), expected '1'",
+ depth=2, jump_kind="value", expect="Suggestion Count summary == '1'")
+ restore_listpref("Suggestion Count", "3")
+
+
+@and_test(expects=("computation_key_size_large",))
+def test_key_size_large():
+ """Key Size: options Small/Medium/Large/Extra Large (Medium selected). Pick
+ 'Large' -> summary becomes 'Large' (observed). Restore 'Medium'."""
+ name = "computation_key_size_large"
+ open_settings()
+ ok, note = and_enter_fragment("Appearance")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Large'")
+ return
+ before = summary_text(ui(), "Key Size") # observed "Medium"
+ okd, noted = and_enter_dialog("Key Size")
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Large'")
+ return
+ pick_option("Large")
+ got = summary_text(ui(), "Key Size")
+ ok = (got == "Large") and (before != "Large")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Key Size summary {got!r} after picking "
+ f"'Large' (before {before!r}), expected 'Large'",
+ depth=2, jump_kind="value", expect="Key Size summary == 'Large'")
+ restore_listpref("Key Size", "Medium")
+
+
+@and_test(expects=("computation_key_label_size_large",))
+def test_key_label_size_large():
+ """Key Label Size: options Small/Medium/Large (Medium selected). Pick 'Large'
+ -> summary becomes 'Large' (observed). Restore 'Medium'."""
+ name = "computation_key_label_size_large"
+ open_settings()
+ ok, note = and_enter_fragment("Appearance")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Large'")
+ return
+ before = summary_text(ui(), "Key Label Size")
+ okd, noted = and_enter_dialog("Key Label Size")
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Large'")
+ return
+ pick_option("Large")
+ got = summary_text(ui(), "Key Label Size")
+ ok = (got == "Large") and (before != "Large")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Key Label Size summary {got!r} after "
+ f"picking 'Large' (before {before!r}), expected 'Large'",
+ depth=2, jump_kind="value", expect="Key Label Size summary == 'Large'")
+ restore_listpref("Key Label Size", "Medium")
+
+
+@and_test(expects=("computation_cursor_speed_fast",))
+def test_cursor_speed_fast():
+ """Cursor Speed: options Slow/Medium/Fast/Very Fast (Medium selected). Pick
+ 'Fast' -> summary becomes 'Fast' (observed). Row needs scrolling. Restore 'Medium'."""
+ name = "computation_cursor_speed_fast"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Fast'")
+ return
+ scroll_into_view("Cursor Speed")
+ before = summary_text(ui(), "Cursor Speed")
+ okd, noted = and_enter_dialog("Cursor Speed", scroll=True)
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Fast'")
+ return
+ pick_option("Fast")
+ got = summary_text(ui(), "Cursor Speed")
+ ok = (got == "Fast") and (before != "Fast")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Cursor Speed summary {got!r} after "
+ f"picking 'Fast' (before {before!r}), expected 'Fast'",
+ depth=2, jump_kind="value", expect="Cursor Speed summary == 'Fast'")
+ restore_listpref("Cursor Speed", "Medium", scroll=True)
+
+
+@and_test(expects=("computation_long_press_punctuation_spacebar",))
+def test_long_press_punctuation_spacebar():
+ """Long Press Punctuation: options Off/Spacebar/Period Key (Period Key selected).
+ Pick 'Spacebar' -> summary becomes 'Spacebar' (observed). Restore 'Period Key'."""
+ name = "computation_long_press_punctuation_spacebar"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Spacebar'")
+ return
+ scroll_into_view("Long Press Punctuation")
+ before = summary_text(ui(), "Long Press Punctuation") # observed "Period Key"
+ okd, noted = and_enter_dialog("Long Press Punctuation", scroll=True)
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Spacebar'")
+ return
+ pick_option("Spacebar")
+ got = summary_text(ui(), "Long Press Punctuation")
+ ok = (got == "Spacebar") and (before != "Spacebar")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Long Press Punctuation summary {got!r} "
+ f"after picking 'Spacebar' (before {before!r}), expected 'Spacebar'",
+ depth=2, jump_kind="value", expect="Long Press Punctuation summary == 'Spacebar'")
+ restore_listpref("Long Press Punctuation", "Period Key", scroll=True)
+
+
+@and_test(expects=("computation_long_press_duration_long",))
+def test_long_press_duration_long():
+ """Long Press Duration: options Short/Medium/Long (Medium selected). Pick
+ 'Long' -> summary becomes 'Long' (observed). Restore 'Medium'."""
+ name = "computation_long_press_duration_long"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Long'")
+ return
+ scroll_into_view("Long Press Duration")
+ before = summary_text(ui(), "Long Press Duration")
+ okd, noted = and_enter_dialog("Long Press Duration", scroll=True)
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Long'")
+ return
+ pick_option("Long")
+ got = summary_text(ui(), "Long Press Duration")
+ ok = (got == "Long") and (before != "Long")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Long Press Duration summary {got!r} after "
+ f"picking 'Long' (before {before!r}), expected 'Long'",
+ depth=2, jump_kind="value", expect="Long Press Duration summary == 'Long'")
+ restore_listpref("Long Press Duration", "Medium", scroll=True)
+
+
+@and_test(expects=("computation_space_bar_size_wide",))
+def test_space_bar_size_wide():
+ """Space Bar Size (Layout & Input): options Compact/Standard/Wide (Standard
+ selected). Pick 'Wide' -> summary becomes 'Wide' (observed). Restore 'Standard'."""
+ name = "computation_space_bar_size_wide"
+ open_settings()
+ ok, note = and_enter_layout_fragment()
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'Wide'")
+ return
+ if not find_node(ui(), text="Space Bar Size"):
+ scroll_into_view("Space Bar Size")
+ before = summary_text(ui(), "Space Bar Size") # observed "Standard"
+ okd, noted = and_enter_dialog("Space Bar Size", scroll=True)
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'Wide'")
+ return
+ pick_option("Wide")
+ got = summary_text(ui(), "Space Bar Size")
+ ok = (got == "Wide") and (before != "Wide")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Space Bar Size summary {got!r} after "
+ f"picking 'Wide' (before {before!r}), expected 'Wide'",
+ depth=2, jump_kind="value", expect="Space Bar Size summary == 'Wide'")
+ restore_listpref("Space Bar Size", "Standard", scroll=True)
+
+
+@and_test(expects=("computation_keyboard_layout_qwertz", "computation_keyboard_layout_dialog_vlm"))
+def test_keyboard_layout_qwertz():
+ """Keyboard Layout (Layout & Input): default summary 'Default (Language Layout)'.
+ Options include QWERTY/AZERTY/QWERTZ/Dvorak/... Pick 'QWERTZ' -> summary becomes
+ EXACTLY 'QWERTZ' (observed verbatim). VLM: the dialog is a rendered option list.
+ Restore to 'Default (Language Layout)'."""
+ name = "computation_keyboard_layout_qwertz"
+ open_settings()
+ ok, note = and_enter_layout_fragment()
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="summary 'QWERTZ'")
+ return
+ before = summary_text(ui(), "Keyboard Layout") # observed "Default (Language Layout)"
+ okd, noted = and_enter_dialog("Keyboard Layout")
+ if not okd:
+ record(name, False, noted, depth=2, jump_kind="value", expect="summary 'QWERTZ'")
+ return
+ vlm_assert("computation_keyboard_layout_dialog",
+ "Is a dialog shown listing multiple keyboard-layout choices (such as "
+ "QWERTY / QWERTZ / AZERTY) as a vertical list of selectable rows?",
+ RESULTS_DIR, tag="shape")
+ pick_option("QWERTZ")
+ got = summary_text(ui(), "Keyboard Layout")
+ ok = (got == "QWERTZ") and (before != "QWERTZ")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: Keyboard Layout summary {got!r} after "
+ f"picking 'QWERTZ' (before {before!r}), expected 'QWERTZ'",
+ depth=2, jump_kind="value", expect="Keyboard Layout summary == 'QWERTZ'")
+ restore_listpref("Keyboard Layout", "Default (Language Layout)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Vibration Strength SeekBar: tap a position -> numeric label (deterministic)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_vibration_seekbar_min",
+ "computation_vibration_seekbar_min_vlm"))
+def test_vibration_seekbar_min():
+ """Vibration Strength SeekBar (min 1, max 255, starts at 128). Tapping the far
+ LEFT (2% of the bar width) deterministically sets seekbar_value to '6'
+ (reproduced 3x). Positive/negative: value is '128' before, '6' after. VLM: the
+ thumb visibly sits at the left end. Restore toward 128 (centre tap -> 128)."""
+ name = "computation_vibration_seekbar_min"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="seekbar_value '6'")
+ return
+ if not scroll_into_view("Vibration Strength"):
+ record(name, False, "setup_failed: 'Vibration Strength' not reached",
+ depth=2, jump_kind="value", expect="seekbar_value '6'")
+ return
+ and_enter("Vibration Strength seekbar")
+ before = seek_value(ui()) # observed "128"
+ got, found = tap_seekbar_fraction(0.02)
+ if not found:
+ record(name, False, "setup_failed: seekbar node not found",
+ depth=2, jump_kind="value", expect="seekbar_value '6'")
+ return
+ # VLM: thumb pushed to the far-left after the tap.
+ vlm_assert("computation_vibration_seekbar_min",
+ "Is the slider (SeekBar) thumb positioned at the far-LEFT end of the "
+ "Vibration Strength track, near the start of the bar?",
+ RESULTS_DIR, tag="position")
+ ok = (got == "6") and (before == "128")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: seekbar_value {got!r} after far-left tap "
+ f"(before {before!r}), expected '6'",
+ depth=2, jump_kind="value", expect="seekbar_value == '6' (far-left tap)")
+ tap_seekbar_fraction(0.5) # restore toward centre (-> 128)
+
+
+@and_test(expects=("computation_vibration_seekbar_max",
+ "computation_vibration_seekbar_max_vlm"))
+def test_vibration_seekbar_max():
+ """Tapping the far RIGHT (98% of the bar width) deterministically sets
+ seekbar_value to '250' (reproduced 3x). Positive/negative: '250' absent before,
+ present after. VLM: the thumb visibly sits at the right end. Restore toward 128."""
+ name = "computation_vibration_seekbar_max"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="seekbar_value '250'")
+ return
+ if not scroll_into_view("Vibration Strength"):
+ record(name, False, "setup_failed: 'Vibration Strength' not reached",
+ depth=2, jump_kind="value", expect="seekbar_value '250'")
+ return
+ and_enter("Vibration Strength seekbar")
+ before = seek_value(ui())
+ got, found = tap_seekbar_fraction(0.98)
+ if not found:
+ record(name, False, "setup_failed: seekbar node not found",
+ depth=2, jump_kind="value", expect="seekbar_value '250'")
+ return
+ vlm_assert("computation_vibration_seekbar_max",
+ "Is the slider (SeekBar) thumb positioned at the far-RIGHT end of the "
+ "Vibration Strength track, near the end of the bar?",
+ RESULTS_DIR, tag="position")
+ ok = (got == "250") and (before != "250")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: seekbar_value {got!r} after far-right tap "
+ f"(before {before!r}), expected '250'",
+ depth=2, jump_kind="value", expect="seekbar_value == '250' (far-right tap)")
+ tap_seekbar_fraction(0.5) # restore toward centre (-> 128)
+
+
+@and_test(expects=("computation_vibration_seekbar_center",))
+def test_vibration_seekbar_center():
+ """Tapping the CENTRE (50% of the bar width) deterministically sets
+ seekbar_value to '128' (reproduced 3x; also the default). Verify by first
+ driving it to the far-left ('6') then a centre tap returns it to '128' —
+ so the assertion is a specific set->read, not merely 'unchanged'."""
+ name = "computation_vibration_seekbar_center"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect="seekbar_value '128'")
+ return
+ if not scroll_into_view("Vibration Strength"):
+ record(name, False, "setup_failed: 'Vibration Strength' not reached",
+ depth=2, jump_kind="value", expect="seekbar_value '128'")
+ return
+ and_enter("Vibration Strength seekbar")
+ low, found = tap_seekbar_fraction(0.02) # drive down to '6' first
+ if not found:
+ record(name, False, "setup_failed: seekbar node not found",
+ depth=2, jump_kind="value", expect="seekbar_value '128'")
+ return
+ got, _ = tap_seekbar_fraction(0.5) # centre -> back to '128'
+ ok = (low == "6") and (got == "128")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: centre tap gave {got!r} (from {low!r}), "
+ f"expected '128'",
+ depth=2, jump_kind="value", expect="seekbar_value == '128' (centre tap)")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) test_field EditText echo: type a string -> field text equals it exactly
+# (different fragments from the interaction lane; distinct markers)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("computation_test_field_echo_typing",
+ "computation_test_field_echo_typing_vlm"))
+def test_test_field_echo_typing():
+ """Typing Behavior fragment's bottom test_field: type 'kbdcompute7' -> the
+ field's text equals exactly 'kbdcompute7' (observed). VLM: the typed text is
+ rendered in the field."""
+ name = "computation_test_field_echo_typing"
+ marker = "kbdcompute7"
+ open_settings()
+ ok, note = and_enter_fragment("Typing Behavior Settings")
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ tf = test_field(ui())
+ if not tf:
+ record(name, False, "feature_missing: no test_field EditText",
+ depth=2, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ if not type_text(tf, marker):
+ record(name, False, "setup_failed: could not type into test_field",
+ depth=2, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ got = (node_by_id(ui(), "test_field") or {}).get("text", "")
+ ok = got.strip() == marker
+ # VLM: the field visibly renders the typed characters.
+ vlm_assert("computation_test_field_echo_typing",
+ f"Does the 'Test changes' input field at the bottom visibly display "
+ f"the typed text '{marker}'?",
+ RESULTS_DIR, tag="content")
+ record(name, ok,
+ "" if ok else f"behavior_wrong: test_field held {got!r}, expected {marker!r}",
+ depth=2, jump_kind="value", expect=f"test_field text == {marker!r}")
+
+
+@and_test(expects=("computation_test_field_echo_layout",))
+def test_test_field_echo_layout():
+ """Layout & Input fragment's bottom test_field: type 'kbdlayout9' -> the
+ field's text equals exactly 'kbdlayout9' (observed)."""
+ name = "computation_test_field_echo_layout"
+ marker = "kbdlayout9"
+ open_settings()
+ ok, note = and_enter_layout_fragment()
+ if not ok:
+ record(name, False, note, depth=1, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ tf = test_field(ui())
+ if not tf:
+ record(name, False, "feature_missing: no test_field EditText",
+ depth=2, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ if not type_text(tf, marker):
+ record(name, False, "setup_failed: could not type into test_field",
+ depth=2, jump_kind="value", expect=f"field == {marker!r}")
+ return
+ got = (node_by_id(ui(), "test_field") or {}).get("text", "")
+ ok = got.strip() == marker
+ record(name, ok,
+ "" if ok else f"behavior_wrong: test_field held {got!r}, expected {marker!r}",
+ depth=2, jump_kind="value", expect=f"test_field text == {marker!r}")
+
+
+TESTS = [
+ # ListPreference pick -> summary
+ test_suggestion_count_2,
+ test_suggestion_count_1,
+ test_key_size_large,
+ test_key_label_size_large,
+ test_cursor_speed_fast,
+ test_long_press_punctuation_spacebar,
+ test_long_press_duration_long,
+ test_space_bar_size_wide,
+ test_keyboard_layout_qwertz,
+ # SeekBar set -> value
+ test_vibration_seekbar_min,
+ test_vibration_seekbar_max,
+ test_vibration_seekbar_center,
+ # test_field echo
+ test_test_field_echo_typing,
+ test_test_field_echo_layout,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/urikdev-urik/tests/test_android_interaction.py b/android/urikdev-urik/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c002c56df46b664bef0074da1622fea6e43531d
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_interaction.py
@@ -0,0 +1,799 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — Urik Keyboard (com.urik.keyboard).
+
+EFFECT-BY-CONSEQUENCE on user DATA/state: theme selection & favorites (CRUD-ish,
+persist across activity navigation AND process death), LayoutMapper custom-char
+multi-step (navigate depth 3 -> open sheet -> type -> save), multi-step settings
+sequences (Spell Check disables two dependent rows), settings persistence across
+process death (Haptic / Key Press Highlight / Suggestion Count), and test_field
+input echo.
+
+Every test restarts the app and navigates FORWARD (nested back() chains are flaky
+per recon). Every mutated piece of state is RESTORED so the baseline stays clean.
+
+ python3 test_android_interaction.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── shared helpers (plain; the and_enter/and_reach NAMES back declared depth) ────
+
+def switch_for(nodes, title):
+ """The Switch widget whose center-y is closest to the row `title` TextView.
+ All switches share resource-id .../switchWidget, so id alone cannot pick one."""
+ tn = find_node(nodes, text=title)
+ if not tn:
+ return None
+ ty = tn["_center"][1]
+ cands = [n for n in nodes
+ if "Switch" in n.get("class", "")
+ and n.get("resource-id", "").endswith("switchWidget")]
+ return min(cands, key=lambda n: abs(n["_center"][1] - ty)) if cands else None
+
+
+def summary_near(nodes, title, ymax=90):
+ """The .../summary TextView vertically adjacent to the row `title`."""
+ tn = find_node(nodes, text=title)
+ if not tn:
+ return None
+ ty = tn["_center"][1]
+ best = None
+ for n in nodes:
+ if n.get("resource-id", "").endswith("summary"):
+ cy = n.get("_center", (0, 10 ** 9))[1]
+ if abs(cy - ty) < ymax:
+ best = n
+ return best
+
+
+def main_theme_label(nodes):
+ """The theme-name TextView under the preview card on the launcher (no id).
+ It sits below the rendered keyboard, above the buttons."""
+ for n in nodes:
+ if (n.get("class", "").endswith("TextView")
+ and 1100 < n.get("_center", (0, 0))[1] < 1400
+ and n.get("text", "")):
+ return n
+ return None
+
+
+# ── surface-entry helpers (named and_enter_* / and_reach_* to back depth) ────────
+
+def and_enter_settings():
+ """Launcher -> SettingsActivity (MainSettingsFragment). depth +1."""
+ nodes = ui()
+ trig = find_node_ci(nodes, "Open Settings")
+ if not trig or not tap_node(trig):
+ return None
+ and_enter("settings")
+ return ui()
+
+
+def and_enter_fragment(title):
+ """SettingsActivity -> a preference sub-fragment by row title. depth +1.
+ Assumes the settings list is already showing."""
+ nodes = ui()
+ row = find_node(nodes, text=title) or scroll_into_view(title)
+ if not row or not tap_node(row):
+ return None
+ and_enter(title)
+ return ui()
+
+
+def and_reach_frag_from_launcher(title):
+ """Launcher -> Settings -> . Returns the fragment's node list or None.
+ Two surfaces crossed (depth ends at 2)."""
+ restart_app()
+ wait_for_foreground()
+ if and_enter_settings() is None:
+ return None
+ return and_enter_fragment(title)
+
+
+def and_enter_theme_picker_from_main():
+ """Launcher -> ThemePickerActivity by tapping the theme-name label. depth +1."""
+ restart_app()
+ wait_for_foreground()
+ label = main_theme_label(ui())
+ if not label or not tap_node(label):
+ return None
+ and_enter("theme_picker")
+ settle("tap")
+ return ui()
+
+
+# ── ThemePicker robustness: the RecyclerView reorders (favorites float up) and
+# recycles children, so always scroll to the top then scan DOWN by text. ──────
+
+def _scroll_picker_top(times=5):
+ for _ in range(times):
+ scroll_up(0.8)
+
+
+def find_theme_card(name, max_swipes=8):
+ """The FrameLayout card for `name` (content-desc " theme"[, currently
+ selected]), located by scrolling from the top."""
+ _scroll_picker_top()
+ for _ in range(max_swipes):
+ nodes = ui()
+ for n in nodes:
+ cd = n.get("content-desc", "")
+ if cd == f"{name} theme" or cd.startswith(f"{name} theme,"):
+ return n, cd
+ scroll_down(0.5)
+ return None, None
+
+
+def find_fav_control(name, max_swipes=8):
+ """The favorite ImageView for `name`, whose content-desc is either
+ 'Add to favorites' or 'Remove from favorites'. Scrolls from
+ the top so a just-favorited (floated-up) row is still found."""
+ _scroll_picker_top()
+ want = (f"Add {name} to favorites", f"Remove {name} from favorites")
+ for _ in range(max_swipes):
+ nodes = ui()
+ for n in nodes:
+ if n.get("content-desc", "") in want:
+ return n, n.get("content-desc", "")
+ scroll_down(0.5)
+ return None, None
+
+
+def select_theme_card(name):
+ """Tap the theme card if it is not already selected. Returns the resulting
+ content-desc (contains 'currently selected' when applied) or None."""
+ card, cd = find_theme_card(name)
+ if not card:
+ return None
+ if "currently selected" not in (cd or ""):
+ tap_node(card)
+ settle("tap")
+ _c, cd2 = find_theme_card(name)
+ return cd2
+
+
+def restore_default_theme():
+ """Set the theme back to Default so the suite leaves a clean baseline."""
+ if and_enter_theme_picker_from_main() is None:
+ return
+ select_theme_card("Default")
+
+
+def unfavorite(name):
+ """Ensure `name` is NOT favorited (best-effort cleanup)."""
+ n, cd = find_fav_control(name)
+ if n and cd and cd.startswith("Remove"):
+ tap_node(n)
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# THEMES — selection & favorites: persist across navigation and process death
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_theme_selection_persists_to_main",
+ "interaction_theme_selection_persists_to_main_vlm"))
+def test_theme_selection_persists_to_main():
+ """Select the Light theme in the picker, return to the launcher, and read the
+ NEW theme name off the main-screen label — a consequence that crossed two
+ surfaces (picker -> launcher). Then screenshot the recoloured preview."""
+ NAME = "interaction_theme_selection_persists_to_main"
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False,
+ "setup_failed: could not open ThemePicker from the launcher label",
+ depth=1, jump_kind="transition", expect="main label 'Light'")
+ vlm_assert(NAME, "Does this screen show a keyboard theme picker with "
+ "multiple theme preview cards?", expect="YES",
+ depth=1, jump_kind="transition", tag="layout")
+ return
+ cd = select_theme_card("Light")
+ applied = bool(cd and "currently selected" in cd)
+ # cross back to the launcher (theme is persisted, not on the back stack)
+ restart_app()
+ wait_for_foreground()
+ label = main_theme_label(ui())
+ text_after = label.get("text") if label else None
+ ok = applied and text_after == "Light"
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: main label was {text_after!r}, "
+ f"expected 'Light' after selecting the Light theme",
+ depth=2, jump_kind="transition", expect="main label 'Light'")
+ # VLM: the main-screen preview keyboard should now render in LIGHT colours
+ # (white/pale keys) instead of the dark Default palette.
+ vlm_assert(NAME,
+ "The keyboard preview card near the centre of this screen: are its "
+ "keys drawn on a predominantly WHITE / very light background "
+ "(a light colour theme), rather than dark?",
+ expect="YES", depth=2, jump_kind="transition", tag="color")
+ restore_default_theme()
+
+
+@and_test(expects=("interaction_theme_selection_survives_restart",))
+def test_theme_selection_survives_restart():
+ """Select Abyss, kill the process, relaunch, and confirm the launcher label
+ still reads Abyss — an in-memory-only recreation cannot pass this."""
+ NAME = "interaction_theme_selection_survives_restart"
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False,
+ "setup_failed: could not open ThemePicker from the launcher label",
+ depth=1, jump_kind="transition", expect="main label 'Abyss'")
+ return
+ cd = select_theme_card("Abyss")
+ applied = bool(cd and "currently selected" in cd)
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ label = main_theme_label(ui())
+ text_after = label.get("text") if label else None
+ ok = applied and text_after == "Abyss"
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: main label was {text_after!r} after "
+ f"process death, expected persisted 'Abyss'",
+ depth=1, jump_kind="transition", expect="main label 'Abyss' after relaunch")
+ restore_default_theme()
+
+
+@and_test(expects=("interaction_theme_favorite_persists",
+ "interaction_theme_favorite_persists_vlm"))
+def test_theme_favorite_persists():
+ """Favorite the Crimson theme: its heart control flips Add->Remove, and the
+ favorite survives a process restart (re-found after the list reorders)."""
+ NAME = "interaction_theme_favorite_persists"
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False, "setup_failed: could not open ThemePicker",
+ depth=1, jump_kind="transition",
+ expect="Remove Crimson from favorites")
+ vlm_assert(NAME, "Is a favorite (heart) icon shown filled/solid on one of "
+ "the theme cards?", expect="YES",
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ n0, cd0 = find_fav_control("Crimson")
+ absent_before = cd0 == "Add Crimson to favorites"
+ if n0 is None:
+ record(NAME, False, "feature_missing: no favorite control on Crimson card",
+ depth=1, jump_kind="transition",
+ expect="Remove Crimson from favorites")
+ vlm_assert(NAME, "Is a favorite (heart) icon shown on the Crimson theme "
+ "card, drawn as a filled/solid heart?", expect="YES",
+ depth=1, jump_kind="transition", tag="shape")
+ return
+ tap_node(n0)
+ settle("tap")
+ _n1, cd1 = find_fav_control("Crimson")
+ flipped = cd1 == "Remove Crimson from favorites"
+ # persistence across process death
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False, "setup_failed: could not reopen ThemePicker after restart",
+ depth=1, jump_kind="transition",
+ expect="Remove Crimson from favorites")
+ else:
+ _n2, cd2 = find_fav_control("Crimson")
+ persisted = cd2 == "Remove Crimson from favorites"
+ ok = absent_before and flipped and persisted
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: favorite flip/persist failed "
+ f"(before={cd0!r} after={cd1!r} restart={cd2!r})",
+ depth=1, jump_kind="transition",
+ expect="Remove Crimson from favorites after relaunch")
+ # VLM: the favorited Crimson card should show a FILLED heart
+ find_fav_control("Crimson") # scroll it into view for the screenshot
+ vlm_assert(NAME,
+ "On this theme list, is at least one theme card's favorite heart "
+ "icon drawn as a FILLED / solid heart (as opposed to an empty "
+ "outline)?",
+ expect="YES", depth=1, jump_kind="transition", tag="shape")
+ unfavorite("Crimson") # restore clean baseline
+
+
+@and_test(expects=("interaction_theme_favorite_multi_integrity",))
+def test_theme_favorite_multi_integrity():
+ """Favorite TWO themes (Crimson then Forest) and confirm BOTH independently
+ report favorited — a recreation that keeps only one 'favorite' slot fails."""
+ NAME = "interaction_theme_favorite_multi_integrity"
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False, "setup_failed: could not open ThemePicker",
+ depth=1, jump_kind="value",
+ expect="Crimson & Forest both 'Remove ... from favorites'")
+ return
+ results = {}
+ for name in ("Crimson", "Forest"):
+ n, cd = find_fav_control(name)
+ if n and cd and cd.startswith("Add"):
+ tap_node(n)
+ settle("tap")
+ _n2, cd2 = find_fav_control(name)
+ results[name] = cd2
+ both = (results.get("Crimson") == "Remove Crimson from favorites"
+ and results.get("Forest") == "Remove Forest from favorites")
+ record(NAME, both,
+ "" if both else f"behavior_wrong: expected both favorited, got {results!r}",
+ depth=1, jump_kind="value",
+ expect="Crimson='Remove Crimson from favorites' & "
+ "Forest='Remove Forest from favorites'")
+ unfavorite("Crimson")
+ unfavorite("Forest")
+
+
+@and_test(expects=("interaction_theme_reselect_sequence",))
+def test_theme_reselect_sequence():
+ """3-step dependent sequence: select Light (becomes selected) -> then select
+ Abyss -> assert the FINAL selection is Abyss AND Light is no longer marked
+ selected. A dead shell that echoes the first pick fails the last step."""
+ NAME = "interaction_theme_reselect_sequence"
+ if and_enter_theme_picker_from_main() is None:
+ record(NAME, False, "setup_failed: could not open ThemePicker",
+ depth=1, jump_kind="value",
+ expect="Abyss selected, Light not selected")
+ return
+ cd_light = select_theme_card("Light")
+ light_sel = bool(cd_light and "currently selected" in cd_light)
+ cd_abyss = select_theme_card("Abyss")
+ abyss_sel = bool(cd_abyss and "currently selected" in cd_abyss)
+ # re-read Light: it must no longer be selected
+ _c, cd_light2 = find_theme_card("Light")
+ light_cleared = bool(cd_light2) and "currently selected" not in cd_light2
+ ok = light_sel and abyss_sel and light_cleared
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: light_sel={light_sel} abyss_sel="
+ f"{abyss_sel} light_after={cd_light2!r}",
+ depth=1, jump_kind="value",
+ expect="final selected='Abyss theme, currently selected', "
+ "Light no longer selected")
+ restore_default_theme()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# LAYOUT MAPPER — long-press-key customization, multi-step (depth 3)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_layout_mapper():
+ """Launcher -> Settings -> Layout & Input -> Customize Keys (LayoutMapper).
+ Three surfaces. Returns the mapper node list (with the QWERTY buttons) or None."""
+ restart_app()
+ wait_for_foreground()
+ if and_enter_settings() is None:
+ return None
+ nodes = ui()
+ row = (find_node(nodes, text="Layout & Input")
+ or find_node(nodes, text="Number row, space bar size")
+ or scroll_into_view("Number row, space bar size"))
+ if not row or not tap_node(row):
+ return None
+ and_enter("layout_input")
+ ck = scroll_into_view("Customize Keys")
+ if not ck or not tap_node(ck):
+ return None
+ and_enter("layout_mapper")
+ settle("tap") # let the rendered keyboard settle
+ return ui()
+
+
+def _reset_all_mappings():
+ """Tap 'Reset All' and confirm — non-destructive to user vocab, clears only
+ custom key maps (safe cleanup per recon)."""
+ nodes = ui()
+ rst = find_node_ci(nodes, "Reset All")
+ if not rst or not tap_node(rst):
+ return
+ settle("tap")
+ nodes = ui()
+ for n in nodes: # the confirm dialog's Reset button
+ if n.get("class", "").endswith("Button") and n.get("text", "") == "Reset":
+ tap_node(n)
+ settle("tap")
+ return
+
+
+@and_test(expects=("interaction_layoutmapper_custom_char",
+ "interaction_layoutmapper_custom_char_vlm"))
+def test_layoutmapper_custom_char():
+ """Multi-step (navigate depth 3 -> open bottom sheet -> type -> save): tap the
+ 'G' key, the 'Edit key: G' sheet appears, type 'z' into its EditText (field
+ then HOLDS 'z'), tap Save, and the sheet CLOSES. Reset All to restore."""
+ NAME = "interaction_layoutmapper_custom_char"
+ nodes = and_reach_layout_mapper()
+ if nodes is None:
+ record(NAME, False,
+ "setup_failed: could not reach LayoutMapper (Customize Keys)",
+ depth=3, jump_kind="transition", expect="edit field holds 'z'")
+ vlm_assert(NAME, "Is a bottom sheet titled like 'Edit key' shown over a "
+ "rendered keyboard?", expect="YES",
+ depth=3, jump_kind="transition", tag="layout")
+ return
+ # pick a stable middle-row key ('G' is reliably on screen)
+ letters = [n for n in nodes
+ if n.get("class", "").endswith("Button")
+ and len(n.get("text", "")) == 1 and n.get("text", "").isalpha()]
+ key = next((n for n in letters if n.get("text") == "G"),
+ letters[0] if letters else None)
+ if key is None:
+ record(NAME, False, "feature_missing: no rendered letter keys to remap",
+ depth=3, jump_kind="transition", expect="edit field holds 'z'")
+ vlm_assert(NAME, "Is a bottom sheet titled like 'Edit key' shown over a "
+ "rendered keyboard?", expect="YES",
+ depth=3, jump_kind="transition", tag="layout")
+ return
+ letter = key.get("text")
+ tap_node(key)
+ settle("tap")
+ nodes = ui()
+ sheet_title = find_node(nodes, text=f"Edit key: {letter}")
+ # the sheet's EditText is the one that is NOT the bottom test_field
+ edits = [e for e in find_by_class(nodes, "EditText")
+ if not e.get("resource-id", "").endswith("test_field")]
+ edit = edits[0] if edits else None
+ field_holds = False
+ sheet_closed = False
+ if sheet_title and edit:
+ type_text(edit, "z")
+ nodes = ui()
+ fresh = find_closest_match(nodes, edit)
+ field_holds = bool(fresh and fresh.get("text") == "z")
+ # capture the sheet for the VLM before dismissing it
+ vlm_assert(NAME,
+ "Is a bottom sheet / panel (containing a text input field and a "
+ "'Save' button) displayed in the lower part of the screen, "
+ "overlaying a rendered keyboard above it?",
+ expect="YES", depth=3, jump_kind="transition", tag="layout")
+ save = find_node_ci(ui(), "Save")
+ if save:
+ tap_node(save)
+ settle("tap")
+ after = ui()
+ sheet_closed = find_node(after, text=f"Edit key: {letter}") is None
+ else:
+ vlm_assert(NAME,
+ "Is a bottom sheet / panel (containing a text input field and a "
+ "'Save' button) displayed in the lower part of the screen, "
+ "overlaying a rendered keyboard above it?",
+ expect="YES", depth=3, jump_kind="transition", tag="layout")
+ ok = bool(sheet_title) and field_holds and sheet_closed
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: sheet={bool(sheet_title)} "
+ f"field_holds_z={field_holds} sheet_closed_after_save={sheet_closed}",
+ depth=3, jump_kind="transition",
+ expect=f"'Edit key: {letter}' sheet, field holds 'z', closes on Save")
+ _reset_all_mappings() # restore clean key-map state
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# MULTI-STEP SETTINGS SEQUENCE — one toggle changes TWO dependent rows
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_spellcheck_disables_dependents",))
+def test_spellcheck_disables_dependents():
+ """Multi-step consequence: toggle Spell Check OFF and read BACK the enabled
+ state of the TWO dependent rows ('Pause on Misspelled Word' and
+ 'Autocorrection'), which both drop to enabled=false. Restore Spell Check ON."""
+ NAME = "interaction_spellcheck_disables_dependents"
+ if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
+ record(NAME, False,
+ "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="transition",
+ expect="Pause & Autocorrection enabled=false")
+ return
+ nodes = ui()
+ sc = switch_for(nodes, "Spell Check")
+ pause_b = find_node(nodes, text="Pause on Misspelled Word")
+ auto_b = find_node(nodes, text="Autocorrection")
+ both_enabled_before = (pause_b and pause_b.get("enabled") == "true"
+ and auto_b and auto_b.get("enabled") == "true")
+ if not sc:
+ record(NAME, False, "feature_missing: no Spell Check switch",
+ depth=2, jump_kind="transition",
+ expect="Pause & Autocorrection enabled=false")
+ return
+ tap_node(sc)
+ settle("tap")
+ nodes = ui()
+ pause_a = find_node(nodes, text="Pause on Misspelled Word")
+ auto_a = find_node(nodes, text="Autocorrection")
+ both_disabled_after = (pause_a and pause_a.get("enabled") == "false"
+ and auto_a and auto_a.get("enabled") == "false")
+ ok = bool(both_enabled_before) and bool(both_disabled_after)
+ record(NAME, ok,
+ "" if ok else "behavior_wrong: dependent rows did not both flip to "
+ f"enabled=false (before both_enabled={bool(both_enabled_before)}, "
+ f"after both_disabled={bool(both_disabled_after)})",
+ depth=2, jump_kind="transition",
+ expect="Pause & Autocorrection both enabled=false after Spell Check OFF")
+ # restore Spell Check ON
+ sc2 = switch_for(ui(), "Spell Check")
+ if sc2 and sc2.get("checked") == "false":
+ tap_node(sc2)
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SETTINGS PERSISTENCE ACROSS PROCESS DEATH (DATA survival)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _toggle_switch_survives_restart(name, frag, title):
+ """Toggle the switch `title` in fragment `frag` OFF, kill+relaunch, renavigate,
+ and assert it is STILL off; then restore ON. Records `name`."""
+ if and_reach_frag_from_launcher(frag) is None:
+ record(name, False, f"setup_failed: could not reach {frag}",
+ depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
+ return
+ scroll_into_view(title)
+ sw = switch_for(ui(), title)
+ if not sw:
+ record(name, False, f"feature_missing: no {title} switch",
+ depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
+ return
+ was_on = sw.get("checked") == "true"
+ if was_on:
+ tap_node(sw)
+ settle("tap")
+ off_now = switch_for(ui(), title)
+ turned_off = off_now and off_now.get("checked") == "false"
+ # process death + renavigate FORWARD
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ if and_reach_frag_from_launcher(frag) is None:
+ record(name, False, f"setup_failed: could not re-reach {frag} after restart",
+ depth=2, jump_kind="transition", expect=f"{title} checked=false after restart")
+ return
+ scroll_into_view(title)
+ sw2 = switch_for(ui(), title)
+ still_off = sw2 and sw2.get("checked") == "false"
+ ok = bool(was_on) and bool(turned_off) and bool(still_off)
+ record(name, ok,
+ "" if ok else f"behavior_wrong: {title} did not persist OFF across "
+ f"process death (was_on={bool(was_on)} off_now={bool(turned_off)} "
+ f"still_off={bool(still_off)})",
+ depth=2, jump_kind="transition",
+ expect=f"{title} checked=false after relaunch")
+ # restore ON
+ sw3 = switch_for(ui(), title)
+ if sw3 and sw3.get("checked") == "false":
+ tap_node(sw3)
+ settle("tap")
+
+
+@and_test(expects=("interaction_haptic_survives_restart",))
+def test_haptic_survives_restart():
+ """Haptic Feedback OFF -> force stop + relaunch -> renavigate -> still OFF."""
+ _toggle_switch_survives_restart(
+ "interaction_haptic_survives_restart",
+ "Typing Behavior Settings", "Haptic Feedback")
+
+
+@and_test(expects=("interaction_keypress_highlight_survives_restart",))
+def test_keypress_highlight_survives_restart():
+ """Key Press Highlight OFF -> force stop + relaunch -> renavigate -> still OFF."""
+ _toggle_switch_survives_restart(
+ "interaction_keypress_highlight_survives_restart",
+ "Appearance", "Key Press Highlight")
+
+
+@and_test(expects=("interaction_suggestion_count_survives_restart",))
+def test_suggestion_count_survives_restart():
+ """Pick Suggestion Count '1' -> the ListPref summary becomes '1' -> force stop
+ + relaunch -> renavigate -> summary STILL '1'. Restore to '3'."""
+ NAME = "interaction_suggestion_count_survives_restart"
+ if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
+ record(NAME, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="transition", expect="Suggestion Count summary '1'")
+ return
+ scroll_into_view("Suggestion Count")
+ nodes = ui()
+ summ0 = summary_near(nodes, "Suggestion Count")
+ before = summ0.get("text") if summ0 else None
+ title = find_node(nodes, text="Suggestion Count")
+ if not title:
+ record(NAME, False, "feature_missing: no Suggestion Count preference",
+ depth=2, jump_kind="transition", expect="Suggestion Count summary '1'")
+ return
+ tap_node(title)
+ settle("tap")
+ nodes = ui()
+ opt1 = next((n for n in nodes
+ if n.get("class", "").endswith("CheckedTextView")
+ and n.get("text", "") == "1"), None)
+ picked = False
+ if opt1:
+ tap_node(opt1)
+ settle("tap")
+ picked = True
+ nodes = ui()
+ summ1 = summary_near(nodes, "Suggestion Count")
+ after_pick = summ1.get("text") if summ1 else None
+ # process death + renavigate
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ persisted_val = None
+ if and_reach_frag_from_launcher("Auto-Correct Settings") is not None:
+ scroll_into_view("Suggestion Count")
+ summ2 = summary_near(ui(), "Suggestion Count")
+ persisted_val = summ2.get("text") if summ2 else None
+ ok = picked and after_pick == "1" and persisted_val == "1"
+ record(NAME, ok,
+ "" if ok else f"behavior_wrong: Suggestion Count did not persist "
+ f"(before={before!r} after_pick={after_pick!r} after_restart="
+ f"{persisted_val!r})",
+ depth=2, jump_kind="transition",
+ expect="Suggestion Count summary '1' after relaunch")
+ # restore to '3'
+ nodes = ui()
+ title = find_node(nodes, text="Suggestion Count")
+ if title:
+ tap_node(title)
+ settle("tap")
+ opt3 = next((n for n in ui()
+ if n.get("class", "").endswith("CheckedTextView")
+ and n.get("text", "") == "3"), None)
+ if opt3:
+ tap_node(opt3)
+ settle("tap")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# test_field INPUT ECHO — input persists in the field within a fragment
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _test_field_echo(name, frag, marker):
+ """Type `marker` into the fragment's bottom test_field and read it back.
+ Asserts the marker was ABSENT before typing and PRESENT after."""
+ if and_reach_frag_from_launcher(frag) is None:
+ record(name, False, f"setup_failed: could not reach {frag}",
+ depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")
+ return
+ scroll_into_view("Test changes")
+ tf = node_by_id(ui(), "test_field")
+ if not tf:
+ record(name, False, "feature_missing: no test_field EditText",
+ depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")
+ return
+ absent_before = tf.get("text", "") != marker
+ type_text(tf, marker)
+ fresh = node_by_id(ui(), "test_field")
+ present_after = bool(fresh and fresh.get("text") == marker)
+ ok = absent_before and present_after
+ record(name, ok,
+ "" if ok else f"behavior_wrong: test_field held "
+ f"{(fresh or {}).get('text')!r}, expected {marker!r}",
+ depth=2, jump_kind="value", expect=f"test_field holds {marker!r}")
+
+
+@and_test(expects=("interaction_test_field_echo_autocorrect",))
+def test_test_field_echo_autocorrect():
+ """Type a distinctive marker into the Auto-Correct fragment's test_field."""
+ _test_field_echo("interaction_test_field_echo_autocorrect",
+ "Auto-Correct Settings", "kit_echo_A")
+
+
+@and_test(expects=("interaction_test_field_echo_appearance",))
+def test_test_field_echo_appearance():
+ """Type a distinctive marker into the Appearance fragment's test_field."""
+ _test_field_echo("interaction_test_field_echo_appearance",
+ "Appearance", "kit_echo_B")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# EXTRA VLM — visual consequences that the dump cannot express
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("interaction_theme_dark_applied_vlm",))
+def test_theme_dark_applied_vlm():
+ """Select the dark Abyss theme, return to the launcher, and confirm the
+ preview keyboard renders in a DARK/BLACK palette (colour consequence)."""
+ NAME = "interaction_theme_dark_applied"
+ if and_enter_theme_picker_from_main() is None:
+ vlm_assert(NAME, "Is a keyboard theme picker with multiple preview cards "
+ "shown?", expect="YES", depth=2, jump_kind="transition",
+ tag="color")
+ return
+ select_theme_card("Abyss")
+ restart_app()
+ wait_for_foreground()
+ ui() # settle the launcher render before the screenshot
+ vlm_assert(NAME,
+ "The keyboard preview card near the centre of this screen: are its "
+ "keys drawn on a predominantly BLACK / very dark background "
+ "(a dark colour theme)?",
+ expect="YES", depth=2, jump_kind="transition", tag="color")
+ restore_default_theme()
+
+
+@and_test(expects=("interaction_spellcheck_dependents_dimmed_vlm",))
+def test_spellcheck_dependents_dimmed_vlm():
+ """After Spell Check OFF the two dependent rows are disabled — visually they
+ render greyed/dimmed. Screenshot the AutoCorrect list in that state."""
+ NAME = "interaction_spellcheck_dependents_dimmed"
+ if and_reach_frag_from_launcher("Auto-Correct Settings") is None:
+ vlm_assert(NAME, "Is a settings list with several toggle switches shown?",
+ expect="YES", depth=2, jump_kind="transition", tag="color")
+ return
+ sc = switch_for(ui(), "Spell Check")
+ toggled = False
+ if sc and sc.get("checked") == "true":
+ tap_node(sc)
+ settle("tap")
+ toggled = True
+ vlm_assert(NAME,
+ "In this settings list, are the 'Pause on Misspelled Word' and "
+ "'Autocorrection' rows shown greyed-out / dimmed (a faded, "
+ "disabled appearance) compared with the fully-black active rows "
+ "above them?",
+ expect="YES", depth=2, jump_kind="transition", tag="color")
+ # restore Spell Check ON
+ sc2 = switch_for(ui(), "Spell Check")
+ if toggled and sc2 and sc2.get("checked") == "false":
+ tap_node(sc2)
+ settle("tap")
+
+
+@and_test(expects=("interaction_favorite_floats_to_top_vlm",))
+def test_favorite_floats_to_top_vlm():
+ """Favoriting a theme reorders the list so the favorited card floats up.
+ Favorite Ocean, scroll to the top, and ask whether a filled-heart card is at
+ the top of the list (position consequence)."""
+ NAME = "interaction_favorite_floats_to_top"
+ if and_enter_theme_picker_from_main() is None:
+ vlm_assert(NAME, "Is a scrollable list of keyboard theme cards shown?",
+ expect="YES", depth=1, jump_kind="transition", tag="position")
+ return
+ n, cd = find_fav_control("Ocean")
+ if n and cd and cd.startswith("Add"):
+ tap_node(n)
+ settle("tap")
+ _scroll_picker_top()
+ ui()
+ vlm_assert(NAME,
+ "At the very TOP of this theme list (the first one or two cards), "
+ "is there a theme card whose favorite heart icon is FILLED / solid "
+ "rather than an empty outline?",
+ expect="YES", depth=1, jump_kind="transition", tag="position")
+ unfavorite("Ocean") # restore clean baseline
+
+
+@and_test(expects=("interaction_selected_theme_checkmark_vlm",))
+def test_selected_theme_checkmark_vlm():
+ """Selecting a theme marks exactly that card as chosen with a checkmark badge.
+ Select Abyss, then screenshot the picker (Abyss scrolled into view) and ask
+ whether that card carries a distinct check/tick mark (shape consequence)."""
+ NAME = "interaction_selected_theme_checkmark"
+ if and_enter_theme_picker_from_main() is None:
+ vlm_assert(NAME, "Is a keyboard theme picker with preview cards shown?",
+ expect="YES", depth=1, jump_kind="transition", tag="shape")
+ return
+ select_theme_card("Abyss")
+ find_theme_card("Abyss") # bring the selected card into view for the shot
+ ui()
+ vlm_assert(NAME,
+ "On this theme list, is exactly one theme card marked as the "
+ "currently-selected one with a check-mark / tick badge (a small "
+ "checkmark icon), while the other cards have no such checkmark?",
+ expect="YES", depth=1, jump_kind="transition", tag="shape")
+ restore_default_theme()
+
+
+# ── registry & entry point ──────────────────────────────────────────────────────
+
+TESTS = [
+ test_theme_selection_persists_to_main, # +1 vlm
+ test_theme_selection_survives_restart,
+ test_theme_favorite_persists, # +1 vlm
+ test_theme_favorite_multi_integrity,
+ test_theme_reselect_sequence,
+ test_layoutmapper_custom_char, # +1 vlm
+ test_spellcheck_disables_dependents,
+ test_haptic_survives_restart,
+ test_keypress_highlight_survives_restart,
+ test_suggestion_count_survives_restart,
+ test_test_field_echo_autocorrect,
+ test_test_field_echo_appearance,
+ test_theme_dark_applied_vlm, # vlm-only
+ test_spellcheck_dependents_dimmed_vlm, # vlm-only
+ test_favorite_floats_to_top_vlm, # vlm-only
+ test_selected_theme_checkmark_vlm, # vlm-only
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/urikdev-urik/tests/test_android_navigation.py b/android/urikdev-urik/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..23a89399f24765e659d2f66d9774ed6c3f07c1b2
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_navigation.py
@@ -0,0 +1,670 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane — Urik Keyboard (com.urik.keyboard).
+
+Owns surface REACHABILITY + back-stack integrity: this lane is the sole owner of
+jump_kind="reach" and of the depth>=2 chains. Every forward jump is proven with
+and_reach(before, after, target, source): the TARGET surface's discriminating
+element APPEARED and the SOURCE surface's DISAPPEARED. A screen that was already
+in the tree was never reached. Every test opens its own entry point (the S0
+launcher, via open_launcher()) and navigates FORWARD from there; back-navigation
+is exercised as its own short forward-then-BACK test (nested cross-surface back()
+chains are flaky).
+
+Relaunching is only ever how a test re-establishes its S0 entry point — it is
+NEVER the mechanism that reaches a destination. The reach is always a forward tap
+proven by and_reach*, so restart lives in open_launcher()/open_settings(), one
+level below the reach call.
+
+Ground truth for every target/source string below was observed live on the
+original app before the assertion was written (see recon.md + recon_shots/).
+
+Two source-collision hazards were found live and encoded here:
+ * The Privacy screen contains the summary "Save keyboard settings and custom
+ key mappings...", so the substring "Keyboard Settings" does NOT vanish on the
+ S2->Privacy jump — the source for that jump is a distinctive list row instead.
+ * Several destination TOOLBAR titles equal their originating list-row text
+ (Open Source Licenses / Dictionary Data / Customize Keys / Reset to Defaults),
+ so those jumps assert a destination-only element (a content view id or a
+ unique button/message), never the colliding title.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403
+
+TESTS = []
+
+
+def test(fn):
+ TESTS.append(fn)
+ return fn
+
+
+# ── Shared helpers ──────────────────────────────────────────────────────────────
+
+def open_launcher():
+ """Re-establish this test's S0 (MainActivity launcher) entry point and return
+ its fresh node list. Relaunch is the ISOLATION mechanism (kit contract: each
+ test owns its entry point), never the navigation under test."""
+ restart_app()
+ wait_for_foreground()
+ return ui()
+
+
+def open_settings():
+ """S0 -> SettingsActivity. Returns the fresh Settings node list, or None."""
+ nodes = open_launcher()
+ trig = find_node(nodes, text="Open Settings") or find_node_ci(nodes, "Open Settings")
+ if not trig or not tap_node(trig):
+ return None
+ after = ui()
+ # Confirm we are on the Settings list before any test navigates further.
+ if find_node(after, text="Keyboard Settings") is None:
+ return None
+ return after
+
+
+def theme_name_tv(nodes):
+ """The dynamic theme-name TextView on S0 (reads 'Default'/'Abyss'/...). It is
+ the only short TextView that is neither the app title nor a button label, so
+ locate it structurally rather than by a value that persists across runs."""
+ known = {"urik keyboard", "enable", "open settings", "about"}
+ btnlabels = {b.get("text", "").strip().lower() for b in find_by_class(nodes, "Button")}
+ for n in nodes:
+ if not n.get("class", "").endswith("TextView"):
+ continue
+ t = n.get("text", "").strip()
+ if t and t.lower() not in known and t.lower() not in btnlabels and len(t) < 20:
+ return n
+ return None
+
+
+def tap_up(nodes):
+ """Tap the toolbar up-affordance (ImageButton content-desc 'Navigate up') and
+ settle for the surface transition. This IS the back action under test, so it
+ presses BACK exactly once — callers must NOT also call and_back()."""
+ up = find_node(nodes, content_desc="Navigate up")
+ if not up or not tap_node(up):
+ return False
+ settle("tap") # a fragment/activity pop can outlast the default tap settle
+ return True
+
+
+# Depth-family helpers. The and_enter_*/and_reach_* NAME is what the depth audit
+# looks for; the implementation is ours. Each proves ONE surface crossing.
+
+def and_enter_settings():
+ """S0 -> Settings, proven (Keyboard Settings appeared, Open Settings gone)."""
+ trig = find_node(open_launcher(), text="Open Settings")
+ return bool(trig) and and_reach_surface(trig, "Keyboard Settings", "Open Settings")
+
+
+def and_reach_appearance():
+ """Settings -> Appearance, proven."""
+ nodes = open_settings()
+ if not nodes:
+ return False
+ row = find_node(nodes, text="Appearance")
+ return bool(row) and and_reach_surface(row, "Key Press Highlight", "Keyboard Settings")
+
+
+def and_reach_layout_input():
+ """Settings -> Layout & Input, proven (row text is literally 'Layout & Input')."""
+ nodes = open_settings()
+ if not nodes:
+ return False
+ row = find_node(nodes, text="Layout & Input")
+ return bool(row) and and_reach_surface(row, "Keyboard Layout", "Keyboard Settings")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (A) S0 top-level destinations — depth 1, reach
+# ══════════════════════════════════════════════════════════════════════════════
+
+@test
+@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))
+def test_reach_settings():
+ nodes = open_launcher()
+ trig = find_node(nodes, text="Open Settings") or find_node_ci(nodes, "Open Settings")
+ ok = trig is not None and and_reach_surface(trig, "Keyboard Settings", "Open Settings")
+ record("nav_reach_settings", ok,
+ "" if ok else "feature_missing: Settings surface not reachable from 'Open Settings'",
+ depth=1, jump_kind="reach",
+ expect="'Keyboard Settings' title appeared; launcher 'Open Settings' button gone")
+ vlm_assert("nav_reach_settings",
+ "Is a settings screen showing a top toolbar with a left-pointing back "
+ "arrow at the top-left and a vertical list of labelled rows below it?",
+ RESULTS_DIR, tag="position")
+
+
+@test
+@and_test(expects=("nav_reach_about", "nav_reach_about_vlm"))
+def test_reach_about():
+ nodes = open_launcher()
+ trig = find_node(nodes, text="About") or find_node_ci(nodes, "About")
+ # Discriminator = About page text substring ('GNU GPL v3.0'), which is unique to
+ # the About screen; the toolbar title 'About' collides with the launcher button.
+ ok = trig is not None and and_reach_surface(trig, "GNU GPL v3.0", "Open Settings")
+ record("nav_reach_about", ok,
+ "" if ok else "feature_missing: About surface not reachable from 'About' button",
+ depth=1, jump_kind="reach",
+ expect="About text ('...GNU GPL v3.0...') appeared; launcher 'Open Settings' gone")
+ vlm_assert("nav_reach_about",
+ "Is this an 'About' text page: a screen filled mostly with lines of text "
+ "(version, copyright, links) and NO keyboard preview or list of toggle rows?",
+ RESULTS_DIR, tag="layout")
+
+
+@test
+@and_test(expects=("nav_reach_themepicker", "nav_reach_themepicker_vlm"))
+def test_reach_themepicker():
+ nodes = open_launcher()
+ trig = theme_name_tv(nodes)
+ ok = trig is not None and and_reach_surface(trig, "Keyboard Theme", "Open Settings")
+ record("nav_reach_themepicker", ok,
+ "" if ok else "feature_missing: ThemePicker not reachable from the theme-name card",
+ depth=1, jump_kind="reach",
+ expect="'Keyboard Theme' title appeared; launcher 'Open Settings' gone")
+ vlm_assert("nav_reach_themepicker",
+ "Does this screen show a vertical list of keyboard theme previews rendered "
+ "in several DIFFERENT colors (e.g. a dark one, a white/light one, a black one)?",
+ RESULTS_DIR, tag="color")
+
+
+@test
+@and_test(expects=("nav_reach_features_sheet", "nav_reach_features_sheet_vlm"))
+def test_reach_features_sheet():
+ nodes = open_launcher()
+ fabs = find_by_class(nodes, "FloatingActionButton")
+ trig = fabs[0] if fabs else None
+ # The sheet slides over the launcher, so 'Open Settings' is covered (disappears)
+ # while a tip string ('Learning Words') appears.
+ ok = trig is not None and and_reach_surface(trig, "Learning Words", "Open Settings")
+ record("nav_reach_features_sheet", ok,
+ "" if ok else "feature_missing: Features bottom sheet not reachable from the FAB",
+ depth=1, jump_kind="reach",
+ expect="Features tip 'Learning Words' appeared; launcher 'Open Settings' covered/gone")
+ vlm_assert("nav_reach_features_sheet",
+ "Is a bottom sheet panel covering the lower portion of the screen, showing a "
+ "list of tip titles with descriptions, while the top of the screen is dimmed?",
+ RESULTS_DIR, tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (B) Settings -> each of the 8 rows — depth 2, reach (this lane's depth>=2 core)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@test
+@and_test(expects=("nav_settings_to_autocorrect",))
+def test_settings_to_autocorrect():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_autocorrect", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Auto-Correct fragment after tapping its row")
+ return
+ and_enter("Settings") # crossed S0 -> Settings
+ row = find_node(nodes, text="Auto-Correct Settings")
+ ok = row is not None and and_reach_surface(row, "Spell Check", "Keyboard Settings")
+ record("nav_settings_to_autocorrect", ok,
+ "" if ok else "feature_missing: Auto-Correct fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Spell Check' row appeared; 'Keyboard Settings' title gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_languages",))
+def test_settings_to_languages():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_languages", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Languages fragment after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Language Settings")
+ ok = row is not None and and_reach_surface(row, "Merged Dictionaries", "Keyboard Settings")
+ record("nav_settings_to_languages", ok,
+ "" if ok else "feature_missing: Languages fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Merged Dictionaries' row appeared; 'Keyboard Settings' title gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_typing",))
+def test_settings_to_typing():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_typing", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Typing Behavior fragment after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Typing Behavior Settings")
+ ok = row is not None and and_reach_surface(row, "Double-Space Period", "Keyboard Settings")
+ record("nav_settings_to_typing", ok,
+ "" if ok else "feature_missing: Typing Behavior fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Double-Space Period' row appeared; 'Keyboard Settings' title gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_layout",))
+def test_settings_to_layout():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_layout", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Layout & Input fragment after tapping its row")
+ return
+ and_enter("Settings")
+ # The dump keeps '&' un-unescaped: the row text is literally 'Layout & Input'.
+ row = find_node(nodes, text="Layout & Input")
+ ok = row is not None and and_reach_surface(row, "Keyboard Layout", "Keyboard Settings")
+ record("nav_settings_to_layout", ok,
+ "" if ok else "feature_missing: Layout & Input fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Keyboard Layout' row appeared; 'Keyboard Settings' title gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_appearance",))
+def test_settings_to_appearance():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_appearance", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Appearance fragment after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Appearance")
+ ok = row is not None and and_reach_surface(row, "Key Press Highlight", "Keyboard Settings")
+ record("nav_settings_to_appearance", ok,
+ "" if ok else "feature_missing: Appearance fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Key Press Highlight' row appeared; 'Keyboard Settings' title gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_privacy",))
+def test_settings_to_privacy():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_privacy", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Privacy & Data fragment after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Privacy & Data")
+ # SOURCE note: the Privacy screen itself contains the Export-Settings summary
+ # "Save keyboard settings and custom key mappings...", so the substring
+ # "Keyboard Settings" SURVIVES the jump. Use a distinctive Settings-list row
+ # ("Dictionary Data") that genuinely vanishes and has no substring collision.
+ ok = row is not None and and_reach_surface(row, "Clipboard History", "Dictionary Data")
+ record("nav_settings_to_privacy", ok,
+ "" if ok else "feature_missing: Privacy & Data fragment not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="'Clipboard History' row appeared; Settings-list 'Dictionary Data' row gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_licenses",))
+def test_settings_to_licenses():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_licenses", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Open Source Licenses screen after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Open Source Licenses")
+ # The toolbar title equals the row text (same node_key), so use the licenses
+ # content view (resource-id 'oss_licenses_text'), unique to the destination.
+ ok = row is not None and and_reach_surface(row, "oss_licenses_text", "Dictionary Data")
+ record("nav_settings_to_licenses", ok,
+ "" if ok else "feature_missing: Open Source Licenses screen not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="licenses text view appeared; 'Dictionary Data' row gone")
+
+
+@test
+@and_test(expects=("nav_settings_to_dictionary",))
+def test_settings_to_dictionary():
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_settings_to_dictionary", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Dictionary Data screen after tapping its row")
+ return
+ and_enter("Settings")
+ row = find_node(nodes, text="Dictionary Data")
+ # Title collides with the row; the attribution body text is unique to the screen.
+ ok = row is not None and and_reach_surface(row, "DICTIONARY DATA ATTRIBUTION",
+ "Open Source Licenses")
+ record("nav_settings_to_dictionary", ok,
+ "" if ok else "feature_missing: Dictionary Data screen not reachable from its row",
+ depth=2, jump_kind="reach",
+ expect="attribution text appeared; 'Open Source Licenses' row gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (C) Deep chains — and_enter per surface, prove the final reach
+# ══════════════════════════════════════════════════════════════════════════════
+
+@test
+@and_test(expects=("nav_chain_appearance_themepicker", "nav_chain_appearance_themepicker_vlm"))
+def test_chain_appearance_themepicker():
+ """S0 -> Settings -> Appearance -> ThemePicker (depth 2 chain)."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_chain_appearance_themepicker", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="ThemePicker after Settings->Appearance->Theme")
+ vlm_assert("nav_chain_appearance_themepicker",
+ "Does this screen show a vertical list of keyboard theme previews in "
+ "several different colors?", RESULTS_DIR, tag="color")
+ return
+ and_enter("Settings") # S0 -> Settings
+ appr = find_node(nodes, text="Appearance")
+ hop1 = appr is not None and and_reach_surface(appr, "Key Press Highlight", "Keyboard Settings")
+ hop2 = False
+ if hop1:
+ theme_row = find_node(ui(), text="Theme")
+ hop2 = theme_row is not None and and_reach_surface(theme_row, "Keyboard Theme",
+ "Key Press Highlight")
+ ok = hop1 and hop2
+ record("nav_chain_appearance_themepicker", ok,
+ "" if ok else "behavior_wrong: Appearance->Theme did not reach the ThemePicker",
+ depth=2, jump_kind="reach",
+ expect="'Keyboard Theme' appeared after the Appearance 'Theme' row; "
+ "'Key Press Highlight' gone")
+ vlm_assert("nav_chain_appearance_themepicker",
+ "Does this screen show a vertical list of keyboard theme previews rendered "
+ "in several DIFFERENT colors (dark, light/white, black, etc.)?",
+ RESULTS_DIR, tag="color")
+
+
+@test
+@and_test(expects=("nav_chain_layout_mapper", "nav_chain_layout_mapper_vlm"))
+def test_chain_layout_mapper():
+ """S0 -> Settings -> Layout & Input -> LayoutMapper (depth 3 chain)."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_chain_layout_mapper", False,
+ "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
+ expect="LayoutMapper after Settings->Layout->Customize Keys")
+ vlm_assert("nav_chain_layout_mapper",
+ "Does this screen show a full rendered QWERTY keyboard (rows of letter "
+ "keys) with a button below it?", RESULTS_DIR, tag="layout")
+ return
+ and_enter("Settings") # S0 -> Settings
+ li = find_node(nodes, text="Layout & Input")
+ hop1 = li is not None and and_reach_surface(li, "Keyboard Layout", "Keyboard Settings")
+ hop2 = False
+ if hop1:
+ ck = find_node(ui(), text="Customize Keys")
+ # LayoutMapper title 'Customize Keys' collides with the row; 'Reset All'
+ # (a button unique to the mapper) is the discriminator.
+ hop2 = ck is not None and and_reach_surface(ck, "Reset All", "Keyboard Layout")
+ ok = hop1 and hop2
+ record("nav_chain_layout_mapper", ok,
+ "" if ok else "behavior_wrong: Layout->Customize Keys did not reach the LayoutMapper",
+ depth=3, jump_kind="reach",
+ expect="'Reset All' appeared after the 'Customize Keys' row; 'Keyboard Layout' gone")
+ vlm_assert("nav_chain_layout_mapper",
+ "Is a full keyboard laid out as horizontal rows of keys (number row, then "
+ "letter rows Q-P, A-L, Z-M) rendered in the center of this screen?",
+ RESULTS_DIR, tag="layout")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (D) Dialog reachability + dismissal (a dialog is a surface)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@test
+@and_test(expects=("nav_reset_dialog_reach", "nav_reset_dialog_reach_vlm"))
+def test_reset_dialog_reach():
+ """Privacy -> Reset to Defaults -> the confirm dialog appears (SAFE: never tap OK)."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_reset_dialog_reach", False,
+ "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
+ expect="Reset confirm dialog after tapping 'Reset to Defaults'")
+ vlm_assert("nav_reset_dialog_reach",
+ "Is a small modal dialog box centered over a dimmed screen, with two text "
+ "buttons in its bottom-right?", RESULTS_DIR, tag="position")
+ return
+ and_enter("Settings")
+ pv = find_node(nodes, text="Privacy & Data")
+ # Privacy hop source: distinctive list row (see nav_settings_to_privacy note).
+ hop1 = pv is not None and and_reach_surface(pv, "Clipboard History", "Dictionary Data")
+ hop2 = False
+ if hop1:
+ reset = find_node(ui(), text="Reset to Defaults")
+ # Title 'Reset to Defaults' collides with the row; the dialog MESSAGE is unique.
+ hop2 = reset is not None and and_reach_surface(reset, "Reset all settings to defaults?",
+ "Clipboard History")
+ ok = hop1 and hop2
+ record("nav_reset_dialog_reach", ok,
+ "" if ok else "behavior_wrong: 'Reset to Defaults' did not raise a confirm dialog",
+ depth=3, jump_kind="reach",
+ expect="dialog message 'Reset all settings to defaults?' appeared; "
+ "'Clipboard History' row covered/gone")
+ vlm_assert("nav_reset_dialog_reach",
+ "Is a small modal dialog box centered on the screen (with a title, a short "
+ "message, and Cancel/OK buttons) over a dimmed background?",
+ RESULTS_DIR, tag="position")
+
+
+@test
+@and_test(expects=("nav_reset_dialog_cancel",))
+def test_reset_dialog_cancel():
+ """Reset dialog -> Cancel -> dialog gone, back on Privacy (SAFE)."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_reset_dialog_cancel", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Privacy screen restored after Cancel")
+ return
+ and_enter("Settings")
+ pv = find_node(nodes, text="Privacy & Data")
+ ok_pv = pv is not None and and_reach_surface(pv, "Clipboard History", "Dictionary Data")
+ dismissed = False
+ if ok_pv:
+ reset = find_node(ui(), text="Reset to Defaults")
+ if reset and and_reach_surface(reset, "Reset all settings to defaults?", "Clipboard History"):
+ dlg = ui()
+ cancel = find_node(dlg, text="Cancel") # SAFETY: only ever Cancel, never OK
+ before = and_showing(dlg)
+ if cancel and tap_node(cancel):
+ settle("tap")
+ dismissed = and_reach(before, and_showing(),
+ "Clipboard History", "Reset all settings to defaults?")
+ record("nav_reset_dialog_cancel", ok_pv and dismissed,
+ "" if (ok_pv and dismissed) else
+ "behavior_wrong: Cancel did not dismiss the reset dialog back to Privacy",
+ depth=2, jump_kind="reach",
+ expect="after Cancel: dialog message gone, 'Clipboard History' row restored")
+
+
+@test
+@and_test(expects=("nav_suggestion_dialog_reach", "nav_suggestion_dialog_reach_vlm"))
+def test_suggestion_dialog_reach():
+ """Auto-Correct -> Suggestion Count -> the list dialog appears."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_suggestion_dialog_reach", False,
+ "setup_failed: could not reach the Settings list", depth=3, jump_kind="reach",
+ expect="Suggestion Count list dialog")
+ vlm_assert("nav_suggestion_dialog_reach",
+ "Is a modal dialog showing a short vertical list of selectable options "
+ "each with a round radio button on its left?", RESULTS_DIR, tag="shape")
+ return
+ and_enter("Settings")
+ ac = find_node(nodes, text="Auto-Correct Settings")
+ hop1 = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
+ hop2 = False
+ if hop1:
+ sc = find_node(ui(), text="Suggestion Count")
+ # The list dialog adds a select list; 'Learn New Words' (a row below in the
+ # fragment) is covered by the dialog.
+ hop2 = sc is not None and and_reach_surface(sc, "select_dialog_listview", "Learn New Words")
+ ok = hop1 and hop2
+ record("nav_suggestion_dialog_reach", ok,
+ "" if ok else "behavior_wrong: 'Suggestion Count' did not open a list dialog",
+ depth=3, jump_kind="reach",
+ expect="dialog list ('select_dialog_listview') appeared; 'Learn New Words' covered/gone")
+ vlm_assert("nav_suggestion_dialog_reach",
+ "Is a modal dialog showing a short vertical list of numeric options, each with "
+ "a round radio-button circle to its left, and a Cancel button?",
+ RESULTS_DIR, tag="shape")
+
+
+@test
+@and_test(expects=("nav_suggestion_dialog_cancel",))
+def test_suggestion_dialog_cancel():
+ """Suggestion Count dialog -> Cancel -> back on the Auto-Correct fragment."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_suggestion_dialog_cancel", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Auto-Correct fragment restored after Cancel")
+ return
+ and_enter("Settings")
+ ac = find_node(nodes, text="Auto-Correct Settings")
+ ok_ac = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
+ dismissed = False
+ if ok_ac:
+ sc = find_node(ui(), text="Suggestion Count")
+ if sc and and_reach_surface(sc, "select_dialog_listview", "Learn New Words"):
+ dlg = ui()
+ cancel = find_node(dlg, text="Cancel")
+ before = and_showing(dlg)
+ if cancel and tap_node(cancel):
+ settle("tap")
+ dismissed = and_reach(before, and_showing(),
+ "Learn New Words", "select_dialog_listview")
+ record("nav_suggestion_dialog_cancel", ok_ac and dismissed,
+ "" if (ok_ac and dismissed) else
+ "behavior_wrong: Cancel did not dismiss the Suggestion Count dialog",
+ depth=2, jump_kind="reach",
+ expect="after Cancel: dialog list gone, 'Learn New Words' row restored")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (E) Back-stack integrity — forward-then-BACK, proven in reverse with and_reach.
+# The trigger under test (up-affordance / BACK) presses BACK exactly ONCE; these
+# tests never double-pop.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@test
+@and_test(expects=("nav_backstack_up_autocorrect", "nav_backstack_up_autocorrect_vlm"))
+def test_backstack_up_autocorrect():
+ """Settings -> Auto-Correct, then the toolbar up-affordance returns to the list."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_backstack_up_autocorrect", False,
+ "setup_failed: could not reach the Settings list", depth=1, jump_kind="reach",
+ expect="Settings list restored after Navigate up")
+ vlm_assert("nav_backstack_up_autocorrect",
+ "Does the toolbar at the top of this screen show a left-pointing back "
+ "arrow (up affordance) at its far left?", RESULTS_DIR, tag="shape")
+ return
+ and_enter("Settings")
+ ac = find_node(nodes, text="Auto-Correct Settings")
+ forward = ac is not None and and_reach_surface(ac, "Spell Check", "Keyboard Settings")
+ sub = ui() if forward else []
+ # VLM on the SUB-fragment: the up affordance must be present there. Captured
+ # BEFORE we pop so the screenshot is of the sub-screen toolbar.
+ vlm_assert("nav_backstack_up_autocorrect",
+ "Does the toolbar at the very top of this screen show a left-pointing back "
+ "arrow at its far left, next to the screen title?",
+ RESULTS_DIR, tag="shape")
+ returned = False
+ if forward:
+ before = and_showing(sub)
+ if tap_up(sub): # the up-affordance IS the back action; single BACK
+ returned = and_reach(before, and_showing(), "Keyboard Settings", "Spell Check")
+ record("nav_backstack_up_autocorrect", forward and returned,
+ "" if (forward and returned) else
+ "behavior_wrong: the up-affordance did not return to the Settings list",
+ depth=1, jump_kind="reach",
+ expect="'Keyboard Settings' title reappeared; 'Spell Check' row gone")
+
+
+@test
+@and_test(expects=("nav_backstack_about_to_home",))
+def test_backstack_about_to_home():
+ """S0 -> About, then BACK returns to the launcher."""
+ trig = find_node(open_launcher(), text="About")
+ forward = trig is not None and and_reach_surface(trig, "GNU GPL v3.0", "Open Settings")
+ returned = False
+ if forward:
+ before = and_showing()
+ and_back() # BACK pops the About activity (single press)
+ settle("tap")
+ returned = and_reach(before, and_showing(), "Open Settings", "GNU GPL v3.0")
+ record("nav_backstack_about_to_home", forward and returned,
+ "" if (forward and returned) else
+ "behavior_wrong: BACK from About did not return to the launcher",
+ depth=1, jump_kind="reach",
+ expect="launcher 'Open Settings' button restored; About text ('GNU GPL v3.0') gone")
+
+
+@test
+@and_test(expects=("nav_backstack_themepicker_to_home",))
+def test_backstack_themepicker_to_home():
+ """S0 -> ThemePicker (card), then BACK returns to the launcher."""
+ trig = theme_name_tv(open_launcher())
+ forward = trig is not None and and_reach_surface(trig, "Keyboard Theme", "Open Settings")
+ returned = False
+ if forward:
+ before = and_showing()
+ and_back() # BACK pops the ThemePicker activity (single press)
+ settle("tap")
+ returned = and_reach(before, and_showing(), "Open Settings", "Keyboard Theme")
+ record("nav_backstack_themepicker_to_home", forward and returned,
+ "" if (forward and returned) else
+ "behavior_wrong: BACK from ThemePicker did not return to the launcher",
+ depth=1, jump_kind="reach",
+ expect="launcher 'Open Settings' button restored; 'Keyboard Theme' title gone")
+
+
+@test
+@and_test(expects=("nav_backstack_2hop_unwind",))
+def test_backstack_2hop_unwind():
+ """Depth-2 chain unwound hop by hop: S0->Settings->Appearance->ThemePicker,
+ then the up-affordance TWICE, asserting the expected surface after each pop."""
+ nodes = open_settings()
+ if nodes is None:
+ record("nav_backstack_2hop_unwind", False,
+ "setup_failed: could not reach the Settings list", depth=2, jump_kind="reach",
+ expect="Settings restored after unwinding ThemePicker->Appearance->Settings")
+ return
+ and_enter("Settings") # S0 -> Settings
+ appr = find_node(nodes, text="Appearance")
+ hop1 = appr is not None and and_reach_surface(appr, "Key Press Highlight", "Keyboard Settings")
+ hop2 = False
+ if hop1:
+ theme_row = find_node(ui(), text="Theme")
+ hop2 = theme_row is not None and and_reach_surface(theme_row, "Keyboard Theme",
+ "Key Press Highlight")
+ pop1 = pop2 = False
+ if hop2:
+ tp = ui()
+ b_tp = and_showing(tp)
+ if tap_up(tp): # pop ThemePicker -> Appearance (single BACK)
+ pop1 = and_reach(b_tp, and_showing(), "Key Press Highlight", "Keyboard Theme")
+ if pop1:
+ appr_now = ui()
+ b_appr = and_showing(appr_now)
+ if tap_up(appr_now): # pop Appearance -> Settings (single BACK)
+ pop2 = and_reach(b_appr, and_showing(), "Keyboard Settings", "Key Press Highlight")
+ ok = hop1 and hop2 and pop1 and pop2
+ record("nav_backstack_2hop_unwind", ok,
+ "" if ok else "behavior_wrong: BACK did not unwind ThemePicker->Appearance->Settings hop by hop",
+ depth=2, jump_kind="reach",
+ expect="pop1 -> Appearance ('Key Press Highlight'), pop2 -> Settings ('Keyboard Settings')")
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/urikdev-urik/tests/test_android_states.py b/android/urikdev-urik/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7bd1603f48cdbe3467178cbe2e24756e82bd627
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_states.py
@@ -0,0 +1,991 @@
+#!/usr/bin/env python3
+"""STATES lane — Urik Keyboard (com.urik.keyboard).
+
+Owns checked/enabled/selected/focused transitions PAIRED WITH THEIR
+APP-AUTHORED CONSEQUENCE, the two conditional-enable state machines, and
+SETTINGS/mode persistence across process death.
+
+Every checked/enabled flip is paired with the summary string that changes OR the
+dependent control whose `enabled` flips — a bare checked flip never ships.
+All ground truth below was OBSERVED live on the running original before writing.
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403
+
+
+# ── Inlined locator helpers (kit-forbidden shortcuts avoided) ────────────────────
+# ALL Switches share resource-id .../switchWidget and ALL language CheckBoxes share
+# .../checkbox, so NEVER locate one by id alone: find the row's title TextView by
+# text, then pick the widget whose _center y is closest to that title.
+
+def switch_for(nodes, title):
+ """The Switch belonging to the preference row whose title TextView == `title`."""
+ tn = find_node(nodes, text=title)
+ if not tn or "_center" not in tn:
+ return None
+ ty = tn["_center"][1]
+ cands = [n for n in nodes if "Switch" in n.get("class", "")
+ and n.get("resource-id", "").endswith("switchWidget")
+ and "_center" in n]
+ return min(cands, key=lambda n: abs(n["_center"][1] - ty)) if cands else None
+
+
+def checkbox_for(nodes, title):
+ """The CheckBox belonging to the language row whose title TextView == `title`."""
+ tn = find_node(nodes, text=title)
+ if not tn or "_center" not in tn:
+ return None
+ ty = tn["_center"][1]
+ cands = [n for n in nodes if "CheckBox" in n.get("class", "")
+ and n.get("resource-id", "").endswith("checkbox")
+ and "_center" in n]
+ return min(cands, key=lambda n: abs(n["_center"][1] - ty)) if cands else None
+
+
+def enabled_of(nodes, title):
+ """The `enabled` attribute of the title TextView of a preference row."""
+ tn = find_node(nodes, text=title)
+ return tn.get("enabled") if tn else None
+
+
+def summary_of(nodes, title):
+ """The summary TextView (id .../summary) directly below `title` in the row."""
+ tn = find_node(nodes, text=title)
+ if not tn or "_center" not in tn:
+ return None
+ tx, ty = tn["_center"]
+ best, bestdy = None, 10 ** 9
+ for n in nodes:
+ if n.get("resource-id", "").endswith("summary") and n.get("text") \
+ and "_center" in n:
+ cx, cy = n["_center"]
+ dy = cy - ty
+ if 0 < dy < 200 and abs(cx - tx) < 400 and dy < bestdy:
+ best, bestdy = n, dy
+ return best.get("text") if best else None
+
+
+# ── Navigation: every test enters FORWARD from the launcher (nested back is flaky) ─
+# depth-2 surface = SettingsActivity -> a preference fragment. and_reach_fragment /
+# and_enter back the declared depth=2 for the audit.
+
+def and_reach_settings():
+ """Launcher -> Open Settings (depth 1). Returns nodes on the Settings list."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ btn = find_node(nodes, text="Open Settings")
+ if btn is None:
+ return None
+ if not and_reach_surface(btn, "Keyboard Settings", "Open Settings"):
+ # surface may not expose the exact toolbar key; fall back to a plain enter
+ and_enter("Settings")
+ return ui()
+
+
+def and_reach_fragment(row_text):
+ """Launcher -> Open Settings -> tap a settings row (depth 2). Returns fragment
+ nodes, or None if the row is unreachable. `row_text` is the EXACT dump text
+ ("Layout & Input" keeps the & entity)."""
+ nodes = and_reach_settings()
+ if nodes is None:
+ return None
+ row = find_node(nodes, text=row_text)
+ if row is None:
+ row = scroll_into_view(row_text)
+ nodes = ui()
+ if row is None:
+ return None
+ and_enter(row_text) # backs depth 2
+ tap_node(row)
+ return ui()
+
+
+def ensure_visible(title):
+ """Scroll `title` into view inside the current fragment; return fresh nodes."""
+ n = find_node(ui(), text=title)
+ if n is None:
+ scroll_into_view(title)
+ return ui()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# STATE MACHINE 1 — Spell Check gates Pause-on-Misspelled-Word + Autocorrection
+# (SettingsActivity -> AutoCorrectionFragment, depth 2)
+# Observed: Spell Check checked=true, summary "Spell check enabled".
+# OFF -> "Pause on Misspelled Word" AND "Autocorrection" rows go enabled=false
+# (both title and switch); summary -> "Spell check disabled".
+# ON -> both dependents back to enabled=true.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_sm1_spellcheck_checked_summary",))
+def test_sm1_spellcheck_checked_and_summary():
+ """Spell Check: checked true->false PAIRED WITH summary flip. Restore ON."""
+ nm = "states_sm1_spellcheck_checked_summary"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Spell check enabled'->'Spell check disabled'")
+ return
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None:
+ record(nm, False, "feature_missing: no 'Spell Check' switch",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Spell check enabled'->'Spell check disabled'")
+ return
+ before_c = sw.get("checked")
+ before_s = summary_of(nodes, "Spell Check")
+ tap_node(sw)
+ fresh = ui()
+ after_c = (switch_for(fresh, "Spell Check") or {}).get("checked")
+ after_s = summary_of(fresh, "Spell Check")
+ ok = (before_c == "true" and after_c == "false"
+ and before_s == "Spell check enabled" and after_s == "Spell check disabled")
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: checked {before_c}->{after_c}, "
+ f"summary {before_s!r}->{after_s!r} (expected true->false / "
+ f"'Spell check enabled'->'Spell check disabled')",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Spell check enabled'->'Spell check disabled'")
+ # restore Spell Check ON
+ back = switch_for(ui(), "Spell Check")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm1_spellcheck_greyed_vlm",))
+def test_sm1_spellcheck_dependents_greyed_vlm():
+ """After Spell Check OFF, the two dependent rows render visibly greyed/dimmed.
+ Dump cannot show the greying colour -> VLM. Restore Spell Check ON."""
+ nm = "states_sm1_spellcheck_greyed"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm + "_vlm", False,
+ "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="none", tag="color")
+ return
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None or sw.get("checked") != "true":
+ record(nm + "_vlm", False,
+ "setup_failed: Spell Check not in expected ON start state",
+ depth=2, jump_kind="none", tag="color")
+ return
+ tap_node(sw) # turn OFF -> dependents grey out
+ ui()
+ vlm_assert(nm,
+ "In this settings list the 'Spell Check' row text is bright white. "
+ "Are the 'Pause on Misspelled Word' and 'Autocorrection' rows below "
+ "it rendered in a noticeably dimmer / greyed-out grey colour "
+ "(disabled appearance) compared to 'Spell Check'?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
+ # restore Spell Check ON
+ back = switch_for(ui(), "Spell Check")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm1_pause_enable_flip",))
+def test_sm1_pause_enable_flip():
+ """CONDITIONAL-ENABLE: Spell Check OFF -> 'Pause on Misspelled Word' row
+ enabled true->false. Restore Spell Check ON."""
+ nm = "states_sm1_pause_enable_flip"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="value", expect="false")
+ return
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None or find_node(nodes, text="Pause on Misspelled Word") is None:
+ record(nm, False, "feature_missing: Spell Check / Pause row not present",
+ depth=2, jump_kind="value", expect="false")
+ return
+ before_en = enabled_of(nodes, "Pause on Misspelled Word")
+ tap_node(sw) # Spell Check OFF
+ fresh = ui()
+ after_en = enabled_of(fresh, "Pause on Misspelled Word")
+ sw_en = (switch_for(fresh, "Pause on Misspelled Word") or {}).get("enabled")
+ ok = before_en == "true" and after_en == "false" and sw_en == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: Pause row enabled {before_en}->{after_en} "
+ f"(switch enabled={sw_en}); expected true->false when Spell Check off",
+ depth=2, jump_kind="value", expect="false")
+ back = switch_for(ui(), "Spell Check")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm1_autocorrection_enable_flip",))
+def test_sm1_autocorrection_enable_flip():
+ """CONDITIONAL-ENABLE: Spell Check OFF -> 'Autocorrection' row enabled
+ true->false. Restore Spell Check ON."""
+ nm = "states_sm1_autocorrection_enable_flip"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="value", expect="false")
+ return
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None or find_node(nodes, text="Autocorrection") is None:
+ record(nm, False, "feature_missing: Spell Check / Autocorrection row not present",
+ depth=2, jump_kind="value", expect="false")
+ return
+ before_en = enabled_of(nodes, "Autocorrection")
+ tap_node(sw) # Spell Check OFF
+ fresh = ui()
+ after_en = enabled_of(fresh, "Autocorrection")
+ sw_en = (switch_for(fresh, "Autocorrection") or {}).get("enabled")
+ ok = before_en == "true" and after_en == "false" and sw_en == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: Autocorrection row enabled "
+ f"{before_en}->{after_en} (switch enabled={sw_en}); expected true->false",
+ depth=2, jump_kind="value", expect="false")
+ back = switch_for(ui(), "Spell Check")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm1_reenable_restores",))
+def test_sm1_reenable_restores_dependents():
+ """CONDITIONAL-ENABLE recovery: Spell Check OFF then ON -> BOTH dependents
+ return to enabled=true. Leaves Spell Check ON (its natural end state)."""
+ nm = "states_sm1_reenable_restores"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="value", expect="true")
+ return
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None:
+ record(nm, False, "feature_missing: no 'Spell Check' switch",
+ depth=2, jump_kind="value", expect="true")
+ return
+ tap_node(sw) # OFF
+ off = ui()
+ off_pause = enabled_of(off, "Pause on Misspelled Word")
+ off_auto = enabled_of(off, "Autocorrection")
+ sw2 = switch_for(ui(), "Spell Check")
+ tap_node(sw2) # back ON
+ on = ui()
+ on_pause = enabled_of(on, "Pause on Misspelled Word")
+ on_auto = enabled_of(on, "Autocorrection")
+ ok = (off_pause == "false" and off_auto == "false"
+ and on_pause == "true" and on_auto == "true")
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: dependents off(pause={off_pause},"
+ f"auto={off_auto}) on(pause={on_pause},auto={on_auto}); expected "
+ f"false when off and true when re-enabled",
+ depth=2, jump_kind="value", expect="true")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# STATE MACHINE 2 — Show Number Row gates Show Number Hints
+# (SettingsActivity -> LayoutInputFragment, depth 2). Row text keeps &.
+# Observed: Show Number Row checked=true, summary "Number row shown";
+# Show Number Hints enabled=false while Number Row ON.
+# Number Row OFF -> Number Hints enabled=true, summary "Number row hidden".
+# Number Row ON -> Number Hints enabled=false.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_sm2_numberrow_checked_summary",))
+def test_sm2_numberrow_checked_and_summary():
+ """Show Number Row: checked true->false PAIRED WITH summary flip. Restore ON."""
+ nm = "states_sm2_numberrow_checked_summary"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Number row shown'->'Number row hidden'")
+ return
+ nodes = ensure_visible("Show Number Row")
+ sw = switch_for(nodes, "Show Number Row")
+ if sw is None:
+ record(nm, False, "feature_missing: no 'Show Number Row' switch",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Number row shown'->'Number row hidden'")
+ return
+ before_c = sw.get("checked")
+ before_s = summary_of(nodes, "Show Number Row")
+ tap_node(sw)
+ fresh = ui()
+ after_c = (switch_for(fresh, "Show Number Row") or {}).get("checked")
+ after_s = summary_of(fresh, "Show Number Row")
+ ok = (before_c == "true" and after_c == "false"
+ and before_s == "Number row shown" and after_s == "Number row hidden")
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: checked {before_c}->{after_c}, "
+ f"summary {before_s!r}->{after_s!r} (expected true->false / "
+ f"'Number row shown'->'Number row hidden')",
+ depth=2, jump_kind="transition",
+ expect="checked true->false; summary 'Number row shown'->'Number row hidden'")
+ back = switch_for(ui(), "Show Number Row")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm2_numberhints_enable_flip",))
+def test_sm2_numberhints_enable_flip():
+ """CONDITIONAL-ENABLE: Show Number Row OFF -> 'Show Number Hints' enabled
+ false->true. Restore Number Row ON."""
+ nm = "states_sm2_numberhints_enable_flip"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="value", expect="true")
+ return
+ nodes = ensure_visible("Show Number Hints")
+ sw = switch_for(nodes, "Show Number Row")
+ if sw is None or find_node(nodes, text="Show Number Hints") is None:
+ record(nm, False,
+ "feature_missing: Show Number Row / Show Number Hints not present",
+ depth=2, jump_kind="value", expect="true")
+ return
+ before_en = enabled_of(nodes, "Show Number Hints")
+ tap_node(sw) # Number Row OFF
+ fresh = ui()
+ after_en = enabled_of(fresh, "Show Number Hints")
+ sw_en = (switch_for(fresh, "Show Number Hints") or {}).get("enabled")
+ ok = before_en == "false" and after_en == "true" and sw_en == "true"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: Number Hints enabled {before_en}->{after_en} "
+ f"(switch enabled={sw_en}); expected false->true when Number Row off",
+ depth=2, jump_kind="value", expect="true")
+ back = switch_for(ui(), "Show Number Row")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+@and_test(expects=("states_sm2_numberhints_undimmed_vlm",))
+def test_sm2_numberhints_undimmed_vlm():
+ """After Number Row OFF, 'Show Number Hints' renders un-dimmed/active (was
+ greyed). Dump shows enabled bool, not the colour -> VLM. Restore Number Row ON."""
+ nm = "states_sm2_numberhints_undimmed"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="none", tag="color")
+ return
+ nodes = ensure_visible("Show Number Row")
+ sw = switch_for(nodes, "Show Number Row")
+ if sw is None or sw.get("checked") != "true":
+ record(nm + "_vlm", False,
+ "setup_failed: Show Number Row not in expected ON start state",
+ depth=2, jump_kind="none", tag="color")
+ return
+ tap_node(sw) # Number Row OFF -> Number Hints activates
+ ensure_visible("Show Number Hints")
+ vlm_assert(nm,
+ "Is the 'Show Number Hints' row text rendered in bright, active "
+ "white (the same brightness as the other enabled setting titles "
+ "on screen), i.e. NOT greyed-out or dimmed?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="color")
+ back = switch_for(ui(), "Show Number Row")
+ if back and back.get("checked") == "false":
+ tap_node(back)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Checked + summary-consequence single-switch flips across fragments.
+# Each: read checked+summary, tap, re-ui, assert checked flipped AND summary
+# became the exact observed off string, then RESTORE.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _checked_summary_case(nm, row_text, title, on_summary, off_summary,
+ start_checked="true"):
+ """Reusable: flip one switch, assert checked flip + exact summary flip, restore.
+ start_checked is the ORIGINAL checked value; the flip goes to its opposite."""
+ nodes = and_reach_fragment(row_text)
+ exp = (f"checked {start_checked}->{'false' if start_checked=='true' else 'true'}; "
+ f"summary {on_summary!r}->{off_summary!r}")
+ if nodes is None:
+ record(nm, False, f"setup_failed: could not reach {row_text}",
+ depth=2, jump_kind="transition", expect=exp)
+ return
+ nodes = ensure_visible(title)
+ sw = switch_for(nodes, title)
+ if sw is None:
+ record(nm, False, f"feature_missing: no {title!r} switch",
+ depth=2, jump_kind="transition", expect=exp)
+ return
+ before_c = sw.get("checked")
+ before_s = summary_of(nodes, title)
+ want_after_c = "false" if before_c == "true" else "true"
+ tap_node(sw)
+ fresh = ui()
+ after_c = (switch_for(fresh, title) or {}).get("checked")
+ after_s = summary_of(fresh, title)
+ # on/off strings map to whichever direction we flipped
+ exp_before_s = on_summary if before_c == "true" else off_summary
+ exp_after_s = off_summary if before_c == "true" else on_summary
+ ok = (after_c == want_after_c and before_c != after_c
+ and before_s == exp_before_s and after_s == exp_after_s)
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: {title} checked {before_c}->{after_c}, "
+ f"summary {before_s!r}->{after_s!r} (expected {exp_before_s!r}->{exp_after_s!r})",
+ depth=2, jump_kind="transition", expect=exp)
+ # restore to original checked
+ b = switch_for(ui(), title)
+ if b and b.get("checked") != before_c:
+ tap_node(b)
+
+
+@and_test(expects=("states_show_suggestions_summary",))
+def test_show_suggestions_summary():
+ _checked_summary_case("states_show_suggestions_summary", "Auto-Correct Settings",
+ "Show Suggestions", "Suggestions shown", "Suggestions hidden")
+
+
+@and_test(expects=("states_learn_new_words_summary",))
+def test_learn_new_words_summary():
+ _checked_summary_case("states_learn_new_words_summary", "Auto-Correct Settings",
+ "Learn New Words", "Learning enabled", "Learning disabled")
+
+
+@and_test(expects=("states_haptic_feedback_summary",))
+def test_haptic_feedback_summary():
+ _checked_summary_case("states_haptic_feedback_summary", "Typing Behavior Settings",
+ "Haptic Feedback", "Haptic enabled", "Haptic disabled")
+
+
+@and_test(expects=("states_swipe_typing_summary",))
+def test_swipe_typing_summary():
+ _checked_summary_case("states_swipe_typing_summary", "Typing Behavior Settings",
+ "Swipe Typing", "Swipe to type enabled",
+ "Swipe to type disabled")
+
+
+@and_test(expects=("states_auto_capitalization_summary",))
+def test_auto_capitalization_summary():
+ _checked_summary_case("states_auto_capitalization_summary",
+ "Typing Behavior Settings", "Auto-Capitalization",
+ "Capitalize at sentence start",
+ "No automatic capitalization")
+
+
+@and_test(expects=("states_spacebar_cursor_summary",))
+def test_spacebar_cursor_summary():
+ _checked_summary_case("states_spacebar_cursor_summary",
+ "Typing Behavior Settings", "Spacebar Cursor Control",
+ "Swipe spacebar to move cursor",
+ "Spacebar cursor control disabled")
+
+
+@and_test(expects=("states_double_space_period_summary",))
+def test_double_space_period_summary():
+ _checked_summary_case("states_double_space_period_summary",
+ "Typing Behavior Settings", "Double-Space Period",
+ "Double-space inserts period",
+ "Double-space inserts space")
+
+
+@and_test(expects=("states_one_handed_mode_summary",))
+def test_one_handed_mode_summary():
+ # ORIGINAL is OFF (checked=false, summary "Standard full-width keyboard").
+ _checked_summary_case("states_one_handed_mode_summary", "Layout & Input",
+ "One-Handed Mode", "Enabled",
+ "Standard full-width keyboard", start_checked="false")
+
+
+@and_test(expects=("states_lang_switch_key_summary",))
+def test_lang_switch_key_summary():
+ # ORIGINAL is OFF (checked=false, summary "Disabled").
+ _checked_summary_case("states_lang_switch_key_summary", "Layout & Input",
+ "Show Language Switch Key", "Enabled", "Disabled",
+ start_checked="false")
+
+
+@and_test(expects=("states_key_press_highlight_summary",))
+def test_key_press_highlight_summary():
+ _checked_summary_case("states_key_press_highlight_summary", "Appearance",
+ "Key Press Highlight", "Visual feedback shown",
+ "Visual feedback hidden")
+
+
+@and_test(expects=("states_clipboard_history_summary",))
+def test_clipboard_history_summary():
+ _checked_summary_case("states_clipboard_history_summary", "Privacy & Data",
+ "Clipboard History", "Clipboard history enabled",
+ "Clipboard history disabled")
+
+
+# ── A switch-in-ON shows the thumb right / coloured track vs OFF grey (VLM). ─────
+@and_test(expects=("states_switch_thumb_position_vlm",))
+def test_switch_thumb_position_vlm():
+ """A switch that is ON renders its thumb to the RIGHT on a coloured track.
+ Uses One-Handed Mode (originally OFF) turned ON so we know its state. The
+ dump gives the checked bool; the thumb POSITION is a rendered property -> VLM.
+ Restore One-Handed Mode OFF."""
+ nm = "states_switch_thumb_position"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="none", tag="position")
+ return
+ nodes = ensure_visible("One-Handed Mode")
+ sw = switch_for(nodes, "One-Handed Mode")
+ if sw is None or sw.get("checked") != "false":
+ record(nm + "_vlm", False,
+ "setup_failed: One-Handed Mode not in expected OFF start state",
+ depth=2, jump_kind="none", tag="position")
+ return
+ tap_node(sw) # turn ON -> thumb slides right
+ ensure_visible("One-Handed Mode")
+ vlm_assert(nm,
+ "Look at the toggle switch on the right of the 'One-Handed Mode' "
+ "row. Is its round thumb positioned at the RIGHT end of the track "
+ "(the ON position), rather than the left?",
+ RESULTS_DIR, depth=2, jump_kind="transition", tag="position")
+ b = switch_for(ui(), "One-Handed Mode")
+ if b and b.get("checked") == "true":
+ tap_node(b) # restore OFF
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Languages CheckBox selection + "Current layout" selected-state indicator
+# (SettingsActivity -> LanguagesFragment, depth 2)
+# Observed: English checked=true, summary "Current layout". Others checked=false.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_language_checkbox_select",))
+def test_language_checkbox_select():
+ """Check a currently-unchecked language (German): CheckBox checked false->true.
+ Then UNCHECK to restore."""
+ nm = "states_language_checkbox_select"
+ nodes = and_reach_fragment("Language Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Language Settings",
+ depth=2, jump_kind="transition", expect="checked false->true")
+ return
+ nodes = ensure_visible("German")
+ cb = checkbox_for(nodes, "German")
+ if cb is None:
+ record(nm, False, "feature_missing: no 'German' language checkbox",
+ depth=2, jump_kind="transition", expect="checked false->true")
+ return
+ before = cb.get("checked")
+ tap_node(cb)
+ fresh = ui()
+ after = (checkbox_for(fresh, "German") or {}).get("checked")
+ ok = before == "false" and after == "true"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: German checkbox {before}->{after} "
+ f"(expected false->true on selecting the language)",
+ depth=2, jump_kind="transition", expect="checked false->true")
+ # restore: uncheck German
+ b = checkbox_for(ui(), "German")
+ if b and b.get("checked") == "true":
+ tap_node(b)
+
+
+@and_test(expects=("states_english_current_layout_indicator",))
+def test_english_current_layout_indicator():
+ """The active language shows its selected state: English CheckBox checked=true
+ AND summary 'Current layout' (a state-consequence). Read-only, no mutation."""
+ nm = "states_english_current_layout_indicator"
+ nodes = and_reach_fragment("Language Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Language Settings",
+ depth=2, jump_kind="value", expect="checked true; summary 'Current layout'")
+ return
+ nodes = ensure_visible("English")
+ cb = checkbox_for(nodes, "English")
+ if cb is None:
+ record(nm, False, "feature_missing: no 'English' language row",
+ depth=2, jump_kind="value", expect="checked true; summary 'Current layout'")
+ return
+ checked = cb.get("checked")
+ summary = summary_of(nodes, "English")
+ ok = checked == "true" and summary == "Current layout"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: English checked={checked}, "
+ f"summary={summary!r} (expected true / 'Current layout')",
+ depth=2, jump_kind="value", expect="checked true; summary 'Current layout'")
+
+
+@and_test(expects=("states_english_selected_checkbox_vlm",))
+def test_english_selected_checkbox_vlm():
+ """The English (current) row renders a FILLED/checked checkbox while the other
+ language rows render EMPTY checkboxes. Filled-vs-empty is a rendered shape ->
+ VLM. Read-only."""
+ nm = "states_english_selected_checkbox"
+ nodes = and_reach_fragment("Language Settings")
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach Language Settings",
+ depth=2, jump_kind="none", tag="shape")
+ return
+ ensure_visible("English")
+ vlm_assert(nm,
+ "In this language list, the 'English' row is marked as the current "
+ "layout. Does the checkbox on the 'English' row appear CHECKED / "
+ "filled (a tick or filled box), while the checkboxes on the other "
+ "language rows appear empty / unchecked?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="shape")
+
+
+@and_test(expects=("states_merged_dictionaries_summary",))
+def test_merged_dictionaries_summary():
+ _checked_summary_case("states_merged_dictionaries_summary", "Language Settings",
+ "Merged Dictionaries",
+ "All language dictionaries used for suggestions",
+ "Only active layout language used for suggestions")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# CheckedTextView checked-state in the Suggestion Count ListPref dialog
+# (SettingsActivity -> AutoCorrectionFragment -> tap Suggestion Count, depth 2)
+# Observed: rows "1"/"2"/"3" (id text1); "3" checked=true, "1"/"2" checked=false.
+# We own the CheckedTextView CHECKED indicator (computation owns the summary value).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _open_suggestion_count_dialog():
+ """Reach AutoCorrect (depth 2) and open the Suggestion Count dialog. Returns
+ (dialog_nodes, opened_bool)."""
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ return None, False
+ sc = find_node(nodes, text="Suggestion Count")
+ if sc is None:
+ return None, False
+ tap_node(sc)
+ return ui(), True
+
+
+def _ctv_checked(nodes, value):
+ for n in nodes:
+ if "CheckedTextView" in n.get("class", "") and n.get("text") == value:
+ return n.get("checked")
+ return None
+
+
+@and_test(expects=("states_suggestion_count_ctv_checked",))
+def test_suggestion_count_ctv_checked_state():
+ """Open the Suggestion Count dialog: the current value '3' shows its
+ CheckedTextView checked=true while '1'/'2' are checked=false (the checked
+ indicator). Cancel to leave state untouched."""
+ nm = "states_suggestion_count_ctv_checked"
+ dlg, opened = _open_suggestion_count_dialog()
+ if not opened:
+ record(nm, False, "setup_failed: could not open Suggestion Count dialog",
+ depth=2, jump_kind="value", expect="'3' checked=true; '1'/'2' checked=false")
+ return
+ c3 = _ctv_checked(dlg, "3")
+ c1 = _ctv_checked(dlg, "1")
+ c2 = _ctv_checked(dlg, "2")
+ if c3 is None and c1 is None and c2 is None:
+ record(nm, False, "feature_missing: no CheckedTextView options in dialog",
+ depth=2, jump_kind="value", expect="'3' checked=true; '1'/'2' checked=false")
+ _cancel_dialog()
+ return
+ ok = c3 == "true" and c1 == "false" and c2 == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: CheckedTextView checked 1={c1} 2={c2} "
+ f"3={c3} (expected 3=true, 1/2=false)",
+ depth=2, jump_kind="value", expect="'3' checked=true; '1'/'2' checked=false")
+ _cancel_dialog()
+
+
+def _cancel_dialog():
+ c = find_node(ui(), text="Cancel")
+ if c:
+ tap_node(c)
+ else:
+ back()
+
+
+@and_test(expects=("states_suggestion_count_ctv_moves",))
+def test_suggestion_count_ctv_checked_moves():
+ """Selecting '1' MOVES the CheckedTextView checked indicator: reopen -> '1'
+ checked=true and '3' checked=false. RESTORE selection to '3'."""
+ nm = "states_suggestion_count_ctv_moves"
+ dlg, opened = _open_suggestion_count_dialog()
+ if not opened:
+ record(nm, False, "setup_failed: could not open Suggestion Count dialog",
+ depth=2, jump_kind="value", expect="'1' checked=true; '3' checked=false after picking 1")
+ return
+ one = None
+ for n in dlg:
+ if "CheckedTextView" in n.get("class", "") and n.get("text") == "1":
+ one = n
+ break
+ if one is None:
+ record(nm, False, "feature_missing: no '1' CheckedTextView option",
+ depth=2, jump_kind="value", expect="'1' checked=true; '3' checked=false after picking 1")
+ _cancel_dialog()
+ return
+ tap_node(one) # picks 1, dialog closes
+ # reopen to read the persisted checked indicator
+ dlg2, opened2 = _open_suggestion_count_dialog()
+ if not opened2:
+ record(nm, False, "setup_failed: could not reopen dialog to verify",
+ depth=2, jump_kind="value", expect="'1' checked=true; '3' checked=false after picking 1")
+ return
+ c1 = _ctv_checked(dlg2, "1")
+ c3 = _ctv_checked(dlg2, "3")
+ ok = c1 == "true" and c3 == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: after picking '1' the indicator shows "
+ f"1={c1} 3={c3} (expected 1=true, 3=false)",
+ depth=2, jump_kind="value", expect="'1' checked=true; '3' checked=false after picking 1")
+ # RESTORE to '3'
+ three = None
+ for n in dlg2:
+ if "CheckedTextView" in n.get("class", "") and n.get("text") == "3":
+ three = n
+ break
+ if three:
+ tap_node(three)
+ else:
+ _cancel_dialog()
+
+
+@and_test(expects=("states_suggestion_count_dialog_mark_vlm",))
+def test_suggestion_count_dialog_mark_vlm():
+ """The Suggestion Count dialog renders a radio/check MARK next to the selected
+ option '3'. The mark glyph is a rendered shape -> VLM. Cancel afterwards."""
+ nm = "states_suggestion_count_dialog_mark"
+ dlg, opened = _open_suggestion_count_dialog()
+ if not opened:
+ record(nm + "_vlm", False,
+ "setup_failed: could not open Suggestion Count dialog",
+ depth=2, jump_kind="none", tag="shape")
+ return
+ vlm_assert(nm,
+ "This is a single-choice dialog listing options 1, 2 and 3. Is "
+ "there a selection mark (a filled radio button or a check/tick) "
+ "shown next to exactly ONE option, indicating the currently "
+ "selected value?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="shape")
+ _cancel_dialog()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Theme selection selected-state indicator (VLM)
+# (SettingsActivity -> AppearanceFragment -> Theme -> ThemePickerActivity, depth 2)
+# Observed: the currently-selected 'Default' card shows a highlighted border +
+# checkmark; unselected cards (Light/Material You/Abyss) show only a heart.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_themepicker():
+ """SettingsActivity -> Appearance -> Theme -> ThemePickerActivity (depth 2).
+ Returns nodes on the ThemePicker, or None."""
+ nodes = and_reach_fragment("Appearance") # depth 2 (Settings->Appearance)
+ if nodes is None:
+ return None
+ th = find_node(nodes, text="Theme")
+ if th is None:
+ return None
+ # opening the ThemePicker is a deeper surface but we cap the declared depth at 2
+ if not and_reach_surface(th, "Keyboard Theme", "Theme"):
+ tap_node(th)
+ return ui()
+
+
+@and_test(expects=("states_theme_selected_checkmark_vlm",))
+def test_theme_selected_checkmark_vlm():
+ """The selected theme card ('Default') renders a highlighted border AND a
+ checkmark distinguishing it from unselected cards (which show only a heart).
+ The checkmark/border is a rendered shape -> VLM. Read-only (no theme change)."""
+ nm = "states_theme_selected_checkmark"
+ nodes = and_reach_themepicker()
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach ThemePicker",
+ depth=2, jump_kind="none", tag="shape")
+ return
+ if not any(n.get("content-desc", "").endswith(" theme") for n in nodes):
+ record(nm + "_vlm", False, "setup_failed: no theme cards visible",
+ depth=2, jump_kind="none", tag="shape")
+ return
+ vlm_assert(nm,
+ "This is a keyboard theme picker showing several theme preview "
+ "cards. Does the currently-selected theme card at the top have a "
+ "distinct highlighted/coloured BORDER and a checkmark (tick), "
+ "which the other theme cards below it do NOT have?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="shape")
+
+
+@and_test(expects=("states_theme_color_distinct_vlm",))
+def test_theme_color_distinct_vlm():
+ """Theme preview cards render in DISTINCT colours (e.g. a light/white 'Light'
+ card vs a dark 'Default'/'Abyss' card). The colour is only in the render ->
+ VLM. Read-only."""
+ nm = "states_theme_color_distinct"
+ nodes = and_reach_themepicker()
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach ThemePicker",
+ depth=2, jump_kind="none", tag="color")
+ return
+ if not any(n.get("content-desc", "").endswith(" theme") for n in nodes):
+ record(nm + "_vlm", False, "setup_failed: no theme cards visible",
+ depth=2, jump_kind="none", tag="color")
+ return
+ vlm_assert(nm,
+ "Among these keyboard theme preview cards, is there at least one "
+ "card with a predominantly LIGHT/white keyboard background and at "
+ "least one card with a predominantly DARK/black keyboard "
+ "background (i.e. the themes are rendered in clearly different "
+ "colours)?",
+ RESULTS_DIR, depth=2, jump_kind="value", tag="color")
+
+
+# ── Selected-state colour rendering: the launcher preview card reflects the ──────
+# currently-selected theme ('Default' = dark bluish keys with cream/tan labels).
+# The colour is only in the render; the dump only carries the "Default" label text.
+@and_test(expects=("states_main_preview_selected_theme_color_vlm",))
+def test_main_preview_selected_theme_color_vlm():
+ """On the launcher, the keyboard preview card is drawn in the currently-selected
+ theme's colours (the 'Default' theme: a dark bluish keyboard with light
+ cream/tan key labels). Selected-theme colour rendering -> VLM. Read-only."""
+ nm = "states_main_preview_selected_theme_color"
+ restart_app()
+ if not wait_for_foreground():
+ record(nm + "_vlm", False, "setup_failed: launcher did not come to foreground",
+ depth=0, jump_kind="none", tag="color")
+ return
+ nodes = ui()
+ if find_node(nodes, text="Default") is None:
+ record(nm + "_vlm", False,
+ "setup_failed: no 'Default' theme label on the launcher preview",
+ depth=0, jump_kind="none", tag="color")
+ return
+ vlm_assert(nm,
+ "This screen shows a keyboard preview card labelled 'Default'. Is "
+ "the preview keyboard drawn with a DARK (dark blue / near-black) key "
+ "background and LIGHT (cream / pale) key letters, matching a dark "
+ "theme?",
+ RESULTS_DIR, depth=0, jump_kind="value", tag="color")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SETTINGS persistence across process death (sole owner). Toggle a switch, kill
+# the process, relaunch, renavigate, assert still flipped, then RESTORE.
+# Uses Swipe Typing + Merged Dictionaries — DIFFERENT from the switches the
+# interaction lane persists (Haptic Feedback, Key Press Highlight, Suggestion Count).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("states_persist_swipe_typing",))
+def test_persist_swipe_typing_across_restart():
+ """Swipe Typing OFF -> force-stop + relaunch -> renavigate -> still checked=false.
+ Restore ON."""
+ nm = "states_persist_swipe_typing"
+ nodes = and_reach_fragment("Typing Behavior Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Typing Behavior Settings",
+ depth=2, jump_kind="value", expect="false")
+ return
+ nodes = ensure_visible("Swipe Typing")
+ sw = switch_for(nodes, "Swipe Typing")
+ if sw is None:
+ record(nm, False, "feature_missing: no 'Swipe Typing' switch",
+ depth=2, jump_kind="value", expect="false")
+ return
+ if sw.get("checked") != "true":
+ # normalise to ON first so the OFF flip is meaningful
+ tap_node(sw)
+ sw = switch_for(ui(), "Swipe Typing")
+ tap_node(sw) # -> OFF
+ off_now = (switch_for(ui(), "Swipe Typing") or {}).get("checked")
+ # kill + relaunch, then renavigate FORWARD
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ renav = and_reach_fragment("Typing Behavior Settings")
+ if renav is None:
+ record(nm, False, "setup_failed: could not renavigate after relaunch",
+ depth=2, jump_kind="value", expect="false")
+ return
+ renav = ensure_visible("Swipe Typing")
+ persisted = (switch_for(renav, "Swipe Typing") or {}).get("checked")
+ ok = off_now == "false" and persisted == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: Swipe Typing was {off_now} before "
+ f"restart, {persisted} after (expected false to persist across process death)",
+ depth=2, jump_kind="value", expect="false")
+ # restore ON
+ b = switch_for(ui(), "Swipe Typing")
+ if b and b.get("checked") == "false":
+ tap_node(b)
+
+
+@and_test(expects=("states_persist_merged_dictionaries",))
+def test_persist_merged_dictionaries_across_restart():
+ """Merged Dictionaries OFF -> force-stop + relaunch -> renavigate -> still
+ checked=false. Restore ON."""
+ nm = "states_persist_merged_dictionaries"
+ nodes = and_reach_fragment("Language Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Language Settings",
+ depth=2, jump_kind="value", expect="false")
+ return
+ sw = switch_for(nodes, "Merged Dictionaries")
+ if sw is None:
+ record(nm, False, "feature_missing: no 'Merged Dictionaries' switch",
+ depth=2, jump_kind="value", expect="false")
+ return
+ if sw.get("checked") != "true":
+ tap_node(sw)
+ sw = switch_for(ui(), "Merged Dictionaries")
+ tap_node(sw) # -> OFF
+ off_now = (switch_for(ui(), "Merged Dictionaries") or {}).get("checked")
+ force_stop_and_relaunch()
+ wait_for_foreground()
+ renav = and_reach_fragment("Language Settings")
+ if renav is None:
+ record(nm, False, "setup_failed: could not renavigate after relaunch",
+ depth=2, jump_kind="value", expect="false")
+ return
+ persisted = (switch_for(renav, "Merged Dictionaries") or {}).get("checked")
+ ok = off_now == "false" and persisted == "false"
+ record(nm, ok,
+ "" if ok else f"behavior_wrong: Merged Dictionaries was {off_now} before "
+ f"restart, {persisted} after (expected false to persist)",
+ depth=2, jump_kind="value", expect="false")
+ b = switch_for(ui(), "Merged Dictionaries")
+ if b and b.get("checked") == "false":
+ tap_node(b)
+
+
+# ── Registry ────────────────────────────────────────────────────────────────────
+TESTS = [
+ # State machine 1 — Spell Check gates two dependents (4 + 1 vlm)
+ test_sm1_spellcheck_checked_and_summary,
+ test_sm1_pause_enable_flip,
+ test_sm1_autocorrection_enable_flip,
+ test_sm1_reenable_restores_dependents,
+ test_sm1_spellcheck_dependents_greyed_vlm,
+ # State machine 2 — Number Row gates Number Hints (2 + 1 vlm)
+ test_sm2_numberrow_checked_and_summary,
+ test_sm2_numberhints_enable_flip,
+ test_sm2_numberhints_undimmed_vlm,
+ # Checked + summary-consequence single-switch flips
+ test_show_suggestions_summary,
+ test_learn_new_words_summary,
+ test_haptic_feedback_summary,
+ test_swipe_typing_summary,
+ test_auto_capitalization_summary,
+ test_spacebar_cursor_summary,
+ test_double_space_period_summary,
+ test_one_handed_mode_summary,
+ test_lang_switch_key_summary,
+ test_key_press_highlight_summary,
+ test_clipboard_history_summary,
+ test_switch_thumb_position_vlm,
+ # Languages CheckBox select/deselect + current-layout indicator (+ vlm)
+ test_language_checkbox_select,
+ test_english_current_layout_indicator,
+ test_merged_dictionaries_summary,
+ test_english_selected_checkbox_vlm,
+ # CheckedTextView dialog checked-state (+ vlm)
+ test_suggestion_count_ctv_checked_state,
+ test_suggestion_count_ctv_checked_moves,
+ test_suggestion_count_dialog_mark_vlm,
+ # Theme selected-state (vlm x2)
+ test_theme_selected_checkmark_vlm,
+ test_theme_color_distinct_vlm,
+ test_main_preview_selected_theme_color_vlm,
+ # Settings persistence across process death
+ test_persist_swipe_typing_across_restart,
+ test_persist_merged_dictionaries_across_restart,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/urikdev-urik/tests/test_android_structure.py b/android/urikdev-urik/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb9a73c1d6d924e4e644ca4ca46f72a6bd63d8fb
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_structure.py
@@ -0,0 +1,398 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — Urik Keyboard.
+
+Owns the GATE (app launches with its top-level surfaces present) and tree-SHAPE
+deltas (an interaction changes the view tree's shape: a RecyclerView appears, a
+dialog/sheet subtree is added, a rendered keyboard grid appears). SHAPE ONLY —
+never content strings, checked/enabled/selected state, focus, or reachability.
+
+Every observed count below was confirmed on the running original app:
+ S0 launcher : FAB + 3 named Buttons (Enable/Open Settings/About) + CardView
+ preview card holding ~14 rendered key Buttons; container is
+ LinearLayout/FrameLayout (this app has NO ViewGroup / no Compose).
+ Settings : RecyclerView of 8 preference rows; the 3 launcher buttons gone.
+ AutoCorrect : 5 Switch rows + a bottom test_field EditText.
+ Sugg. dialog: adds 3 CheckedTextView (a new AlertDialog window layer).
+ Features : bottom-sheet subtree of 14 TextViews (7 tip title/desc pairs).
+ ThemePicker : RecyclerView of theme cards (6 FrameLayout content-desc "* theme"
+ visible; recycles, so we assert >3).
+ LayoutMapper: 40 rendered Buttons (number row + QWERTY rows + Reset All).
+ Typing : 7 Switch rows and, after scrolling, a SeekBar (id seekbar).
+ Languages : 12 CheckBox children (assert >=5).
+"""
+import os, sys
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403
+
+
+# ── local navigation helpers (depth-family: name backs a declared depth>=1) ──
+def and_enter_settings():
+ """S0 -> SettingsActivity. Returns (ok, nodes_after)."""
+ tap_text(ui(), "Open Settings")
+ nodes = ui()
+ ok = find_by_class(nodes, "RecyclerView") and find_node(nodes, text="Auto-Correct Settings")
+ if ok:
+ and_enter("settings")
+ return bool(ok), nodes
+
+
+def and_enter_autocorrect():
+ """S0 -> Settings -> AutoCorrectionFragment. Returns (ok, nodes_after)."""
+ ok, _ = and_enter_settings()
+ if not ok:
+ return False, []
+ tap_text(ui(), "Auto-Correct Settings")
+ nodes = ui()
+ ok2 = node_by_id(nodes, "test_field") or find_node(nodes, text="Spell Check")
+ if ok2:
+ and_enter("autocorrect")
+ return bool(ok2), nodes
+
+
+def and_enter_fragment(row_text):
+ """S0 -> Settings -> a settings sub-fragment reached by row_text.
+ Returns (ok, nodes_after). row_text is matched literally (heed '&')."""
+ ok, _ = and_enter_settings()
+ if not ok:
+ return False, []
+ row = find_node(ui(), text=row_text)
+ if not row:
+ return False, []
+ tap_node(row)
+ and_enter(row_text)
+ return True, ui()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE — the app launches and its top-level surfaces exist (depth 0, none)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch",))
+def test_gate_launch():
+ restart_app()
+ fg = wait_for_foreground()
+ nodes = ui()
+ container = find_by_class(nodes, "FrameLayout") and find_by_class(nodes, "LinearLayout")
+ ok = fg and bool(container)
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach the foreground with a top-level container",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_gate_s0_surfaces", "structure_gate_s0_surfaces_vlm"))
+def test_gate_s0_surfaces():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ fab = len(find_by_class(nodes, "FloatingActionButton")) >= 1
+ named = sum(1 for t in ("Enable", "Open Settings", "About")
+ if find_node(nodes, text=t) is not None)
+ card = len(find_by_class(nodes, "CardView")) >= 1
+ ok = fab and named >= 3 and card
+ record("structure_gate_s0_surfaces", ok,
+ "" if ok else f"feature_missing: S0 top-level surfaces absent "
+ f"(fab={fab} named_buttons={named}/3 card={card})",
+ depth=0, jump_kind="none")
+ vlm_assert("structure_gate_s0_surfaces",
+ "Is the app logo/icon near the top-center of the screen with a "
+ "vertical stack of full-width action buttons positioned at the "
+ "bottom of the screen?",
+ RESULTS_DIR, tag="position")
+
+
+@and_test(expects=("structure_gate_preview_card", "structure_gate_preview_card_vlm"))
+def test_gate_preview_card():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ # The preview card renders a mini keyboard: many Buttons that are neither the
+ # info FAB nor the three named action buttons.
+ action = {"Enable", "Open Settings", "About"}
+ preview = [n for n in find_by_class(nodes, "Button")
+ if "FloatingActionButton" not in n.get("class", "")
+ and n.get("text", "") not in action]
+ ok = len(preview) >= 8
+ record("structure_gate_preview_card", ok,
+ "" if ok else f"feature_missing: keyboard-preview card has too few rendered "
+ f"key buttons ({len(preview)})",
+ depth=0, jump_kind="none")
+ vlm_assert("structure_gate_preview_card",
+ "Is there a keyboard preview showing letter keys (like Z X C V B N M) "
+ "arranged in horizontal rows like a keyboard?",
+ RESULTS_DIR, tag="shape")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SHAPE DELTAS — a trigger changes the tree's shape (transition; reversed)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_settings_shape", "structure_settings_shape_vlm"))
+def test_settings_shape():
+ restart_app()
+ wait_for_foreground()
+ before_nodes = ui()
+ before_rv = len(find_by_class(before_nodes, "RecyclerView"))
+ before_btn = len(find_by_class(before_nodes, "Button"))
+ ok_nav, after_nodes = and_enter_settings()
+ after_rv = len(find_by_class(after_nodes, "RecyclerView"))
+ after_rows = sum(1 for n in after_nodes
+ if n.get("resource-id", "").endswith("title") and n.get("text", "").strip())
+ after_btn = len(find_by_class(after_nodes, "Button"))
+ # SHAPE delta: a preference RecyclerView with many rows appears; the launcher's
+ # 3 named action buttons + preview grid collapse away.
+ appeared = before_rv == 0 and after_rv >= 1 and after_rows >= 6
+ collapsed = after_btn < before_btn
+ # Capture the VLM screenshot NOW, while the Settings list is on screen — before
+ # reversing the transition, or the shot would be of S0 again.
+ vlm_assert("structure_settings_shape",
+ "Is this a settings screen showing a vertical list of text rows "
+ "stacked top to bottom, each row a bold title with a smaller grey "
+ "subtitle beneath it?",
+ RESULTS_DIR, tag="layout")
+ # reverse: back to S0 -> RecyclerView gone, launcher buttons return.
+ restart_app()
+ wait_for_foreground()
+ restored = len(find_by_class(ui(), "RecyclerView")) == 0
+ ok = ok_nav and appeared and collapsed and restored
+ record("structure_settings_shape", ok,
+ "" if ok else f"behavior_wrong: Settings shape delta wrong "
+ f"(rv {before_rv}->{after_rv}, rows={after_rows}, "
+ f"btn {before_btn}->{after_btn}, restored={restored})",
+ depth=1, jump_kind="transition",
+ expect="RecyclerView 0->1 with >=6 preference rows on Settings; "
+ "launcher buttons collapse; restored to 0 RecyclerView on relaunch")
+
+
+@and_test(expects=("structure_autocorrect_shape", "structure_autocorrect_shape_vlm"))
+def test_autocorrect_shape():
+ restart_app()
+ wait_for_foreground()
+ ok_nav, nodes = and_enter_autocorrect()
+ n_switch = len(find_by_class(nodes, "Switch"))
+ has_field = node_by_id(nodes, "test_field") is not None
+ # SHAPE: a preference list composed of several Switch rows plus a bottom
+ # EditText (the "Test changes" field) — a composition absent from S0/Settings.
+ ok = ok_nav and n_switch >= 4 and has_field
+ record("structure_autocorrect_shape", ok,
+ "" if ok else f"behavior_wrong: AutoCorrect shape wrong "
+ f"(switches={n_switch} expected>=4, test_field={has_field})",
+ depth=2, jump_kind="transition",
+ expect="AutoCorrect list has >=4 Switch rows and a bottom test_field EditText")
+ # Not "every" row has a switch (Suggestion Count does not), so ask about the
+ # switches that ARE present being aligned on the right edge — a position fact.
+ vlm_assert("structure_autocorrect_shape",
+ "Are there several toggle switches on this screen, each aligned "
+ "against the right edge of its row?",
+ RESULTS_DIR, tag="position")
+
+
+@and_test(expects=("structure_suggestion_dialog_shape",))
+def test_suggestion_dialog_shape():
+ restart_app()
+ wait_for_foreground()
+ ok_nav, nodes = and_enter_autocorrect()
+ if not ok_nav:
+ record("structure_suggestion_dialog_shape", False,
+ "setup_failed: could not reach AutoCorrect fragment",
+ depth=2, jump_kind="transition",
+ expect="Suggestion Count dialog adds >=3 CheckedTextView; 0 when dismissed")
+ return
+ before = len(find_by_class(nodes, "CheckedTextView"))
+ tap_text(nodes, "Suggestion Count")
+ after_nodes = ui()
+ after = len(find_by_class(after_nodes, "CheckedTextView"))
+ has_cancel = find_node_ci(after_nodes, "Cancel") is not None
+ # SHAPE: a dialog subtree (list of CheckedTextView options + Cancel) is added.
+ appeared = before == 0 and after >= 3 and has_cancel
+ # reverse: dismiss the dialog -> CheckedTextView subtree gone.
+ back()
+ restored = len(find_by_class(ui(), "CheckedTextView")) == 0
+ ok = appeared and restored
+ record("structure_suggestion_dialog_shape", ok,
+ "" if ok else f"behavior_wrong: dialog shape delta wrong "
+ f"(CheckedTextView {before}->{after}, cancel={has_cancel}, "
+ f"restored={restored})",
+ depth=2, jump_kind="transition",
+ expect="Suggestion Count dialog adds CheckedTextView 0->3 (+Cancel), "
+ "restored to 0 on dismiss")
+
+
+@and_test(expects=("structure_features_sheet_shape", "structure_features_sheet_shape_vlm"))
+def test_features_sheet_shape():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ before_tv = sum(1 for n in find_by_class(nodes, "TextView") if n.get("text", "").strip())
+ fabs = find_by_class(nodes, "FloatingActionButton")
+ if not fabs:
+ record("structure_features_sheet_shape", False,
+ "feature_missing: info FAB not found on S0",
+ depth=1, jump_kind="transition",
+ expect="Features bottom sheet adds many TextViews (tip pairs)")
+ else:
+ before = and_showing(nodes)
+ tap_node(fabs[0])
+ and_enter("features_sheet")
+ after_nodes = ui()
+ after = and_showing(after_nodes)
+ after_tv = sum(1 for n in find_by_class(after_nodes, "TextView") if n.get("text", "").strip())
+ # SHAPE: a bottom-sheet subtree with many stacked TextViews is added.
+ ok = surface_changed(before, after) and after_tv >= before_tv + 8
+ record("structure_features_sheet_shape", ok,
+ "" if ok else f"behavior_wrong: Features sheet shape delta too small "
+ f"(TextViews {before_tv}->{after_tv})",
+ depth=1, jump_kind="transition",
+ expect="Features bottom sheet adds >=8 TextViews over S0's 2")
+ vlm_assert("structure_features_sheet_shape",
+ "Is a panel showing a vertical stacked list of feature tips, each "
+ "with a bold title and a description line beneath it?",
+ RESULTS_DIR, tag="layout")
+
+
+@and_test(expects=("structure_themepicker_shape", "structure_themepicker_shape_vlm"))
+def test_themepicker_shape():
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ before_rv = len(find_by_class(nodes, "RecyclerView"))
+ # The theme-name label under the preview card opens ThemePicker; its text is
+ # the current theme (state-dependent), so locate it as the tappable TextView
+ # sitting just below the preview CardView rather than by a fixed string.
+ card = find_by_class(nodes, "CardView")
+ theme_label = None
+ if card:
+ cy2 = card[0]["_bounds"][3]
+ cands = [n for n in find_by_class(nodes, "TextView")
+ if n.get("text", "").strip() and n.get("text", "") != "Urik Keyboard"
+ and n.get("_bounds", (0, 0, 0, 0))[1] >= cy2 - 120]
+ theme_label = cands[0] if cands else None
+ if not theme_label:
+ record("structure_themepicker_shape", False,
+ "setup_failed: theme-name label under the preview card not found",
+ depth=1, jump_kind="transition",
+ expect="ThemePicker RecyclerView shows >3 theme-card children")
+ else:
+ tap_node(theme_label)
+ and_enter("themepicker")
+ after_nodes = ui()
+ after_rv = len(find_by_class(after_nodes, "RecyclerView"))
+ cards = [n for n in after_nodes
+ if "theme" in n.get("content-desc", "").lower()
+ and "FrameLayout" in n.get("class", "")]
+ # SHAPE: a RecyclerView whose children are theme cards (child count > 3).
+ ok = before_rv == 0 and after_rv >= 1 and len(cards) > 3
+ record("structure_themepicker_shape", ok,
+ "" if ok else f"behavior_wrong: ThemePicker shape wrong "
+ f"(rv {before_rv}->{after_rv}, theme cards={len(cards)})",
+ depth=1, jump_kind="transition",
+ expect="ThemePicker adds a RecyclerView with >3 theme-card FrameLayouts")
+ vlm_assert("structure_themepicker_shape",
+ "Is this a scrollable vertical list of keyboard-theme preview cards, "
+ "each card showing a small keyboard rendering?",
+ RESULTS_DIR, tag="layout")
+
+
+@and_test(expects=("structure_layoutmapper_shape", "structure_layoutmapper_shape_vlm"))
+def test_layoutmapper_shape():
+ restart_app()
+ wait_for_foreground()
+ ok_nav, nodes = and_enter_fragment("Layout & Input")
+ if not ok_nav:
+ record("structure_layoutmapper_shape", False,
+ "setup_failed: could not reach Layout & Input fragment",
+ depth=3, jump_kind="transition",
+ expect="LayoutMapper renders a full QWERTY grid of >=30 Button keys")
+ else:
+ ck = find_node(nodes, text="Customize Keys")
+ before_btn = len(find_by_class(nodes, "Button"))
+ if not ck:
+ record("structure_layoutmapper_shape", False,
+ "feature_missing: Customize Keys row not found",
+ depth=3, jump_kind="transition",
+ expect="LayoutMapper renders a full QWERTY grid of >=30 Button keys")
+ else:
+ tap_node(ck)
+ and_enter("layoutmapper")
+ after_nodes = ui()
+ after_btn = len(find_by_class(after_nodes, "Button"))
+ # SHAPE: a rendered full keyboard — many Button children in rows.
+ ok = after_btn >= 30 and after_btn > before_btn
+ record("structure_layoutmapper_shape", ok,
+ "" if ok else f"behavior_wrong: LayoutMapper key grid too small "
+ f"(buttons {before_btn}->{after_btn}, expected >=30)",
+ depth=3, jump_kind="transition",
+ expect="LayoutMapper renders >=30 Button keys (number row + QWERTY)")
+ vlm_assert("structure_layoutmapper_shape",
+ "Is a full QWERTY keyboard rendered as multiple horizontal rows of "
+ "square keys (a number row on top, then letter rows)?",
+ RESULTS_DIR, tag="shape")
+
+
+@and_test(expects=("structure_typing_seekbar_shape",))
+def test_typing_seekbar_shape():
+ restart_app()
+ wait_for_foreground()
+ ok_nav, nodes = and_enter_fragment("Typing Behavior Settings")
+ if not ok_nav:
+ record("structure_typing_seekbar_shape", False,
+ "setup_failed: could not reach Typing Behavior fragment",
+ depth=2, jump_kind="transition",
+ expect="Typing Behavior list contains a SeekBar among many Switch rows")
+ return
+ n_switch = len(find_by_class(nodes, "Switch"))
+ # The Vibration Strength SeekBar sits near the bottom; scroll it into view.
+ scroll_into_view("Vibration Strength", max_swipes=5)
+ after_nodes = ui()
+ has_seekbar = (len(find_by_class(after_nodes, "SeekBar")) >= 1
+ or node_by_id(after_nodes, "seekbar") is not None)
+ # SHAPE: this fragment's composition uniquely includes a SeekBar widget class
+ # alongside its several Switch rows (other fragments have none).
+ ok = n_switch >= 4 and has_seekbar
+ record("structure_typing_seekbar_shape", ok,
+ "" if ok else f"behavior_wrong: Typing Behavior shape wrong "
+ f"(switches={n_switch}, seekbar_present={has_seekbar})",
+ depth=2, jump_kind="transition",
+ expect="Typing Behavior has >=4 Switch rows and a SeekBar widget")
+
+
+@and_test(expects=("structure_languages_shape", "structure_languages_shape_vlm"))
+def test_languages_shape():
+ restart_app()
+ wait_for_foreground()
+ ok_nav, nodes = and_enter_fragment("Language Settings")
+ if not ok_nav:
+ record("structure_languages_shape", False,
+ "setup_failed: could not reach Language Settings fragment",
+ depth=2, jump_kind="transition",
+ expect="Languages fragment shows a list of >=5 CheckBox children")
+ else:
+ n_checkbox = len(find_by_class(nodes, "CheckBox"))
+ # SHAPE: a list whose children are language CheckBoxes (>=5).
+ ok = n_checkbox >= 5
+ record("structure_languages_shape", ok,
+ "" if ok else f"behavior_wrong: too few language CheckBoxes "
+ f"({n_checkbox}, expected >=5)",
+ depth=2, jump_kind="transition",
+ expect="Languages fragment shows >=5 CheckBox children")
+ vlm_assert("structure_languages_shape",
+ "Does this screen show a vertical scrollable list of language rows, "
+ "each row having a checkbox?",
+ RESULTS_DIR, tag="layout")
+
+
+TESTS = [
+ test_gate_launch,
+ test_gate_s0_surfaces,
+ test_gate_preview_card,
+ test_settings_shape,
+ test_autocorrect_shape,
+ test_suggestion_dialog_shape,
+ test_features_sheet_shape,
+ test_themepicker_shape,
+ test_layoutmapper_shape,
+ test_typing_seekbar_shape,
+ test_languages_shape,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "structure")
diff --git a/android/urikdev-urik/tests/test_android_text.py b/android/urikdev-urik/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd1847be662614dead8ccc51a84b4ac6ad9872fe
--- /dev/null
+++ b/android/urikdev-urik/tests/test_android_text.py
@@ -0,0 +1,710 @@
+#!/usr/bin/env python3
+"""TEXT lane — Urik Keyboard (com.urik.keyboard).
+
+Owns CONTENT / OUTPUT text and exact-string equality: screen/toolbar titles that
+change with the surface you reach, preference SUMMARY strings a row shows, the
+summary an ACTION produces (Spell Check toggle -> "Spell check disabled"),
+static tip strings on the Features sheet, content-desc content on theme cards,
+and the About info block (a genuinely-rendered TextView -> the two VLM records).
+
+Every string below was OBSERVED live on the running ORIGINAL before it was
+asserted; nothing is copied from the source tree. Titles/summaries are matched
+by their EXACT dump text -- the uiautomator dump does NOT unescape '&', so the
+"Layout & Input" row carries literal text "Layout & Input" and is matched
+that way (find_node_ci would fail on it).
+
+VLM budget: exactly 2 records, both on the About info block (a rendered text
+block) -- one asks the block is present, one asks the Copyright line is rendered
+in the observed colour. A separate RULE test asserts the exact About substrings.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── Locator helpers (inlined; the kit is never edited/reimplemented) ─────────────
+
+def all_text(nodes):
+ """All non-empty visible text joined -- for a fast "contains" check."""
+ return " | ".join(n.get("text", "") for n in nodes if n.get("text"))
+
+
+def toolbar_title(nodes):
+ """The activity toolbar title: the topmost non-empty TextView that is NOT a
+ preference title/summary. Toolbar titles sit near the top of the screen."""
+ best, besty = None, 10 ** 9
+ for n in nodes:
+ if "TextView" not in n.get("class", ""):
+ continue
+ t = n.get("text", "")
+ if not t:
+ continue
+ rid = n.get("resource-id", "").rsplit("/", 1)[-1]
+ if rid in ("title", "summary"):
+ continue
+ b = n.get("_bounds")
+ if not b or b[1] >= 500: # toolbar lives in the top strip
+ continue
+ if b[1] < besty:
+ best, besty = n, b[1]
+ return best.get("text") if best else None
+
+
+def summary_of(nodes, title):
+ """The summary TextView (id .../summary) directly below the row whose title
+ TextView text == `title`. Summaries sit just under their title, same column."""
+ tn = find_node(nodes, text=title)
+ if not tn or "_center" not in tn:
+ return None
+ tx, ty = tn["_center"]
+ best, bestdy = None, 10 ** 9
+ for n in nodes:
+ if (n.get("resource-id", "").endswith("summary") and n.get("text")
+ and "_center" in n):
+ cx, cy = n["_center"]
+ dy = cy - ty
+ if 0 < dy < 200 and abs(cx - tx) < 400 and dy < bestdy:
+ best, bestdy = n, dy
+ return best.get("text") if best else None
+
+
+def switch_for(nodes, title):
+ """The Switch belonging to the preference row whose title TextView == `title`.
+ ALL switches share id .../switchWidget, so pick the one nearest the title."""
+ tn = find_node(nodes, text=title)
+ if not tn or "_center" not in tn:
+ return None
+ ty = tn["_center"][1]
+ cands = [n for n in nodes if "Switch" in n.get("class", "")
+ and n.get("resource-id", "").endswith("switchWidget")
+ and "_center" in n]
+ return min(cands, key=lambda n: abs(n["_center"][1] - ty)) if cands else None
+
+
+def desc_present(nodes, needle):
+ """True iff some node's content-desc contains `needle` (case-sensitive)."""
+ return any(needle in n.get("content-desc", "") for n in nodes)
+
+
+# ── Reach helpers (named and_reach_*/and_enter_* so the depth audit counts them) ──
+
+def and_reach_settings():
+ """Launcher -> Open Settings (depth 1). Returns nodes on the Settings list."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ btn = find_node(nodes, text="Open Settings")
+ if btn is None:
+ return None
+ if not and_reach_surface(btn, "Keyboard Settings", "Open Settings"):
+ and_enter("Settings") # backs depth 1 even if the reach probe missed
+ return ui()
+
+
+def and_reach_about():
+ """Launcher -> About button -> AboutActivity (depth 1). Returns About nodes."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ btn = find_node(nodes, text="About") or find_node_ci(nodes, "About")
+ if btn is None:
+ return None
+ if not and_reach_surface(btn, "About", "Open Settings"):
+ and_enter("About")
+ return ui()
+
+
+def and_reach_features_sheet():
+ """Launcher -> top-right info FAB -> Features bottom sheet (depth 1)."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ fabs = find_by_class(nodes, "FloatingActionButton")
+ if not fabs:
+ return None
+ and_enter("Features") # backs depth 1
+ tap_node(fabs[0])
+ return ui()
+
+
+def and_reach_themepicker_from_card():
+ """Launcher -> tap the preview theme-name text -> ThemePicker (depth 1)."""
+ restart_app()
+ wait_for_foreground()
+ nodes = ui()
+ card = find_node(nodes, text="Default") # theme-name TextView under the preview
+ if card is None:
+ return None
+ if not and_reach_surface(card, "Keyboard Theme", "Open Settings"):
+ and_enter("ThemePicker")
+ return ui()
+
+
+def and_reach_fragment(row_text):
+ """Launcher -> Open Settings -> tap a settings row (depth 2). `row_text` is the
+ EXACT dump text ("Layout & Input" keeps the & entity). Returns fragment
+ nodes, or None if the row is unreachable."""
+ nodes = and_reach_settings()
+ if nodes is None:
+ return None
+ row = find_node(nodes, text=row_text)
+ if row is None:
+ row = scroll_into_view(row_text)
+ nodes = ui()
+ if row is None:
+ return None
+ nodes = ui()
+ row = find_node(nodes, text=row_text)
+ if row is None:
+ return None
+ and_enter(row_text) # backs depth 2
+ tap_node(row)
+ return ui()
+
+
+def and_reach_customize_keys():
+ """Settings -> Layout & Input -> Customize Keys -> LayoutMapper (depth 3)."""
+ nodes = and_reach_fragment("Layout & Input") # depth 2
+ if nodes is None:
+ return None
+ row = find_node(nodes, text="Customize Keys")
+ if row is None:
+ row = scroll_into_view("Customize Keys")
+ nodes = ui()
+ if row is None:
+ return None
+ nodes = ui()
+ row = find_node(nodes, text="Customize Keys")
+ if row is None:
+ return None
+ if not and_reach_surface(row, "Customize Keys", "Layout"):
+ and_enter("Customize Keys") # backs depth 3
+ return ui()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEPTH 1 — toolbar / screen titles reached from the launcher, and produced text
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_settings_toolbar_title",))
+def test_settings_toolbar_title():
+ """SettingsActivity toolbar title is EXACTLY "Keyboard Settings". Absent on the
+ launcher, present after opening Settings -> the change discriminates."""
+ nm = "text_settings_toolbar_title"
+ exp = "Keyboard Settings"
+ restart_app()
+ wait_for_foreground()
+ absent = exp not in all_text(ui())
+ nodes = and_reach_settings()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Settings from launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ got = find_node(nodes, text=exp) is not None or (title == exp)
+ ok = absent and got
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Settings toolbar title {title!r} != {exp!r}"
+ if not got else "behavior_wrong: title present before navigation",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_about_toolbar_title",))
+def test_about_toolbar_title():
+ """AboutActivity toolbar title is EXACTLY "About"."""
+ nm = "text_about_toolbar_title"
+ exp = "About"
+ nodes = and_reach_about()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach About from launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ ok = title == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: About toolbar title {title!r} != {exp!r}",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_about_block_substrings",))
+def test_about_block_substrings():
+ """The About info TextView contains the app-unique static substrings. The
+ version NUMBER is deliberately NOT asserted (a recreation may differ); only the
+ stable wording is. Absent on the launcher, present on the About screen."""
+ nm = "text_about_block_substrings"
+ needles = ("Copyright © 2025 Urik Development",
+ "License: GNU GPL v3.0", "Source Code",
+ "Release Notes", "Report a Bug", "Privacy Policy")
+ exp = "About block contains 'Copyright © 2025 Urik Development' + 'License: GNU GPL v3.0' + 'Source Code'"
+ restart_app()
+ wait_for_foreground()
+ launch_blob = all_text(ui())
+ absent = "GNU GPL v3.0" not in launch_blob
+ nodes = and_reach_about()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach About from launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ node = node_by_id(nodes, "about_text")
+ blob = node.get("text", "") if node else all_text(nodes)
+ missing = [s for s in needles if s not in blob]
+ ok = absent and not missing
+ record(nm, ok, "" if ok else
+ (f"behavior_wrong: About block missing {missing!r}" if missing
+ else "behavior_wrong: About text present before navigation"),
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_about_block_rendered_vlm",))
+def test_about_block_rendered_vlm():
+ """VLM #1: the About screen renders its info block as body text with the
+ Version / Copyright / License lines visible in the content area (below the
+ 'About' toolbar). The block is a real rendered TextView -> a visual check."""
+ nm = "text_about_block_rendered"
+ nodes = and_reach_about()
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach About screen",
+ depth=1, jump_kind="none", tag="position")
+ return
+ vlm_assert(nm,
+ "This is an app's About screen. Is a block of body text rendered in "
+ "the content area below the top 'About' title bar, containing lines "
+ "that start with 'Version', 'Copyright' and 'License'?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="position")
+
+
+@and_test(expects=("text_about_copyright_rendered_vlm",))
+def test_about_copyright_rendered_vlm():
+ """VLM #2: the Copyright line of the About block is rendered as light-coloured
+ text on the dark screen background (OBSERVED: pale text on a dark navy
+ background -- a rendered-colour check on the same genuinely-drawn block)."""
+ nm = "text_about_copyright_rendered"
+ nodes = and_reach_about()
+ if nodes is None:
+ record(nm + "_vlm", False, "setup_failed: could not reach About screen",
+ depth=1, jump_kind="none", tag="color")
+ return
+ vlm_assert(nm,
+ "On this About screen, is the line reading 'Copyright © 2025 Urik "
+ "Development' displayed as light/pale-coloured text against a dark "
+ "background?",
+ RESULTS_DIR, depth=1, jump_kind="value", tag="color")
+
+
+@and_test(expects=("text_features_sheet_tips",))
+def test_features_sheet_tips():
+ """The Features bottom sheet (top-right FAB) shows its static tip titles. Absent
+ on the launcher, present after opening the sheet."""
+ nm = "text_features_sheet_tips"
+ needles = ("Clipboard Manager", "Cursor Control", "Quick Delete")
+ exp = "Features sheet shows 'Clipboard Manager' + 'Cursor Control' + 'Quick Delete'"
+ restart_app()
+ wait_for_foreground()
+ absent = "Clipboard Manager" not in all_text(ui())
+ nodes = and_reach_features_sheet()
+ if nodes is None:
+ record(nm, False, "setup_failed: no info FAB on the launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ blob = all_text(nodes)
+ missing = [s for s in needles if s not in blob]
+ ok = absent and not missing
+ record(nm, ok, "" if ok else
+ (f"feature_missing: Features sheet missing {missing!r}" if missing
+ else "behavior_wrong: tips present before opening the sheet"),
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_features_sheet_learning_words",))
+def test_features_sheet_learning_words():
+ """The first Features tip pairs the EXACT title "Learning Words" with its
+ description sentence -- a static content pair a recreation must reproduce."""
+ nm = "text_features_sheet_learning_words"
+ title = "Learning Words"
+ desc = "Press space after a highlighted typo to add the word to your dictionary."
+ exp = f"tip '{title}' + its description"
+ restart_app()
+ wait_for_foreground()
+ absent = title not in all_text(ui())
+ nodes = and_reach_features_sheet()
+ if nodes is None:
+ record(nm, False, "setup_failed: no info FAB on the launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ blob = all_text(nodes)
+ ok = absent and title in blob and desc in blob
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: '{title}' tip or its description not shown on the sheet",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_themepicker_toolbar_title",))
+def test_themepicker_toolbar_title():
+ """ThemePicker toolbar title is EXACTLY "Keyboard Theme" (reached by tapping the
+ preview theme-name on the launcher)."""
+ nm = "text_themepicker_toolbar_title"
+ exp = "Keyboard Theme"
+ restart_app()
+ wait_for_foreground()
+ absent = exp not in all_text(ui())
+ nodes = and_reach_themepicker_from_card()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach ThemePicker from the card",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ got = find_node(nodes, text=exp) is not None or title == exp
+ ok = absent and got
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: ThemePicker toolbar title {title!r} != {exp!r}",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_themepicker_theme_content_desc",))
+def test_themepicker_theme_content_desc():
+ """Theme cards expose their name as content-desc: the selected card reads
+ "Default theme, currently selected" and another card reads "Light theme".
+ content-desc is text-lane content -- assert both are produced on the picker."""
+ nm = "text_themepicker_theme_content_desc"
+ exp = "content-desc 'Default theme, currently selected' + 'Light theme'"
+ nodes = and_reach_themepicker_from_card()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach ThemePicker from the card",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ has_default = desc_present(nodes, "Default theme")
+ has_light = desc_present(nodes, "Light theme")
+ ok = has_default and has_light
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: theme content-desc missing (Default={has_default}, "
+ f"Light={has_light})",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_themepicker_favorite_content_desc",))
+def test_themepicker_favorite_content_desc():
+ """Each theme card's favorite control exposes the EXACT content-desc
+ "Add Default to favorites" -- an icon-only control's app-unique label, which is
+ text-lane content a recreation must get right."""
+ nm = "text_themepicker_favorite_content_desc"
+ exp = "content-desc 'Add Default to favorites'"
+ nodes = and_reach_themepicker_from_card()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach ThemePicker from the card",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ ok = find_node(nodes, content_desc="Add Default to favorites") is not None
+ record(nm, ok, "" if ok else
+ "behavior_wrong: no 'Add Default to favorites' content-desc on any card",
+ depth=1, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_settings_row_titles",))
+def test_settings_row_titles():
+ """The Settings list shows all 8 preference row titles verbatim, including the
+ &-entity ones ("Layout & Input", "Privacy & Data") which are the exact
+ dump text. Absent on the launcher, present after opening Settings."""
+ nm = "text_settings_row_titles"
+ titles = ("Auto-Correct Settings", "Language Settings",
+ "Typing Behavior Settings", "Layout & Input",
+ "Appearance", "Privacy & Data",
+ "Open Source Licenses", "Dictionary Data")
+ exp = "all 8 row titles incl. 'Layout & Input' and 'Privacy & Data'"
+ restart_app()
+ wait_for_foreground()
+ absent = "Layout & Input" not in all_text(ui())
+ nodes = and_reach_settings()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Settings from launcher",
+ depth=1, jump_kind="value", expect=exp)
+ return
+ missing = [t for t in titles if find_node(nodes, text=t) is None]
+ ok = absent and not missing
+ record(nm, ok, "" if ok else
+ (f"behavior_wrong: Settings list missing titles {missing!r}" if missing
+ else "behavior_wrong: settings titles present before navigation"),
+ depth=1, jump_kind="value", expect=exp)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEPTH 2 — preference SUMMARY strings a row shows on a settings fragment
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_appearance_keysize_summary",))
+def test_appearance_keysize_summary():
+ """Appearance -> "Key Size" row summary is EXACTLY "Medium"."""
+ nm = "text_appearance_keysize_summary"
+ exp = "Medium"
+ nodes = and_reach_fragment("Appearance")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Appearance",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ if find_node(nodes, text="Key Size") is None:
+ record(nm, False, "feature_missing: no 'Key Size' row on Appearance",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Key Size")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Key Size summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_appearance_theme_summary",))
+def test_appearance_theme_summary():
+ """Appearance -> "Theme" row summary is the current theme name "Default"."""
+ nm = "text_appearance_theme_summary"
+ exp = "Default"
+ nodes = and_reach_fragment("Appearance")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Appearance",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ if find_node(nodes, text="Theme") is None:
+ record(nm, False, "feature_missing: no 'Theme' row on Appearance",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Theme")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Theme summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_typing_cursor_speed_summary",))
+def test_typing_cursor_speed_summary():
+ """Typing Behavior -> "Cursor Speed" ListPreference summary is "Medium"."""
+ nm = "text_typing_cursor_speed_summary"
+ exp = "Medium"
+ nodes = and_reach_fragment("Typing Behavior Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Typing Behavior Settings",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ if find_node(nodes, text="Cursor Speed") is None:
+ record(nm, False, "feature_missing: no 'Cursor Speed' row",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Cursor Speed")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Cursor Speed summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_typing_longpress_punct_summary",))
+def test_typing_longpress_punct_summary():
+ """Typing Behavior -> "Long Press Punctuation" summary is EXACTLY "Period Key"."""
+ nm = "text_typing_longpress_punct_summary"
+ exp = "Period Key"
+ nodes = and_reach_fragment("Typing Behavior Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Typing Behavior Settings",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ row = find_node(nodes, text="Long Press Punctuation")
+ if row is None:
+ row = scroll_into_view("Long Press Punctuation")
+ nodes = ui()
+ if find_node(nodes, text="Long Press Punctuation") is None:
+ record(nm, False, "feature_missing: no 'Long Press Punctuation' row",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Long Press Punctuation")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Long Press Punctuation summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_layout_keyboard_layout_summary",))
+def test_layout_keyboard_layout_summary():
+ """Layout & Input -> "Keyboard Layout" summary is "Default (Language Layout)"."""
+ nm = "text_layout_keyboard_layout_summary"
+ exp = "Default (Language Layout)"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ if find_node(nodes, text="Keyboard Layout") is None:
+ record(nm, False, "feature_missing: no 'Keyboard Layout' row",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Keyboard Layout")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Keyboard Layout summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_layout_onehanded_summary",))
+def test_layout_onehanded_summary():
+ """Layout & Input -> "One-Handed Mode" summary is "Standard full-width keyboard"."""
+ nm = "text_layout_onehanded_summary"
+ exp = "Standard full-width keyboard"
+ nodes = and_reach_fragment("Layout & Input")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Layout & Input",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ row = find_node(nodes, text="One-Handed Mode")
+ if row is None:
+ row = scroll_into_view("One-Handed Mode")
+ nodes = ui()
+ if find_node(nodes, text="One-Handed Mode") is None:
+ record(nm, False, "feature_missing: no 'One-Handed Mode' row",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "One-Handed Mode")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: One-Handed Mode summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_autocorrect_suggestion_count_summary",))
+def test_autocorrect_suggestion_count_summary():
+ """Auto-Correct -> "Suggestion Count" ListPreference summary is "3"."""
+ nm = "text_autocorrect_suggestion_count_summary"
+ exp = "3"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ if find_node(nodes, text="Suggestion Count") is None:
+ record(nm, False, "feature_missing: no 'Suggestion Count' row",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ got = summary_of(nodes, "Suggestion Count")
+ ok = got == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Suggestion Count summary {got!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_autocorrect_spellcheck_summary_toggle",))
+def test_autocorrect_spellcheck_summary_toggle():
+ """The summary an ACTION PRODUCES: Spell Check reads "Spell check enabled" ON;
+ toggling it OFF makes the summary read EXACTLY "Spell check disabled". Restores
+ ON afterwards. This is text a state flip produces -> jump_kind="transition"."""
+ nm = "text_autocorrect_spellcheck_summary_toggle"
+ exp = "summary 'Spell check enabled' -> 'Spell check disabled'"
+ nodes = and_reach_fragment("Auto-Correct Settings")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Auto-Correct Settings",
+ depth=2, jump_kind="transition", expect=exp)
+ return
+ before = summary_of(nodes, "Spell Check")
+ sw = switch_for(nodes, "Spell Check")
+ if sw is None or before != "Spell check enabled":
+ record(nm, False,
+ f"feature_missing: Spell Check row/summary not as expected "
+ f"(summary={before!r}, switch={'ok' if sw else 'missing'})",
+ depth=2, jump_kind="transition", expect=exp)
+ return
+ tap_node(sw)
+ nodes = ui()
+ after = summary_of(nodes, "Spell Check")
+ ok = after == "Spell check disabled"
+ # Restore ON regardless of the assertion outcome.
+ sw2 = switch_for(ui(), "Spell Check")
+ if sw2 is not None:
+ tap_node(sw2)
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: toggled-off summary {after!r} != 'Spell check disabled'",
+ depth=2, jump_kind="transition", expect=exp)
+
+
+@and_test(expects=("text_oss_licenses_toolbar_title",))
+def test_oss_licenses_toolbar_title():
+ """OssLicensesActivity toolbar title is EXACTLY "Open Source Licenses" (reached
+ Settings -> Open Source Licenses, depth 2)."""
+ nm = "text_oss_licenses_toolbar_title"
+ exp = "Open Source Licenses"
+ nodes = and_reach_fragment("Open Source Licenses")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Open Source Licenses",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ ok = title == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: OSS toolbar title {title!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+@and_test(expects=("text_dictionary_data_toolbar_title",))
+def test_dictionary_data_toolbar_title():
+ """DictionaryAttributionActivity toolbar title is EXACTLY "Dictionary Data"
+ (reached Settings -> Dictionary Data, depth 2)."""
+ nm = "text_dictionary_data_toolbar_title"
+ exp = "Dictionary Data"
+ nodes = and_reach_fragment("Dictionary Data")
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Dictionary Data",
+ depth=2, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ ok = title == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Dictionary Data toolbar title {title!r} != {exp!r}",
+ depth=2, jump_kind="value", expect=exp)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEPTH 3 — a title on a surface three hops from the launcher
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("text_customize_keys_toolbar_title",))
+def test_customize_keys_toolbar_title():
+ """LayoutMapperActivity toolbar title is EXACTLY "Customize Keys" (reached
+ Settings -> Layout & Input -> Customize Keys, depth 3)."""
+ nm = "text_customize_keys_toolbar_title"
+ exp = "Customize Keys"
+ nodes = and_reach_customize_keys()
+ if nodes is None:
+ record(nm, False, "setup_failed: could not reach Customize Keys (depth 3)",
+ depth=3, jump_kind="value", expect=exp)
+ return
+ title = toolbar_title(nodes)
+ ok = title == exp
+ record(nm, ok, "" if ok else
+ f"behavior_wrong: Customize Keys toolbar title {title!r} != {exp!r}",
+ depth=3, jump_kind="value", expect=exp)
+
+
+TESTS = [
+ # depth 1
+ test_settings_toolbar_title,
+ test_about_toolbar_title,
+ test_about_block_substrings,
+ test_about_block_rendered_vlm,
+ test_about_copyright_rendered_vlm,
+ test_features_sheet_tips,
+ test_features_sheet_learning_words,
+ test_themepicker_toolbar_title,
+ test_themepicker_theme_content_desc,
+ test_themepicker_favorite_content_desc,
+ test_settings_row_titles,
+ # depth 2
+ test_appearance_keysize_summary,
+ test_appearance_theme_summary,
+ test_typing_cursor_speed_summary,
+ test_typing_longpress_punct_summary,
+ test_layout_keyboard_layout_summary,
+ test_layout_onehanded_summary,
+ test_autocorrect_suggestion_count_summary,
+ test_autocorrect_spellcheck_summary_toggle,
+ test_oss_licenses_toolbar_title,
+ test_dictionary_data_toolbar_title,
+ # depth 3
+ test_customize_keys_toolbar_title,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/urikdev-urik/tests/test_manifest.json b/android/urikdev-urik/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..55bd724be63f2ea1b7c6377ee26ee806bbc72f21
--- /dev/null
+++ b/android/urikdev-urik/tests/test_manifest.json
@@ -0,0 +1,922 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "urik",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 142,
+ "manifest_sha": "0e88eb318c71",
+ "tests": [
+ {
+ "name": "computation::computation_cursor_speed_fast",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_key_label_size_large",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_key_size_large",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_keyboard_layout_dialog_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_keyboard_layout_qwertz",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_long_press_duration_long",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_long_press_punctuation_spacebar",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_space_bar_size_wide",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_suggestion_count_1",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_suggestion_count_2",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_suggestion_count_dialog_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_field_echo_layout",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_field_echo_typing",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_test_field_echo_typing_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_center",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_max",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_max_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_min",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_min_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_favorite_floats_to_top_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_haptic_survives_restart",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_keypress_highlight_survives_restart",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_layoutmapper_custom_char",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_layoutmapper_custom_char_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_selected_theme_checkmark_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_spellcheck_dependents_dimmed_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_spellcheck_disables_dependents",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_suggestion_count_survives_restart",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_test_field_echo_appearance",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_test_field_echo_autocorrect",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_dark_applied_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_favorite_multi_integrity",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_favorite_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_favorite_persists_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_reselect_sequence",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_selection_persists_to_main",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_selection_persists_to_main_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_theme_selection_survives_restart",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_2hop_unwind",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_about_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_themepicker_to_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_up_autocorrect",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_up_autocorrect_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_appearance_themepicker",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_appearance_themepicker_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_layout_mapper",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_chain_layout_mapper_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_about_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_features_sheet",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_features_sheet_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_themepicker",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_themepicker_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reset_dialog_cancel",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reset_dialog_reach",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reset_dialog_reach_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_appearance",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_autocorrect",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_dictionary",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_languages",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_layout",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_licenses",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_privacy",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_settings_to_typing",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_suggestion_dialog_cancel",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_suggestion_dialog_reach",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_suggestion_dialog_reach_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_auto_capitalization_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_clipboard_history_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_double_space_period_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_english_current_layout_indicator",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_english_selected_checkbox_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_haptic_feedback_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_key_press_highlight_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_lang_switch_key_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_language_checkbox_select",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_learn_new_words_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_main_preview_selected_theme_color_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_merged_dictionaries_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_one_handed_mode_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_persist_merged_dictionaries",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_persist_swipe_typing",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_show_suggestions_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm1_autocorrection_enable_flip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm1_pause_enable_flip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm1_reenable_restores",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm1_spellcheck_checked_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm1_spellcheck_greyed_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm2_numberhints_enable_flip",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm2_numberhints_undimmed_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_sm2_numberrow_checked_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_spacebar_cursor_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_suggestion_count_ctv_checked",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_suggestion_count_ctv_moves",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_suggestion_count_dialog_mark_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_swipe_typing_summary",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_switch_thumb_position_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_color_distinct_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_selected_checkmark_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_autocorrect_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_autocorrect_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_features_sheet_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_features_sheet_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_preview_card",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_preview_card_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_s0_surfaces",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_s0_surfaces_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_languages_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_languages_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_layoutmapper_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_layoutmapper_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_suggestion_dialog_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_themepicker_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_themepicker_shape_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_typing_seekbar_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_block_rendered_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_block_substrings",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_copyright_rendered_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_about_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_appearance_keysize_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_appearance_theme_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_autocorrect_spellcheck_summary_toggle",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_autocorrect_suggestion_count_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_customize_keys_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_dictionary_data_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_features_sheet_learning_words",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_features_sheet_tips",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_layout_keyboard_layout_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_layout_onehanded_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_oss_licenses_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_row_titles",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_themepicker_favorite_content_desc",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_themepicker_theme_content_desc",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_themepicker_toolbar_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_typing_cursor_speed_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_typing_longpress_punct_summary",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_suggestion_count_dialog_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_keyboard_layout_dialog_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_min_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "computation::computation_vibration_seekbar_max_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "computation::computation_test_field_echo_typing_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "interaction::interaction_theme_selection_persists_to_main_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_theme_favorite_persists_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_layoutmapper_custom_char_vlm",
+ "module": "interaction",
+ "tag": "layout"
+ },
+ {
+ "name": "interaction::interaction_theme_dark_applied_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_spellcheck_dependents_dimmed_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_favorite_floats_to_top_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_selected_theme_checkmark_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_about_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_reach_themepicker_vlm",
+ "module": "navigation",
+ "tag": "color"
+ },
+ {
+ "name": "navigation::nav_reach_features_sheet_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_chain_appearance_themepicker_vlm",
+ "module": "navigation",
+ "tag": "color"
+ },
+ {
+ "name": "navigation::nav_chain_layout_mapper_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_reset_dialog_reach_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_suggestion_dialog_reach_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_backstack_up_autocorrect_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_sm1_spellcheck_greyed_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_sm2_numberhints_undimmed_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_switch_thumb_position_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_english_selected_checkbox_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_suggestion_count_dialog_mark_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_theme_selected_checkmark_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_theme_color_distinct_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_main_preview_selected_theme_color_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_gate_s0_surfaces_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_gate_preview_card_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_settings_shape_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_autocorrect_shape_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_features_sheet_shape_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_themepicker_shape_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_layoutmapper_shape_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_languages_shape_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "text::text_about_block_rendered_vlm",
+ "module": "text",
+ "tag": "position"
+ },
+ {
+ "name": "text::text_about_copyright_rendered_vlm",
+ "module": "text",
+ "tag": "color"
+ }
+ ],
+ "vlm_total": 39,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/urikdev-urik/vlm_assertions.json b/android/urikdev-urik/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..789a38298b4b4554c6860f1a9bb6954c5adf77dc
--- /dev/null
+++ b/android/urikdev-urik/vlm_assertions.json
@@ -0,0 +1,803 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/urikdev-urik",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 39,
+ "with_verdict": 39,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 39,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "structure_gate_s0_surfaces_vlm",
+ "screenshot": "structure_gate_s0_surfaces_vlm.png",
+ "assertion": "Is the app logo/icon near the top-center of the screen with a row of action buttons positioned at the bottom of the screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "structure_gate_s0_surfaces",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_gate_preview_card_vlm",
+ "screenshot": "structure_gate_preview_card_vlm.png",
+ "assertion": "Is there a keyboard preview showing letter keys (like Z X C V B N M) arranged in horizontal rows like a keyboard?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_gate_preview_card",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_settings_shape_vlm",
+ "screenshot": "structure_settings_shape_vlm.png",
+ "assertion": "Is this a settings screen showing a vertical list of preference rows stacked from top to bottom?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_settings_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_autocorrect_shape_vlm",
+ "screenshot": "structure_autocorrect_shape_vlm.png",
+ "assertion": "Does this settings screen show a vertical list of rows where each row has a toggle switch aligned on the right side?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_autocorrect_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_features_sheet_shape_vlm",
+ "screenshot": "structure_features_sheet_shape_vlm.png",
+ "assertion": "Is a panel showing a vertical stacked list of feature tips, each with a bold title and a description line beneath it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_features_sheet_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_themepicker_shape_vlm",
+ "screenshot": "structure_themepicker_shape_vlm.png",
+ "assertion": "Is this a scrollable vertical list of keyboard-theme preview cards, each card showing a small keyboard rendering?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_themepicker_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_layoutmapper_shape_vlm",
+ "screenshot": "structure_layoutmapper_shape_vlm.png",
+ "assertion": "Is a full QWERTY keyboard rendered as multiple horizontal rows of square keys (a number row on top, then letter rows)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "structure_layoutmapper_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "structure_languages_shape_vlm",
+ "screenshot": "structure_languages_shape_vlm.png",
+ "assertion": "Does this screen show a vertical scrollable list of language rows, each row having a checkbox?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "structure_languages_shape",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_settings_vlm",
+ "screenshot": "nav_reach_settings_vlm.png",
+ "assertion": "Is a settings screen showing a top toolbar with a left-pointing back arrow at the top-left and a vertical list of labelled rows below it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_settings",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_about_vlm",
+ "screenshot": "nav_reach_about_vlm.png",
+ "assertion": "Is this an 'About' text page: a screen filled mostly with lines of text (version, copyright, links) and NO keyboard preview or list of toggle rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_reach_about",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_themepicker_vlm",
+ "screenshot": "nav_reach_themepicker_vlm.png",
+ "assertion": "Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (e.g. a dark one, a white/light one, a black one)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "nav_reach_themepicker",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reach_features_sheet_vlm",
+ "screenshot": "nav_reach_features_sheet_vlm.png",
+ "assertion": "Is a bottom sheet panel covering the lower portion of the screen, showing a list of tip titles with descriptions, while the top of the screen is dimmed?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reach_features_sheet",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_chain_appearance_themepicker_vlm",
+ "screenshot": "nav_chain_appearance_themepicker_vlm.png",
+ "assertion": "Does this screen show a vertical list of keyboard theme previews rendered in several DIFFERENT colors (dark, light/white, black, etc.)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "nav_chain_appearance_themepicker",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_chain_layout_mapper_vlm",
+ "screenshot": "nav_chain_layout_mapper_vlm.png",
+ "assertion": "Is a full keyboard laid out as horizontal rows of keys (number row, then letter rows Q-P, A-L, Z-M) rendered in the center of this screen?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "nav_chain_layout_mapper",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_reset_dialog_reach_vlm",
+ "screenshot": "nav_reset_dialog_reach_vlm.png",
+ "assertion": "Is a small modal dialog box centered on the screen (with a title, a short message, and Cancel/OK buttons) over a dimmed background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "nav_reset_dialog_reach",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_suggestion_dialog_reach_vlm",
+ "screenshot": "nav_suggestion_dialog_reach_vlm.png",
+ "assertion": "Is a modal dialog showing a short vertical list of numeric options, each with a round radio-button circle to its left, and a Cancel button?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_suggestion_dialog_reach",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "nav_backstack_up_autocorrect_vlm",
+ "screenshot": "nav_backstack_up_autocorrect_vlm.png",
+ "assertion": "Does the toolbar at the very top of this screen show a left-pointing back arrow at its far left, next to the screen title?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "nav_backstack_up_autocorrect",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_theme_selection_persists_to_main_vlm",
+ "screenshot": "interaction_theme_selection_persists_to_main_vlm.png",
+ "assertion": "The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly WHITE / very light background (a light colour theme), rather than dark?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_theme_selection_persists_to_main",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_theme_favorite_persists_vlm",
+ "screenshot": "interaction_theme_favorite_persists_vlm.png",
+ "assertion": "On this theme list, is at least one theme card's favorite heart icon drawn as a FILLED / solid heart (as opposed to an empty outline)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_theme_favorite_persists",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_layoutmapper_custom_char_vlm",
+ "screenshot": "interaction_layoutmapper_custom_char_vlm.png",
+ "assertion": "Is a bottom sheet / panel (containing a text input field and a 'Save' button) displayed in the lower part of the screen, overlaying a rendered keyboard above it?",
+ "form": "question",
+ "expected": true,
+ "aspect": "layout",
+ "modality": null,
+ "links_to": "interaction_layoutmapper_custom_char",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 3
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_theme_dark_applied_vlm",
+ "screenshot": "interaction_theme_dark_applied_vlm.png",
+ "assertion": "The keyboard preview card near the centre of this screen: are its keys drawn on a predominantly BLACK / very dark background (a dark colour theme)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_theme_dark_applied",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_spellcheck_dependents_dimmed_vlm",
+ "screenshot": "interaction_spellcheck_dependents_dimmed_vlm.png",
+ "assertion": "In this settings list, are the 'Pause on Misspelled Word' and 'Autocorrection' rows shown greyed-out / dimmed (a faded, disabled appearance) compared with the fully-black active rows above them?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "interaction_spellcheck_dependents_dimmed",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_favorite_floats_to_top_vlm",
+ "screenshot": "interaction_favorite_floats_to_top_vlm.png",
+ "assertion": "At the very TOP of this theme list (the first one or two cards), is there a theme card whose favorite heart icon is FILLED / solid rather than an empty outline?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "interaction_favorite_floats_to_top",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "interaction_selected_theme_checkmark_vlm",
+ "screenshot": "interaction_selected_theme_checkmark_vlm.png",
+ "assertion": "On this theme list, is exactly one theme card marked as the currently-selected one with a check-mark / tick badge (a small checkmark icon), while the other cards have no such checkmark?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "interaction_selected_theme_checkmark",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_suggestion_count_dialog_vlm",
+ "screenshot": "computation_suggestion_count_dialog_vlm.png",
+ "assertion": "Is a dialog shown containing a vertical list of selectable options each preceded by a round radio-button circle (one filled/selected)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_suggestion_count_dialog",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_keyboard_layout_dialog_vlm",
+ "screenshot": "computation_keyboard_layout_dialog_vlm.png",
+ "assertion": "Is a dialog shown listing multiple keyboard-layout choices (such as QWERTY / QWERTZ / AZERTY) as a vertical list of selectable rows?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "computation_keyboard_layout_dialog",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_vibration_seekbar_min_vlm",
+ "screenshot": "computation_vibration_seekbar_min_vlm.png",
+ "assertion": "Is the slider (SeekBar) thumb positioned at the far-LEFT end of the Vibration Strength track, near the start of the bar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "computation_vibration_seekbar_min",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_vibration_seekbar_max_vlm",
+ "screenshot": "computation_vibration_seekbar_max_vlm.png",
+ "assertion": "Is the slider (SeekBar) thumb positioned at the far-RIGHT end of the Vibration Strength track, near the end of the bar?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "computation_vibration_seekbar_max",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "computation_test_field_echo_typing_vlm",
+ "screenshot": "computation_test_field_echo_typing_vlm.png",
+ "assertion": "Does the 'Test changes' input field at the bottom visibly display the typed text 'kbdcompute7'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "content",
+ "modality": null,
+ "links_to": "computation_test_field_echo_typing",
+ "rigor": {
+ "jump_kind": "none",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_sm1_spellcheck_greyed_vlm",
+ "screenshot": "states_sm1_spellcheck_greyed_vlm.png",
+ "assertion": "In this settings list the 'Spell Check' row text is bright white. Are the 'Pause on Misspelled Word' and 'Autocorrection' rows below it rendered in a noticeably dimmer / greyed-out grey colour (disabled appearance) compared to 'Spell Check'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_sm1_spellcheck_greyed",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_sm2_numberhints_undimmed_vlm",
+ "screenshot": "states_sm2_numberhints_undimmed_vlm.png",
+ "assertion": "Is the 'Show Number Hints' row text rendered in bright, active white (the same brightness as the other enabled setting titles on screen), i.e. NOT greyed-out or dimmed?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_sm2_numberhints_undimmed",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_switch_thumb_position_vlm",
+ "screenshot": "states_switch_thumb_position_vlm.png",
+ "assertion": "Look at the toggle switch on the right of the 'One-Handed Mode' row. Is its round thumb positioned at the RIGHT end of the track (the ON position), rather than the left?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "states_switch_thumb_position",
+ "rigor": {
+ "jump_kind": "transition",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_english_selected_checkbox_vlm",
+ "screenshot": "states_english_selected_checkbox_vlm.png",
+ "assertion": "In this language list, the 'English' row is marked as the current layout. Does the checkbox on the 'English' row appear CHECKED / filled (a tick or filled box), while the checkboxes on the other language rows appear empty / unchecked?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_english_selected_checkbox",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_suggestion_count_dialog_mark_vlm",
+ "screenshot": "states_suggestion_count_dialog_mark_vlm.png",
+ "assertion": "This is a single-choice dialog listing options 1, 2 and 3. Is there a selection mark (a filled radio button or a check/tick) shown next to exactly ONE option, indicating the currently selected value?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_suggestion_count_dialog_mark",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_selected_checkmark_vlm",
+ "screenshot": "states_theme_selected_checkmark_vlm.png",
+ "assertion": "This is a keyboard theme picker showing several theme preview cards. Does the currently-selected theme card at the top have a distinct highlighted/coloured BORDER and a checkmark (tick), which the other theme cards below it do NOT have?",
+ "form": "question",
+ "expected": true,
+ "aspect": "shape",
+ "modality": null,
+ "links_to": "states_theme_selected_checkmark",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_theme_color_distinct_vlm",
+ "screenshot": "states_theme_color_distinct_vlm.png",
+ "assertion": "Among these keyboard theme preview cards, is there at least one card with a predominantly LIGHT/white keyboard background and at least one card with a predominantly DARK/black keyboard background (i.e. the themes are rendered in clearly different colours)?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_theme_color_distinct",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 2
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "states_main_preview_selected_theme_color_vlm",
+ "screenshot": "states_main_preview_selected_theme_color_vlm.png",
+ "assertion": "This screen shows a keyboard preview card labelled 'Default'. Is the preview keyboard drawn with a DARK (dark blue / near-black) key background and LIGHT (cream / pale) key letters, matching a dark theme?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "states_main_preview_selected_theme_color",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 0
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_about_block_rendered_vlm",
+ "screenshot": "text_about_block_rendered_vlm.png",
+ "assertion": "This is an app's About screen. Is a block of body text rendered in the content area below the top 'About' title bar, containing lines that start with 'Version', 'Copyright' and 'License'?",
+ "form": "question",
+ "expected": true,
+ "aspect": "position",
+ "modality": null,
+ "links_to": "text_about_block_rendered",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ },
+ {
+ "id": "text_about_copyright_rendered_vlm",
+ "screenshot": "text_about_copyright_rendered_vlm.png",
+ "assertion": "On this About screen, is the line reading 'Copyright © 2025 Urik Development' displayed as dark-coloured text against a light background?",
+ "form": "question",
+ "expected": true,
+ "aspect": "color",
+ "modality": null,
+ "links_to": "text_about_copyright_rendered",
+ "rigor": {
+ "jump_kind": "value",
+ "depth": 1
+ },
+ "verdict": {
+ "answer": true,
+ "passed": true,
+ "raw": null
+ },
+ "calibration": null
+ }
+ ],
+ "merged_from_files": 1,
+ "source_shapes": {
+ "list": 1
+ }
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/LICENSE b/android/v1tzor-timeplanner/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/android/v1tzor-timeplanner/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/android/v1tzor-timeplanner/instance.json b/android/v1tzor-timeplanner/instance.json
new file mode 100644
index 0000000000000000000000000000000000000000..73af29b96ccc3d30aab4006b1fbeb0d5a3cdafeb
--- /dev/null
+++ b/android/v1tzor-timeplanner/instance.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "instance_id": "android/v1tzor-timeplanner",
+ "platform": "android",
+ "repo": "https://github.com/v1tzor/TimePlanner",
+ "commit": "945b222df2b7a7e559751a1efddd3c18aa30b17e",
+ "patches": [],
+ "package": "ru.aleshin.timeplanner.debug",
+ "license": null
+}
diff --git a/android/v1tzor-timeplanner/reference/launch.sh b/android/v1tzor-timeplanner/reference/launch.sh
new file mode 100644
index 0000000000000000000000000000000000000000..09e1c18c8ccd98b2564163914d67ed0ba586bac8
--- /dev/null
+++ b/android/v1tzor-timeplanner/reference/launch.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# TEMPLATE (rb_unify) — review before use.
+set -euo pipefail
+: "${RB_PACKAGE:?must be exported by the runner from instance.json}"
+D="$(cd "$(dirname "$0")" && pwd)"; SER="${DEVICE_SERIAL:-emulator-5554}"
+APK="$(find "$D" -name '*.apk' | head -1)"
+[ -n "$APK" ] || { echo "ERROR: no apk found; extract reference.tar.gz first" >&2; exit 1; }
+adb -s "$SER" install -r -g "$APK"
+adb -s "$SER" shell monkey -p "$RB_PACKAGE" -c android.intent.category.LAUNCHER 1
diff --git a/android/v1tzor-timeplanner/tests/android_computation_eval.json b/android/v1tzor-timeplanner/tests/android_computation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..4787a8f21cc93f1b734f2426fedfa70d2d581954
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_computation_eval.json
@@ -0,0 +1,155 @@
+{
+ "module": "computation",
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 7,
+ "passed": 7,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 6,
+ "passed": 6,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.8571,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 6,
+ "liveness": 0,
+ "interactive": 7,
+ "depth_ge1": 7,
+ "depth_ge2": 4,
+ "value": 7,
+ "vlm_fine": 4
+ },
+ "results": [
+ {
+ "test": "computation_default_duration",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "duration '23h 59m'"
+ },
+ {
+ "test": "computation_duration_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this task editor, is there a duration label of the form 'h m' displayed on the same horizontal row as, and to the right of, the Start and End time fields?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In this task editor, is there a duration label of the form 'h m' displayed on the same horizontal row as, and to the right of, the Start and End time fields?",
+ "tag": "position"
+ },
+ {
+ "test": "computation_end_6am",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "End '6:59 AM' and duration '6h 59m'"
+ },
+ {
+ "test": "computation_end_3am",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "End '3:59 AM' and duration '3h 59m'"
+ },
+ {
+ "test": "computation_duration_differential",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "duration goes 23h 59m -> 6h 59m"
+ },
+ {
+ "test": "computation_duration_shrinks_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this task editor show a duration label of the form 'h m' next to the Start/End time fields?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does this task editor show a duration label of the form 'h m' next to the Start/End time fields?",
+ "tag": "content"
+ },
+ {
+ "test": "computation_analytics_study_pct",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "Study 100%"
+ },
+ {
+ "test": "computation_donut_full_vlm",
+ "passed": true,
+ "message": "VLM: Q='There is a ring/doughnut chart. Is the MAJORITY of the ring taken up by a single large arc of one dominant colour (one segment covering most of the circle), rather than the ring being divided into several roughly equal wedges?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: There is a ring/doughnut chart. Is the MAJORITY of the ring taken up by a single large arc of one dominant colour (one segment covering most of the circle), rather than the ring being divided into several roughly equal wedges?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_legend_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Below the ring chart is a legend of category rows, each with a small coloured dot to the left of its name. Is exactly ONE row showing a non-zero percentage while the other rows show 0%?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Below the ring chart is a legend of category rows, each with a small coloured dot to the left of its name. Is exactly ONE row showing a non-zero percentage while the other rows show 0%?",
+ "tag": "layout"
+ },
+ {
+ "test": "computation_analytics_others_zero",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "one 100% row, every other category 0%"
+ },
+ {
+ "test": "computation_donut_center_total",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "value",
+ "tier": 3,
+ "expect": "donut centre '23h 59m'"
+ },
+ {
+ "test": "computation_workload_bars_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the 'Workload stats' bar chart, is there a single tall coloured vertical bar that rises well above the chart baseline, while the other x-axis positions have no visible bar?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the 'Workload stats' bar chart, is there a single tall coloured vertical bar that rises well above the chart baseline, while the other x-axis positions have no visible bar?",
+ "tag": "shape"
+ },
+ {
+ "test": "computation_legend_dots_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the category legend under the ring chart, does each category name have a small round COLOURED dot marker beside it (the dots are coloured, not grey/black bullets)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the category legend under the ring chart, does each category name have a small round COLOURED dot marker beside it (the dots are coloured, not grey/black bullets)?",
+ "tag": "color"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/android_interaction_eval.json b/android/v1tzor-timeplanner/tests/android_interaction_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..f01c014b4c118a3a27264cd74b7a6162b9b2388d
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_interaction_eval.json
@@ -0,0 +1,184 @@
+{
+ "module": "interaction",
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.0,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 2,
+ "liveness": 0,
+ "interactive": 14,
+ "depth_ge1": 14,
+ "depth_ge2": 11,
+ "value": 0,
+ "vlm_fine": 6
+ },
+ "results": [
+ {
+ "test": "interaction_create_task",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Study' task card present on Home (was 'Nothing planned yet')"
+ },
+ {
+ "test": "interaction_create_task_running_vlm",
+ "passed": true,
+ "message": "VLM: Q='There is a task row on the schedule (not the empty 'Nothing planned yet' state). Is that task row visually highlighted with a distinct coloured/tinted background different from the plain page background?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: There is a task row on the schedule (not the empty 'Nothing planned yet' state). Is that task row visually highlighted with a distinct coloured/tinted background different from the plain page background?",
+ "tag": "color"
+ },
+ {
+ "test": "interaction_create_task_icon_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the task row on the schedule show a small coloured category icon/symbol (a glyph such as a graduation cap) positioned to the left of the category name text?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Does the task row on the schedule show a small coloured category icon/symbol (a glyph such as a graduation cap) positioned to the left of the category name text?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_create_persists",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Study' task card still on Home after force_stop_and_relaunch"
+ },
+ {
+ "test": "interaction_edit_category",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "schedule shows 'Health' card and no 'Study' card"
+ },
+ {
+ "test": "interaction_edit_icon_vlm",
+ "passed": true,
+ "message": "VLM: Q='The schedule shows one task row. Does its category icon look like a health/medical symbol (a cross or heart) rather than an academic graduation-cap symbol?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: The schedule shows one task row. Does its category icon look like a health/medical symbol (a cross or heart) rather than an academic graduation-cap symbol?",
+ "tag": "shape"
+ },
+ {
+ "test": "interaction_schedule_grows",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "schedule shows a 'Study' card AND an 'Add a task' add row"
+ },
+ {
+ "test": "interaction_schedule_grows_vlm",
+ "passed": true,
+ "message": "VLM: Q='On the schedule/timeline, is there a filled task block near the top and, directly below it, a separate row containing a plus (+) 'add' control (i.e. the list has grown to two stacked rows)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On the schedule/timeline, is there a filled task block near the top and, directly below it, a separate row containing a plus (+) 'add' control (i.e. the list has grown to two stacked rows)?",
+ "tag": "layout"
+ },
+ {
+ "test": "interaction_second_task",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "task-card count rises from 1 to >=2"
+ },
+ {
+ "test": "interaction_two_tasks_vlm",
+ "passed": true,
+ "message": "VLM: Q='There are two separate coloured task blocks on the schedule, each with its own category name. Is one task block positioned directly ABOVE the other (they are stacked vertically, not overlapping and not side by side)?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: There are two separate coloured task blocks on the schedule, each with its own category name. Is one task block positioned directly ABOVE the other (they are stacked vertically, not overlapping and not side by side)?",
+ "tag": "position"
+ },
+ {
+ "test": "interaction_running_expand",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Add time' and 'Reduce the time' controls appear after tapping the running card"
+ },
+ {
+ "test": "interaction_running_progress_vlm",
+ "passed": true,
+ "message": "VLM: Q='The highlighted task row shows a horizontal progress indicator. Is that progress bar filled only PART of the way across (a partial fill, not empty and not completely full)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: The highlighted task row shows a horizontal progress indicator. Is that progress bar filled only PART of the way across (a partial fill, not empty and not completely full)?",
+ "tag": "size"
+ },
+ {
+ "test": "interaction_running_controls_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the expanded task row, are there two labelled buttons shown side by side, one reading 'Increase' (with a plus) and one reading 'Reduce' (with a minus)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the expanded task row, are there two labelled buttons shown side by side, one reading 'Increase' (with a plus) and one reading 'Reduce' (with a minus)?",
+ "tag": "layout"
+ },
+ {
+ "test": "interaction_cancel_no_persist",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "no categorized task card on Home after Cancel"
+ },
+ {
+ "test": "interaction_note_roundtrip",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Note placeholder 'Optional' clears after typing 'kitreadchapter' (data entered)"
+ },
+ {
+ "test": "interaction_sheet_selected_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a category picker list. Is exactly one category row visibly marked as selected (a filled/checked radio button or a highlighted background) while the other rows are not?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: This is a category picker list. Is exactly one category row visibly marked as selected (a filled/checked radio button or a highlighted background) while the other rows are not?",
+ "tag": "color"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/android_navigation_eval.json b/android/v1tzor-timeplanner/tests/android_navigation_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..a485d9ebbcc627c12935832f7d89bb3780c39e3c
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_navigation_eval.json
@@ -0,0 +1,256 @@
+{
+ "module": "navigation",
+ "total": 24,
+ "passed": 24,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 16,
+ "passed": 16,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 8,
+ "passed": 8,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.5,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 1,
+ "liveness": 0,
+ "interactive": 23,
+ "depth_ge1": 23,
+ "depth_ge2": 7,
+ "value": 0,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "nav_reach_analytics",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Analytics 'Planning stats' visible; Home 'Schedule' title gone"
+ },
+ {
+ "test": "nav_reach_analytics_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a donut or pie chart (a ring/circle segmented into colored slices) shown on this analytics screen?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a donut or pie chart (a ring/circle segmented into colored slices) shown on this analytics screen?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_reach_analytics_tabs_vlm",
+ "passed": true,
+ "message": "VLM: Q='Near the top are there two side-by-side tabs, one bearing a round pie-chart icon and the other a bar-chart icon (vertical bars)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Near the top are there two side-by-side tabs, one bearing a round pie-chart icon and the other a bar-chart icon (vertical bars)?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_reach_settings",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings 'Appearance' section visible; Analytics 'Planning stats' gone"
+ },
+ {
+ "test": "nav_reach_settings_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under a 'Color' label, are there four filled color swatches whose shape is a rounded square (not a circle)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Under a 'Color' label, are there four filled color swatches whose shape is a rounded square (not a circle)?",
+ "tag": "shape"
+ },
+ {
+ "test": "nav_reach_home_tab",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Home 'Schedule' title restored; Settings 'Appearance' gone"
+ },
+ {
+ "test": "nav_reach_editor",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Editor 'Category'/'Save' visible; Home 'Schedule' gone"
+ },
+ {
+ "test": "nav_reach_editor_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the top app-bar, is a left-pointing back arrow positioned at the very top-left corner, with action icons over on the right side?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: In the top app-bar, is a left-pointing back arrow positioned at the very top-left corner, with action icons over on the right side?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_backstack_editor_home",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Home 'Schedule' restored after one BACK; Editor title gone"
+ },
+ {
+ "test": "nav_reach_overview",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Overview 'Schedules' section visible; Home 'Compact view' gone"
+ },
+ {
+ "test": "nav_reach_overview_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does this screen show a horizontal row of date cards, each with a circular progress ring and a status word like Completed/Current/Planned?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Does this screen show a horizontal row of date cards, each with a circular progress ring and a status word like Completed/Current/Planned?",
+ "tag": "layout"
+ },
+ {
+ "test": "nav_open_drawer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Drawer header 'Time Planner' + items Templates/Categories appeared"
+ },
+ {
+ "test": "nav_open_drawer_vlm",
+ "passed": true,
+ "message": "VLM: Q='Has a navigation drawer panel slid in from the left, covering the left portion of the screen, with a logo/title header at the top and a vertical list of menu items below it?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Has a navigation drawer panel slid in from the left, covering the left portion of the screen, with a logo/title header at the top and a vertical list of menu items below it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_reach_templates",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Templates 'List is empty' visible; drawer 'Time Planner' gone"
+ },
+ {
+ "test": "nav_reach_categories",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Categories 'Subcategories' visible; drawer 'Time Planner' gone"
+ },
+ {
+ "test": "nav_reach_overview_drawer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Overview 'Schedules' visible; drawer 'Time Planner' gone"
+ },
+ {
+ "test": "nav_deepchain_backstack",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Templates then Categories stacked; two BACKs unwind Categories->Templates->Home hop by hop"
+ },
+ {
+ "test": "nav_reach_category_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Category sheet 'Select' button visible; Editor 'Save' gone"
+ },
+ {
+ "test": "nav_reach_category_sheet_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a panel/sheet overlaid on the lower part of the screen on top of a dimmed (darkened) background behind it?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a panel/sheet overlaid on the lower part of the screen on top of a dimmed (darkened) background behind it?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_backstack_sheet_editor",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Editor 'Priority' field restored after Cancel; sheet 'Close sheet' gone"
+ },
+ {
+ "test": "nav_reach_time_picker",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Time picker 'Enter time' visible; Editor 'Priority' field gone"
+ },
+ {
+ "test": "nav_reach_time_picker_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a time-entry dialog shown roughly centered on the screen, with large hour and minute number fields and AM / PM buttons?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "VLM YES: Is a time-entry dialog shown roughly centered on the screen, with large hour and minute number fields and AM / PM buttons?",
+ "tag": "position"
+ },
+ {
+ "test": "nav_backstack_picker_editor",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Editor 'Priority' field restored after Cancel; picker 'Enter time' gone"
+ },
+ {
+ "test": "nav_reach_date_picker",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Date picker (day grid, 'Change to next month') visible; Home 'Compact view' gone"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/android_states_eval.json b/android/v1tzor-timeplanner/tests/android_states_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..81d8f6be8d3a8de3a4c1945cfe3cf206fbe46b64
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_states_eval.json
@@ -0,0 +1,278 @@
+{
+ "module": "states",
+ "total": 26,
+ "passed": 26,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 12,
+ "passed": 12,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.8571,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 1,
+ "liveness": 0,
+ "interactive": 25,
+ "depth_ge1": 23,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 11
+ },
+ "results": [
+ {
+ "test": "states_statistics_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Statistics switch checked true->false"
+ },
+ {
+ "test": "states_statistics_off_track_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a settings row labelled Statistics with a toggle switch. Is the switch track grey/uncoloured (thumb to the LEFT, OFF position) rather than filled with the accent purple colour?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: This is a settings row labelled Statistics with a toggle switch. Is the switch track grey/uncoloured (thumb to the LEFT, OFF position) rather than filled with the accent purple colour?",
+ "tag": "color"
+ },
+ {
+ "test": "states_statistics_toggle_back",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Statistics switch checked true->false then false->true"
+ },
+ {
+ "test": "states_notifications_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Notifications checked true->false AND reminder-gear button disappears"
+ },
+ {
+ "test": "states_notifications_off_track_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a settings row labelled Notifications with a toggle switch. Is the switch track grey/uncoloured (thumb to the LEFT, OFF position) rather than filled with the accent purple colour?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: This is a settings row labelled Notifications with a toggle switch. Is the switch track grey/uncoloured (thumb to the LEFT, OFF position) rather than filled with the accent purple colour?",
+ "tag": "color"
+ },
+ {
+ "test": "states_priority_standard_medium",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "priority 'Selected' marker moves Standard->Medium"
+ },
+ {
+ "test": "states_priority_medium_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the Priority row of three segments, is the 'Medium' segment filled with a pink/coloured background while 'Standard' and 'Max' have a plain uncoloured background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the Priority row of three segments, is the 'Medium' segment filled with a pink/coloured background while 'Standard' and 'Max' have a plain uncoloured background?",
+ "tag": "color"
+ },
+ {
+ "test": "states_priority_medium_check_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the Priority row, does the 'Medium' segment show a small check-mark (tick) glyph positioned to the LEFT of the word 'Medium'?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the Priority row, does the 'Medium' segment show a small check-mark (tick) glyph positioned to the LEFT of the word 'Medium'?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_priority_medium_max",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "priority 'Selected' marker moves Medium->Max"
+ },
+ {
+ "test": "states_theme_system_dark",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "theme 'Selected' marker moves System->Dark"
+ },
+ {
+ "test": "states_theme_dark_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the Theme row of three segments (Light / System / Dark), is the 'Dark' segment filled with a pink/coloured background while the other two have a plain uncoloured background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the Theme row of three segments (Light / System / Dark), is the 'Dark' segment filled with a pink/coloured background while the other two have a plain uncoloured background?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_dark_applied_vlm",
+ "passed": true,
+ "message": "VLM: Q='Look at the whole screen. Is the app background now DARK (near-black or dark grey surfaces) with light/white text, rather than the light near-white background it had before?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Look at the whole screen. Is the app background now DARK (near-black or dark grey surfaces) with light/white text, rather than the light near-white background it had before?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_dark_light",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "theme 'Selected' marker moves Dark->Light"
+ },
+ {
+ "test": "states_calendar_behavior",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "calendar 'Selected' marker moves Set to today->Pick a date"
+ },
+ {
+ "test": "states_calendar_pick_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the 'Calendar icon behavior' row (two segments 'Pick a date' / 'Set to today'), is the 'Pick a date' segment filled with a pink/coloured background while 'Set to today' has a plain uncoloured background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In the 'Calendar icon behavior' row (two segments 'Pick a date' / 'Set to today'), is the 'Pick a date' segment filled with a pink/coloured background while 'Set to today' has a plain uncoloured background?",
+ "tag": "color"
+ },
+ {
+ "test": "states_dynamic_colors_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Dynamic colors switch checked false->true"
+ },
+ {
+ "test": "states_dynamic_colors_on_track_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a settings row labelled 'Dynamic colors' with a toggle switch. Is the switch track filled with a coloured (purple/accent) fill and the thumb to the RIGHT (ON position), rather than a plain grey OFF track?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: This is a settings row labelled 'Dynamic colors' with a toggle switch. Is the switch track filled with a coloured (purple/accent) fill and the thumb to the RIGHT (ON position), rather than a plain grey OFF track?",
+ "tag": "color"
+ },
+ {
+ "test": "states_secure_screen_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Secure screen checked false->true then restored to false"
+ },
+ {
+ "test": "states_compact_view_toggle",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "view-mode label toggles 'Compact view' <-> 'Expanded view'"
+ },
+ {
+ "test": "states_compact_view_density_vlm",
+ "passed": true,
+ "message": "VLM: Q='On this schedule screen, at the right end of the date row, is there a small toggle icon made of stacked horizontal lines (a list-density / view control) next to the 'view' text?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: On this schedule screen, at the right end of the date row, is there a small toggle icon made of stacked horizontal lines (a list-density / view control) next to the 'view' text?",
+ "tag": "layout"
+ },
+ {
+ "test": "states_category_radio",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "RadioButton checked moves from Absent (true->false) to Study (false->true)"
+ },
+ {
+ "test": "states_category_study_highlight_vlm",
+ "passed": true,
+ "message": "VLM: Q='In this category picker list, is the 'Study' row highlighted with a pink/coloured background and a FILLED radio button, while the other rows (Absent, Shopping, Health, ...) have a plain background and EMPTY radio buttons?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: In this category picker list, is the 'Study' row highlighted with a pink/coloured background and a FILLED radio button, while the other rows (Absent, Shopping, Health, ...) have a plain background and EMPTY radio buttons?",
+ "tag": "color"
+ },
+ {
+ "test": "states_theme_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "theme 'Selected' marker still on Dark after force_stop_and_relaunch"
+ },
+ {
+ "test": "states_calendar_persists",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "calendar 'Selected' marker still on 'Pick a date' after force_stop_and_relaunch"
+ },
+ {
+ "test": "states_color_swatch_check_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a 'Color' row of four coloured square swatches. Does exactly ONE swatch show a white check-mark (tick) drawn on it, while the other three have no check mark?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: This is a 'Color' row of four coloured square swatches. Does exactly ONE swatch show a white check-mark (tick) drawn on it, while the other three have no check mark?",
+ "tag": "shape"
+ },
+ {
+ "test": "states_color_swatch_moved_vlm",
+ "passed": true,
+ "message": "VLM: Q='This is a 'Color' row of four coloured square swatches. Is the white check-mark now drawn on the RIGHTMOST (fourth) swatch, and NOT on the second swatch?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: This is a 'Color' row of four coloured square swatches. Is the white check-mark now drawn on the RIGHTMOST (fourth) swatch, and NOT on the second swatch?",
+ "tag": "position"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/android_structure_eval.json b/android/v1tzor-timeplanner/tests/android_structure_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..11bd1c78b47f4be8fbdecd429260642f4b28223a
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_structure_eval.json
@@ -0,0 +1,213 @@
+{
+ "module": "structure",
+ "total": 19,
+ "passed": 19,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 9,
+ "passed": 9,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 10,
+ "passed": 10,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 1.1111,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 12,
+ "liveness": 0,
+ "interactive": 7,
+ "depth_ge1": 6,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 7
+ },
+ "results": [
+ {
+ "test": "structure_gate_launch",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_gate_home_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is this a day-planner Home screen: a top app bar with a title, a date row with left/right chevron arrows, and a bottom navigation bar? Answer YES only if that overall schedule-screen layout is visible.' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is this a day-planner Home screen: a top app bar with a title, a date row with left/right chevron arrows, and a bottom navigation bar? Answer YES only if that overall schedule-screen layout is visible.",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_gate_home_topbar",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_bottom_nav_three_tabs",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": ""
+ },
+ {
+ "test": "structure_bottom_nav_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a bottom navigation bar containing exactly 3 icon+label items, evenly spaced across the bottom edge of the screen?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a bottom navigation bar containing exactly 3 icon+label items, evenly spaced across the bottom edge of the screen?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_empty_state_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Does the centre of the screen show a single large placeholder icon with a short line of text under it and one outlined button below that (an empty-state), rather than a list of rows?' A=YES expect=YES",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Does the centre of the screen show a single large placeholder icon with a short line of text under it and one outlined button below that (an empty-state), rather than a list of rows?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_home_empty_to_planned",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "empty-state (Nothing planned yet + Plan now) -> free-slot row 'Unassigned' appears in-place; restored to empty-state on data wipe"
+ },
+ {
+ "test": "structure_editor_cards_layout_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is the main area a vertically stacked list of rounded rectangular field cards (a form), with a Cancel and a Save button at the bottom?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is the main area a vertically stacked list of rounded rectangular field cards (a form), with a Cancel and a Save button at the bottom?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_editor_priority_segmented_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is there a horizontal segmented control divided into exactly 3 side-by-side options labelled Standard, Medium and Max?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Is there a horizontal segmented control divided into exactly 3 side-by-side options labelled Standard, Medium and Max?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_editor_field_cards",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "switch count 0->2 and EditText +1 and Priority/Statistics appear on opening Editor; restored to 0 switches on BACK"
+ },
+ {
+ "test": "structure_category_sheet_position_vlm",
+ "passed": true,
+ "message": "VLM: Q='Is a bottom sheet panel overlaid on the lower part of the screen (its top edge is below the middle, sliding up from the bottom) showing a scrollable list of selectable category rows?' A=YES expect=YES",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "VLM YES: Is a bottom sheet panel overlaid on the lower part of the screen (its top edge is below the middle, sliding up from the bottom) showing a scrollable list of selectable category rows?",
+ "tag": "position"
+ },
+ {
+ "test": "structure_category_sheet_radios",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "RadioButton count 0->5 (+Select button) on opening the Category sheet; restored to 0 on Cancel"
+ },
+ {
+ "test": "structure_settings_color_swatches_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under a 'Color' label, is there a horizontal row of exactly 4 coloured swatch tiles side by side, in distinct colours (reddish, purple, indigo and blue)?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under a 'Color' label, is there a horizontal row of exactly 4 coloured swatch tiles side by side, in distinct colours (reddish, purple, indigo and blue)?",
+ "tag": "color"
+ },
+ {
+ "test": "structure_settings_theme_segmented_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under a 'Theme' label, is there a horizontal segmented control with 3 options (Light, System, Dark) where one option is highlighted with a filled/tinted background?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under a 'Theme' label, is there a horizontal segmented control with 3 options (Light, System, Dark) where one option is highlighted with a filled/tinted background?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_settings_sections",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Settings adds section headers Appearance/Interface/Security + >=2 switches over Home; restored to Schedule on Home tab"
+ },
+ {
+ "test": "structure_analytics_donut_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under 'Category stats', is there a circular ring / donut (pie) chart with a hole in the centre and a number in the middle?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under 'Category stats', is there a circular ring / donut (pie) chart with a hole in the centre and a number in the middle?",
+ "tag": "shape"
+ },
+ {
+ "test": "structure_analytics_heatmap_vlm",
+ "passed": true,
+ "message": "VLM: Q='Under 'Planning stats', is there a grid of small squares arranged in rows and columns (a calendar heatmap), with weekday labels like Mon/Wed/Fri along the left?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: Under 'Planning stats', is there a grid of small squares arranged in rows and columns (a calendar heatmap), with weekday labels like Mon/Wed/Fri along the left?",
+ "tag": "layout"
+ },
+ {
+ "test": "structure_analytics_tab_switch",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Planning stats' block present on Time tab, removed on Workload tab, restored on Time tab"
+ },
+ {
+ "test": "structure_overview_shape",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "Overview adds ProgressBar widgets + Schedules/Current task headers over Home; restored to Schedule on BACK"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/android_testgen_kit.py b/android/v1tzor-timeplanner/tests/android_testgen_kit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2075a22eeb366bd836946556f26c2270c1f3c7e6
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_testgen_kit.py
@@ -0,0 +1,1910 @@
+#!/usr/bin/env python3
+"""Android TestGen Kit — the single source of every test helper, so a test's
+NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
+and self-auditable.
+
+LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
+eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
+`import` it from every test file:
+
+ import os, sys
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+ from android_testgen_kit import * # noqa: F403
+
+WHY THIS EXISTS
+ Helpers used to be re-emitted verbatim into every generated test file (~370
+ lines x 6 files). That blew the output-token ceiling, forced a "write the script
+ in pieces" protocol, let each copy drift, and duplicated one API key into every
+ file. Everything mechanical now lives here; prompts carry only judgement.
+
+ Two orthogonal properties decide whether a suite really exercises an app:
+ * navigation DEPTH — how many SURFACES you cross before the assertion
+ (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
+ * jump RIGOR — what the assertion after the trigger actually checks
+ Prose alone let these drift, so every behavioral test DECLARES both:
+
+ @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
+ def test_create_note():
+ ...
+ record("interaction_create_note", ok, "behavior_wrong: ...",
+ depth=1, jump_kind="value", expect="list shows 'Milk'")
+
+ jump_kind (verbatim strings — audit/stats key off them):
+ "none" no trigger; existence/gate only -> tier 0
+ "liveness" only "did not crash / still foreground" -> tier 1 (weak; never ship)
+ "reach" a real surface jump: the TARGET surface's element
+ APPEARED *and* the SOURCE surface's DISAPPEARED -> tier 2
+ "transition" a state flip (checked/enabled/selected/mode) with before->after -> tier 2
+ "value" a specific expected value/content was asserted -> tier 3
+
+WHAT A "SURFACE" IS ON ANDROID
+ NOT the Activity — single-Activity Compose/Fragment apps never change it, so
+ get_current_activity() cannot discriminate. A surface is the SET of visible
+ discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
+ and_reach(before, after, target, source) therefore proves a real jump; reading a
+ flat tree for an always-present element cannot fake it.
+
+DETERMINISTIC DENOMINATOR
+ Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
+ the same number of records on every code path. @and_test(expects=(...)) owns the
+ try/except and back-fills any declared-but-unrecorded name as a failure, and
+ record() refuses duplicates. N is a literal in the decorator.
+
+PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
+name differs): always use the module-level PACKAGE (argv[1]). Never write a package
+name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
+ python3 android_testgen_kit.py lint_sources # flags all of those
+
+SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
+ python3 android_testgen_kit.py audit
+ python3 android_testgen_kit.py lint
+ python3 android_testgen_kit.py lint_sources
+ python3 android_testgen_kit.py audit_depth [results_dir]
+"""
+from __future__ import annotations
+
+import ast
+import base64
+import functools
+import glob
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.request
+
+KIT_API_VERSION = 1
+
+# ── Runtime context ────────────────────────────────────────────────────────────
+# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
+# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
+PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
+RESULTS_DIR = (
+ sys.argv[2]
+ if len(sys.argv) > 2
+ else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
+)
+ADB = os.environ.get("ADB_PATH", "adb")
+DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")
+
+# Known emulator packages (from adb-tips). Used by type_text, never by tests.
+CLIPPER_PKG = "ca.zgrs.clipper"
+ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
+
+# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
+_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
+_SETTLE_MULT = 2.0 if _REMOTE else 1.0
+SETTLE = {
+ "launch": 3.0,
+ "tap": 1.0,
+ "key": 0.5,
+ "keyboard": 0.5,
+ "dump": 1.0,
+ "ime": 0.5,
+ "text": 0.5,
+ "swipe": 1.0,
+ "dump_retry": 2.0,
+}
+
+JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}
+
+# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
+# gate. Tune here only — never restate them in a prompt.
+QUOTAS = {
+ "existence_max": 0.30, # jump_kind=="none" share of ALL tests
+ "interactive_min": 0.60, # reach|transition|value share of ALL tests
+ "depth_ge1_min": 0.40, # depth>=1 share of INTERACTIVE tests
+ "depth_ge2_min": 0.15, # depth>=2 share of INTERACTIVE tests
+ "value_min": 0.25, # jump_kind=="value" share of INTERACTIVE tests
+ # Suite-wide VLM budget, measured as vlm records / ALL records. The right
+ # share is app-dependent (a chart/canvas app earns more than a list app) and
+ # individual modules may legitimately contribute zero, so this is a BAND on
+ # the whole suite, never a per-module requirement.
+ "vlm_share_min": 0.30,
+ "vlm_share_max": 0.50,
+ "vlm_fine_min": 0.66, # fine-grained share of VLM records
+}
+
+# Depth family (naming convention — see and_audit_depth). A test "crosses a
+# surface" iff it calls a member of this family; and_back* pops one. Semantic
+# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
+# small and the authored tests stay diverse.
+DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
+DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
+DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")
+
+# VLM tags. The fine-grained ones test an exact rendered property; and_audit
+# computes the >=2/3 fine share from these instead of trusting self-report.
+VLM_FINE_TAGS = {"color", "shape", "position", "size"}
+VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}
+
+# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
+FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")
+
+# Never tap these (tests mutate real device state).
+DANGEROUS_TEXTS = [
+ "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
+ "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
+ "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
+]
+
+_MODULE_ALIAS = {
+ "states": "states", "state": "states",
+ "structure": "structure", "structures": "structure",
+ "navigation": "navigation", "nav": "navigation",
+ "interaction": "interaction", "interactions": "interaction",
+ "computation": "computation", "computations": "computation",
+ "text": "text", "texts": "text",
+}
+
+_DEPTH = 0 # surface counter for and_enter/and_back
+_results: list[dict] = []
+_seen: set[str] = set()
+_module: str = ""
+_screen_info: dict | None = None
+
+
+def require_kit(min_version: int) -> None:
+ """Fail loudly at import time if the kit is older than the test expects."""
+ if KIT_API_VERSION < min_version:
+ raise RuntimeError(
+ f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
+ f"v{min_version}; the restored testcase bundle and the kit disagree"
+ )
+
+
+def _infer_module() -> str:
+ stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
+ if stem.startswith("test_android_"):
+ return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
+ return ""
+
+
+def init(module: str = "", package: str = "", results_dir: str = "") -> None:
+ """Optional. Overrides the values inferred from argv/env."""
+ global _module, PACKAGE, RESULTS_DIR
+ if module:
+ _module = _MODULE_ALIAS.get(module, module)
+ if package:
+ PACKAGE = package
+ if results_dir:
+ RESULTS_DIR = results_dir
+
+
+_module = _infer_module()
+
+
+def tier_of(jump_kind: str) -> int:
+ return JUMP_KINDS.get(jump_kind, 2)
+
+
+def settle(kind: str = "tap") -> None:
+ """Sleep the calibrated settling time for `kind` (see SETTLE)."""
+ time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (1) Results / recording
+# ══════════════════════════════════════════════════════════════════════════════
+
+def record(test_name, passed, message="", *, depth=None, jump_kind="none",
+ expect="", tag=None, backfilled=False) -> bool:
+ """Record ONE test result. Returns bool(passed).
+
+ The three positional parameters are unchanged from the legacy inline helper.
+ Everything new is keyword-only with a default, so old call sites still work.
+
+ depth surfaces this test crossed before asserting (see and_enter/and_reach)
+ jump_kind none | liveness | reach | transition | value
+ expect MANDATORY for reach/transition/value — the exact target you
+ OBSERVED on the original app (and_lint flags an empty one)
+ tag for VLM records: color|shape|position|size|layout|content
+ message on failure, start it with setup_failed: / feature_missing: /
+ behavior_wrong: / exception:
+ """
+ if test_name in _seen:
+ print(f" [DUP ] {_module}:{test_name} refused (already recorded) — "
+ f"a duplicate would drift the denominator")
+ return bool(passed)
+ if jump_kind not in JUMP_KINDS:
+ jump_kind = "none"
+ d = _DEPTH if depth is None else int(depth)
+ p = bool(passed)
+ rec = {
+ "test": test_name,
+ "passed": p,
+ "message": str(message),
+ "depth": max(0, d),
+ "jump_kind": jump_kind,
+ "tier": tier_of(jump_kind),
+ "expect": str(expect),
+ }
+ if tag:
+ rec["tag"] = str(tag)
+ if backfilled:
+ rec["backfilled"] = True
+ _results.append(rec)
+ _seen.add(test_name)
+ print(f" [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
+ f"(depth={rec['depth']}, {jump_kind})"
+ + (f" {message}" if message and not p else ""))
+ _flush()
+ return p
+
+
+def _payload(module_name: str) -> dict:
+ """The eval JSON. Shape is byte-compatible with the legacy helper: the
+ aggregator reads module/total/passed/pass_rate, and the results extraction
+ reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
+ rule = [r for r in _results if not r["test"].endswith("_vlm")]
+ vlm = [r for r in _results if r["test"].endswith("_vlm")]
+ rt, rp = len(rule), sum(1 for r in rule if r["passed"])
+ vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
+ total, passed = len(_results), sum(1 for r in _results if r["passed"])
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
+ return {
+ "module": module_name,
+ "total": total,
+ "passed": passed,
+ "failed": total - passed,
+ "pass_rate": round(passed / total, 4) if total else 0,
+ "rule": {"total": rt, "passed": rp, "failed": rt - rp,
+ "pass_rate": round(rp / rt, 4) if rt else 0},
+ "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
+ "pass_rate": round(vp / vt, 4) if vt else 0},
+ "vlm_ratio": round(vt / rt, 4) if rt else 0,
+ "audit": {
+ "kit_api_version": KIT_API_VERSION,
+ "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
+ "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
+ "interactive": len(inter),
+ "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
+ "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
+ "value": sum(1 for r in inter if r["jump_kind"] == "value"),
+ "vlm_fine": fine,
+ },
+ "results": _results,
+ }
+
+
+def _write_json(path: str, data: dict) -> None:
+ """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+
+
+def _flush() -> None:
+ """Persist after EVERY record, so a timeout/emulator hang leaves N results
+ instead of zero. save_results() stays the documented finalizer."""
+ if not _module:
+ return
+ try:
+ _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
+ _payload(_module))
+ except Exception:
+ pass
+
+
+def save_results(module_name: str) -> dict:
+ """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
+ confirmed module name, prints the summary, and runs the in-process audit.
+ Idempotent."""
+ global _module
+ _module = _MODULE_ALIAS.get(module_name, module_name)
+ out = _payload(_module)
+ path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
+ _write_json(path, out)
+ print(f"Results: {out['passed']}/{out['total']} passed "
+ f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
+ f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
+ try:
+ and_audit(RESULTS_DIR)
+ and_lint(RESULTS_DIR)
+ except Exception as exc:
+ print(f"[audit] skipped: {exc}")
+ return out
+
+
+def declared_names() -> list[str]:
+ """Every record name produced so far. The eval run MUST produce this same set
+ against the recreation — a missing feature FAILS, it never vanishes from the
+ denominator."""
+ return [r["test"] for r in _results]
+
+
+def and_test(*, expects, module: str = ""):
+ """Wrap a test function so it contributes EXACTLY len(expects) records on
+ every code path — the deterministic-denominator guarantee.
+
+ Any name in `expects` still unrecorded when the function returns or raises is
+ back-filled as a failure. The literal also lets and_audit_depth attribute
+ records to this function exactly.
+
+ @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
+ def test_toggle_dark():
+ ...
+ """
+ names = tuple(expects)
+
+ def deco(fn):
+ @functools.wraps(fn)
+ def wrapper(*a, **kw):
+ if module:
+ init(module=module)
+ err = ""
+ try:
+ return fn(*a, **kw)
+ except Exception as exc:
+ err = f"{type(exc).__name__}: {exc}"
+ print(f" [EXC ] {fn.__name__}: {err}")
+ return None
+ finally:
+ for n in names:
+ if n not in _seen:
+ record(n, False,
+ f"exception: not_reached ({err})" if err
+ else "setup_failed: not_reached (no exception raised)",
+ backfilled=True)
+ wrapper._and_expects = names
+ return wrapper
+ return deco
+
+
+def run_suite(tests, module: str) -> dict:
+ """Run every test, then finalize. Each test owns its own entry point, so one
+ failure never cascades."""
+ init(module=module)
+ n_fix = len(fixture_names())
+ print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
+ + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
+ if n_fix and not push_fixtures():
+ print(" [fixtures] WARNING: not all fixtures reached the device — every "
+ "test that opens one will record setup_failed")
+ for t in tests:
+ and_reset_depth()
+ try:
+ t()
+ except Exception as exc:
+ print(f" [EXC ] {getattr(t, '__name__', t)}: {exc}")
+ return save_results(module)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (2) Device & adb primitives
+# ══════════════════════════════════════════════════════════════════════════════
+
+def adb_shell(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
+ a multi-device host can never dispatch to the wrong emulator."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except subprocess.TimeoutExpired:
+ return ""
+ except Exception:
+ return ""
+
+
+def adb_raw(*args, timeout: int = 30) -> str:
+ """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
+ try:
+ r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
+ capture_output=True, text=True, timeout=timeout)
+ return r.stdout.strip()
+ except Exception:
+ return ""
+
+
+def device_online() -> bool:
+ try:
+ out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
+ timeout=15).stdout
+ except Exception:
+ return False
+ return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
+ for ln in out.splitlines()[1:])
+
+
+def get_screen_info() -> dict:
+ """Cached screen geometry. EVERY coordinate must be derived from this, never
+ written as a literal — density and font scale differ across devices."""
+ global _screen_info
+ if _screen_info:
+ return _screen_info
+ m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
+ w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
+ md = re.search(r"(\d+)", adb_shell("wm", "density"))
+ _screen_info = {"width": w, "height": h,
+ "density": int(md.group(1)) if md else 440,
+ "center_x": w // 2, "center_y": h // 2}
+ return _screen_info
+
+
+def screencap(path: str) -> bool:
+ """Screenshot to a local path. exec-out first; falls back to on-device
+ screencap + pull, which is what survives a tunnelled adb connection."""
+ os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
+ try:
+ with open(path, "wb") as f:
+ subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
+ stdout=f, timeout=20)
+ if os.path.getsize(path) > 0:
+ return True
+ except Exception:
+ pass
+ remote = "/sdcard/_kit_shot.png"
+ adb_shell("screencap", "-p", remote)
+ adb_raw("pull", remote, path, timeout=40)
+ adb_shell("rm", "-f", remote)
+ return os.path.exists(path) and os.path.getsize(path) > 0
+
+
+# ── Fixtures: sample files a file/image/document app needs to have anything to
+# open. These MUST be a pipeline artifact, not something you push by hand while
+# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
+# hand-pushed file is gone by eval and every test that opens it records
+# setup_failed — blaming the recreation for a harness gap.
+#
+# authoring (once, during recon): write the files into /fixtures/
+# consuming (every test run): run_suite() pushes them before the first test
+#
+# The directory rides along with the test files into the testcases bank, so the
+# bytes are restored on every later eval. Sub-directories are preserved, so
+# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
+FIXTURES_DEVICE_DIR = "/sdcard/Download"
+_fixtures_pushed = False
+
+
+def fixtures_dir() -> str:
+ """The host fixtures directory, or "" when this app needs none.
+
+ The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
+ eval_results/ dir, while the fixtures were restored next to the test files.
+ """
+ for cand in (os.environ.get("FIXTURES_DIR", ""),
+ os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
+ "fixtures"),
+ os.path.join(RESULTS_DIR, "fixtures")):
+ if cand and os.path.isdir(cand):
+ return cand
+ return ""
+
+
+def fixture_names() -> list[str]:
+ """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
+ src = fixtures_dir()
+ if not src:
+ return []
+ out = []
+ for root, _dirs, files in os.walk(src):
+ for fn in sorted(files):
+ if fn.startswith("."):
+ continue
+ out.append(os.path.relpath(os.path.join(root, fn), src))
+ return sorted(out)
+
+
+def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
+ """Where `name` lives on the device after push_fixtures()."""
+ return f"{dest.rstrip('/')}/{name}"
+
+
+def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
+ """Mirror the host fixtures onto the device. Idempotent and safe to call from
+ every test — a file already there with the same size is not re-pushed, so the
+ six module processes cost one real push between them.
+
+ Returns True when the device holds every fixture (including the vacuous case
+ of an app that needs none).
+ """
+ global _fixtures_pushed
+ if _fixtures_pushed and not force:
+ return True
+ src = fixtures_dir()
+ names = fixture_names()
+ if not src or not names:
+ _fixtures_pushed = True
+ return True
+ ok = True
+ pushed = 0
+ for rel in names:
+ local = os.path.join(src, rel)
+ remote = fixture_on_device(rel, dest)
+ try:
+ want = os.path.getsize(local)
+ except OSError:
+ ok = False
+ continue
+ got = adb_shell("stat", "-c", "%s", remote)
+ if not force and got.isdigit() and int(got) == want:
+ continue
+ parent = remote.rsplit("/", 1)[0]
+ if parent:
+ adb_shell("mkdir", "-p", parent)
+ adb_raw("push", local, remote, timeout=120)
+ check = adb_shell("stat", "-c", "%s", remote)
+ if check.isdigit() and int(check) == want:
+ pushed += 1
+ else:
+ ok = False
+ print(f" [fixtures] FAILED to push {rel} -> {remote}")
+ if pushed:
+ # Make the files visible to gallery/media-backed pickers. Both forms are
+ # API-level dependent and neither is required for plain SAF browsing, so
+ # failures here are not fatal.
+ adb_shell("content", "call", "--uri", "content://media/external/file",
+ "--method", "scan_volume", "--arg", "external_primary")
+ adb_shell("am", "broadcast", "-a",
+ "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
+ "-d", f"file://{dest}")
+ print(f" [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
+ _fixtures_pushed = ok
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (3) UI tree query & element matching
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
+ """uiautomator dump -> XML text. Retries because the dump fails outright
+ while an animation is in flight."""
+ if settle_first:
+ settle("dump")
+ remote = "/sdcard/_kit_ui.xml"
+ for attempt in range(retries):
+ adb_shell("uiautomator", "dump", remote)
+ xml = adb_shell("cat", remote, timeout=60)
+ if " list[dict]:
+ """XML -> list of attribute dicts, each with _bounds and _center."""
+ nodes = []
+ for m in re.finditer(r"]+?)/?>", xml_str):
+ attrs_str = m.group(1)
+ attrs = {am.group(1): am.group(2)
+ for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
+ b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
+ if b:
+ x1, y1, x2, y2 = (int(v) for v in b.groups())
+ attrs["_bounds"] = (x1, y1, x2, y2)
+ attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
+ nodes.append(attrs)
+ return nodes
+
+
+def ui(retries: int = 3) -> list[dict]:
+ """THE entry point for a fresh tree. Call it again after ANY state change —
+ a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
+ return parse_nodes(dump_xml(retries=retries))
+
+
+def find_nodes(nodes, **criteria) -> list[dict]:
+ """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
+ "true"/"false" attribute strings. Underscores in keys become dashes
+ (content_desc -> content-desc)."""
+ out = []
+ for n in nodes:
+ ok = True
+ for k, v in criteria.items():
+ key = k.replace("_", "-") if "_" in k and k != "class" else k
+ if key not in n:
+ ok = False
+ break
+ if v is True and n[key] != "true":
+ ok = False
+ break
+ if v is False and n[key] != "false":
+ ok = False
+ break
+ if v is not True and v is not False and n[key] != v:
+ ok = False
+ break
+ if ok:
+ out.append(n)
+ return out
+
+
+def find_node(nodes, **criteria) -> dict | None:
+ f = find_nodes(nodes, **criteria)
+ return f[0] if f else None
+
+
+def find_by_class(nodes, widget_class: str) -> list[dict]:
+ """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
+ return [n for n in nodes if widget_class in n.get("class", "")]
+
+
+def find_node_ci(nodes, text: str) -> dict | None:
+ """Case-insensitive text or content-desc match. Use for user-visible labels
+ whose casing a faithful recreation may legitimately differ on."""
+ t = text.strip().lower()
+ for n in nodes:
+ if (n.get("text", "").strip().lower() == t
+ or n.get("content-desc", "").strip().lower() == t):
+ return n
+ return None
+
+
+def node_by_id(nodes, rid_suffix: str) -> dict | None:
+ """Match the LAST segment of resource-id, so the package prefix (which
+ differs between original and recreation) is never compared."""
+ for n in nodes:
+ rid = n.get("resource-id", "")
+ if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
+ return n
+ return None
+
+
+def find_closest_match(nodes, original_node) -> dict | None:
+ """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
+ best, best_score = None, 0
+ for n in nodes:
+ score = 0
+ if n.get("class") == original_node.get("class"):
+ score += 3
+ if n.get("text") and n.get("text") == original_node.get("text"):
+ score += 5
+ if (n.get("content-desc")
+ and n.get("content-desc") == original_node.get("content-desc")):
+ score += 4
+ if "_center" in n and "_center" in original_node:
+ if (abs(n["_center"][0] - original_node["_center"][0]) < 100
+ and abs(n["_center"][1] - original_node["_center"][1]) < 100):
+ score += 2
+ if score > best_score:
+ best, best_score = n, score
+ return best if best_score >= 3 else None
+
+
+def node_key(n: dict) -> str:
+ """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
+ text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
+ (pure layout containers), which are excluded from a surface."""
+ cls = n.get("class", "").rsplit(".", 1)[-1]
+ ident = (n.get("text", "").strip()
+ or n.get("content-desc", "").strip()
+ or n.get("resource-id", "").rsplit("/", 1)[-1])
+ return f"{cls}|{ident}" if ident else ""
+
+
+def and_showing(nodes=None) -> set[str]:
+ """Snapshot the current SURFACE as a set of discriminating element keys.
+ Only on-screen, non-degenerate, identity-bearing nodes count. Take one
+ before and one after a trigger and feed them to and_reach()."""
+ nodes = ui() if nodes is None else nodes
+ s = get_screen_info()
+ out = set()
+ for n in nodes:
+ b = n.get("_bounds")
+ if not b:
+ continue
+ x1, y1, x2, y2 = b
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ continue
+ if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
+ continue
+ k = node_key(n)
+ if k:
+ out.add(k)
+ return out
+
+
+def and_reach(before, after, target: str, source: str | None = None) -> bool:
+ """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
+ given) the SOURCE surface's element DISAPPEARED. This is what separates a
+ real surface jump from reading an element that was in the tree all along."""
+ before, after = set(before or []), set(after or [])
+ t = target.strip().lower()
+ appeared = any(t in k.lower() for k in (after - before))
+ if source is None:
+ return appeared
+ s = source.strip().lower()
+ return (appeared
+ and any(s in k.lower() for k in before)
+ and not any(s in k.lower() for k in after))
+
+
+def surface_changed(before, after, min_delta: int = 2) -> bool:
+ """Weaker than and_reach: the surface changed materially but you are not
+ naming the target. Use for shape deltas, never to claim a `reach`."""
+ return len(set(before or []) ^ set(after or [])) >= min_delta
+
+
+def and_surface_id(nodes=None) -> str:
+ """A stable-ish fingerprint of the current surface, for "did this change?"."""
+ keys = sorted(and_showing(nodes))
+ return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (4) Interaction
+# ══════════════════════════════════════════════════════════════════════════════
+
+def tap(x, y) -> None:
+ adb_shell("input", "tap", int(x), int(y))
+ settle("tap")
+
+
+def tap_node(node) -> bool:
+ """Tap a node's centre, validating bounds against the real screen first."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ s = get_screen_info()
+ if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
+ return False
+ if "_bounds" in node:
+ x1, y1, x2, y2 = node["_bounds"]
+ if (x2 - x1) < 5 or (y2 - y1) < 5:
+ return False
+ tap(x, y)
+ return True
+
+
+def tap_text(nodes, text: str) -> bool:
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ return tap_node(n) if n else False
+
+
+def is_safe(node) -> bool:
+ """False for destructive controls. Tests mutate real device state, so every
+ exploratory tap must go through this."""
+ blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
+ node.get("resource-id", "")]).lower()
+ return not any(d in blob for d in DANGEROUS_TEXTS)
+
+
+def safe_tap(node) -> bool:
+ return tap_node(node) if node and is_safe(node) else False
+
+
+def long_press(node, ms: int = 800) -> bool:
+ """Long-press = a zero-distance swipe with a duration."""
+ if not node or "_center" not in node:
+ return False
+ x, y = node["_center"]
+ adb_shell("input", "swipe", x, y, x, y, int(ms))
+ settle("tap")
+ return True
+
+
+def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
+ adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
+ settle("swipe")
+
+
+def scroll_down(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.7),
+ s["center_x"], int(s["height"] * (0.7 - frac)))
+
+
+def scroll_up(frac: float = 0.5) -> None:
+ s = get_screen_info()
+ swipe(s["center_x"], int(s["height"] * 0.3),
+ s["center_x"], int(s["height"] * (0.3 + frac)))
+
+
+def open_drawer() -> None:
+ s = get_screen_info()
+ swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)
+
+
+def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
+ """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
+ "after a scroll every previous coordinate is invalid" as code."""
+ for _ in range(max_swipes + 1):
+ nodes = ui()
+ n = find_node(nodes, text=text) or find_node_ci(nodes, text)
+ if n:
+ return n
+ scroll_down(0.4)
+ return None
+
+
+def press_key(keycode) -> None:
+ adb_shell("input", "keyevent", keycode)
+ settle("key")
+
+
+def back() -> None:
+ """Raw BACK. Use and_back() when you are leaving a surface you entered."""
+ press_key("KEYCODE_BACK")
+
+
+def home() -> None:
+ press_key("KEYCODE_HOME")
+
+
+def enter() -> None:
+ press_key("KEYCODE_ENTER")
+
+
+def keyboard_visible() -> bool:
+ return "mInputShown=true" in adb_shell("dumpsys", "input_method")
+
+
+def hide_keyboard() -> bool:
+ """Dismiss the soft keyboard without navigating away. Tries, in order: the
+ collapse affordance, an empty region, then BACK — and BACK is only accepted
+ if the surface did NOT change, because BACK can navigate instead."""
+ if not keyboard_visible():
+ return True
+ nodes = ui()
+ for n in nodes:
+ blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
+ if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
+ if tap_node(n):
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ s = get_screen_info()
+ tap(s["center_x"], int(s["height"] * 0.12)) # top strip is rarely interactive
+ settle("keyboard")
+ if not keyboard_visible():
+ return True
+ sid = and_surface_id()
+ back()
+ settle("keyboard")
+ if keyboard_visible():
+ return False
+ if and_surface_id() != sid:
+ print(" [warn] hide_keyboard: BACK also changed the surface")
+ return True
+
+
+def _quote_for_device(text: str) -> str:
+ """Quote a string for the on-device shell (adb joins argv with spaces)."""
+ return shlex.quote(text)
+
+
+def type_text(node, text: str, *, method: str = "auto",
+ verify_focus: bool = True) -> bool:
+ """Type into an EditText, safely.
+
+ An unfocused EditText silently swallows ALL input (including paste and the
+ ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
+ focused="true" before typing — retrying the tap once.
+
+ Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
+ method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
+ switch drops focus) and ALWAYS restores the original IME in a finally.
+ """
+ if not node:
+ return False
+ target = node
+ if verify_focus:
+ ok = False
+ for _ in range(2):
+ if not tap_node(target):
+ return False
+ settle("keyboard")
+ fresh = find_closest_match(ui(), target) or target
+ if fresh.get("focused") == "true":
+ target, ok = fresh, True
+ break
+ target = fresh
+ if not ok:
+ print(" [warn] type_text: field never reported focused=true")
+ else:
+ tap_node(target)
+ settle("keyboard")
+
+ is_ascii = all(ord(c) < 128 for c in text)
+ use = method
+ if use == "auto":
+ use = "input" if is_ascii else "clipper"
+
+ if use == "input":
+ adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
+ settle("text")
+ return True
+
+ if use == "clipper":
+ adb_shell("am", "broadcast", "-a", "clipper.set",
+ "-e", "text", _quote_for_device(text))
+ settle("text")
+ press_key(279) # KEYCODE_PASTE
+ settle("text")
+ return True
+
+ # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
+ original = adb_shell("settings", "get", "secure", "default_input_method")
+ try:
+ adb_shell("ime", "set", ADB_KEYBOARD_IME)
+ settle("ime")
+ tap_node(target) # IME switch dropped focus
+ settle("keyboard")
+ adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
+ "--es", "msg", _quote_for_device(text))
+ settle("text")
+ return True
+ finally:
+ if original and "null" not in original.lower():
+ adb_shell("ime", "set", original) # NEVER leave it switched
+ settle("ime")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (5) Navigation & the depth family
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reset_depth() -> None:
+ global _DEPTH
+ _DEPTH = 0
+
+
+def and_enter(surface: str = "") -> int:
+ """Call right AFTER your test navigates into a new surface. This is what
+ backs a declared depth>=1 — and_audit_depth looks for a call from the
+ and_enter*/and_reach* family."""
+ global _DEPTH
+ _DEPTH += 1
+ return _DEPTH
+
+
+def and_back() -> int:
+ """Press BACK and pop one surface."""
+ global _DEPTH
+ back()
+ _DEPTH = max(0, _DEPTH - 1)
+ return _DEPTH
+
+
+def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
+ rid: str = "") -> tuple[bool, str]:
+ """Tap a named trigger, then confirm the surface changed. Counts one surface
+ on success. Returns (ok, note). Prefer and_reach_surface when you can name
+ the destination — that yields jump_kind="reach"."""
+ n = None
+ if target_text:
+ n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
+ if n is None and content_desc:
+ n = find_node(nodes, content_desc=content_desc)
+ if n is None and rid:
+ n = node_by_id(nodes, rid)
+ if n is None:
+ return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
+ before = and_showing(nodes)
+ if not tap_node(n):
+ return False, "setup_failed: trigger not tappable"
+ after = and_showing()
+ if not surface_changed(before, after):
+ return False, "behavior_wrong: surface did not change after tapping the trigger"
+ and_enter(target_text or content_desc or rid)
+ return True, ""
+
+
+def and_reach_surface(node, target: str, source: str | None = None) -> bool:
+ """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
+ Counts one surface. This is the only honest way to claim jump_kind="reach"."""
+ before = and_showing()
+ if not tap_node(node):
+ return False
+ after = and_showing()
+ ok = and_reach(before, after, target, source)
+ if ok:
+ and_enter(target)
+ return ok
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
+# ══════════════════════════════════════════════════════════════════════════════
+
+def launch_app() -> None:
+ adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
+ settle("launch")
+
+
+def force_stop() -> None:
+ adb_shell("am", "force-stop", PACKAGE)
+ settle("key")
+
+
+def clear_data() -> None:
+ """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
+ adb_shell("pm", "clear", PACKAGE)
+ settle("key")
+
+
+def restart_app() -> None:
+ force_stop()
+ launch_app()
+
+
+def force_stop_and_relaunch() -> None:
+ """The persistence probe: kill the process, relaunch, then assert the state
+ survived. An in-memory-only recreation fails this."""
+ force_stop()
+ settle("key")
+ launch_app()
+
+
+def get_current_activity() -> str:
+ out = adb_shell("dumpsys", "activity", "activities")
+ m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
+ if m:
+ return m.group(1)
+ m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
+ return m.group(1) if m else ""
+
+
+def is_app_foreground() -> bool:
+ return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")
+
+
+def wait_for_foreground(timeout: int = 10) -> bool:
+ deadline = time.time() + timeout
+ while time.time() < deadline:
+ if is_app_foreground():
+ return True
+ time.sleep(0.5)
+ return False
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (7) VLM
+# ══════════════════════════════════════════════════════════════════════════════
+
+# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
+# endpoint rejected the key that pods are provisioned with, so every generated
+# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
+# shim to reroute it. This speaks plain chat/completions over the standard library
+# only — no `pip install`, and the stale shims in the testcases bank can no longer
+# shadow the transport because nothing imports `dashscope` any more.
+VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
+_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
+# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
+# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
+VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
+# Repeating these cannot help: the request itself is wrong (malformed, missing,
+# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
+_VLM_TERMINAL_CODES = {400, 404, 413, 422}
+
+
+def _vlm_key() -> str:
+ """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
+ VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
+ for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
+ v = os.environ.get(name, "").strip()
+ if v:
+ return v
+ return ""
+
+
+def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
+ """Ask the VLM one question about a local screenshot. Returns the answer text.
+
+ Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
+ `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
+ var. Terminal errors (bad key, malformed/oversized request) are not retried.
+ """
+ retries = retries or VLM_RETRIES
+ key = _vlm_key() or _VLM_DEFAULT_KEY
+ try:
+ with open(image_path, "rb") as f:
+ b64 = base64.b64encode(f.read()).decode()
+ except Exception as exc:
+ print(f"[VLM] cannot read screenshot {image_path}: {exc}")
+ return None
+ mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
+ body = json.dumps({
+ "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
+ "temperature": 0,
+ "messages": [{"role": "user", "content": [
+ {"type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{b64}"}},
+ {"type": "text", "text": prompt},
+ ]}],
+ }).encode()
+
+ for attempt in range(retries):
+ backoff = 2 * (attempt + 1)
+ req = urllib.request.Request(
+ f"{VLM_BASE_URL}/chat/completions", data=body,
+ headers={"Authorization": f"Bearer {key}",
+ "Content-Type": "application/json"})
+ try:
+ with urllib.request.urlopen(req, timeout=120) as resp:
+ data = json.loads(resp.read().decode())
+ text = (data["choices"][0]["message"]["content"] or "").strip()
+ if text:
+ return text
+ print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
+ except urllib.error.HTTPError as exc:
+ detail = exc.read().decode(errors="replace")[:200]
+ print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
+ if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
+ return None # repeating cannot help
+ if exc.code == 429:
+ backoff = 10 * (attempt + 1) # rate limit, not a blip
+ except Exception as exc: # timeout, DNS, reset, bad JSON
+ print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
+ if attempt < retries - 1:
+ time.sleep(backoff)
+ print(f"[VLM] giving up after {retries} attempt(s)")
+ return None
+
+
+def _vlm_log(results_dir: str, entry: dict) -> None:
+ """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
+ path, including failures — a `_vlm` case with no entry here then provably never
+ invoked the VLM, which is what build_manifest keys off."""
+ af = os.path.join(results_dir, "vlm_assertions.json")
+ try:
+ existing = json.load(open(af)) if os.path.exists(af) else []
+ if not isinstance(existing, list):
+ existing = []
+ except Exception:
+ existing = []
+ existing.append(entry)
+ try:
+ _write_json(af, existing) # type: ignore[arg-type]
+ except Exception:
+ try:
+ with open(af, "w") as f:
+ json.dump(existing, f, indent=2, ensure_ascii=False)
+ except Exception as exc:
+ print(f" [warn] vlm_assert: cannot write {af}: {exc}")
+
+
+def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
+ depth=None, jump_kind="none", tag=None) -> bool:
+ """Screenshot the current screen, ask the VLM one YES/NO question, record it.
+
+ `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
+ track in save_results(). `tag` (color|shape|position|size|layout|content) lets
+ and_audit compute the fine-grained share mechanically — always set it.
+
+ Ask about a SPECIFIC observable rendered property. A question that a blank
+ screen or any app would pass is worthless.
+ """
+ if not test_name.endswith("_vlm"):
+ test_name += "_vlm"
+ rd = results_dir or RESULTS_DIR
+ if tag and tag not in VLM_TAGS:
+ print(f" [warn] vlm_assert: unknown tag {tag!r}")
+ ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")
+
+ def _fail(msg: str, resp=None, answer="") -> bool:
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": False, "tag": tag or "", "error": msg})
+ return record(test_name, False, msg,
+ depth=depth, jump_kind=jump_kind, tag=tag)
+
+ if not screencap(ss_path):
+ return _fail("setup_failed: screenshot capture failed")
+
+ prompt = ("Look at this Android app screenshot and answer the following question "
+ "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
+ f"Question: {question}\n\nAnswer (YES or NO):")
+ # An unparseable answer is the same class of flakiness as an empty body, so
+ # re-ask rather than scoring harness noise against the VLM track.
+ answer, resp = "", None
+ for ask in range(VLM_RETRIES):
+ resp = call_vlm(ss_path, prompt)
+ if resp is None:
+ return _fail("setup_failed: VLM API call failed")
+ a = resp.strip().upper()
+ # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
+ # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
+ # failing the test on harness noise instead of re-asking.
+ has_yes = re.search(r"\bYES\b", a) is not None
+ has_no = re.search(r"\bNO\b", a) is not None
+ if a.startswith("YES"):
+ answer = "YES"
+ elif a.startswith("NO"):
+ answer = "NO"
+ elif has_yes and not has_no:
+ answer = "YES"
+ elif has_no and not has_yes:
+ answer = "NO"
+ if answer:
+ break
+ print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
+ if not answer:
+ return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
+ f"asks {resp!r}", resp=resp)
+
+ passed = answer == expect.upper()
+ record(test_name, passed,
+ (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
+ else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
+ depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
+ _vlm_log(rd, {"test_name": test_name, "question": question,
+ "screenshot": ss_path, "vlm_response": resp,
+ "vlm_answer": answer, "expected": expect,
+ "passed": passed, "tag": tag or ""})
+ return passed
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _load_all(results_dir: str) -> list[dict]:
+ recs, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in glob.glob(pat):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ recs.append(t)
+ return recs
+
+
+def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
+ """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
+ quota TARGETS with the concrete gap. GOALS, not a gate."""
+ results_dir = results_dir or RESULTS_DIR
+ q = quotas or QUOTAS
+ recs = _load_all(results_dir)
+ backfilled = [r for r in recs if r.get("backfilled")]
+ recs = [r for r in recs if not r.get("backfilled")]
+ n = len(recs)
+ if not n:
+ print(f"[and_audit] no records under {results_dir}")
+ return {"total": 0}
+ kinds = [r.get("jump_kind", "none") for r in recs]
+ none_n = sum(1 for k in kinds if k == "none")
+ live_n = sum(1 for k in kinds if k == "liveness")
+ inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
+ ni = len(inter) or 1
+ d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
+ d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
+ val = sum(1 for r in inter if r.get("jump_kind") == "value")
+ vlm = [r for r in recs if r["test"].endswith("_vlm")]
+ fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
+ vlm_share = len(vlm) / n
+
+ def line(label, got, need, kind):
+ ok = got >= need if kind == "min" else got <= need
+ return ok, (f" [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
+ f"({'>=' if kind == 'min' else '<='} {need:.0%})")
+
+ lo, hi = q["vlm_share_min"], q["vlm_share_max"]
+ vlm_ok = lo <= vlm_share <= hi
+ if vlm_share < lo:
+ # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
+ need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
+ vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
+ f"per lane NEXT run; do not re-run to chase it")
+ elif vlm_share > hi:
+ vlm_hint = "over budget — allocate fewer per lane next run"
+ else:
+ vlm_hint = "in budget"
+ vlm_msg = (f" [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
+ f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
+ f"— {vlm_hint}")
+
+ checks = [
+ line("existence(none)/all", none_n / n, q["existence_max"], "max"),
+ line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
+ line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
+ line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
+ line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
+ (vlm_ok, vlm_msg),
+ line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
+ ]
+ print(f"[and_audit] {results_dir} total={n} interactive={len(inter)} "
+ f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
+ f"value={val} vlm={len(vlm)} vlm_fine={fine}")
+ if backfilled:
+ print(f" [!!!] {len(backfilled)} record(s) never reached their assertion "
+ f"(back-filled as failures) — excluded from the ratios above; the "
+ f"100%-pass gate on the original app must catch these")
+ for _ok, msg in checks:
+ print(msg)
+ passed = all(ok for ok, _ in checks)
+ print("[and_audit] " + ("ALL TARGETS MET" if passed else
+ "some targets below — this is a REPORT, not a task: finalize now and fix "
+ "the shortfall in the NEXT run's plan. Re-running the suite to move these "
+ "numbers costs hours and changes nothing about the app under test"))
+ return {"total": n, "interactive": len(inter), "none": none_n,
+ "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
+ "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
+ "backfilled": len(backfilled),
+ "passed": passed, "checks": [m for _o, m in checks]}
+
+
+def and_lint(results_dir: str = "") -> list[str]:
+ """Flag weak or inconsistent DECLARATIONS."""
+ results_dir = results_dir or RESULTS_DIR
+ issues, names = [], set()
+ for r in _load_all(results_dir):
+ jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
+ if nm in names:
+ issues.append(f"{nm}: duplicate record name (drifts the denominator)")
+ names.add(nm)
+ if jk not in JUMP_KINDS:
+ issues.append(f"{nm}: unknown jump_kind {jk!r}")
+ if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
+ issues.append(f"{nm}: jump_kind={jk} but empty expect "
+ f"(name the specific observed target)")
+ if jk == "liveness":
+ issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
+ if int(r.get("depth", 0)) < 0:
+ issues.append(f"{nm}: negative depth")
+ msg = str(r.get("message", ""))
+ if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
+ issues.append(f"{nm}: failure message must start with one of "
+ f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
+ if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
+ issues.append(f"{nm}: VLM record has no tag "
+ f"(color|shape|position|size|layout|content)")
+ if issues:
+ print(f"[and_lint] {len(issues)} issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint] no issues")
+ return issues
+
+
+# Non-portable source patterns: they pass on the ORIGINAL app and break on the
+# RECREATION (different package, different install path). Each is a hard defect.
+_BAD_SOURCE_PATTERNS = [
+ (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
+ "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
+ "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
+ "com.android.adbkeyboard", "ca.zgrs.clipper",
+ "android.intent.", "com.google.android.inputmethod")),
+ (r"""["'][^"']*\.apk["']|clean\.apk""",
+ "names an APK path; the test must never install or locate the app", ()),
+ (r"/data/data/|/sdcard/Android/data/",
+ "uses a per-package data path, which breaks when the recreation's package "
+ "differs; drive state through the GUI", ()),
+ (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
+ "taps a hardcoded pixel coordinate; derive it from a node's _center or "
+ "get_screen_info()", ()),
+ (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
+ "seeds state outside the GUI; the recreation may not honor it — drive the "
+ "same state through the UI", ()),
+ (r"am\s+start\s+-n\s",
+ "deep-links straight to a component: not portable, and not navigation "
+ "(it cannot back a depth claim)", ()),
+ (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
+ "hardcodes a device serial; use the module-level DEVICE", ()),
+]
+
+
+def and_lint_sources(testgen_dir: str = "") -> list[str]:
+ """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
+ drift. A clean result means the suite will actually drive the recreation, not
+ just the original."""
+ testgen_dir = testgen_dir or RESULTS_DIR
+ kit_base = os.path.basename(__file__)
+ py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
+ if os.path.basename(p) != kit_base]
+ kit_names = set(globals().keys())
+ # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
+ # emulators, so naming one without pushing it means it only ever existed
+ # because someone put it there by hand while exploring.
+ _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
+ _DOC_RE = re.compile(
+ r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
+ _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
+ recursive=True) if os.path.isfile(f)]
+ issues = []
+ srcs = {}
+ for p in py:
+ try:
+ srcs[p] = open(p, errors="replace").read()
+ except Exception:
+ continue
+ suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
+ for s in srcs.values())
+ if _fix_files and not suite_pushes:
+ issues.append(
+ f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
+ f"calls push_fixtures() — they never reach the device, so every test "
+ f"that opens one records setup_failed. Call it once via run_suite(), "
+ f"or drop the directory.")
+ for p, src in srcs.items():
+ base = os.path.basename(p)
+ # Strip comments AND docstrings: prose describing the app under test names
+ # files it opens, which is not the same as the code depending on one.
+ scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
+ scan = re.sub(r"#[^\n]*", "", scan)
+ # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
+ # the quote-comma-quote separators to read those calls as command lines.
+ flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
+ if not suite_pushes:
+ for ln in scan.splitlines():
+ m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
+ if m:
+ issues.append(
+ f"{base}: needs a sample file on the device "
+ f"[{ln.strip()[:60]}] but the suite never calls "
+ f"push_fixtures() — testgen and eval run on DIFFERENT "
+ f"emulators, so at eval the file is absent. Author the bytes "
+ f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
+ f"run_suite() push them.")
+ break
+ for pat, why, allow in _BAD_SOURCE_PATTERNS:
+ hit = None
+ for form in (scan, flat):
+ for m in re.finditer(pat, form):
+ cand = m.group(0)
+ if allow and any(a in cand for a in allow):
+ continue
+ hit = cand
+ break
+ if hit:
+ break
+ if hit:
+ issues.append(f"{base}: {why} [{hit[:48]}]")
+ # kit API drift — an import/attr the kit does not define
+ imported: list[str] = []
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
+ imported += m.group(1).split(",")
+ for m in re.finditer(
+ r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
+ imported += m.group(1).split(",")
+ for raw in imported:
+ nm = raw.strip().split(" as ")[0].strip()
+ if nm and nm != "*" and nm not in kit_names:
+ issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
+ f"kit does not define (would ImportError at eval)")
+ for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
+ if m.group(1) not in kit_names:
+ issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
+ f"not define (would AttributeError at eval)")
+ if issues:
+ print(f"[and_lint_sources] {len(issues)} portability issue(s):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_lint_sources] no portability issues")
+ return issues
+
+
+# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
+def _ast_call_name(node) -> str:
+ f = node.func
+ if isinstance(f, ast.Attribute):
+ return f.attr
+ if isinstance(f, ast.Name):
+ return f.id
+ return ""
+
+
+def _string_locals(fn_node) -> dict[str, str]:
+ """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
+ out = {}
+ for n in ast.walk(fn_node):
+ if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
+ and isinstance(n.value.value, str):
+ for t in n.targets:
+ if isinstance(t, ast.Name):
+ out[t.id] = n.value.value
+ return out
+
+
+def _record_names(fn_node) -> list[str]:
+ """Literal record()/vlm_assert() names in this function, preferring the
+ @and_test(expects=(...)) literal when present."""
+ for dec in getattr(fn_node, "decorator_list", []):
+ if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
+ for kw in dec.keywords:
+ if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
+ return [e.value for e in kw.value.elts
+ if isinstance(e, ast.Constant) and isinstance(e.value, str)]
+ slocals = _string_locals(fn_node)
+ names = []
+ for n in ast.walk(fn_node):
+ if not (isinstance(n, ast.Call)
+ and _ast_call_name(n) in ("record", "vlm_assert")):
+ continue
+ if not n.args:
+ continue
+ a0 = n.args[0]
+ if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
+ names.append(a0.value)
+ elif isinstance(a0, ast.Name) and a0.id in slocals:
+ names.append(slocals[a0.id])
+ return names
+
+
+def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
+ """(fwd, back, reach) depth-family calls, descending `budget` levels into
+ file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
+ seen = seen if seen is not None else set()
+ fwd = bk = rch = 0
+ relaunch = False
+ for node in ast.walk(fn_node):
+ if not isinstance(node, ast.Call):
+ continue
+ cn = _ast_call_name(node)
+ if DEPTH_FWD_RE.match(cn):
+ fwd += 1
+ if cn.startswith("and_reach"):
+ rch += 1
+ elif DEPTH_BACK_RE.match(cn):
+ bk += 1
+ elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
+ relaunch = True
+ elif budget > 0 and cn in local_funcs and cn not in seen:
+ seen.add(cn)
+ f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
+ fwd, bk, rch = fwd + f, bk + b, rch + r
+ return fwd, bk, rch, relaunch
+
+
+def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
+ """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
+ DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.
+
+ Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
+ depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
+ or anywhere in the module for variable-named records), plus a "reach" that was
+ achieved by relaunching the app rather than navigating.
+ """
+ testgen_dir = testgen_dir or RESULTS_DIR
+ results_dir = results_dir or testgen_dir
+ files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
+ + glob.glob(os.path.join(testgen_dir, "tests",
+ "test_android_*.py")))]
+ per_record, per_module = {}, {}
+ for p in files:
+ try:
+ tree = ast.parse(open(p, errors="replace").read())
+ except Exception:
+ continue
+ stem = os.path.basename(p)[len("test_android_"):-len(".py")]
+ mod = _MODULE_ALIAS.get(stem, stem)
+ local_funcs = {n.name: n for n in ast.walk(tree)
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
+ module_backing = any(
+ isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
+ for n in ast.walk(tree))
+ per_module[mod] = {"module_backing": module_backing}
+ for fn in local_funcs.values():
+ if not fn.name.startswith("test_"):
+ continue
+ fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
+ measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
+ for nm in _record_names(fn):
+ per_record[(mod, nm)] = {"measured_depth": measured,
+ "backing": fwd >= 1, "n_reach": rch,
+ "relaunch": relaunch, "fn": fn.name}
+ issues = []
+ for r in _load_all(results_dir):
+ nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
+ depth = int(r.get("depth", 0) or 0)
+ strong = depth >= 1 or jk == "reach"
+ hit = None
+ for (mod, rname), v in per_record.items():
+ if rname == nm:
+ hit = v
+ break
+ if hit is not None:
+ if strong and not hit["backing"]:
+ issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
+ f"jump_kind={jk} but NO backing and_enter*/and_reach* "
+ f"call (fake depth)")
+ elif jk == "reach" and hit["n_reach"] == 0:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
+ f"and_reach* call in its code")
+ elif jk == "reach" and hit["relaunch"]:
+ issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
+ f"relaunches the app — that is not navigation")
+ elif strong and not any(v.get("module_backing", True)
+ for v in per_module.values()):
+ issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
+ f"and_enter*/and_reach* call anywhere (fake depth)")
+ if issues:
+ print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
+ f"fix by adding the and_reach/and_enter you navigated with, or lower "
+ f"the declared depth):")
+ for i in issues:
+ print(" - " + i)
+ else:
+ print("[and_audit_depth] no fake-depth issues "
+ "(declared depth/reach backed by nav calls)")
+ return issues
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
+#
+# Without this, the eval denominator is whatever the candidate happened to emit:
+# a recreation that crashes a module SHRINKS its own denominator instead of
+# counting the missing behaviour as failures. The manifest is frozen ONCE per
+# task from the ORIGINAL app's run and is the denominator authority for every
+# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
+# ══════════════════════════════════════════════════════════════════════════════
+
+MANIFEST_NAME = "test_manifest.json"
+MANIFEST_VERSION = 1
+
+
+def qualify_name(module: str, test: str) -> str:
+ """`module::test` — two modules may legitimately reuse a short test name."""
+ return test if "::" in test else f"{module}::{test}"
+
+
+def _record_status(rec: dict) -> str:
+ if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
+ return rec["status"]
+ return "passed" if rec.get("passed") else "failed"
+
+
+def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
+ """Like _load_all but keeps the owning module, so names can be qualified."""
+ out, seen_files = [], set()
+ for pat in (os.path.join(results_dir, "android_*_eval.json"),
+ os.path.join(results_dir, "eval_results", "android_*_eval.json")):
+ for path in sorted(glob.glob(pat)):
+ base = os.path.basename(path)
+ if base in seen_files:
+ continue
+ seen_files.add(base)
+ try:
+ data = json.load(open(path))
+ except Exception:
+ continue
+ mod = data.get("module") or base[len("android_"):-len("_eval.json")]
+ for t in data.get("results", []):
+ if isinstance(t, dict) and "test" in t:
+ out.append((str(mod), t))
+ return out
+
+
+def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
+ """(names with >=1 logged VLM attempt, whether any log file was found).
+
+ Checks the root AND eval_results/ — the agent's self-validation run drives
+ test_verify.sh with --output-dir, which puts the log one level down.
+ """
+ names, found = set(), False
+ for sub in ("", "eval_results"):
+ p = os.path.join(results_dir, sub, "vlm_assertions.json")
+ if not os.path.isfile(p):
+ continue
+ found = True
+ try:
+ for x in json.load(open(p)):
+ if isinstance(x, dict) and x.get("test_name"):
+ names.add(str(x["test_name"]))
+ except Exception:
+ pass
+ return names, found
+
+
+def build_manifest(results_dir: str = "", *, task_id: str = "",
+ baseline_model: str = "", out_path: str = "") -> dict:
+ """Freeze the ORIGINAL app's PASSING tests as the denominator.
+
+ A test that fails on the original is not a signal about any recreation, so it
+ is moved to `ignored[reason=baseline_fail]` instead of counting against every
+ candidate. This is the only denominator-shrinking mechanism, and it is applied
+ identically to all candidates.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ logged, log_found = _vlm_logged_names(results_dir)
+ tests, ignored, vlm_assertions = [], [], []
+ n_unverified = 0
+ for mod, rec in _load_by_module(results_dir):
+ name = qualify_name(mod, str(rec.get("test", "")))
+ status = _record_status(rec)
+ entry = {"name": name, "module": mod, "baseline_status": status}
+ is_vlm = name.endswith("_vlm")
+ # A passing _vlm case with no logged attempt never provably reached the
+ # judge on the original app — it must not sit in the VLM denominator that
+ # every recreation is scored against.
+ if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
+ n_unverified += 1
+ ignored.append({"name": name, "module": mod,
+ "reason": "vlm_unverified",
+ "baseline_status": status,
+ "message": "no attempt in vlm_assertions.json — the VLM "
+ "was never provably invoked for this case"})
+ continue
+ if status == "passed":
+ tests.append(entry)
+ if is_vlm:
+ vlm_assertions.append({"name": name, "module": mod,
+ "tag": rec.get("tag", "")})
+ else:
+ ignored.append({"name": name, "module": mod,
+ "reason": "baseline_fail",
+ "baseline_status": status,
+ "message": str(rec.get("message", ""))[:300]})
+ tests.sort(key=lambda t: t["name"])
+ ignored.sort(key=lambda t: t["name"])
+ payload = "\n".join(t["name"] for t in tests)
+ pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
+ or (PACKAGE if "." in PACKAGE else ""))
+ manifest = {
+ "manifest_version": MANIFEST_VERSION,
+ "kit_api_version": KIT_API_VERSION,
+ "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
+ "baseline_model": baseline_model or os.environ.get("MODEL", ""),
+ "baseline_package": pkg,
+ "total": len(tests),
+ "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
+ "tests": tests,
+ "ignored": ignored,
+ "vlm_assertions": vlm_assertions,
+ "vlm_total": len(vlm_assertions),
+ "n_vlm_unverified": n_unverified,
+ "vlm_log_found": log_found,
+ }
+ dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
+ tmp = dest + ".tmp"
+ with open(tmp, "w") as f:
+ json.dump(manifest, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, dest)
+ print(f"[build_manifest] {dest} total={manifest['total']} "
+ f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
+ f"sha={manifest['manifest_sha']}")
+ if n_unverified:
+ print(f" [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
+ f"vlm_unverified — no attempt logged in vlm_assertions.json"
+ + ("" if log_found else " (no log file found at all — the suite may "
+ "have bypassed the kit's vlm_assert)")
+ + ". They are out of the VLM denominator; fix the VLM path rather "
+ "than accepting the smaller denominator.")
+ base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
+ if base_fail:
+ print(f" {len(base_fail)} baseline failure(s) excluded from the denominator "
+ f"(they say nothing about a recreation):")
+ for i in base_fail[:20]:
+ print(f" - {i['name']}: {i['message'][:120]}")
+ return manifest
+
+
+def load_manifest(d: str = "") -> dict | None:
+ """Return the frozen manifest from `d` (or its eval_results/), else None."""
+ d = d or RESULTS_DIR
+ for p in (os.path.join(d, MANIFEST_NAME),
+ os.path.join(d, "eval_results", MANIFEST_NAME)):
+ if os.path.isfile(p):
+ try:
+ m = json.load(open(p))
+ except Exception:
+ continue
+ if isinstance(m, dict) and m.get("tests"):
+ return m
+ return None
+
+
+def score_against_manifest(results_dir: str = "",
+ manifest: dict | None = None) -> dict:
+ """Score a candidate run against the frozen denominator.
+
+ denominator = len(manifest["tests"]) regardless of what the candidate emitted.
+ A manifest test the candidate never reported is injected as `not_run` (a
+ non-pass); a test the candidate invented is excluded. A module that crashed
+ on import therefore scores 0/full instead of vanishing.
+ """
+ results_dir = results_dir or RESULTS_DIR
+ manifest = manifest or load_manifest(results_dir)
+ if not manifest:
+ return {}
+ expected = {t["name"]: t for t in manifest["tests"]}
+ got = {}
+ for mod, rec in _load_by_module(results_dir):
+ got[qualify_name(mod, str(rec.get("test", "")))] = rec
+
+ per_test, by_module = {}, {}
+ injected = 0
+ for name, meta in expected.items():
+ rec = got.get(name)
+ if rec is None:
+ status, msg = "not_run", "not_run: absent from the candidate's output"
+ injected += 1
+ else:
+ status, msg = _record_status(rec), str(rec.get("message", ""))
+ per_test[name] = {"status": status, "message": msg[:300]}
+ m = by_module.setdefault(meta.get("module", "?"),
+ {"total": 0, "passed": 0, "not_run": 0})
+ m["total"] += 1
+ m["passed"] += status == "passed"
+ m["not_run"] += status == "not_run"
+
+ unexpected = sorted(set(got) - set(expected))
+ total = len(expected)
+ passed = sum(1 for v in per_test.values() if v["status"] == "passed")
+ vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
+ vlm_total = len(vlm_names)
+ vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
+ rule_total = total - vlm_total
+ rule_passed = passed - vlm_passed
+ for m in by_module.values():
+ m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0
+
+ out = {
+ "scored_against": "manifest",
+ "manifest_sha": manifest.get("manifest_sha", ""),
+ "manifest_total": total,
+ "total": total,
+ "passed": passed,
+ "pass_rate": round(passed / total, 4) if total else 0.0,
+ "n_injected_not_run": injected,
+ "n_unexpected": len(unexpected),
+ "unexpected": unexpected[:50],
+ "rule": {"total": rule_total, "passed": rule_passed,
+ "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
+ "vlm": {"total": vlm_total, "passed": vlm_passed,
+ "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
+ "by_module": by_module,
+ "per_test": per_test,
+ }
+ print(f"[score_against_manifest] sha={out['manifest_sha']} "
+ f"{passed}/{total} = {out['pass_rate']:.4f} "
+ f"(injected_not_run={injected} unexpected={len(unexpected)}) "
+ f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
+ return out
+
+
+if __name__ == "__main__":
+ _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
+ "build_manifest": build_manifest}
+ _argv = sys.argv[1:]
+ if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
+ and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
+ elif _argv[:1] == ["score"] and len(_argv) >= 2:
+ _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
+ _out = score_against_manifest(_argv[1], _m)
+ if not _out:
+ print("no manifest found — cannot score against a fixed denominator",
+ file=sys.stderr)
+ sys.exit(2)
+ print(json.dumps(_out, ensure_ascii=False))
+ elif len(_argv) >= 2 and _argv[0] in _fns:
+ _fns[_argv[0]](_argv[1])
+ else:
+ print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} \n"
+ " android_testgen_kit.py audit_depth [results_dir]\n"
+ " android_testgen_kit.py score [manifest_dir]")
diff --git a/android/v1tzor-timeplanner/tests/android_text_eval.json b/android/v1tzor-timeplanner/tests/android_text_eval.json
new file mode 100644
index 0000000000000000000000000000000000000000..fca505873487a313c29e583b56a5f1ed6f451076
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/android_text_eval.json
@@ -0,0 +1,159 @@
+{
+ "module": "text",
+ "total": 14,
+ "passed": 14,
+ "failed": 0,
+ "pass_rate": 1.0,
+ "rule": {
+ "total": 13,
+ "passed": 13,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm": {
+ "total": 1,
+ "passed": 1,
+ "failed": 0,
+ "pass_rate": 1.0
+ },
+ "vlm_ratio": 0.0769,
+ "audit": {
+ "kit_api_version": 1,
+ "existence": 3,
+ "liveness": 0,
+ "interactive": 11,
+ "depth_ge1": 11,
+ "depth_ge2": 2,
+ "value": 0,
+ "vlm_fine": 1
+ },
+ "results": [
+ {
+ "test": "text_home_title",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "top-bar title == 'Schedule'"
+ },
+ {
+ "test": "text_empty_state",
+ "passed": true,
+ "message": "",
+ "depth": 0,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "empty-state 'Nothing planned yet' + button 'Plan now'"
+ },
+ {
+ "test": "text_unassigned_after_plan",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "transition",
+ "tier": 2,
+ "expect": "'Unassigned' absent before Plan now, present after"
+ },
+ {
+ "test": "text_analytics_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Analytics' title + 'Category stats' / 'Planning stats' headers"
+ },
+ {
+ "test": "text_pie_center_total_vlm",
+ "passed": true,
+ "message": "VLM: Q='In the centre of the circular donut/ring chart under the 'Category stats' section, is a time total drawn as 'h m' (for example '0h 0m') positioned INSIDE the ring's hole (surrounded by the coloured ring), rather than off to the side in the legend?' A=YES expect=YES",
+ "depth": 1,
+ "jump_kind": "none",
+ "tier": 0,
+ "expect": "VLM YES: In the centre of the circular donut/ring chart under the 'Category stats' section, is a time total drawn as 'h m' (for example '0h 0m') positioned INSIDE the ring's hole (surrounded by the coloured ring), rather than off to the side in the legend?",
+ "tag": "position"
+ },
+ {
+ "test": "text_analytics_legend",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "legend category names 'Misc' and 'Else'"
+ },
+ {
+ "test": "text_settings_appearance",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Settings 'Appearance' section + 'Theme' row"
+ },
+ {
+ "test": "text_settings_developer",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Developer row value == 'Stanislav Aleshin'"
+ },
+ {
+ "test": "text_editor_statistics",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Editor title 'Editor' + 'Statistics' / 'Include in analytics'"
+ },
+ {
+ "test": "text_editor_notifications",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Editor 'Notifications' + 'Set a reminder for the task start'"
+ },
+ {
+ "test": "text_category_sheet",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "'Select a category' + radio rows 'Study' / 'Shopping'"
+ },
+ {
+ "test": "text_drawer_header",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "drawer header 'Time Planner' + items 'Templates' / 'Categories'"
+ },
+ {
+ "test": "text_templates_empty",
+ "passed": true,
+ "message": "",
+ "depth": 2,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Templates empty-state 'List is empty' + 'Sort'"
+ },
+ {
+ "test": "text_overview_headers",
+ "passed": true,
+ "message": "",
+ "depth": 1,
+ "jump_kind": "reach",
+ "tier": 2,
+ "expect": "Overview 'Schedules' + 'Undistributed tasks' + status chip"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/tests/conftest.py b/android/v1tzor-timeplanner/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..93bec384d3f093c68396a0c55ce68ca277bf4c27
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/conftest.py
@@ -0,0 +1 @@
+pytest_plugins = ["rb_unify.pytest_rb", "rb_unify.android_bridge"]
diff --git a/android/v1tzor-timeplanner/tests/requirements.txt b/android/v1tzor-timeplanner/tests/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..33527cc259d16af37f80a019c74faab64898923c
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/requirements.txt
@@ -0,0 +1,2 @@
+pytest
+pillow
diff --git a/android/v1tzor-timeplanner/tests/test_android_computation.py b/android/v1tzor-timeplanner/tests/test_android_computation.py
new file mode 100644
index 0000000000000000000000000000000000000000..e359879242d63bf07d28a13bdd3cb07a16d3175c
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_computation.py
@@ -0,0 +1,699 @@
+#!/usr/bin/env python3
+"""COMPUTATION lane — CORE FUNCTION input->output for TimePlanner.
+
+Owns jump_kind="value": apply a specific INPUT (Start/End times, a category, a
+task count) then assert the SPECIFIC computed OUTPUT string the RUNNING original
+produced. Every expected value here was OBSERVED live on the original app, never
+derived from source or from arithmetic — the app is the ground truth.
+
+The two computations this planner actually performs:
+ * Editor duration = End - Start, formatted "Xh Ym" (recomputed live as the
+ Material time picker changes End). Independent of the wall clock, so stable.
+ * Analytics category proportion: with a single categorized task the donut/legend
+ show that category at "100%" and every other at "0%"; the donut CENTER shows
+ the summed total time. Stable for a controlled single-task input.
+
+Wall-clock-dependent values (a running task's ELAPSED time, "today") are NEVER
+asserted — only schedule geometry (End-Start) and controlled proportions.
+
+Run:
+ python3 test_android_computation.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+# The category we create/read for the Analytics proportion. A real built-in
+# (verified in recon: Absent/Shopping/Health/Study/Sleep/Work), so the golden
+# create flow yields a legend row we can read straight out of the dump. "Study"
+# never accidentally matches an empty analytics page.
+CAT = "Study"
+
+# KEYCODE_MOVE_END / KEYCODE_DEL — used ONLY to clear the time-picker hour field
+# via the kit's press_key (never a raw `input`).
+_KEY_MOVE_END = 123
+_KEY_DEL = 67
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Trap handling — copied verbatim from the interaction lane's proven pattern.
+# (A) LeakCanary launcher alias: the .debug build bundles a SECOND launcher
+# activity in the SAME package; monkey LAUNCHER non-deterministically opens
+# it and wait_for_foreground()/is_app_foreground() then LIE (same package).
+# We detect it by the ABSENCE of a Home surface and force-stop + relaunch.
+# (B) Onboarding: after clear_data() a notification-permission dialog appears
+# ("Allow"/"Don't allow", curly apostrophe); ui() sees it, so dismiss it.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_onboarding(nodes=None):
+ """Tap the notification-permission dialog's button if present. Returns True if
+ it dismissed one (so the caller re-loops)."""
+ nodes = nodes if nodes is not None else ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
+ None)
+ if btn is None:
+ return False
+ tap_node(btn)
+ return True
+
+
+def _home_ready(nodes):
+ """Home's own surface — the top-bar title, the empty-state prompt, or the
+ 'Plan now' control. Any means the REAL app (not LeakCanary, not the launcher)
+ is on screen."""
+ return (find_node_ci(nodes, "Schedule") is not None
+ or find_node_ci(nodes, "Plan now") is not None
+ or find_node_ci(nodes, "Nothing planned yet") is not None)
+
+
+def ensure_home(max_tries=20):
+ for _ in range(max_tries):
+ nodes = ui()
+ if dismiss_onboarding(nodes):
+ settle("tap")
+ continue
+ if _home_ready(nodes):
+ settle("launch")
+ if _home_ready(ui()):
+ return True
+ continue
+ force_stop(); settle("key")
+ launch_app(); settle("launch")
+ return _home_ready(ui())
+
+
+def start_home_clean():
+ """Virgin-database entry point: clear data, relaunch, dismiss onboarding,
+ settle on the empty Home. Tests that need a KNOWN empty schedule start here."""
+ clear_data()
+ launch_app()
+ return ensure_home()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Compose tap helpers — leaves report clickable="false"; tap the clickable
+# ancestor whose bounds enclose the label's centre. (Pattern reused from the
+# interaction lane; not imported, so this file stands alone.)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _clickable_ancestor(nodes, anchor):
+ """Tightest clickable node whose bounds contain `anchor`'s centre."""
+ if not anchor or "_center" not in anchor:
+ return None
+ cx, cy = anchor["_center"]
+ cands = [n for n in nodes
+ if n.get("clickable") == "true" and "_bounds" in n
+ and n["_bounds"][0] <= cx <= n["_bounds"][2]
+ and n["_bounds"][1] <= cy <= n["_bounds"][3]]
+ cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return cands[0] if cands else None
+
+
+def _tap_anchor(nodes, anchor):
+ """Tap `anchor`'s clickable ancestor (or the anchor itself, which hits the
+ same ancestor by coordinate)."""
+ if anchor is None:
+ return False
+ anc = _clickable_ancestor(nodes, anchor)
+ return tap_node(anc) if anc else tap_node(anchor)
+
+
+# ── Reading the computed outputs out of a fresh tree ────────────────────────────
+
+def _duration_text(nodes):
+ """The Editor's duration string — the sole TextView shaped like 'Xh Ym'
+ (ends in 'm', contains 'h'). Returns "" when none is present."""
+ for n in nodes:
+ t = (n.get("text") or "").strip()
+ if t.endswith("m") and "h" in t:
+ return t
+ return ""
+
+
+def _norm(s):
+ """Normalise a duration/time string for comparison: collapse whitespace."""
+ return " ".join((s or "").split())
+
+
+def _time_field(nodes, desc):
+ """The clock value shown in the Start/End field. The field node carries
+ content-desc=`desc` ('Start'/'End'); its value is the 'H:MM AM/PM' TextView
+ horizontally closest to that field's centre (Start sits left of End, so a
+ nearest-centre match disambiguates the two clock labels even when neither
+ centre falls exactly inside the field's reported bounds)."""
+ field = find_node(nodes, content_desc=desc)
+ if field is None or "_center" not in field:
+ return ""
+ fcx, fcy = field["_center"]
+ clocks = [n for n in nodes
+ if "_center" in n
+ and (n.get("text") or "").strip().count(":") == 1
+ and ("AM" in (n.get("text") or "") or "PM" in (n.get("text") or ""))]
+ if not clocks:
+ return ""
+ # prefer clocks on the same row (|dy| small), then nearest in x
+ clocks.sort(key=lambda n: (abs(n["_center"][1] - fcy) > 80,
+ abs(n["_center"][0] - fcx)))
+ return (clocks[0].get("text") or "").strip()
+
+
+def _pct_for_category(nodes, cat):
+ """The percentage string on the Analytics legend row for `cat`. The legend
+ renders the category name and its '%' value on the SAME row (same y-band), so
+ pair `cat`'s TextView with the nearest '%' TextView at the same vertical
+ centre. Returns "" when not found."""
+ name = None
+ for n in nodes:
+ if (n.get("text") or "").strip() == cat and "_center" in n:
+ name = n
+ break
+ if name is None:
+ return ""
+ ny = name["_center"][1]
+ best, best_dy = "", 10 ** 9
+ for n in nodes:
+ t = (n.get("text") or "").strip()
+ if t.endswith("%") and "_center" in n:
+ dy = abs(n["_center"][1] - ny)
+ if dy < best_dy and dy <= 40: # same row (rows are ~85px apart)
+ best, best_dy = t, dy
+ return best
+
+
+def _donut_center_total(nodes):
+ """The time total rendered in the donut centre — a 'Xh Ym' TextView. With a
+ single full-day task this equals that task's duration. (Dump-readable here, so
+ asserted as a rule value, not via the VLM.)"""
+ return _duration_text(nodes)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# NAMED navigation helpers — these BACK every depth>=1 claim (the depth audit
+# looks for an and_enter*/and_reach* call, directly or in a helper a test calls).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_free_row():
+ """Home empty -> tap 'Plan now' (CREATES the day's schedule) -> the free-time
+ 'Unassigned' add row appears. Stays on Home, so counts NO surface."""
+ n = find_node_ci(ui(), "Plan now")
+ if n is not None:
+ tap_node(n)
+ settle("tap")
+ return find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")
+
+
+def and_enter_editor():
+ """Home -> free/add row -> Editor (title 'Editor', 'Category', 'Save').
+ Counts ONE surface. Returns True on success."""
+ row = and_reach_free_row()
+ if row is None:
+ return False
+ nodes = ui()
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, row):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Category", "Schedule"):
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_reach_category_sheet():
+ """Editor -> tap the Category card -> Category bottom sheet ('Select' confirm;
+ the Editor has 'Save', not 'Select'). Counts ONE surface. True on success."""
+ nodes = ui()
+ card = _clickable_ancestor(nodes, find_node(nodes, text="Category"))
+ if card is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(card):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Select", "Save"):
+ return False
+ and_enter("category_sheet")
+ return True
+
+
+def and_reach_analytics():
+ """Any root -> tap the 'Analytics' bottom tab -> the Analytics screen (the
+ 'Time'/'Workload' tabs and 'Category stats' appear; the Home schedule leaves).
+ Counts ONE surface. Ensures the 'Time' tab is selected so the donut + legend
+ are visible. True on success."""
+ nodes = ui()
+ tab = find_node(nodes, content_desc="Analytics") or find_node(nodes, text="Analytics")
+ if tab is None:
+ return False
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, tab):
+ return False
+ settle("launch")
+ after_nodes = ui()
+ after = and_showing(after_nodes)
+ reached = (and_reach(before, after, "Category stats")
+ or find_node(after_nodes, content_desc="Time") is not None
+ or find_node_ci(after_nodes, "Category stats") is not None)
+ if not reached:
+ return False
+ and_enter("analytics")
+ # make sure the Time tab (donut + legend) is showing
+ t = find_node(ui(), content_desc="Time")
+ if t is not None:
+ _tap_anchor(ui(), t)
+ settle("tap")
+ return True
+
+
+def _open_end_picker():
+ """From an open Editor, open the End time picker. Returns the hour EditText
+ node (the sole EditText in the Material 'Enter time' dialog), or None."""
+ e = ui()
+ end = find_node(e, content_desc="End")
+ if end is None:
+ return None
+ if not _tap_anchor(e, end):
+ return None
+ settle("tap")
+ fields = find_by_class(ui(), "EditText")
+ return fields[0] if fields else None
+
+
+def _set_end_hour(hour_str, ampm="AM"):
+ """From an open Editor, set End's hour to `hour_str` at `ampm` via the Material
+ time picker (keyboard-entry mode). Leaves the original minute (:59) untouched,
+ matching the proven mechanic. Returns True if the picker was driven to OK."""
+ hour = _open_end_picker()
+ if hour is None:
+ return False
+ if not tap_node(hour):
+ return False
+ settle("keyboard")
+ press_key(_KEY_MOVE_END)
+ for _ in range(3):
+ press_key(_KEY_DEL)
+ settle("text")
+ type_text(hour, hour_str, verify_focus=False)
+ m = find_node_ci(ui(), ampm)
+ if m is not None:
+ _tap_anchor(ui(), m)
+ settle("tap")
+ ok = find_node_ci(ui(), "OK")
+ if ok is None or not safe_tap(ok):
+ return False
+ settle("tap")
+ return True
+
+
+def _select_category_and_save(cat):
+ """From an open Editor: open the Category sheet, choose `cat`, Select, Save.
+ Returns True if it ran the full sequence."""
+ if not and_reach_category_sheet():
+ return False
+ row = find_node(ui(), content_desc=cat) or find_node(ui(), text=cat)
+ if row is None:
+ fields = find_by_class(ui(), "EditText") # filter via the search field
+ if fields:
+ type_text(fields[0], cat)
+ settle("tap")
+ row = find_node(ui(), content_desc=cat) or find_node(ui(), text=cat)
+ if row is None:
+ return False
+ _tap_anchor(ui(), row)
+ settle("tap")
+ sel = find_node_ci(ui(), "Select")
+ if sel is None or not safe_tap(sel):
+ return False
+ settle("tap")
+ save = find_node_ci(ui(), "Save")
+ if save is None or not safe_tap(save):
+ return False
+ settle("tap")
+ return True
+
+
+def _create_fullday_task(cat):
+ """Golden create with DEFAULT times (12:00 AM -> 11:59 PM => full day): empty
+ Home -> Plan now -> Editor -> set category `cat` -> Save. Leaves the app on
+ Home with one full-day categorized task. Returns True on success."""
+ if not and_enter_editor():
+ return False
+ return _select_category_and_save(cat)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS — every assertion jump_kind="value" with an exact observed `expect`.
+# ══════════════════════════════════════════════════════════════════════════════
+
+# 1) Default duration: a fresh day's free slot spans 12:00 AM -> 11:59 PM, and the
+# Editor computes the duration "23h 59m".
+@and_test(expects=("computation_default_duration",
+ "computation_duration_layout_vlm"))
+def test_default_duration():
+ if not start_home_clean():
+ record("computation_default_duration", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="value", expect="duration '23h 59m'")
+ vlm_assert("computation_duration_layout",
+ "In this task editor, is there a duration label of the form "
+ "'h m' displayed on the same horizontal row as, "
+ "and to the right of, the Start and End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="position")
+ return
+ if not and_enter_editor():
+ record("computation_default_duration", False,
+ "feature_missing: no create path (Plan now -> free row -> Editor)",
+ depth=2, jump_kind="value", expect="duration '23h 59m'")
+ vlm_assert("computation_duration_layout",
+ "In this task editor, is there a duration label of the form "
+ "'h m' displayed on the same horizontal row as, "
+ "and to the right of, the Start and End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="position")
+ return
+ got = _duration_text(ui())
+ ok = _norm(got) == "23h 59m"
+ record("computation_default_duration", ok,
+ "" if ok else f"behavior_wrong: duration shows {got!r}, expected '23h 59m'",
+ depth=2, jump_kind="value", expect="duration '23h 59m'")
+
+ # VLM: the duration is RENDERED as text positioned beside the time fields (a
+ # layout property the tree confirms but this checks visually as rendered).
+ vlm_assert("computation_duration_layout",
+ "In this task editor, is there a duration label of the form "
+ "'h m' displayed on the same horizontal row as, and "
+ "to the right of, the Start and End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="position")
+
+
+# 2) Duration recompute: setting End -> 6:00 AM makes End read "6:59 AM" (minute
+# preserved) and the duration recompute to "6h 59m" (12:00 AM -> 6:59 AM). One
+# record asserts BOTH computed outputs.
+@and_test(expects=("computation_end_6am",))
+def test_end_6am_duration():
+ if not start_home_clean():
+ record("computation_end_6am", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="value",
+ expect="End '6:59 AM' and duration '6h 59m'")
+ return
+ if not and_enter_editor():
+ record("computation_end_6am", False,
+ "feature_missing: could not open the Editor",
+ depth=2, jump_kind="value",
+ expect="End '6:59 AM' and duration '6h 59m'")
+ return
+ if not _set_end_hour("6", "AM"):
+ record("computation_end_6am", False,
+ "setup_failed: could not drive the End time picker to 6 AM",
+ depth=2, jump_kind="value",
+ expect="End '6:59 AM' and duration '6h 59m'")
+ return
+ after = ui()
+ dur = _norm(_duration_text(after))
+ end = _norm(_time_field(after, "End"))
+ ok = dur == "6h 59m" and end == "6:59 AM"
+ record("computation_end_6am", ok,
+ "" if ok else
+ (f"behavior_wrong: after End->6 AM got End={end!r} duration={dur!r}, "
+ "expected End '6:59 AM' duration '6h 59m'"),
+ depth=2, jump_kind="value",
+ expect="End '6:59 AM' and duration '6h 59m'")
+
+
+# 3) Second distinct input: End -> 3:00 AM => End "3:59 AM", duration "3h 59m".
+# A different operand proves the duration is COMPUTED, not a fixed string.
+@and_test(expects=("computation_end_3am",))
+def test_end_3am_duration():
+ if not start_home_clean():
+ record("computation_end_3am", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="value",
+ expect="End '3:59 AM' and duration '3h 59m'")
+ return
+ if not and_enter_editor():
+ record("computation_end_3am", False,
+ "feature_missing: could not open the Editor",
+ depth=2, jump_kind="value",
+ expect="End '3:59 AM' and duration '3h 59m'")
+ return
+ if not _set_end_hour("3", "AM"):
+ record("computation_end_3am", False,
+ "setup_failed: could not drive the End time picker to 3 AM",
+ depth=2, jump_kind="value",
+ expect="End '3:59 AM' and duration '3h 59m'")
+ return
+ after = ui()
+ dur = _norm(_duration_text(after))
+ end = _norm(_time_field(after, "End"))
+ ok = dur == "3h 59m" and end == "3:59 AM"
+ record("computation_end_3am", ok,
+ "" if ok else
+ (f"behavior_wrong: after End->3 AM got End={end!r} duration={dur!r}, "
+ "expected End '3:59 AM' duration '3h 59m'"),
+ depth=2, jump_kind="value",
+ expect="End '3:59 AM' and duration '3h 59m'")
+
+
+# 4) Differential: capture the duration at the default End, change End to 6 AM,
+# assert the duration is NOW "6h 59m" AND DIFFERENT from the "23h 59m" before —
+# proves the value tracks the input rather than being static.
+@and_test(expects=("computation_duration_differential",
+ "computation_duration_shrinks_vlm"))
+def test_duration_differential():
+ if not start_home_clean():
+ record("computation_duration_differential", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="value",
+ expect="duration goes 23h 59m -> 6h 59m")
+ vlm_assert("computation_duration_shrinks",
+ "Does this task editor show a duration label of the form "
+ "'h m' next to the Start/End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="content")
+ return
+ if not and_enter_editor():
+ record("computation_duration_differential", False,
+ "feature_missing: could not open the Editor",
+ depth=2, jump_kind="value",
+ expect="duration goes 23h 59m -> 6h 59m")
+ vlm_assert("computation_duration_shrinks",
+ "Does this task editor show a duration label of the form "
+ "'h m' next to the Start/End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="content")
+ return
+ before = _norm(_duration_text(ui()))
+ changed = _set_end_hour("6", "AM")
+ after = _norm(_duration_text(ui()))
+ ok = (before == "23h 59m" and changed and after == "6h 59m" and after != before)
+ record("computation_duration_differential", ok,
+ "" if ok else
+ (f"behavior_wrong: expected duration 23h 59m -> 6h 59m, "
+ f"got {before!r} -> {after!r}"),
+ depth=2, jump_kind="value",
+ expect="duration goes 23h 59m -> 6h 59m")
+
+ # VLM: the duration text is rendered smaller after shrinking End (a rendered
+ # value now visible in the editor). Verifies the recomputed label draws.
+ vlm_assert("computation_duration_shrinks",
+ "Does this task editor show a duration label of the form "
+ "'h m' next to the Start/End time fields?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="content")
+
+
+# 5) Analytics proportion: with exactly ONE full-day Study task, the Category
+# stats legend shows "Study" = "100%".
+@and_test(expects=("computation_analytics_study_pct",
+ "computation_donut_full_vlm",
+ "computation_legend_layout_vlm"))
+def test_analytics_study_percent():
+ if not start_home_clean():
+ record("computation_analytics_study_pct", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="value", expect="Study 100%")
+ _analytics_vlms_fail()
+ return
+ if not _create_fullday_task(CAT):
+ record("computation_analytics_study_pct", False,
+ f"feature_missing: could not create a full-day {CAT!r} task",
+ depth=1, jump_kind="value", expect="Study 100%")
+ _analytics_vlms_fail()
+ return
+ if not and_reach_analytics():
+ record("computation_analytics_study_pct", False,
+ "setup_failed: could not reach the Analytics Time tab",
+ depth=1, jump_kind="value", expect="Study 100%")
+ _analytics_vlms_fail()
+ return
+ a = ui()
+ pct = _norm(_pct_for_category(a, CAT))
+ ok = pct == "100%"
+ record("computation_analytics_study_pct", ok,
+ "" if ok else
+ f"behavior_wrong: {CAT!r} legend shows {pct!r}, expected '100%'",
+ depth=1, jump_kind="value", expect="Study 100%")
+
+ # VLM: the donut is a single filled ring (one 100% category fills it entirely).
+ vlm_assert("computation_donut_full",
+ "There is a ring/doughnut chart. Is the MAJORITY of the ring taken up "
+ "by a single large arc of one dominant colour (one segment covering "
+ "most of the circle), rather than the ring being divided into several "
+ "roughly equal wedges?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+ # VLM: the legend renders one row with a filled value and the rest at zero,
+ # each with a coloured dot marker.
+ vlm_assert("computation_legend_layout",
+ "Below the ring chart is a legend of category rows, each with a "
+ "small coloured dot to the left of its name. Is exactly ONE row "
+ "showing a non-zero percentage while the other rows show 0%?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")
+
+
+def _analytics_vlms_fail():
+ """Emit the two Analytics VLM records as failures on a setup abort, keeping the
+ denominator fixed."""
+ vlm_assert("computation_donut_full",
+ "There is a ring/doughnut chart. Is the MAJORITY of the ring taken up "
+ "by a single large arc of one dominant colour (one segment covering "
+ "most of the circle), rather than the ring being divided into several "
+ "roughly equal wedges?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+ vlm_assert("computation_legend_layout",
+ "Below the ring chart is a legend of category rows, each with a "
+ "small coloured dot to the left of its name. Is exactly ONE row "
+ "showing a non-zero percentage while the other rows show 0%?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")
+
+
+# 6) Analytics complement: the OTHER categories all read "0%" (the proportion is
+# exclusive — a genuine computed distribution, not just a lone label).
+@and_test(expects=("computation_analytics_others_zero",))
+def test_analytics_others_zero():
+ if not start_home_clean():
+ record("computation_analytics_others_zero", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="value", expect="every other category 0%")
+ return
+ if not _create_fullday_task(CAT):
+ record("computation_analytics_others_zero", False,
+ f"feature_missing: could not create a full-day {CAT!r} task",
+ depth=1, jump_kind="value", expect="every other category 0%")
+ return
+ if not and_reach_analytics():
+ record("computation_analytics_others_zero", False,
+ "setup_failed: could not reach the Analytics Time tab",
+ depth=1, jump_kind="value", expect="every other category 0%")
+ return
+ a = ui()
+ pcts = [( (n.get("text") or "").strip()) for n in a
+ if (n.get("text") or "").strip().endswith("%")]
+ hundred = pcts.count("100%")
+ zeros = pcts.count("0%")
+ # exactly one 100% row and at least one 0% row, and no other non-zero value
+ others_nonzero = [p for p in pcts if p not in ("0%", "100%")]
+ ok = hundred == 1 and zeros >= 1 and not others_nonzero
+ record("computation_analytics_others_zero", ok,
+ "" if ok else
+ (f"behavior_wrong: legend percentages were {sorted(set(pcts))}, expected "
+ "exactly one '100%' and the rest '0%'"),
+ depth=1, jump_kind="value",
+ expect="one 100% row, every other category 0%")
+
+
+# 7) Analytics donut centre total: with the single full-day task the ring centre
+# shows the summed time "23h 59m" (dump-readable here => a rule value test).
+@and_test(expects=("computation_donut_center_total",
+ "computation_workload_bars_vlm"))
+def test_donut_center_total():
+ if not start_home_clean():
+ record("computation_donut_center_total", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="value", expect="donut centre '23h 59m'")
+ _workload_vlm_fail()
+ return
+ if not _create_fullday_task(CAT):
+ record("computation_donut_center_total", False,
+ f"feature_missing: could not create a full-day {CAT!r} task",
+ depth=1, jump_kind="value", expect="donut centre '23h 59m'")
+ _workload_vlm_fail()
+ return
+ if not and_reach_analytics():
+ record("computation_donut_center_total", False,
+ "setup_failed: could not reach the Analytics Time tab",
+ depth=1, jump_kind="value", expect="donut centre '23h 59m'")
+ _workload_vlm_fail()
+ return
+ a = ui()
+ total = _norm(_donut_center_total(a))
+ ok = total == "23h 59m"
+ record("computation_donut_center_total", ok,
+ "" if ok else
+ f"behavior_wrong: donut centre total shows {total!r}, expected '23h 59m'",
+ depth=1, jump_kind="value", expect="donut centre '23h 59m'")
+
+ # VLM: switch to the Workload tab and confirm it renders a bar chart (bars of
+ # differing heights) — a genuinely non-dump-readable graphical property.
+ w = find_node(ui(), content_desc="Workload")
+ if w is not None:
+ _tap_anchor(ui(), w)
+ settle("tap")
+ vlm_assert("computation_workload_bars",
+ "In the 'Workload stats' bar chart, is there a single tall coloured "
+ "vertical bar that rises well above the chart baseline, while the "
+ "other x-axis positions have no visible bar?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+
+
+def _workload_vlm_fail():
+ vlm_assert("computation_workload_bars",
+ "In the 'Workload stats' bar chart, is there a single tall coloured "
+ "vertical bar that rises well above the chart baseline, while the "
+ "other x-axis positions have no visible bar?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+
+
+# 8) Analytics category-dot colour: the legend rows each carry a distinct coloured
+# dot marker (a rendered colour property the tree cannot express).
+@and_test(expects=("computation_legend_dots_vlm",))
+def test_legend_dots_vlm():
+ if not start_home_clean():
+ record("computation_legend_dots_vlm", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="none", tag="color")
+ return
+ if not (_create_fullday_task(CAT) and and_reach_analytics()):
+ record("computation_legend_dots_vlm", False,
+ "setup_failed: could not reach the Analytics Time tab",
+ depth=1, jump_kind="none", tag="color")
+ return
+ vlm_assert("computation_legend_dots",
+ "In the category legend under the ring chart, does each category "
+ "name have a small round COLOURED dot marker beside it (the dots are "
+ "coloured, not grey/black bullets)?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="color")
+
+
+TESTS = [
+ test_default_duration,
+ test_end_6am_duration,
+ test_end_3am_duration,
+ test_duration_differential,
+ test_analytics_study_percent,
+ test_analytics_others_zero,
+ test_donut_center_total,
+ test_legend_dots_vlm,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "computation")
diff --git a/android/v1tzor-timeplanner/tests/test_android_interaction.py b/android/v1tzor-timeplanner/tests/test_android_interaction.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4098533791f72141e29f3510ea4f9a8b9a7d766
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_interaction.py
@@ -0,0 +1,727 @@
+#!/usr/bin/env python3
+"""INTERACTION lane — EFFECT-BY-CONSEQUENCE on user DATA for TimePlanner.
+
+Owns: CRUD lifecycle, 3+ step sequences, multi-record integrity, DATA
+persistence across process death (force_stop_and_relaunch), long-press/context
+menus. Every test drives the app to the surface via the real user path, performs
+the action, then reads the consequence back out of a FRESH ui() and asserts it
+against what was observed on the original.
+
+Run:
+ python3 test_android_interaction.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+# The category we create/read back. All are real built-in categories (verified in
+# recon: Absent/Shopping/Health/Study/Sleep/Work), so the golden create flow
+# (Plan now -> Editor -> Category sheet -> row -> Select -> Save) yields a card
+# whose category we read straight out of the Home schedule dump. "Study" never
+# accidentally matches an empty schedule.
+CAT_A = "Study"
+CAT_B = "Health" # the edit target — a DIFFERENT built-in category
+NOTE_TEXT = "kitreadchapter" # ASCII, no spaces => input-text path is reliable
+
+# Every built-in category name that renders as a task-card icon desc. Used to
+# count DISTINCT task cards on the schedule.
+_CATEGORY_NAMES = ("Study", "Health", "Shopping", "Sleep", "Work", "Absent")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Trap handling — LeakCanary launcher alias + onboarding permission dialog.
+# * LeakCanary: the .debug build bundles a SECOND launcher activity in the same
+# package; monkey non-deterministically opens leakcanary.internal.activity.
+# LeakActivity, and wait_for_foreground()/is_app_foreground() then LIE (same
+# package). We detect it by the ABSENCE of a Home surface and force-stop +
+# relaunch to shake it off. We never press HOME (that lands on the system
+# launcher, whose TimePlanner ICON also fools the package check).
+# * onboarding: the notification-permission dialog after clear_data(), dismissed
+# at the top of the loop.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_onboarding(nodes=None):
+ """Tap the notification-permission dialog's button if present. Returns True
+ if it dismissed one (so the caller re-loops)."""
+ nodes = nodes if nodes is not None else ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
+ None)
+ if btn is None:
+ return False
+ tap_node(btn)
+ return True
+
+
+def _home_ready(nodes):
+ """Home's own surface — the top-bar title, the empty-state prompt, or the
+ 'Plan now' control. Any means the REAL app (not LeakCanary, not the launcher)
+ is on screen."""
+ return (find_node_ci(nodes, "Schedule") is not None
+ or find_node_ci(nodes, "Plan now") is not None
+ or find_node_ci(nodes, "Nothing planned yet") is not None)
+
+
+def ensure_home(max_tries=20):
+ for _ in range(max_tries):
+ nodes = ui()
+ if dismiss_onboarding(nodes):
+ settle("tap")
+ continue
+ if _home_ready(nodes):
+ settle("launch") # confirm a mid-launch frame settled
+ if _home_ready(ui()):
+ return True
+ continue
+ force_stop(); settle("key")
+ launch_app(); settle("launch")
+ return _home_ready(ui())
+
+
+def start_home_clean():
+ """Virgin-database entry point: clear data, relaunch, dismiss onboarding,
+ settle on the empty Home. Every CRUD/persistence test starts here."""
+ clear_data()
+ launch_app()
+ return ensure_home()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Compose tap helpers — leaves report clickable="false"; tap the clickable
+# ancestor whose bounds enclose the label's centre.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _clickable_ancestor(nodes, anchor):
+ """Tightest clickable node whose bounds contain `anchor`'s centre."""
+ if not anchor or "_center" not in anchor:
+ return None
+ cx, cy = anchor["_center"]
+ cands = [n for n in nodes
+ if n.get("clickable") == "true" and "_bounds" in n
+ and n["_bounds"][0] <= cx <= n["_bounds"][2]
+ and n["_bounds"][1] <= cy <= n["_bounds"][3]]
+ cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return cands[0] if cands else None
+
+
+def _tap_anchor(nodes, anchor):
+ """Tap `anchor`'s clickable ancestor (or the anchor itself, which hits the
+ same ancestor by coordinate)."""
+ if anchor is None:
+ return False
+ anc = _clickable_ancestor(nodes, anchor)
+ return tap_node(anc) if anc else tap_node(anchor)
+
+
+def _card_anchor(nodes, cat):
+ """The task-card / category leaf for `cat` (icon desc or label text)."""
+ return find_node(nodes, content_desc=cat) or find_node(nodes, text=cat)
+
+
+def _task_card_names(nodes):
+ """Distinct category names rendered as task cards on the schedule. Each card
+ carries its category as an icon leaf desc= exactly once."""
+ return sorted(n.get("content-desc", "") for n in nodes
+ if n.get("content-desc", "") in _CATEGORY_NAMES)
+
+
+def _count_category(nodes, cat):
+ """How many nodes carry `cat` as text or content-desc (>=1 => a card exists)."""
+ return sum(1 for n in nodes
+ if n.get("content-desc") == cat or n.get("text") == cat)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# The core create flow, decomposed so depth is backed by NAMED and_enter_* /
+# and_reach_* helpers. Each takes the app one surface deeper and calls and_enter.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_free_row():
+ """Home empty -> tap 'Plan now' (CREATES the day's schedule) -> the free-time
+ 'Unassigned' row appears. Stays on Home, so counts NO surface."""
+ n = find_node_ci(ui(), "Plan now")
+ if n is not None:
+ tap_node(n)
+ settle("tap")
+ return find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")
+
+
+def and_enter_editor():
+ """Home -> free/add row -> Editor (title 'Editor', 'Category', 'Save').
+ Counts ONE surface. Returns True on success."""
+ row = and_reach_free_row()
+ if row is None:
+ return False
+ nodes = ui()
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, row):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Category", "Schedule"):
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_enter_editor_via_card(cat):
+ """Home (task exists) -> tap the task card for `cat` -> Editor. A RUNNING card
+ first expands inline (Add-time/Reduce/Edit); if so, tap its 'Edit' control to
+ reach the Editor. Counts ONE surface. Returns True on success."""
+ nodes = ui()
+ anchor = _card_anchor(nodes, cat)
+ if anchor is None:
+ return False
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, anchor):
+ return False
+ if find_node_ci(ui(), "Category") is None: # expanded, not yet in Editor
+ edit = find_node(ui(), content_desc="Edit")
+ if edit is not None:
+ _tap_anchor(ui(), edit)
+ after = and_showing()
+ if not and_reach(before, after, "Category", "Schedule"):
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_reach_category_sheet():
+ """Editor -> tap the Category card -> Category bottom sheet ('Select' confirm;
+ the Editor has 'Save', not 'Select'). Counts ONE surface. True on success."""
+ nodes = ui()
+ card = _clickable_ancestor(nodes, find_node(nodes, text="Category"))
+ if card is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(card):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Select", "Save"):
+ return False
+ and_enter("category_sheet")
+ return True
+
+
+def _select_category_in_sheet(cat):
+ """From an OPEN category sheet: choose `cat`, confirm with 'Select', then land
+ back on the Editor. The sheet opens scrolled to the CURRENTLY selected
+ category, so the wanted row may be off screen; rather than scroll the recycler
+ (which can overshoot), type `cat` into the sheet's search field to FILTER the
+ list down to it. Returns True if it ran the sequence."""
+ row = _card_anchor(ui(), cat)
+ if row is None:
+ # filter via the search field (the sole EditText on the sheet)
+ fields = find_by_class(ui(), "EditText")
+ if fields:
+ type_text(fields[0], cat)
+ settle("tap")
+ row = _card_anchor(ui(), cat)
+ if row is None:
+ return False
+ # Tapping the row both selects it AND dismisses the search keyboard.
+ _tap_anchor(ui(), row)
+ settle("tap")
+ sel = find_node_ci(ui(), "Select")
+ if sel is None or not safe_tap(sel):
+ return False
+ # Tapping 'Select' DISMISSES the sheet by itself and lands back on the Editor
+ # (verified: Save reappears, Select is gone). Do NOT press BACK here — that
+ # would pop the Editor and discard the task.
+ settle("tap")
+ return True
+
+
+def _pick_category_and_save(cat):
+ """From an open Editor: open the Category sheet, choose `cat`, Select, Save.
+ Returns True if it ran the full sequence."""
+ if not and_reach_category_sheet():
+ return False
+ if not _select_category_in_sheet(cat):
+ return False
+ save = find_node_ci(ui(), "Save")
+ if save is None or not safe_tap(save):
+ return False
+ settle("tap")
+ return True
+
+
+# KEYCODE_MOVE_END / KEYCODE_DEL — used only to clear the time-picker hour field
+# via the kit's press_key (never a raw `input`).
+_KEY_MOVE_END = 123
+_KEY_DEL = 67
+
+
+def _set_end_time_earlier(hour_str="6", ampm="AM"):
+ """From an open Editor, shrink the task by moving its End earlier via the
+ Material time picker (hour -> `hour_str`, meridiem -> `ampm`). Leaves a real
+ free block after the task so a SECOND task can be created. Returns True if the
+ Editor's duration text changed (the edit landed)."""
+ e = ui()
+ end = find_node(e, content_desc="End")
+ if end is None:
+ return False
+ dur_before = [n.get("text") for n in e
+ if (n.get("text") or "").endswith("m") and "h" in (n.get("text") or "")]
+ if not _tap_anchor(e, end):
+ return False
+ settle("tap")
+ fields = find_by_class(ui(), "EditText") # the hour input
+ if not fields:
+ return False
+ hour = fields[0]
+ if not tap_node(hour):
+ return False
+ settle("keyboard")
+ press_key(_KEY_MOVE_END)
+ for _ in range(3):
+ press_key(_KEY_DEL)
+ settle("text")
+ type_text(hour, hour_str, verify_focus=False)
+ m = find_node_ci(ui(), ampm)
+ if m is not None:
+ _tap_anchor(ui(), m)
+ settle("tap")
+ ok = find_node_ci(ui(), "OK")
+ if ok is None or not safe_tap(ok):
+ return False
+ settle("tap")
+ after = ui()
+ dur_after = [n.get("text") for n in after
+ if (n.get("text") or "").endswith("m") and "h" in (n.get("text") or "")]
+ return dur_after != dur_before
+
+
+def _create_task(cat):
+ """Full golden create: from empty Home, Plan now -> Editor -> set category
+ `cat` -> Save. Leaves the app on Home. Returns True iff the card is present."""
+ if not and_enter_editor():
+ return False
+ if not _pick_category_and_save(cat):
+ return False
+ settle("tap")
+ return _count_category(ui(), cat) >= 1
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+# 1) CREATE a task (golden path) + VLM on the rendered card.
+@and_test(expects=("interaction_create_task",
+ "interaction_create_task_running_vlm",
+ "interaction_create_task_icon_vlm"))
+def test_create_task():
+ if not start_home_clean():
+ record("interaction_create_task", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect=f"a {CAT_A!r} task card appears on the schedule")
+ return
+ before = ui()
+ absent = (_count_category(before, CAT_A) == 0
+ and find_node_ci(before, "Nothing planned yet") is not None)
+ if not and_enter_editor():
+ record("interaction_create_task", False,
+ "feature_missing: no create path (Plan now -> free row -> Editor)",
+ depth=1, jump_kind="transition",
+ expect="Editor opens for a new task")
+ return
+ ran = _pick_category_and_save(CAT_A)
+ settle("tap")
+ after = ui()
+ present = _count_category(after, CAT_A) >= 1
+ ok = absent and ran and present
+ record("interaction_create_task", ok,
+ "" if ok else
+ (f"behavior_wrong: created task did not appear as a {CAT_A!r} card "
+ "on the schedule"),
+ depth=2, jump_kind="transition",
+ expect=f"{CAT_A!r} task card present on Home (was 'Nothing planned yet')")
+
+ # VLM: the default 12:00 AM-11:59 PM task spans NOW, so it renders as a
+ # running task highlighted with a distinct tinted background.
+ vlm_assert("interaction_create_task_running",
+ "There is a task row on the schedule (not the empty 'Nothing planned "
+ "yet' state). Is that task row visually highlighted with a distinct "
+ "coloured/tinted background different from the plain page background?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="color")
+ # VLM: the card carries a coloured category glyph beside the name.
+ vlm_assert("interaction_create_task_icon",
+ "Does the task row on the schedule show a small coloured category "
+ "icon/symbol (a glyph such as a graduation cap) positioned to the "
+ "left of the category name text?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="shape")
+
+
+# 2) CREATE persists across process death (marquee).
+@and_test(expects=("interaction_create_persists",))
+def test_create_survives_process_death():
+ if not start_home_clean():
+ record("interaction_create_persists", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect=f"{CAT_A!r} task survives process kill")
+ return
+ absent_before = _count_category(ui(), CAT_A) == 0
+ if not _create_task(CAT_A):
+ record("interaction_create_persists", False,
+ "feature_missing: could not create a task to test persistence",
+ depth=2, jump_kind="transition",
+ expect=f"{CAT_A!r} task survives process kill")
+ return
+ # THE probe: kill the process and relaunch. In-memory-only recreations fail.
+ force_stop_and_relaunch()
+ ensure_home() # LeakCanary alias can still intercept
+ present_after = _count_category(ui(), CAT_A) >= 1
+ ok = absent_before and present_after
+ record("interaction_create_persists", ok,
+ "" if ok else
+ f"behavior_wrong: {CAT_A!r} task did not survive process death",
+ depth=2, jump_kind="transition",
+ expect=f"{CAT_A!r} task card still on Home after force_stop_and_relaunch")
+
+
+# 3) EDIT a task: change category Study -> Health, verify the card updated.
+@and_test(expects=("interaction_edit_category",
+ "interaction_edit_icon_vlm"))
+def test_edit_task_category():
+ if not start_home_clean():
+ record("interaction_edit_category", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect=f"task category updates {CAT_A}->{CAT_B}")
+ return
+ if not _create_task(CAT_A):
+ record("interaction_edit_category", False,
+ "feature_missing: could not create the initial task to edit",
+ depth=2, jump_kind="transition",
+ expect=f"task category updates {CAT_A}->{CAT_B}")
+ return
+ had_study = _count_category(ui(), CAT_A) >= 1
+ if not and_enter_editor_via_card(CAT_A):
+ record("interaction_edit_category", False,
+ "setup_failed: could not reopen the task in the Editor",
+ depth=2, jump_kind="transition",
+ expect=f"task category updates {CAT_A}->{CAT_B}")
+ return
+ changed = _pick_category_and_save(CAT_B)
+ settle("tap")
+ after = ui()
+ now_health = _count_category(after, CAT_B) >= 1
+ no_more_study = _count_category(after, CAT_A) == 0
+ ok = had_study and changed and now_health and no_more_study
+ record("interaction_edit_category", ok,
+ "" if ok else
+ (f"behavior_wrong: editing {CAT_A}->{CAT_B} did not update the card "
+ f"(health={now_health}, study_gone={no_more_study})"),
+ depth=2, jump_kind="transition",
+ expect=f"schedule shows {CAT_B!r} card and no {CAT_A!r} card")
+
+ # VLM: the icon changed to a health (cross/heart) glyph.
+ vlm_assert("interaction_edit_icon",
+ "The schedule shows one task row. Does its category icon look like a "
+ "health/medical symbol (a cross or heart) rather than an academic "
+ "graduation-cap symbol?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="shape")
+
+
+# 4) Multi-step schedule build: after saving task #1 the list grows to show the
+# task PLUS a new 'Add a task' free-slot add row.
+@and_test(expects=("interaction_schedule_grows",
+ "interaction_schedule_grows_vlm"))
+def test_schedule_build_grows():
+ if not start_home_clean():
+ record("interaction_schedule_grows", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect="after saving, list shows the task AND a new add row")
+ return
+ b = ui()
+ was_empty = (find_node_ci(b, "Nothing planned yet") is not None
+ and find_node_ci(b, "Add a task") is None)
+ if not _create_task(CAT_A):
+ record("interaction_schedule_grows", False,
+ "feature_missing: could not create the first task",
+ depth=2, jump_kind="transition",
+ expect="after saving, list shows the task AND a new add row")
+ return
+ after = ui()
+ has_task = _count_category(after, CAT_A) >= 1
+ has_add_row = (find_node_ci(after, "Add a task") is not None
+ or find_node_ci(after, "Unassigned") is not None)
+ ok = was_empty and has_task and has_add_row
+ record("interaction_schedule_grows", ok,
+ "" if ok else
+ ("behavior_wrong: after saving, expected both the task card and a new "
+ "add row on the schedule"),
+ depth=2, jump_kind="transition",
+ expect=f"schedule shows a {CAT_A!r} card AND an 'Add a task' add row")
+
+ # VLM: timeline shows a task block followed by an add row below it.
+ vlm_assert("interaction_schedule_grows",
+ "On the schedule/timeline, is there a filled task block near the top "
+ "and, directly below it, a separate row containing a plus (+) 'add' "
+ "control (i.e. the list has grown to two stacked rows)?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="layout")
+
+
+# 5) Add a SECOND task -> two distinct task cards on the schedule.
+@and_test(expects=("interaction_second_task",
+ "interaction_two_tasks_vlm"))
+def test_add_second_task():
+ if not start_home_clean():
+ record("interaction_second_task", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect="two task cards on the schedule")
+ return
+ # Task #1 must NOT span the whole day, or the only free slot left is a
+ # zero-length one (Start==End) whose save REPLACES the first task instead of
+ # adding a second. So build task #1 with an earlier End, leaving a real free
+ # block for task #2.
+ if not and_enter_editor():
+ record("interaction_second_task", False,
+ "feature_missing: could not open the Editor for the first task",
+ depth=2, jump_kind="transition",
+ expect="two task cards on the schedule")
+ return
+ _set_end_time_earlier("6", "AM") # Study now ~12:00 AM-6:59 AM
+ settle("tap")
+ if not _pick_category_and_save(CAT_A):
+ record("interaction_second_task", False,
+ "feature_missing: could not save the first task",
+ depth=2, jump_kind="transition",
+ expect="two task cards on the schedule")
+ return
+ one = len(_task_card_names(ui()))
+ if not and_enter_editor(): # opens the Editor on the free slot
+ record("interaction_second_task", False,
+ "setup_failed: could not open the Editor for the second task",
+ depth=2, jump_kind="transition",
+ expect="two task cards on the schedule")
+ return
+ ran = _pick_category_and_save(CAT_B)
+ settle("tap")
+ after = ui()
+ two = len(_task_card_names(after))
+ ok = ran and one >= 1 and two >= 2 and two > one
+ record("interaction_second_task", ok,
+ "" if ok else
+ (f"behavior_wrong: expected the schedule to grow to >=2 task cards "
+ f"(had {one}, now {two})"),
+ depth=2, jump_kind="transition",
+ expect=f"task-card count rises from {one} to >=2")
+
+ # VLM: two distinct task blocks, one positioned ABOVE the other on the
+ # timeline (a positional property — the second card sits below the first).
+ vlm_assert("interaction_two_tasks",
+ "There are two separate coloured task blocks on the schedule, each "
+ "with its own category name. Is one task block positioned directly "
+ "ABOVE the other (they are stacked vertically, not overlapping and "
+ "not side by side)?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="position")
+
+
+# 6) Running-task expand controls: tapping the running card reveals the inline
+# Add-time / Reduce-the-time / Edit controls that were NOT present collapsed.
+# (Note: the 'Increase' desc also sits on the free 'Add a task' add-row even
+# when collapsed, so the discriminating controls are the 'Add time' /
+# 'Reduce the time' / 'Edit' descs, which appear only when the card expands.)
+@and_test(expects=("interaction_running_expand",
+ "interaction_running_progress_vlm",
+ "interaction_running_controls_vlm"))
+def test_running_task_expand():
+ if not start_home_clean():
+ record("interaction_running_expand", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="transition",
+ expect="running task expands to Add-time/Reduce controls")
+ return
+ if not _create_task(CAT_A):
+ record("interaction_running_expand", False,
+ "feature_missing: could not create a running task",
+ depth=1, jump_kind="transition",
+ expect="running task expands to Add-time/Reduce controls")
+ return
+ coll = ui()
+ controls_before = (find_node(coll, content_desc="Reduce the time") is not None
+ or find_node(coll, content_desc="Add time") is not None
+ or find_node(coll, content_desc="Edit") is not None)
+ anchor = _card_anchor(coll, CAT_A)
+ tapped = _tap_anchor(coll, anchor) if anchor else False
+ and_enter("expanded_card")
+ settle("tap")
+ exp = ui()
+ add_time = find_node(exp, content_desc="Add time") is not None
+ reduce_time = find_node(exp, content_desc="Reduce the time") is not None
+ ok = tapped and (not controls_before) and add_time and reduce_time
+ record("interaction_running_expand", ok,
+ "" if ok else
+ ("behavior_wrong: tapping the running task did not reveal both the "
+ "Add-time and Reduce-the-time controls"),
+ depth=1, jump_kind="transition",
+ expect="'Add time' and 'Reduce the time' controls appear after tapping "
+ "the running card")
+
+ # VLM: a partially-filled progress bar spans part-way across the row.
+ vlm_assert("interaction_running_progress",
+ "The highlighted task row shows a horizontal progress indicator. Is "
+ "that progress bar filled only PART of the way across (a partial "
+ "fill, not empty and not completely full)?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none",
+ tag="size")
+ # VLM: '+ Increase' and '- Reduce' buttons visible side by side.
+ vlm_assert("interaction_running_controls",
+ "In the expanded task row, are there two labelled buttons shown side "
+ "by side, one reading 'Increase' (with a plus) and one reading "
+ "'Reduce' (with a minus)?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="layout")
+
+
+# 7) Cancel does NOT persist: open the free row's Editor, choose a category, then
+# Cancel -> no new categorized task card was created.
+@and_test(expects=("interaction_cancel_no_persist",))
+def test_cancel_discards():
+ if not start_home_clean():
+ record("interaction_cancel_no_persist", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="transition",
+ expect="Cancel discards editor; no new categorized task")
+ return
+ before = ui()
+ no_task_before = len(_task_card_names(before)) == 0
+ if not and_enter_editor():
+ record("interaction_cancel_no_persist", False,
+ "feature_missing: could not open the Editor",
+ depth=2, jump_kind="transition",
+ expect="Cancel discards editor; no new categorized task")
+ return
+ # choose a category IN the editor, then Cancel -> should discard
+ if and_reach_category_sheet():
+ _select_category_in_sheet(CAT_A)
+ cancel = find_node_ci(ui(), "Cancel")
+ cancelled = cancel is not None and safe_tap(cancel)
+ settle("tap")
+ ensure_home()
+ after = ui()
+ no_task_after = len(_task_card_names(after)) == 0
+ ok = no_task_before and cancelled and no_task_after
+ record("interaction_cancel_no_persist", ok,
+ "" if ok else
+ ("behavior_wrong: Cancel did not discard — a categorized task card "
+ "appeared on the schedule"),
+ depth=2, jump_kind="transition",
+ expect="no categorized task card on Home after Cancel")
+
+
+# 8) Note text entry round-trips inside the Editor. The Note is a Compose
+# BasicTextField that does NOT expose its content in the accessibility tree,
+# so the observable consequence of a successful entry is the placeholder
+# 'Optional' disappearing (shown only while the field is empty). We also read
+# the EditText text back in case a recreation DOES expose it.
+@and_test(expects=("interaction_note_roundtrip",))
+def test_note_text_roundtrip():
+ if not start_home_clean():
+ record("interaction_note_roundtrip", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="transition",
+ expect="Note field accepts typed text (placeholder clears)")
+ return
+ if not and_enter_editor():
+ record("interaction_note_roundtrip", False,
+ "feature_missing: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="Note field accepts typed text (placeholder clears)")
+ return
+ e = ui()
+ fields = find_by_class(e, "EditText")
+ placeholder_before = find_node_ci(e, "Optional") is not None
+ if not fields:
+ record("interaction_note_roundtrip", False,
+ "feature_missing: no Note EditText on the Editor",
+ depth=1, jump_kind="transition",
+ expect="Note field accepts typed text (placeholder clears)")
+ return
+ typed = type_text(fields[0], NOTE_TEXT)
+ if not typed:
+ record("interaction_note_roundtrip", False,
+ "setup_failed: could not focus/type into the Note field",
+ depth=1, jump_kind="transition",
+ expect="Note field accepts typed text (placeholder clears)")
+ return
+ hide_keyboard()
+
+ def _entered():
+ u = ui()
+ fresh = find_by_class(u, "EditText")
+ got = (fresh[0].get("text") if fresh else "") or ""
+ placeholder_gone = find_node_ci(u, "Optional") is None
+ return (NOTE_TEXT in got) or placeholder_gone
+
+ if not _entered():
+ # custom field may ignore the ascii paste; retry via ADB Keyboard
+ type_text(fields[0], NOTE_TEXT, method="ime")
+ hide_keyboard()
+ entered = _entered()
+ ok = placeholder_before and entered
+ record("interaction_note_roundtrip", ok,
+ "" if ok else
+ "behavior_wrong: Note field did not accept typed text "
+ "(placeholder did not clear and no text read back)",
+ depth=1, jump_kind="transition",
+ expect="Note placeholder 'Optional' clears after typing "
+ f"{NOTE_TEXT!r} (data entered)")
+
+
+# 9) Category bottom sheet: the currently-selected row is highlighted vs others
+# (VLM-only rendered property; the consequence of a selection in the sheet).
+@and_test(expects=("interaction_sheet_selected_vlm",))
+def test_category_sheet_selection_vlm():
+ if not start_home_clean():
+ record("interaction_sheet_selected_vlm", False,
+ "setup_failed: could not reach empty Home",
+ depth=2, jump_kind="none", tag="color")
+ return
+ if not (and_enter_editor() and and_reach_category_sheet()):
+ record("interaction_sheet_selected_vlm", False,
+ "setup_failed: could not open the Category sheet",
+ depth=2, jump_kind="none", tag="color")
+ return
+ row = _card_anchor(ui(), CAT_A) # select 'Study' -> one row selected
+ if row is not None:
+ _tap_anchor(ui(), row)
+ settle("tap")
+ vlm_assert("interaction_sheet_selected",
+ "This is a category picker list. Is exactly one category row visibly "
+ "marked as selected (a filled/checked radio button or a highlighted "
+ "background) while the other rows are not?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="none",
+ tag="color")
+
+
+TESTS = [
+ test_create_task,
+ test_create_survives_process_death,
+ test_edit_task_category,
+ test_schedule_build_grows,
+ test_add_second_task,
+ test_running_task_expand,
+ test_cancel_discards,
+ test_note_text_roundtrip,
+ test_category_sheet_selection_vlm,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "interaction")
diff --git a/android/v1tzor-timeplanner/tests/test_android_navigation.py b/android/v1tzor-timeplanner/tests/test_android_navigation.py
new file mode 100644
index 0000000000000000000000000000000000000000..172a3404b9de590bf07ed4452c28a21edb08bf90
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_navigation.py
@@ -0,0 +1,489 @@
+#!/usr/bin/env python3
+"""NAVIGATION lane for TimePlanner (ru.aleshin.timeplanner.debug).
+
+Owns surface REACHABILITY + back-stack integrity: every jump is proven with
+and_reach (the TARGET surface's discriminating element APPEARED and the SOURCE
+surface's DISAPPEARED). Sole owner of jump_kind="reach" and of depth>=2 chains.
+
+Run:
+ ADB_PATH=... DEVICE_SERIAL=... python3 test_android_navigation.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Onboarding / launcher recovery (the two documented traps).
+# (A) .debug bundles LeakCanary -> a second LAUNCHER alias; monkey LAUNCHER may
+# open the wrong screen. wait_for_foreground() is True regardless (same pkg).
+# (B) After clear_data() a notification-permission dialog is on screen.
+# ensure_home() force-stops + relaunches until the Home title "Schedule" is stable.
+# Coordinate/component-literal-free -> lint-clean.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_onboarding():
+ for _ in range(2):
+ nodes = ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
+ None)
+ if not btn:
+ return
+ tap_node(btn)
+
+
+def _home_ready(nodes):
+ return find_node_ci(nodes, "Schedule") is not None # top-bar title on Home
+
+
+def ensure_home(max_tries=10):
+ for _ in range(max_tries):
+ dismiss_onboarding()
+ if _home_ready(ui()):
+ for _ in range(3):
+ settle("launch")
+ if _home_ready(ui()):
+ return True
+ continue
+ home(); settle("key"); force_stop(); settle("key")
+ launch_app(); wait_for_foreground()
+ return _home_ready(ui())
+
+
+def start_home():
+ """Every test's own entry point."""
+ restart_app()
+ return ensure_home()
+
+
+# ── shared trigger helpers ──────────────────────────────────────────────────────
+
+def _nav_tab(nodes, label):
+ """Bottom-nav root tab (Home / Analytics / Settings) by its label."""
+ return find_node(nodes, text=label)
+
+
+def _smallest_clickable_containing(nodes, anchor):
+ """The tightest clickable node whose bounds contain `anchor`'s centre — how a
+ Compose card that carries only a child label is turned into a tap target."""
+ if not anchor or "_center" not in anchor:
+ return None
+ cx, cy = anchor["_center"]
+ cands = [n for n in nodes
+ if n.get("clickable") == "true" and "_bounds" in n
+ and n["_bounds"][0] <= cx <= n["_bounds"][2]
+ and n["_bounds"][1] <= cy <= n["_bounds"][3]]
+ cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return cands[0] if cands else None
+
+
+def _open_drawer():
+ """Tap the hamburger (desc 'Open menu'). Returns True if the drawer opened
+ (header 'Time Planner' visible)."""
+ m = find_node(ui(), content_desc="Open menu")
+ if not m or not tap_node(m):
+ return False
+ return find_node_ci(ui(), "Time Planner") is not None
+
+
+# ── depth-family helpers (the and_reach_*/and_enter_* NAME backs the depth audit;
+# the implementation is ours). Each returns bool and, on success, has counted a
+# surface via and_reach_surface. ─────────────────────────────────────────────
+
+def and_reach_editor():
+ """Home -> (Plan now creates the day) -> tap the free 'Unassigned'/'Add a task'
+ row -> Editor. Proves Editor's 'Category' appeared and Home's 'Schedule' left."""
+ n = find_node_ci(ui(), "Plan now")
+ if n:
+ tap_node(n) # creates the day's schedule
+ row = find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")
+ if not row:
+ return False
+ return and_reach_surface(row, "Category", "Schedule")
+
+
+def and_enter_editor():
+ """Alias entry that lands on the Editor and counts the surface."""
+ return and_reach_editor()
+
+
+def and_reach_category_sheet():
+ """Editor -> tap the Category card -> Category bottom sheet. 'Select' is the
+ sheet's confirm button (the Editor has 'Save', not 'Select')."""
+ nodes = ui()
+ card = _smallest_clickable_containing(nodes, find_node(nodes, text="Category"))
+ if not card:
+ return False
+ return and_reach_surface(card, "Select", "Save")
+
+
+def and_reach_time_picker():
+ """Editor -> tap the Start field -> Material time picker ('Enter time'). The
+ Editor's 'Priority' field is fully covered by the modal."""
+ nodes = ui()
+ card = _smallest_clickable_containing(nodes, find_node(nodes, content_desc="Start"))
+ if not card:
+ return False
+ return and_reach_surface(card, "Enter time", "Priority")
+
+
+def and_reach_templates_via_drawer():
+ """(drawer already open) drawer 'Templates' -> Templates screen."""
+ dn = ui()
+ item = find_node(dn, text="Templates")
+ return item is not None and and_reach_surface(item, "List is empty", "Time Planner")
+
+
+def and_reach_categories_via_drawer():
+ """(drawer already open) drawer 'Categories' -> Categories screen."""
+ dn = ui()
+ item = find_node(dn, text="Categories")
+ return item is not None and and_reach_surface(item, "Subcategories", "Time Planner")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# BOTTOM-NAV ROOT SWITCHES (depth 1, reach)
+# The top-bar title and the bottom-nav label share the key "TextView|Analytics"
+# etc., so a tab's own name is a USELESS target (already in `before`). We target a
+# screen-body element instead: Analytics -> "Planning stats", Settings ->
+# "Appearance", Home -> "Schedule".
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_analytics", "nav_reach_analytics_vlm",
+ "nav_reach_analytics_tabs_vlm"))
+def test_reach_analytics():
+ ok = start_home()
+ nodes = ui()
+ tab = _nav_tab(nodes, "Analytics")
+ reached = ok and tab is not None and and_reach_surface(tab, "Planning stats", "Schedule")
+ record("nav_reach_analytics", reached,
+ "" if reached else "feature_missing: Analytics root not reachable from Home",
+ depth=1, jump_kind="reach",
+ expect="Analytics 'Planning stats' visible; Home 'Schedule' title gone")
+ vlm_assert("nav_reach_analytics",
+ "Is a donut or pie chart (a ring/circle segmented into colored "
+ "slices) shown on this analytics screen?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="shape")
+ vlm_assert("nav_reach_analytics_tabs",
+ "Near the top are there two side-by-side tabs, one bearing a "
+ "round pie-chart icon and the other a bar-chart icon (vertical bars)?",
+ RESULTS_DIR, depth=1, jump_kind="none", tag="shape")
+
+
+@and_test(expects=("nav_reach_settings", "nav_reach_settings_vlm"))
+def test_reach_settings():
+ ok = start_home()
+ # Home -> Analytics -> Settings (tab switching between roots).
+ a = _nav_tab(ui(), "Analytics")
+ on_analytics = ok and a is not None and and_reach_surface(a, "Planning stats", "Schedule")
+ nodes = ui()
+ s = _nav_tab(nodes, "Settings")
+ reached = on_analytics and s is not None and and_reach_surface(s, "Appearance", "Planning stats")
+ record("nav_reach_settings", reached,
+ "" if reached else "feature_missing: Settings root not reachable via tabs",
+ depth=1, jump_kind="reach",
+ expect="Settings 'Appearance' section visible; Analytics 'Planning stats' gone")
+ vlm_assert("nav_reach_settings",
+ "Under a 'Color' label, are there four filled color swatches whose "
+ "shape is a rounded square (not a circle)?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="shape")
+
+
+@and_test(expects=("nav_reach_home_tab",))
+def test_reach_home_from_settings():
+ ok = start_home()
+ s = _nav_tab(ui(), "Settings")
+ on_settings = ok and s is not None and and_reach_surface(s, "Appearance", "Schedule")
+ h = _nav_tab(ui(), "Home")
+ reached = on_settings and h is not None and and_reach_surface(h, "Schedule", "Appearance")
+ record("nav_reach_home_tab", reached,
+ "" if reached else "behavior_wrong: Home tab did not restore the Schedule root",
+ depth=1, jump_kind="reach",
+ expect="Home 'Schedule' title restored; Settings 'Appearance' gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HOME -> EDITOR (push) and BACK unwind (depth 1/2, reach)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_editor", "nav_reach_editor_vlm"))
+def test_reach_editor():
+ ok = start_home()
+ reached = ok and and_reach_editor()
+ record("nav_reach_editor", reached,
+ "" if reached else "feature_missing: could not open the Editor from Home",
+ depth=1, jump_kind="reach",
+ expect="Editor 'Category'/'Save' visible; Home 'Schedule' gone")
+ vlm_assert("nav_reach_editor",
+ "In the top app-bar, is a left-pointing back arrow positioned at the "
+ "very top-left corner, with action icons over on the right side?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_backstack_editor_home",))
+def test_editor_back_to_home():
+ ok = start_home()
+ deep = ok and and_reach_editor()
+ # BACK from the Editor pops back to Home.
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ back_ok = deep and and_reach(before, after, "Schedule", "Editor")
+ record("nav_backstack_editor_home", back_ok,
+ "" if back_ok else "behavior_wrong: BACK from Editor did not return to Home",
+ depth=1, jump_kind="reach",
+ expect="Home 'Schedule' restored after one BACK; Editor title gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HOME -> OVERVIEW via the top-bar grid icon (depth 1, reach)
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_overview():
+ ov = find_node(ui(), content_desc="Overview")
+ return ov is not None and and_reach_surface(ov, "Schedules", "Compact view")
+
+
+@and_test(expects=("nav_reach_overview", "nav_reach_overview_vlm"))
+def test_reach_overview():
+ ok = start_home()
+ reached = ok and and_reach_overview()
+ record("nav_reach_overview", reached,
+ "" if reached else "feature_missing: Overview not reachable from the Home top bar",
+ depth=1, jump_kind="reach",
+ expect="Overview 'Schedules' section visible; Home 'Compact view' gone")
+ vlm_assert("nav_reach_overview",
+ "Does this screen show a horizontal row of date cards, each with a "
+ "circular progress ring and a status word like Completed/Current/Planned?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="layout")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DRAWER host (open + each item) (depth 1, reach)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_open_drawer", "nav_open_drawer_vlm"))
+def test_open_drawer():
+ ok = start_home()
+ nodes = ui()
+ menu = find_node(nodes, content_desc="Open menu")
+ before = and_showing(nodes)
+ tapped = ok and menu is not None and tap_node(menu)
+ after = and_showing()
+ # The drawer host reveals its header + item labels that Home never shows.
+ opened = tapped and and_reach(before, after, "Time Planner") \
+ and and_reach(before, after, "Templates") \
+ and and_reach(before, after, "Categories")
+ record("nav_open_drawer", opened,
+ "" if opened else "feature_missing: navigation drawer did not open",
+ depth=1, jump_kind="reach",
+ expect="Drawer header 'Time Planner' + items Templates/Categories appeared")
+ vlm_assert("nav_open_drawer",
+ "Has a navigation drawer panel slid in from the left, covering the "
+ "left portion of the screen, with a logo/title header at the top and "
+ "a vertical list of menu items below it?",
+ RESULTS_DIR, depth=1, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_reach_templates",))
+def test_reach_templates_via_drawer():
+ ok = start_home()
+ opened = ok and _open_drawer()
+ reached = opened and and_reach_templates_via_drawer()
+ record("nav_reach_templates", reached,
+ "" if reached else "feature_missing: Templates not reachable from the drawer",
+ depth=1, jump_kind="reach",
+ expect="Templates 'List is empty' visible; drawer 'Time Planner' gone")
+
+
+@and_test(expects=("nav_reach_categories",))
+def test_reach_categories_via_drawer():
+ ok = start_home()
+ opened = ok and _open_drawer()
+ reached = opened and and_reach_categories_via_drawer()
+ record("nav_reach_categories", reached,
+ "" if reached else "feature_missing: Categories not reachable from the drawer",
+ depth=1, jump_kind="reach",
+ expect="Categories 'Subcategories' visible; drawer 'Time Planner' gone")
+
+
+@and_test(expects=("nav_reach_overview_drawer",))
+def test_reach_overview_via_drawer():
+ ok = start_home()
+ opened = ok and _open_drawer()
+ dn = ui()
+ item = find_node(dn, text="Overview")
+ reached = opened and item is not None and and_reach_surface(item, "Schedules", "Time Planner")
+ record("nav_reach_overview_drawer", reached,
+ "" if reached else "feature_missing: Overview not reachable from the drawer",
+ depth=1, jump_kind="reach",
+ expect="Overview 'Schedules' visible; drawer 'Time Planner' gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# DEEP CHAIN — the back-stack integrity test this lane owns (depth 2, reach)
+# Home -> (drawer) Templates -> (drawer) Categories, then BACK pops Categories ->
+# Templates, and BACK again pops Templates -> Home. Each hop AND each pop is a real
+# and_reach. A recreation that resets to Home on BACK, or cannot stack two drawer
+# screens, FAILS here.
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_deepchain_backstack",))
+def test_deepchain_backstack():
+ ok = start_home()
+ # hop 1: Home -> Templates
+ hop1 = ok and _open_drawer() and and_reach_templates_via_drawer()
+ # hop 2: Templates -> Categories (reopen the drawer over Templates)
+ hop2 = hop1 and _open_drawer() and and_reach_categories_via_drawer()
+
+ # pop 1: BACK -> Templates restored, Categories gone
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ pop1 = hop2 and and_reach(before, after, "List is empty", "Subcategories")
+
+ # pop 2: BACK -> Home restored, Templates gone
+ before = and_showing()
+ and_back()
+ after = and_showing()
+ pop2 = pop1 and and_reach(before, after, "Schedule", "List is empty")
+
+ passed = bool(hop1 and hop2 and pop1 and pop2)
+ if passed:
+ msg = ""
+ elif not hop1:
+ msg = "feature_missing: could not push Templates from the drawer"
+ elif not hop2:
+ msg = "feature_missing: could not stack Categories on top of Templates"
+ elif not pop1:
+ msg = "behavior_wrong: BACK from Categories did not restore Templates"
+ else:
+ msg = "behavior_wrong: BACK from Templates did not restore Home"
+ record("nav_deepchain_backstack", passed, msg,
+ depth=2, jump_kind="reach",
+ expect="Templates then Categories stacked; two BACKs unwind "
+ "Categories->Templates->Home hop by hop")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# EDITOR sub-surfaces (depth 2, reach)
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_category_sheet", "nav_reach_category_sheet_vlm"))
+def test_reach_category_sheet():
+ ok = start_home()
+ in_editor = ok and and_reach_editor()
+ reached = in_editor and and_reach_category_sheet()
+ record("nav_reach_category_sheet", reached,
+ "" if reached else "feature_missing: Category bottom sheet did not open from the Editor",
+ depth=2, jump_kind="reach",
+ expect="Category sheet 'Select' button visible; Editor 'Save' gone")
+ vlm_assert("nav_reach_category_sheet",
+ "Is a panel/sheet overlaid on the lower part of the screen on top of "
+ "a dimmed (darkened) background behind it?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_backstack_sheet_editor",))
+def test_category_sheet_back_to_editor():
+ ok = start_home()
+ in_editor = ok and and_reach_editor()
+ in_sheet = in_editor and and_reach_category_sheet()
+ # Cancel closes the sheet and returns to the Editor. Use the sheet-unique
+ # "Close sheet" desc as the source (the editor's "Select a category"/"Select a
+ # date" descs would substring-collide with a plain "Select" source).
+ nodes = ui()
+ cancel = find_node(nodes, text="Cancel")
+ before = and_showing(nodes)
+ closed = in_sheet and cancel is not None and tap_node(cancel)
+ after = and_showing()
+ back_ok = closed and and_reach(before, after, "Priority", "Close sheet")
+ record("nav_backstack_sheet_editor", back_ok,
+ "" if back_ok else "behavior_wrong: closing the Category sheet did not return to the Editor",
+ depth=2, jump_kind="reach",
+ expect="Editor 'Priority' field restored after Cancel; sheet 'Close sheet' gone")
+
+
+@and_test(expects=("nav_reach_time_picker", "nav_reach_time_picker_vlm"))
+def test_reach_time_picker():
+ ok = start_home()
+ in_editor = ok and and_reach_editor()
+ reached = in_editor and and_reach_time_picker()
+ record("nav_reach_time_picker", reached,
+ "" if reached else "feature_missing: time picker did not open from the Editor Start field",
+ depth=2, jump_kind="reach",
+ expect="Time picker 'Enter time' visible; Editor 'Priority' field gone")
+ vlm_assert("nav_reach_time_picker",
+ "Is a time-entry dialog shown roughly centered on the screen, with "
+ "large hour and minute number fields and AM / PM buttons?",
+ RESULTS_DIR, depth=2, jump_kind="reach", tag="position")
+
+
+@and_test(expects=("nav_backstack_picker_editor",))
+def test_time_picker_back_to_editor():
+ ok = start_home()
+ in_editor = ok and and_reach_editor()
+ in_picker = in_editor and and_reach_time_picker()
+ nodes = ui()
+ cancel = find_node(nodes, text="Cancel")
+ before = and_showing(nodes)
+ closed = in_picker and cancel is not None and tap_node(cancel)
+ after = and_showing()
+ back_ok = closed and and_reach(before, after, "Priority", "Enter time")
+ record("nav_backstack_picker_editor", back_ok,
+ "" if back_ok else "behavior_wrong: cancelling the time picker did not return to the Editor",
+ depth=2, jump_kind="reach",
+ expect="Editor 'Priority' field restored after Cancel; picker 'Enter time' gone")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# HOME date chip -> date picker (depth 1, reach)
+# The picker adds a day grid whose "Change to next month" affordance is
+# picker-unique (Home never renders that content-desc).
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("nav_reach_date_picker",))
+def test_reach_date_picker():
+ ok = start_home()
+ nodes = ui()
+ chip = None
+ for n in nodes:
+ if (n.get("text") or "").startswith(("Thu", "Mon", "Tue", "Wed", "Fri", "Sat", "Sun")):
+ chip = _smallest_clickable_containing(nodes, n)
+ if chip:
+ break
+ before = and_showing(nodes)
+ tapped = ok and chip is not None and tap_node(chip)
+ after = and_showing()
+ reached = tapped and and_reach(before, after, "Change to next month", "Compact view")
+ record("nav_reach_date_picker", reached,
+ "" if reached else "feature_missing: date picker did not open from the Home date chip",
+ depth=1, jump_kind="reach",
+ expect="Date picker (day grid, 'Change to next month') visible; Home 'Compact view' gone")
+
+
+TESTS = [
+ test_reach_analytics,
+ test_reach_settings,
+ test_reach_home_from_settings,
+ test_reach_editor,
+ test_editor_back_to_home,
+ test_reach_overview,
+ test_open_drawer,
+ test_reach_templates_via_drawer,
+ test_reach_categories_via_drawer,
+ test_reach_overview_via_drawer,
+ test_deepchain_backstack,
+ test_reach_category_sheet,
+ test_category_sheet_back_to_editor,
+ test_reach_time_picker,
+ test_time_picker_back_to_editor,
+ test_reach_date_picker,
+]
+
+if __name__ == "__main__":
+ run_suite(TESTS, "navigation")
diff --git a/android/v1tzor-timeplanner/tests/test_android_states.py b/android/v1tzor-timeplanner/tests/test_android_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd6bedcfe83c0b63f46c39205386758f953cf044
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_states.py
@@ -0,0 +1,1001 @@
+#!/usr/bin/env python3
+"""STATES lane — CHECKED/SELECTED/ENABLED/FOCUSED transitions PAIRED WITH THEIR
+APP-AUTHORED CONSEQUENCE, plus SETTINGS/mode PERSISTENCE, for TimePlanner.
+
+Owns (sole owner of `checked` and `focused`):
+ * switch flips paired with a consequence (Statistics/Notifications switch ->
+ checked flips; Notifications OFF -> the reminder-gear button disappears),
+ * segmented-selector transitions marked by a moving "Selected" glyph
+ (Priority Standard/Medium/Max; Settings Theme Light/System/Dark; Calendar
+ icon behavior Pick-a-date/Set-to-today),
+ * real toggle switches (Dynamic colors, Secure screen) whose `checked` flips,
+ * the Home Compact/Expanded-view mode flip (label changes),
+ * the category bottom-sheet RadioButton `checked` moving between rows,
+ * SETTINGS PERSISTENCE across process death (Theme, Calendar behavior).
+
+Every test drives the app to the surface through the REAL user path, reads the
+state BEFORE from a fresh ui(), performs the tap, reads AFTER from a fresh ui(),
+and asserts the transition AND its consequence against what was OBSERVED on the
+running original. Each test owns its own entry point; the two persistence tests
+deliberately span a restart.
+
+Run:
+ python3 test_android_states.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Trap handling — LeakCanary launcher alias + onboarding permission dialog.
+# * LeakCanary: the .debug build bundles a SECOND launcher activity in the same
+# package; monkey non-deterministically opens it and wait_for_foreground()
+# then LIES (same package). We detect it by the ABSENCE of a Home surface and
+# force-stop + relaunch to shake it off (never HOME — the launcher's icon also
+# fools the package check).
+# * onboarding: the notification-permission dialog after clear_data(), dismissed
+# at the top of the loop (curly apostrophe in "Don't allow").
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_onboarding(nodes=None):
+ """Tap the notification-permission dialog's button if present. Returns True if
+ it dismissed one (so the caller re-loops)."""
+ nodes = nodes if nodes is not None else ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
+ None)
+ if btn is None:
+ return False
+ tap_node(btn)
+ return True
+
+
+def _home_ready(nodes):
+ """Home's own surface — the top-bar title, the empty-state prompt, or the
+ 'Plan now' control. Any of these means the REAL app is on screen."""
+ return (find_node_ci(nodes, "Schedule") is not None
+ or find_node_ci(nodes, "Plan now") is not None
+ or find_node_ci(nodes, "Nothing planned yet") is not None)
+
+
+def ensure_home(max_tries=12):
+ for _ in range(max_tries):
+ nodes = ui()
+ if dismiss_onboarding(nodes):
+ settle("tap")
+ continue
+ if _home_ready(nodes):
+ settle("launch")
+ if _home_ready(ui()):
+ return True
+ continue
+ force_stop(); settle("key")
+ launch_app(); settle("launch")
+ return _home_ready(ui())
+
+
+def start_home_clean():
+ """Virgin-database entry point: clear data, relaunch, dismiss onboarding,
+ settle on the empty Home."""
+ clear_data()
+ launch_app()
+ return ensure_home()
+
+
+def start_home():
+ """Data-intact entry point (no onboarding dialog)."""
+ restart_app()
+ return ensure_home()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Compose tap helpers — leaves report clickable="false"; tap the clickable
+# ancestor whose bounds enclose the label's/marker's centre.
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _clickable_ancestor(nodes, anchor):
+ """Tightest clickable node whose bounds contain `anchor`'s centre."""
+ if not anchor or "_center" not in anchor:
+ return None
+ cx, cy = anchor["_center"]
+ cands = [n for n in nodes
+ if n.get("clickable") == "true" and "_bounds" in n
+ and n["_bounds"][0] <= cx <= n["_bounds"][2]
+ and n["_bounds"][1] <= cy <= n["_bounds"][3]]
+ cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return cands[0] if cands else None
+
+
+def _tap_anchor(nodes, anchor):
+ """Tap `anchor`'s clickable ancestor (or the anchor itself, which hits the
+ same ancestor by coordinate)."""
+ if anchor is None:
+ return False
+ anc = _clickable_ancestor(nodes, anchor)
+ return tap_node(anc) if anc else tap_node(anchor)
+
+
+def _switch_near(nodes, label, tol=130):
+ """The checkable View on the same row as text `label` (a Compose Switch, whose
+ `checked` attribute we assert). Matched by vertical proximity to the label."""
+ lab = find_node(nodes, text=label)
+ if not lab or "_center" not in lab:
+ return None
+ ly = lab["_center"][1]
+ sws = [n for n in nodes
+ if n.get("checkable") == "true" and "_center" in n
+ and abs(n["_center"][1] - ly) < tol]
+ sws.sort(key=lambda n: abs(n["_center"][1] - ly))
+ return sws[0] if sws else None
+
+
+def _seg_ancestor(nodes, seg_label):
+ """The clickable segment View that holds segmented-control label `seg_label`
+ (e.g. 'Dark', 'Medium', 'Pick a date')."""
+ lab = find_node(nodes, text=seg_label)
+ return _clickable_ancestor(nodes, lab) if lab else None
+
+
+def _selected_segment(nodes, seg_labels, y_lo=0, y_hi=99999):
+ """Which of `seg_labels` currently holds the content-desc='Selected' marker,
+ restricted to markers whose y is in [y_lo, y_hi] (disambiguates two selectors
+ on one screen). Returns the label string, or None."""
+ marks = [n for n in nodes
+ if n.get("content-desc") == "Selected" and "_center" in n
+ and y_lo <= n["_center"][1] <= y_hi]
+ if not marks:
+ return None
+ mx = marks[0]["_center"][0]
+ my = marks[0]["_center"][1]
+ for lab in seg_labels:
+ seg = _seg_ancestor(nodes, lab)
+ if seg is None:
+ continue
+ x1, sy1, x2, sy2 = seg["_bounds"]
+ if x1 <= mx <= x2 and sy1 - 40 <= my <= sy2 + 40:
+ return lab
+ return None
+
+
+def _radio_checked(nodes, cat):
+ """The `checked` value of the RadioButton on category-row `cat` in the sheet
+ ('true'/'false'/None). Matched by vertical proximity to the row's icon/label."""
+ lab = find_node(nodes, content_desc=cat) or find_node(nodes, text=cat)
+ if not lab or "_center" not in lab:
+ return None
+ ly = lab["_center"][1]
+ rbs = [n for n in nodes
+ if "RadioButton" in n.get("class", "") and "_center" in n
+ and abs(n["_center"][1] - ly) < 90]
+ return rbs[0].get("checked") if rbs else None
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# NAMED navigation helpers — these BACK every depth>=1 claim (the depth audit
+# matches the and_enter*/and_reach* prefix).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_enter_settings():
+ """Home -> bottom-nav 'Settings' -> the Settings screen (title 'Settings',
+ 'Appearance', 'Theme'). Counts ONE surface. Returns True on success."""
+ nodes = ui()
+ tab = find_node_ci(nodes, "Settings")
+ if tab is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(tab):
+ return False
+ settle("launch")
+ after = and_showing()
+ if not and_reach(before, after, "Theme", "Schedule"):
+ # bottom-tab switch: Theme must appear; Schedule (Home title) must go
+ if find_node_ci(ui(), "Theme") is None:
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_reach_free_row():
+ """Home empty -> tap 'Plan now' (CREATES the day's schedule) -> the free-time
+ 'Unassigned' row appears. Stays on Home, so counts NO surface."""
+ n = find_node_ci(ui(), "Plan now")
+ if n is not None:
+ tap_node(n)
+ settle("tap")
+ return find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")
+
+
+def and_enter_editor():
+ """Home -> free/add row -> Editor (title 'Editor', 'Category', 'Save').
+ Counts ONE surface. Returns True on success."""
+ row = and_reach_free_row()
+ if row is None:
+ return False
+ nodes = ui()
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, row):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Category", "Schedule"):
+ if find_node_ci(ui(), "Category") is None or find_node_ci(ui(), "Save") is None:
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_reach_category_sheet():
+ """Editor -> tap the Category card -> Category bottom sheet ('Select' confirm;
+ the Editor has 'Save', not 'Select'). Counts ONE surface. True on success."""
+ nodes = ui()
+ card = _clickable_ancestor(nodes, find_node(nodes, text="Category"))
+ if card is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(card):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Select", "Save"):
+ if find_node_ci(ui(), "Select") is None:
+ return False
+ and_enter("category_sheet")
+ return True
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+# 1) Statistics switch ON->OFF: checked flips true->false + track goes grey (VLM).
+@and_test(expects=("states_statistics_toggle",
+ "states_statistics_off_track_vlm"))
+def test_statistics_switch_toggle():
+ if not start_home_clean():
+ record("states_statistics_toggle", False,
+ "setup_failed: could not reach empty Home",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false")
+ return
+ if not and_enter_editor():
+ record("states_statistics_toggle", False,
+ "setup_failed: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false")
+ return
+ nodes = ui()
+ sw = _switch_near(nodes, "Statistics")
+ if sw is None:
+ record("states_statistics_toggle", False,
+ "feature_missing: no Statistics switch in the Editor",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false")
+ vlm_assert("states_statistics_off_track",
+ "This is a settings row labelled Statistics with a toggle "
+ "switch. Is the switch track grey/uncoloured (in the OFF "
+ "position) rather than filled with the accent purple colour?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ return
+ before = sw.get("checked")
+ _tap_anchor(nodes, sw)
+ fresh = ui()
+ after = (find_closest_match(fresh, sw) or {}).get("checked")
+ ok = before == "true" and after == "false"
+ record("states_statistics_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: Statistics switch did not flip true->false "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false")
+
+ # VLM: after turning OFF, the switch track is grey/empty (not filled purple).
+ vlm_assert("states_statistics_off_track",
+ "This is a settings row labelled Statistics with a toggle switch. "
+ "Is the switch track grey/uncoloured (thumb to the LEFT, OFF "
+ "position) rather than filled with the accent purple colour?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+
+
+# 2) Statistics switch OFF->ON: the same switch flips back (second checked test).
+@and_test(expects=("states_statistics_toggle_back",))
+def test_statistics_switch_toggle_back():
+ if not start_home_clean() or not and_enter_editor():
+ record("states_statistics_toggle_back", False,
+ "setup_failed: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false->true")
+ return
+ nodes = ui()
+ sw = _switch_near(nodes, "Statistics")
+ if sw is None:
+ record("states_statistics_toggle_back", False,
+ "feature_missing: no Statistics switch in the Editor",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false->true")
+ return
+ start = sw.get("checked")
+ _tap_anchor(nodes, sw) # ON -> OFF
+ mid_nodes = ui()
+ mid = (find_closest_match(mid_nodes, sw) or {}).get("checked")
+ sw2 = _switch_near(mid_nodes, "Statistics") or sw
+ _tap_anchor(mid_nodes, sw2) # OFF -> ON
+ back_val = (find_closest_match(ui(), sw2) or {}).get("checked")
+ ok = start == "true" and mid == "false" and back_val == "true"
+ record("states_statistics_toggle_back", ok,
+ "" if ok else
+ f"behavior_wrong: Statistics switch did not round-trip "
+ f"(start={start}, mid={mid}, back={back_val})",
+ depth=1, jump_kind="transition",
+ expect="Statistics switch checked true->false then false->true")
+
+
+# 3) Notifications switch ON->OFF + its reminder-gear button disappears (the
+# conditional-enable consequence). Track goes grey (VLM).
+@and_test(expects=("states_notifications_toggle",
+ "states_notifications_off_track_vlm"))
+def test_notifications_switch_toggle():
+ if not start_home_clean() or not and_enter_editor():
+ record("states_notifications_toggle", False,
+ "setup_failed: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="Notifications switch true->false; reminder gear disappears")
+ return
+ nodes = ui()
+ sw = _switch_near(nodes, "Notifications")
+ if sw is None:
+ record("states_notifications_toggle", False,
+ "feature_missing: no Notifications switch in the Editor",
+ depth=1, jump_kind="transition",
+ expect="Notifications switch true->false; reminder gear disappears")
+ vlm_assert("states_notifications_off_track",
+ "This is a settings row labelled Notifications with a toggle "
+ "switch. Is the switch track grey/uncoloured (OFF position) "
+ "rather than filled with the accent purple colour?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ return
+ before = sw.get("checked")
+ # The reminder-gear Button sits just LEFT of the switch on the same row while
+ # notifications are ON; it is removed when they go OFF.
+ sy = sw["_center"][1]
+
+ def _gear(nn):
+ return any(n.get("class", "").endswith("Button")
+ and n.get("clickable") == "true" and "_center" in n
+ and abs(n["_center"][1] - sy) < 120
+ and n["_center"][0] < sw["_center"][0] - 40
+ for n in nn)
+
+ gear_before = _gear(nodes)
+ _tap_anchor(nodes, sw)
+ fresh = ui()
+ after = (find_closest_match(fresh, sw) or {}).get("checked")
+ gear_after = _gear(fresh)
+ ok = before == "true" and after == "false" and gear_before and not gear_after
+ record("states_notifications_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: Notifications OFF did not both flip checked and remove "
+ f"the reminder gear (before={before}, after={after}, "
+ f"gear {gear_before}->{gear_after})",
+ depth=1, jump_kind="transition",
+ expect="Notifications checked true->false AND reminder-gear button "
+ "disappears")
+
+ # VLM: after OFF, the switch track is grey/empty.
+ vlm_assert("states_notifications_off_track",
+ "This is a settings row labelled Notifications with a toggle switch. "
+ "Is the switch track grey/uncoloured (thumb to the LEFT, OFF "
+ "position) rather than filled with the accent purple colour?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+
+
+# 4) Priority Standard->Medium: the 'Selected' marker moves into the Medium
+# segment. VLM: Medium is highlighted pink; VLM: it shows a leading check mark.
+@and_test(expects=("states_priority_standard_medium",
+ "states_priority_medium_highlight_vlm",
+ "states_priority_medium_check_vlm"))
+def test_priority_standard_to_medium():
+ labels = ("Standard", "Medium", "Max")
+ if not start_home_clean() or not and_enter_editor():
+ record("states_priority_standard_medium", False,
+ "setup_failed: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="priority selection Standard->Medium")
+ return
+ nodes = ui()
+ # The Priority selector sits low (y > 1760); its 'Selected' glyph is below the
+ # Statistics/Notifications switches, so restrict the marker search to y>1760.
+ before = _selected_segment(nodes, labels, y_lo=1760)
+ med = _seg_ancestor(nodes, "Medium")
+ if med is None:
+ record("states_priority_standard_medium", False,
+ "feature_missing: no 'Medium' priority segment in the Editor",
+ depth=1, jump_kind="transition",
+ expect="priority selection Standard->Medium")
+ vlm_assert("states_priority_medium_highlight",
+ "In the Priority row, is the 'Medium' segment filled with a "
+ "pink/coloured background while the other segments are not?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ vlm_assert("states_priority_medium_check",
+ "In the Priority row, does the 'Medium' segment show a small "
+ "check-mark glyph to the left of the word Medium?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="shape")
+ return
+ tap_node(med)
+ settle("tap")
+ after = _selected_segment(ui(), labels, y_lo=1760)
+ ok = before == "Standard" and after == "Medium"
+ record("states_priority_standard_medium", ok,
+ "" if ok else
+ f"behavior_wrong: priority selection did not move Standard->Medium "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="priority 'Selected' marker moves Standard->Medium")
+
+ # VLM: the selected segment (Medium) is highlighted pink.
+ vlm_assert("states_priority_medium_highlight",
+ "In the Priority row of three segments, is the 'Medium' segment "
+ "filled with a pink/coloured background while 'Standard' and 'Max' "
+ "have a plain uncoloured background?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ # VLM: the selected segment shows a leading check mark.
+ vlm_assert("states_priority_medium_check",
+ "In the Priority row, does the 'Medium' segment show a small "
+ "check-mark (tick) glyph positioned to the LEFT of the word "
+ "'Medium'?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="shape")
+
+
+# 5) Priority Medium->Max: continue moving the selection.
+@and_test(expects=("states_priority_medium_max",))
+def test_priority_medium_to_max():
+ labels = ("Standard", "Medium", "Max")
+ if not start_home_clean() or not and_enter_editor():
+ record("states_priority_medium_max", False,
+ "setup_failed: could not open the Editor",
+ depth=1, jump_kind="transition",
+ expect="priority selection Medium->Max")
+ return
+ nodes = ui()
+ med = _seg_ancestor(nodes, "Medium")
+ if med is None:
+ record("states_priority_medium_max", False,
+ "feature_missing: no priority segments in the Editor",
+ depth=1, jump_kind="transition",
+ expect="priority selection Medium->Max")
+ return
+ tap_node(med)
+ settle("tap")
+ mid = _selected_segment(ui(), labels, y_lo=1760)
+ mx = _seg_ancestor(ui(), "Max")
+ if mx is None:
+ record("states_priority_medium_max", False,
+ "feature_missing: no 'Max' priority segment in the Editor",
+ depth=1, jump_kind="transition",
+ expect="priority selection Medium->Max")
+ return
+ tap_node(mx)
+ settle("tap")
+ after = _selected_segment(ui(), labels, y_lo=1760)
+ ok = mid == "Medium" and after == "Max"
+ record("states_priority_medium_max", ok,
+ "" if ok else
+ f"behavior_wrong: priority selection did not move Medium->Max "
+ f"(mid={mid}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="priority 'Selected' marker moves Medium->Max")
+
+
+# 6) Settings Theme System->Dark: the 'Selected' marker moves into the Dark
+# segment. VLM: Dark segment highlighted; VLM (marquee): whole app goes dark.
+@and_test(expects=("states_theme_system_dark",
+ "states_theme_dark_highlight_vlm",
+ "states_theme_dark_applied_vlm"))
+def test_theme_system_to_dark():
+ labels = ("Light", "System", "Dark")
+ if not start_home_clean() or not and_enter_settings():
+ record("states_theme_system_dark", False,
+ "setup_failed: could not reach the Settings Theme selector",
+ depth=1, jump_kind="transition",
+ expect="theme selection System->Dark")
+ return
+ nodes = ui()
+ before = _selected_segment(nodes, labels, y_hi=1000) # Theme row is high
+ dark = _seg_ancestor(nodes, "Dark")
+ if dark is None:
+ record("states_theme_system_dark", False,
+ "feature_missing: no 'Dark' theme segment in Settings",
+ depth=1, jump_kind="transition",
+ expect="theme selection System->Dark")
+ vlm_assert("states_theme_dark_highlight",
+ "In the Theme row, is the 'Dark' segment filled with a "
+ "pink/coloured background while 'Light' and 'System' are not?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ vlm_assert("states_theme_dark_applied",
+ "Is the overall app background dark (near-black / dark grey) "
+ "with light-coloured text?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ return
+ tap_node(dark)
+ settle("tap")
+ after = _selected_segment(ui(), labels, y_hi=1000)
+ ok = before == "System" and after == "Dark"
+ record("states_theme_system_dark", ok,
+ "" if ok else
+ f"behavior_wrong: theme selection did not move System->Dark "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="theme 'Selected' marker moves System->Dark")
+
+ # VLM: the Dark segment is highlighted pink.
+ vlm_assert("states_theme_dark_highlight",
+ "In the Theme row of three segments (Light / System / Dark), is the "
+ "'Dark' segment filled with a pink/coloured background while the "
+ "other two have a plain uncoloured background?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ # VLM (marquee): the whole app turned dark — the strongest visual proof of a
+ # real theme engine.
+ settle("tap")
+ vlm_assert("states_theme_dark_applied",
+ "Look at the whole screen. Is the app background now DARK "
+ "(near-black or dark grey surfaces) with light/white text, rather "
+ "than the light near-white background it had before?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+
+
+# 7) Settings Theme ->Light (a second theme transition, from Dark to Light).
+@and_test(expects=("states_theme_dark_light",))
+def test_theme_dark_to_light():
+ labels = ("Light", "System", "Dark")
+ if not start_home_clean() or not and_enter_settings():
+ record("states_theme_dark_light", False,
+ "setup_failed: could not reach the Settings Theme selector",
+ depth=1, jump_kind="transition",
+ expect="theme selection Dark->Light")
+ return
+ nodes = ui()
+ dark = _seg_ancestor(nodes, "Dark")
+ if dark is None:
+ record("states_theme_dark_light", False,
+ "feature_missing: no theme segments in Settings",
+ depth=1, jump_kind="transition",
+ expect="theme selection Dark->Light")
+ return
+ tap_node(dark)
+ settle("tap")
+ mid = _selected_segment(ui(), labels, y_hi=1000)
+ light = _seg_ancestor(ui(), "Light")
+ if light is None:
+ record("states_theme_dark_light", False,
+ "feature_missing: no 'Light' theme segment in Settings",
+ depth=1, jump_kind="transition",
+ expect="theme selection Dark->Light")
+ return
+ tap_node(light)
+ settle("tap")
+ after = _selected_segment(ui(), labels, y_hi=1000)
+ ok = mid == "Dark" and after == "Light"
+ record("states_theme_dark_light", ok,
+ "" if ok else
+ f"behavior_wrong: theme selection did not move Dark->Light "
+ f"(mid={mid}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="theme 'Selected' marker moves Dark->Light")
+
+
+# 8) Calendar icon behavior 'Set to today'->'Pick a date': marker moves.
+# VLM: the 'Pick a date' segment is highlighted pink.
+@and_test(expects=("states_calendar_behavior",
+ "states_calendar_pick_highlight_vlm"))
+def test_calendar_behavior_toggle():
+ labels = ("Pick a date", "Set to today")
+ if not start_home_clean() or not and_enter_settings():
+ record("states_calendar_behavior", False,
+ "setup_failed: could not reach the Settings Calendar selector",
+ depth=1, jump_kind="transition",
+ expect="calendar behavior Set to today->Pick a date")
+ return
+ nodes = ui()
+ # Calendar-behavior selector sits low (y > 1600); its marker is below Theme's.
+ before = _selected_segment(nodes, labels, y_lo=1600)
+ pick = _seg_ancestor(nodes, "Pick a date")
+ if pick is None:
+ record("states_calendar_behavior", False,
+ "feature_missing: no 'Pick a date' segment in Settings",
+ depth=1, jump_kind="transition",
+ expect="calendar behavior Set to today->Pick a date")
+ vlm_assert("states_calendar_pick_highlight",
+ "In the 'Calendar icon behavior' row, is the 'Pick a date' "
+ "segment filled with a pink/coloured background while "
+ "'Set to today' is not?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ return
+ tap_node(pick)
+ settle("tap")
+ after = _selected_segment(ui(), labels, y_lo=1600)
+ ok = before == "Set to today" and after == "Pick a date"
+ record("states_calendar_behavior", ok,
+ "" if ok else
+ f"behavior_wrong: calendar behavior did not move Set to today->Pick a "
+ f"date (before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="calendar 'Selected' marker moves Set to today->Pick a date")
+
+ # VLM: the newly selected 'Pick a date' segment is highlighted pink.
+ vlm_assert("states_calendar_pick_highlight",
+ "In the 'Calendar icon behavior' row (two segments 'Pick a date' / "
+ "'Set to today'), is the 'Pick a date' segment filled with a "
+ "pink/coloured background while 'Set to today' has a plain "
+ "uncoloured background?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+
+
+# 9) Dynamic colors switch OFF->ON: checked flips false->true; track fills purple
+# (VLM). Restore OFF afterwards.
+@and_test(expects=("states_dynamic_colors_toggle",
+ "states_dynamic_colors_on_track_vlm"))
+def test_dynamic_colors_switch():
+ if not start_home_clean() or not and_enter_settings():
+ record("states_dynamic_colors_toggle", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Dynamic colors switch checked false->true")
+ return
+ nodes = ui()
+ sw = _switch_near(nodes, "Dynamic colors")
+ if sw is None:
+ record("states_dynamic_colors_toggle", False,
+ "feature_missing: no 'Dynamic colors' switch in Settings",
+ depth=1, jump_kind="transition",
+ expect="Dynamic colors switch checked false->true")
+ vlm_assert("states_dynamic_colors_on_track",
+ "This is a settings row labelled 'Dynamic colors' with a toggle "
+ "switch. Is the switch track filled with the accent purple "
+ "colour (ON position) rather than plain grey?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+ return
+ before = sw.get("checked")
+ _tap_anchor(nodes, sw)
+ fresh = ui()
+ after = (find_closest_match(fresh, sw) or {}).get("checked")
+ ok = before == "false" and after == "true"
+ record("states_dynamic_colors_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: Dynamic colors switch did not flip false->true "
+ f"(before={before}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="Dynamic colors switch checked false->true")
+
+ # VLM: after ON, the switch track fills with the accent colour.
+ vlm_assert("states_dynamic_colors_on_track",
+ "This is a settings row labelled 'Dynamic colors' with a toggle "
+ "switch. Is the switch track filled with a coloured (purple/accent) "
+ "fill and the thumb to the RIGHT (ON position), rather than a plain "
+ "grey OFF track?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="color")
+
+ # Restore OFF so a stale ON state cannot bleed into other screenshots.
+ r = _switch_near(ui(), "Dynamic colors")
+ if r is not None and r.get("checked") == "true":
+ _tap_anchor(ui(), r)
+
+
+# 10) Secure screen switch OFF->ON->OFF. FLAG_SECURE can blacken screenshots, so
+# this test asserts ONLY the checked flip and toggles back OFF — NO vlm.
+@and_test(expects=("states_secure_screen_toggle",))
+def test_secure_screen_switch():
+ if not start_home_clean() or not and_enter_settings():
+ record("states_secure_screen_toggle", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="transition",
+ expect="Secure screen switch checked false->true then back to false")
+ return
+ # The Secure-screen row is at the bottom of the scroll view; bring it on screen.
+ sw = _switch_near(ui(), "Secure screen")
+ if sw is None:
+ scroll_into_view("Secure screen", max_swipes=4)
+ sw = _switch_near(ui(), "Secure screen")
+ if sw is None:
+ record("states_secure_screen_toggle", False,
+ "feature_missing: no 'Secure screen' switch in Settings",
+ depth=1, jump_kind="transition",
+ expect="Secure screen switch checked false->true then back to false")
+ return
+ nodes = ui()
+ sw = _switch_near(nodes, "Secure screen") or sw
+ before = sw.get("checked")
+ _tap_anchor(nodes, sw)
+ after = (find_closest_match(ui(), sw) or {}).get("checked")
+ # Toggle back OFF immediately (FLAG_SECURE blackens later screenshots).
+ r = _switch_near(ui(), "Secure screen")
+ restored = None
+ if r is not None:
+ _tap_anchor(ui(), r)
+ restored = (find_closest_match(ui(), r) or {}).get("checked")
+ ok = before == "false" and after == "true" and restored == "false"
+ record("states_secure_screen_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: Secure screen switch did not flip false->true->false "
+ f"(before={before}, after={after}, restored={restored})",
+ depth=1, jump_kind="transition",
+ expect="Secure screen checked false->true then restored to false")
+
+
+# 11) Home Compact-view mode flip: tapping the toggle changes the label from
+# 'Compact view' to 'Expanded view' (a mode transition). VLM: density change.
+@and_test(expects=("states_compact_view_toggle",
+ "states_compact_view_density_vlm"))
+def test_compact_view_toggle():
+ if not start_home_clean():
+ record("states_compact_view_toggle", False,
+ "setup_failed: could not reach Home",
+ depth=0, jump_kind="transition",
+ expect="mode label 'Compact view'->'Expanded view'")
+ return
+ nodes = ui()
+ label = find_node_ci(nodes, "Compact view")
+ if label is None:
+ # tolerate the app starting in the expanded state
+ label = find_node_ci(nodes, "Expanded view")
+ if label is None:
+ record("states_compact_view_toggle", False,
+ "feature_missing: no Compact/Expanded view toggle on Home",
+ depth=0, jump_kind="transition",
+ expect="mode label 'Compact view'->'Expanded view'")
+ vlm_assert("states_compact_view_density",
+ "Is there a small horizontal-lines / list-density toggle icon at "
+ "the right end of the date row on this schedule screen?",
+ RESULTS_DIR, expect="YES", depth=0, jump_kind="none",
+ tag="layout")
+ return
+ before_compact = find_node_ci(nodes, "Compact view") is not None
+ before_expanded = find_node_ci(nodes, "Expanded view") is not None
+ _tap_anchor(nodes, label)
+ settle("tap")
+ fresh = ui()
+ after_compact = find_node_ci(fresh, "Compact view") is not None
+ after_expanded = find_node_ci(fresh, "Expanded view") is not None
+ # The label must have flipped between the two modes.
+ ok = ((before_compact and after_expanded and not after_compact)
+ or (before_expanded and after_compact and not after_expanded))
+ record("states_compact_view_toggle", ok,
+ "" if ok else
+ f"behavior_wrong: view-mode label did not flip "
+ f"(before compact={before_compact}/expanded={before_expanded}, "
+ f"after compact={after_compact}/expanded={after_expanded})",
+ depth=0, jump_kind="transition",
+ expect="view-mode label toggles 'Compact view' <-> 'Expanded view'")
+
+ # VLM: the toggle icon is present at the right of the date row (a stable
+ # rendered property on both states of an empty schedule).
+ vlm_assert("states_compact_view_density",
+ "On this schedule screen, at the right end of the date row, is there "
+ "a small toggle icon made of stacked horizontal lines (a "
+ "list-density / view control) next to the 'view' text?",
+ RESULTS_DIR, expect="YES", depth=0, jump_kind="transition",
+ tag="layout")
+
+
+# 12) Category bottom-sheet radio Absent->Study: the RadioButton `checked` moves
+# from the Absent row to the Study row. VLM: Study row highlighted + filled.
+@and_test(expects=("states_category_radio",
+ "states_category_study_highlight_vlm"))
+def test_category_radio_selection():
+ if not (start_home_clean() and and_enter_editor() and and_reach_category_sheet()):
+ record("states_category_radio", False,
+ "setup_failed: could not open the Category sheet",
+ depth=2, jump_kind="transition",
+ expect="category radio selection Absent->Study")
+ return
+ nodes = ui()
+ absent_before = _radio_checked(nodes, "Absent")
+ study_before = _radio_checked(nodes, "Study")
+ row = find_node(nodes, content_desc="Study") or find_node(nodes, text="Study")
+ if row is None:
+ record("states_category_radio", False,
+ "feature_missing: no 'Study' category row in the sheet",
+ depth=2, jump_kind="transition",
+ expect="category radio selection Absent->Study")
+ vlm_assert("states_category_study_highlight",
+ "In this category list, is exactly one row visibly selected "
+ "(highlighted background and a filled radio button) while the "
+ "others show empty radios?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="color")
+ return
+ _tap_anchor(nodes, row)
+ settle("tap")
+ fresh = ui()
+ absent_after = _radio_checked(fresh, "Absent")
+ study_after = _radio_checked(fresh, "Study")
+ ok = (absent_before == "true" and study_before == "false"
+ and study_after == "true" and absent_after == "false")
+ record("states_category_radio", ok,
+ "" if ok else
+ f"behavior_wrong: radio selection did not move Absent->Study "
+ f"(Absent {absent_before}->{absent_after}, "
+ f"Study {study_before}->{study_after})",
+ depth=2, jump_kind="transition",
+ expect="RadioButton checked moves from Absent (true->false) to Study "
+ "(false->true)")
+
+ # VLM: the selected Study row is highlighted pink with a filled radio.
+ vlm_assert("states_category_study_highlight",
+ "In this category picker list, is the 'Study' row highlighted with a "
+ "pink/coloured background and a FILLED radio button, while the other "
+ "rows (Absent, Shopping, Health, ...) have a plain background and "
+ "EMPTY radio buttons?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="color")
+
+
+# 13) SETTINGS PERSISTENCE — Theme survives process death (marquee for this lane).
+# Set Theme=Dark, force_stop_and_relaunch, reopen Settings, assert still Dark.
+@and_test(expects=("states_theme_persists",))
+def test_theme_survives_process_death():
+ labels = ("Light", "System", "Dark")
+ if not start_home_clean() or not and_enter_settings():
+ record("states_theme_persists", False,
+ "setup_failed: could not reach the Settings Theme selector",
+ depth=1, jump_kind="transition",
+ expect="Dark theme persists across restart")
+ return
+ dark = _seg_ancestor(ui(), "Dark")
+ if dark is None:
+ record("states_theme_persists", False,
+ "feature_missing: no 'Dark' theme segment in Settings",
+ depth=1, jump_kind="transition",
+ expect="Dark theme persists across restart")
+ return
+ tap_node(dark)
+ settle("tap")
+ set_ok = _selected_segment(ui(), labels, y_hi=1000) == "Dark"
+ # THE probe: kill the process and relaunch, then re-navigate to Settings.
+ force_stop_and_relaunch()
+ ensure_home()
+ if not and_enter_settings():
+ record("states_theme_persists", False,
+ "setup_failed: could not reopen Settings after restart",
+ depth=1, jump_kind="transition",
+ expect="Dark theme persists across restart")
+ return
+ after = _selected_segment(ui(), labels, y_hi=1000)
+ ok = set_ok and after == "Dark"
+ record("states_theme_persists", ok,
+ "" if ok else
+ f"behavior_wrong: Theme was not still 'Dark' after restart "
+ f"(set_ok={set_ok}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="theme 'Selected' marker still on Dark after "
+ "force_stop_and_relaunch")
+
+
+# 14) SETTINGS PERSISTENCE — Calendar icon behavior survives process death.
+@and_test(expects=("states_calendar_persists",))
+def test_calendar_behavior_survives_process_death():
+ labels = ("Pick a date", "Set to today")
+ if not start_home_clean() or not and_enter_settings():
+ record("states_calendar_persists", False,
+ "setup_failed: could not reach the Settings Calendar selector",
+ depth=1, jump_kind="transition",
+ expect="calendar behavior 'Pick a date' persists across restart")
+ return
+ pick = _seg_ancestor(ui(), "Pick a date")
+ if pick is None:
+ record("states_calendar_persists", False,
+ "feature_missing: no 'Pick a date' segment in Settings",
+ depth=1, jump_kind="transition",
+ expect="calendar behavior 'Pick a date' persists across restart")
+ return
+ tap_node(pick)
+ settle("tap")
+ set_ok = _selected_segment(ui(), labels, y_lo=1600) == "Pick a date"
+ force_stop_and_relaunch()
+ ensure_home()
+ if not and_enter_settings():
+ record("states_calendar_persists", False,
+ "setup_failed: could not reopen Settings after restart",
+ depth=1, jump_kind="transition",
+ expect="calendar behavior 'Pick a date' persists across restart")
+ return
+ after = _selected_segment(ui(), labels, y_lo=1600)
+ ok = set_ok and after == "Pick a date"
+ record("states_calendar_persists", ok,
+ "" if ok else
+ f"behavior_wrong: calendar behavior was not still 'Pick a date' after "
+ f"restart (set_ok={set_ok}, after={after})",
+ depth=1, jump_kind="transition",
+ expect="calendar 'Selected' marker still on 'Pick a date' after "
+ "force_stop_and_relaunch")
+
+
+# 15) Settings Color swatch selection (VLM-only rendered property — the swatch
+# colours never reach the view tree). One swatch shows a white check; after
+# tapping a DIFFERENT swatch the check moves to it.
+@and_test(expects=("states_color_swatch_check_vlm",
+ "states_color_swatch_moved_vlm"))
+def test_color_swatch_selection_vlm():
+ if not start_home_clean() or not and_enter_settings():
+ record("states_color_swatch_check_vlm", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="none", tag="shape")
+ record("states_color_swatch_moved_vlm", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="none", tag="position")
+ return
+ nodes = ui()
+ # The Color row: 4 clickable swatch Views on one horizontal line under 'Color'.
+ color_lab = find_node(nodes, text="Color")
+ swatches = []
+ if color_lab is not None and "_center" in color_lab:
+ cy = color_lab["_center"][1]
+ swatches = sorted(
+ [n for n in nodes
+ if n.get("clickable") == "true" and "_center" in n
+ and 60 < (n["_center"][1] - cy) < 260
+ and (n["_bounds"][2] - n["_bounds"][0]) < 300],
+ key=lambda n: n["_center"][0])
+
+ # VLM #1: exactly one swatch shows a white check mark.
+ vlm_assert("states_color_swatch_check",
+ "This is a 'Color' row of four coloured square swatches. Does "
+ "exactly ONE swatch show a white check-mark (tick) drawn on it, "
+ "while the other three have no check mark?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none",
+ tag="shape")
+
+ # Tap a DIFFERENT swatch than the currently checked one. From recon the 2nd
+ # (purple) is selected by default, so tapping the 4th (blue) moves the check.
+ if len(swatches) >= 4:
+ safe_tap(swatches[3])
+ settle("tap")
+
+ # VLM #2: the check mark is now on the RIGHTMOST (4th) swatch.
+ vlm_assert("states_color_swatch_moved",
+ "This is a 'Color' row of four coloured square swatches. Is the "
+ "white check-mark now drawn on the RIGHTMOST (fourth) swatch, and "
+ "NOT on the second swatch?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="transition",
+ tag="position")
+
+
+TESTS = [
+ test_statistics_switch_toggle,
+ test_statistics_switch_toggle_back,
+ test_notifications_switch_toggle,
+ test_priority_standard_to_medium,
+ test_priority_medium_to_max,
+ test_theme_system_to_dark,
+ test_theme_dark_to_light,
+ test_calendar_behavior_toggle,
+ test_dynamic_colors_switch,
+ test_secure_screen_switch,
+ test_compact_view_toggle,
+ test_category_radio_selection,
+ test_theme_survives_process_death,
+ test_calendar_behavior_survives_process_death,
+ test_color_swatch_selection_vlm,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "states")
diff --git a/android/v1tzor-timeplanner/tests/test_android_structure.py b/android/v1tzor-timeplanner/tests/test_android_structure.py
new file mode 100644
index 0000000000000000000000000000000000000000..df45cc40b464cfeb2683cb59a964890bd61d25d8
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_structure.py
@@ -0,0 +1,509 @@
+#!/usr/bin/env python3
+"""STRUCTURE lane — TimePlanner (day-planner).
+
+Owns two things only:
+ (1) the GATE — the app launches, is foreground, and its top-level surfaces
+ exist (main Compose container + top bar + 3-tab bottom nav). jump_kind="none".
+ (2) tree-SHAPE deltas — a user interaction that changes the view tree's SHAPE
+ (a class of widget appears/disappears, an empty->populated list, a section
+ of cards appears). Recorded as jump_kind="transition" with a before/after
+ count or surface-set delta, and reversed to assert it restores.
+
+No content-string equality (text lane), no checked/selected assertions (states
+lane), no computed values (computation lane), no reach-by-jump-alone (navigation
+lane). Everything asserted here was OBSERVED on the running original.
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+
+# ── Onboarding: after clear_data() (only then) a notification-permission dialog
+# appears with "Allow"/"Don't allow" (curly apostrophe). It is on-screen so ui()
+# sees it. No-op after a plain restart_app(). Call after every launch. ──────────
+def dismiss_onboarding():
+ for _ in range(2):
+ nodes = ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")),
+ None)
+ if not btn:
+ return
+ tap_node(btn)
+
+
+def _has(nodes, label):
+ return find_node_ci(nodes, label) is not None
+
+
+def _home_ready(nodes):
+ """TimePlanner Home is up iff the 'Schedule' top-bar title is present."""
+ return _has(nodes, "Schedule")
+
+
+def _ensure_home(max_tries=10):
+ """Drive the GUI until TimePlanner's Home is showing.
+
+ The .debug build bundles LeakCanary, which registers a SECOND launcher alias
+ in the SAME package; after a data wipe `monkey LAUNCHER` sometimes opens the
+ LeakCanary screen instead of the app, and monkey then STAYS on that alias
+ (a plain relaunch re-opens LeakCanary). The portable break is a hard reset —
+ HOME, force-stop, relaunch — which clears the task so the launcher re-resolves;
+ empirically this lands on the app within a couple of tries. Nothing here writes
+ a component/package literal: LeakCanary is detected only by its on-screen text.
+ Returns True once Home ('Schedule') is confirmed on a settled dump."""
+ for _ in range(max_tries):
+ dismiss_onboarding() # onboarding dialog IS the app -> Home
+ nodes = ui()
+ if _home_ready(nodes):
+ # A Compose recomposition/animation can leave the very next dump blank,
+ # so confirm Home on a SETTLED re-dump before handing control back.
+ for _ in range(3):
+ settle("launch")
+ if _home_ready(ui()):
+ return True
+ continue
+ # LeakCanary, the system launcher, or a blank frame: hard-reset the task.
+ home()
+ settle("key")
+ force_stop()
+ settle("key")
+ launch_app()
+ wait_for_foreground()
+ return _home_ready(ui())
+
+
+def _clickable_ancestor(nodes, node):
+ """Compose leaf labels are not themselves clickable; the tappable card is an
+ ancestor View whose bounds enclose the leaf. Return the smallest clickable
+ node containing `node`'s centre (else the node itself)."""
+ if not node or "_center" not in node:
+ return node
+ cx, cy = node["_center"]
+ best, best_area = None, None
+ for n in nodes:
+ if n.get("clickable") != "true" or "_bounds" not in n:
+ continue
+ x1, y1, x2, y2 = n["_bounds"]
+ if x1 <= cx <= x2 and y1 <= cy <= y2:
+ area = (x2 - x1) * (y2 - y1)
+ if best_area is None or area < best_area:
+ best, best_area = n, area
+ return best or node
+
+
+def _fresh_empty_home():
+ """Guaranteed clean entry point: wipe data, launch, clear onboarding and any
+ LeakCanary launcher. The day then has no schedule -> the empty-state block
+ ('Nothing planned yet' + 'Plan now') is showing. Returns True iff Home is up."""
+ clear_data()
+ launch_app()
+ wait_for_foreground()
+ return _ensure_home()
+
+
+def _restart_home():
+ """Restart (data intact) and confirm Home — used where the empty state is not
+ required. Still routed through the LeakCanary recovery."""
+ restart_app()
+ wait_for_foreground()
+ return _ensure_home()
+
+
+# ── depth-family helpers (naming BACKS a declared depth>=1; the taps are mine) ──
+def and_enter_editor(nodes):
+ """Home -> Editor by tapping the free-slot 'Unassigned' add-row. Confirms the
+ Editor surface (its 'Save' button appears). Counts one surface."""
+ row = find_node_ci(nodes, "Unassigned") or find_node_ci(nodes, "Add a task")
+ if not row:
+ return False
+ if not tap_node(_clickable_ancestor(nodes, row)):
+ return False
+ if not _has(ui(), "Save"):
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_enter_category_sheet(nodes):
+ """Editor -> Category bottom sheet by tapping the Category card. Confirms the
+ sheet (its 'Select' button appears). Counts one surface."""
+ lbl = find_node_ci(nodes, "Category")
+ if not lbl:
+ return False
+ if not tap_node(_clickable_ancestor(nodes, lbl)):
+ return False
+ if not _has(ui(), "Select"):
+ return False
+ and_enter("category_sheet")
+ return True
+
+
+def and_enter_settings(nodes):
+ """Home -> Settings via the bottom-nav 'Settings' tab. Counts one surface."""
+ if not tap_text(nodes, "Settings"):
+ return False
+ if not _has(ui(), "Appearance"):
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_enter_analytics(nodes):
+ """Home -> Analytics via the bottom-nav 'Analytics' tab. Counts one surface."""
+ if not tap_text(nodes, "Analytics"):
+ return False
+ if not _has(ui(), "Planning stats"):
+ return False
+ and_enter("analytics")
+ return True
+
+
+def and_enter_overview(nodes):
+ """Home -> Overview via the top-bar grid icon (desc 'Overview'). Counts one
+ surface (its 'Schedules' section header appears)."""
+ grid = find_node(nodes, content_desc="Overview")
+ if not grid or not tap_node(grid):
+ return False
+ if not _has(ui(), "Schedules"):
+ return False
+ and_enter("overview")
+ return True
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# GATE (jump_kind="none", depth=0) — kept to <=30% of the file
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_gate_launch", "structure_gate_home_layout_vlm"))
+def test_gate_launch():
+ """App launches, reaches foreground, and its top-level Compose container
+ exists. A dead process or a blank Activity fails this."""
+ ok_home = _fresh_empty_home()
+ nodes = ui()
+ container = bool(find_by_class(nodes, "ComposeView")
+ or find_by_class(nodes, "FrameLayout"))
+ ok = bool(ok_home and container)
+ record("structure_gate_launch", ok,
+ "" if ok else "setup_failed: app did not reach the foreground with a "
+ "top-level Compose container",
+ depth=0, jump_kind="none")
+ vlm_assert("structure_gate_home_layout",
+ "Is this a day-planner Home screen: a top app bar with a title, a "
+ "date row with left/right chevron arrows, and a bottom navigation "
+ "bar? Answer YES only if that overall schedule-screen layout is "
+ "visible.",
+ RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="layout")
+
+
+@and_test(expects=("structure_gate_home_topbar",))
+def test_gate_home_topbar():
+ """Top-bar host: title 'Schedule' plus the menu + overview icon buttons (by
+ content-desc, not internal id)."""
+ _fresh_empty_home()
+ nodes = ui()
+ menu = find_node(nodes, content_desc="Open menu") is not None
+ overview = find_node(nodes, content_desc="Overview") is not None
+ if not (menu and overview): # top bar may still be composing; re-read
+ settle("launch")
+ nodes = ui()
+ menu = find_node(nodes, content_desc="Open menu") is not None
+ overview = find_node(nodes, content_desc="Overview") is not None
+ title = _has(nodes, "Schedule")
+ ok = bool(title and menu and overview)
+ record("structure_gate_home_topbar", ok,
+ "" if ok else "feature_missing: home top-bar host (Schedule title + "
+ "Open menu + Overview icons) not all present",
+ depth=0, jump_kind="none")
+
+
+@and_test(expects=("structure_bottom_nav_three_tabs",
+ "structure_bottom_nav_layout_vlm"))
+def test_bottom_nav_three_tabs():
+ """Bottom-nav host has exactly the 3 tab labels Home / Analytics / Settings —
+ the shape of the navigation container."""
+ _fresh_empty_home()
+ nodes = ui()
+ labels = [t for t in ("Home", "Analytics", "Settings") if _has(nodes, t)]
+ ok = len(labels) == 3
+ record("structure_bottom_nav_three_tabs", ok,
+ "" if ok else f"feature_missing: expected 3 bottom-nav tabs "
+ f"(Home/Analytics/Settings), found {labels}",
+ depth=0, jump_kind="none")
+ vlm_assert("structure_bottom_nav_layout",
+ "Is there a bottom navigation bar containing exactly 3 icon+label "
+ "items, evenly spaced across the bottom edge of the screen?",
+ RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="position")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# SHAPE DELTAS (jump_kind="transition") — the bulk of the file
+# ══════════════════════════════════════════════════════════════════════════════
+
+@and_test(expects=("structure_home_empty_to_planned",
+ "structure_empty_state_layout_vlm"))
+def test_home_empty_to_planned():
+ """Empty day -> tap 'Plan now' -> the tree gains a schedule free-slot row
+ ('Unassigned') and the empty-state block ('Nothing planned yet' + 'Plan now')
+ disappears. Reversed by wiping back to the empty day."""
+ _fresh_empty_home()
+ before = ui()
+ empty_present = _has(before, "Nothing planned yet") and _has(before, "Plan now")
+ b_show = and_showing(before)
+
+ # capture the empty-state layout before we leave it (only if it is really up)
+ vlm_assert("structure_empty_state_layout",
+ "Does the centre of the screen show a single large placeholder "
+ "icon with a short line of text under it and one outlined button "
+ "below that (an empty-state), rather than a list of rows?",
+ RESULTS_DIR, expect="YES", depth=0, jump_kind="none", tag="position")
+
+ tapped = tap_text(before, "Plan now")
+ after = ui()
+ row_appeared = _has(after, "Unassigned")
+ empty_gone = not _has(after, "Nothing planned yet")
+ fwd_ok = bool(empty_present and tapped and row_appeared and empty_gone
+ and surface_changed(b_show, and_showing(after)))
+
+ # reverse: a fresh wipe returns to the empty-state shape
+ _fresh_empty_home()
+ restored = _has(ui(), "Plan now")
+ ok = fwd_ok and restored
+ record("structure_home_empty_to_planned", ok,
+ "" if ok else "behavior_wrong: 'Plan now' did not replace the "
+ "empty-state block with a schedule row (or it did not "
+ "restore on a clean day)",
+ depth=0, jump_kind="transition",
+ expect="empty-state (Nothing planned yet + Plan now) -> free-slot row "
+ "'Unassigned' appears in-place; restored to empty-state on data wipe")
+
+
+@and_test(expects=("structure_editor_field_cards",
+ "structure_editor_cards_layout_vlm",
+ "structure_editor_priority_segmented_vlm"))
+def test_editor_field_cards():
+ """Opening the Editor adds a whole class of field controls that Home never
+ shows: the 'Priority'/'Statistics' labels, 2 toggle switches, and the Note
+ EditText. Reversed with BACK -> those controls are gone again on Home."""
+ _fresh_empty_home()
+ tap_text(ui(), "Plan now")
+ home = ui()
+ home_switches = len([n for n in home if n.get("checkable") == "true"])
+ home_edits = len(find_by_class(home, "EditText"))
+ home_priority = _has(home, "Priority") and _has(home, "Statistics")
+
+ entered = and_enter_editor(home)
+ ed = ui()
+ ed_switches = len([n for n in ed if n.get("checkable") == "true"])
+ ed_edits = len(find_by_class(ed, "EditText"))
+ ed_fields = (_has(ed, "Category") and _has(ed, "Priority")
+ and _has(ed, "Statistics") and _has(ed, "Save"))
+ fwd_ok = bool(entered and not home_priority and home_switches == 0
+ and ed_fields and ed_switches == 2 and ed_edits == home_edits + 1)
+
+ vlm_assert("structure_editor_cards_layout",
+ "Is the main area a vertically stacked list of rounded rectangular "
+ "field cards (a form), with a Cancel and a Save button at the "
+ "bottom?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")
+ vlm_assert("structure_editor_priority_segmented",
+ "Is there a horizontal segmented control divided into exactly 3 "
+ "side-by-side options labelled Standard, Medium and Max?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+
+ and_back()
+ back_home = ui()
+ restored = (not _has(back_home, "Priority")
+ and len([n for n in back_home if n.get("checkable") == "true"]) == 0)
+ ok = fwd_ok and restored
+ record("structure_editor_field_cards", ok,
+ "" if ok else "behavior_wrong: Editor did not add the field-card "
+ "controls (2 switches + Note EditText + Priority) over "
+ "Home, or they did not disappear on BACK",
+ depth=1, jump_kind="transition",
+ expect="switch count 0->2 and EditText +1 and Priority/Statistics "
+ "appear on opening Editor; restored to 0 switches on BACK")
+
+
+@and_test(expects=("structure_category_sheet_radios",
+ "structure_category_sheet_position_vlm"))
+def test_category_sheet_radios():
+ """From the Editor, opening the Category bottom sheet adds a class of widget
+ the Editor never has: RadioButton rows (0 -> 5) plus a 'Select' button.
+ Reversed by dismissing the sheet -> RadioButton count back to 0."""
+ _fresh_empty_home()
+ tap_text(ui(), "Plan now")
+ if not and_enter_editor(ui()):
+ record("structure_category_sheet_radios", False,
+ "setup_failed: could not open the Editor to reach the Category "
+ "sheet", depth=2, jump_kind="transition",
+ expect="RadioButton count 0->5 on opening the Category sheet")
+ record("structure_category_sheet_position_vlm", False,
+ "setup_failed: could not open the Editor", depth=2,
+ jump_kind="transition", tag="position")
+ return
+ ed = ui()
+ ed_radios = len(find_by_class(ed, "RadioButton"))
+
+ opened = and_enter_category_sheet(ed)
+ sheet = ui()
+ sheet_radios = len(find_by_class(sheet, "RadioButton"))
+ has_select = _has(sheet, "Select")
+ fwd_ok = bool(opened and ed_radios == 0 and sheet_radios == 5 and has_select)
+
+ vlm_assert("structure_category_sheet_position",
+ "Is a bottom sheet panel overlaid on the lower part of the screen "
+ "(its top edge is below the middle, sliding up from the bottom) "
+ "showing a scrollable list of selectable category rows?",
+ RESULTS_DIR, expect="YES", depth=2, jump_kind="transition",
+ tag="position")
+
+ # reverse: dismiss via Cancel (safe) -> back on the Editor, no radios
+ if not tap_text(ui(), "Cancel"):
+ and_back()
+ restored = len(find_by_class(ui(), "RadioButton")) == 0
+ ok = fwd_ok and restored
+ record("structure_category_sheet_radios", ok,
+ "" if ok else "behavior_wrong: Category sheet did not add 5 "
+ "RadioButton rows over the Editor (or they did not "
+ "clear on dismiss)",
+ depth=2, jump_kind="transition",
+ expect="RadioButton count 0->5 (+Select button) on opening the "
+ "Category sheet; restored to 0 on Cancel")
+
+
+@and_test(expects=("structure_settings_sections",
+ "structure_settings_color_swatches_vlm",
+ "structure_settings_theme_segmented_vlm"))
+def test_settings_sections():
+ """The Settings root has a distinct section shape: the section headers
+ Appearance / Interface / Security plus 2 toggle switches — none of which the
+ Home schedule shows. Reversed by returning to Home via its bottom-nav tab."""
+ _fresh_empty_home()
+ home = ui()
+ home_sections = _has(home, "Appearance") or _has(home, "Interface")
+
+ entered = and_enter_settings(home)
+ s = ui()
+ headers = [h for h in ("Appearance", "Interface", "Security") if _has(s, h)]
+ s_switches = len([n for n in s if n.get("checkable") == "true"])
+ fwd_ok = bool(entered and not home_sections and len(headers) == 3
+ and s_switches >= 2 and not _has(s, "Nothing planned yet"))
+
+ vlm_assert("structure_settings_color_swatches",
+ "Under a 'Color' label, is there a horizontal row of exactly 4 "
+ "coloured swatch tiles side by side, in distinct colours "
+ "(reddish, purple, indigo and blue)?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="color")
+ vlm_assert("structure_settings_theme_segmented",
+ "Under a 'Theme' label, is there a horizontal segmented control "
+ "with 3 options (Light, System, Dark) where one option is "
+ "highlighted with a filled/tinted background?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+
+ # reverse
+ tap_text(ui(), "Home")
+ restored = _has(ui(), "Schedule")
+ ok = fwd_ok and restored
+ record("structure_settings_sections", ok,
+ "" if ok else "behavior_wrong: Settings did not show the 3 section "
+ "headers + >=2 switches, or Home tab did not restore",
+ depth=1, jump_kind="transition",
+ expect="Settings adds section headers Appearance/Interface/Security "
+ "+ >=2 switches over Home; restored to Schedule on Home tab")
+
+
+@and_test(expects=("structure_analytics_tab_switch",
+ "structure_analytics_donut_vlm",
+ "structure_analytics_heatmap_vlm"))
+def test_analytics_tab_switch():
+ """Analytics Time tab shows 'Planning stats' (heatmap) + 'Category stats'
+ (donut). Switching to the Workload tab REMOVES the 'Planning stats' block —
+ a tree-shape delta. Reversed by switching back to the Time tab."""
+ _fresh_empty_home()
+ entered = and_enter_analytics(ui())
+ time_tab = ui()
+ time_ok = _has(time_tab, "Planning stats") and _has(time_tab, "Category stats")
+ b_show = and_showing(time_tab)
+
+ vlm_assert("structure_analytics_donut",
+ "Under 'Category stats', is there a circular ring / donut (pie) "
+ "chart with a hole in the centre and a number in the middle?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="shape")
+ vlm_assert("structure_analytics_heatmap",
+ "Under 'Planning stats', is there a grid of small squares arranged "
+ "in rows and columns (a calendar heatmap), with weekday labels like "
+ "Mon/Wed/Fri along the left?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="layout")
+
+ wl = find_node(time_tab, content_desc="Workload") or find_node_ci(time_tab, "Workload")
+ switched = tap_node(wl) if wl else False
+ workload = ui()
+ planning_gone = not _has(workload, "Planning stats")
+ fwd_ok = bool(entered and time_ok and switched and planning_gone
+ and surface_changed(b_show, and_showing(workload)))
+
+ # reverse: back to Time tab -> Planning stats returns
+ tm = find_node(ui(), content_desc="Time") or find_node_ci(ui(), "Time")
+ if tm:
+ tap_node(tm)
+ restored = _has(ui(), "Planning stats")
+ ok = fwd_ok and restored
+ record("structure_analytics_tab_switch", ok,
+ "" if ok else "behavior_wrong: Workload tab did not remove the "
+ "'Planning stats' block (or Time tab did not restore it)",
+ depth=1, jump_kind="transition",
+ expect="'Planning stats' block present on Time tab, removed on Workload "
+ "tab, restored on Time tab")
+
+
+@and_test(expects=("structure_overview_shape",))
+def test_overview_shape():
+ """The Overview screen (top-bar grid icon) has a shape Home lacks: it gains
+ ProgressBar widgets plus the 'Schedules' / 'Current task' section headers, and
+ the Home empty-state ('Plan now') disappears. Reversed with BACK to Home."""
+ _fresh_empty_home()
+ home = ui()
+ home_bars = len(find_by_class(home, "ProgressBar"))
+ home_sched_header = _has(home, "Schedules")
+
+ entered = and_enter_overview(home)
+ ov = ui()
+ ov_bars = len(find_by_class(ov, "ProgressBar"))
+ ov_headers = _has(ov, "Schedules") and _has(ov, "Current task")
+ plan_gone = not _has(ov, "Plan now")
+ fwd_ok = bool(entered and not home_sched_header and ov_headers
+ and ov_bars > home_bars and plan_gone)
+
+ and_back()
+ restored = _has(ui(), "Schedule")
+ ok = fwd_ok and restored
+ record("structure_overview_shape", ok,
+ "" if ok else "behavior_wrong: Overview did not add ProgressBar + "
+ "Schedules/Current task sections over Home (or BACK did "
+ "not restore Home)",
+ depth=1, jump_kind="transition",
+ expect="Overview adds ProgressBar widgets + Schedules/Current task "
+ "headers over Home; restored to Schedule on BACK")
+
+
+TESTS = [
+ test_gate_launch,
+ test_gate_home_topbar,
+ test_bottom_nav_three_tabs,
+ test_home_empty_to_planned,
+ test_editor_field_cards,
+ test_category_sheet_radios,
+ test_settings_sections,
+ test_analytics_tab_switch,
+ test_overview_shape,
+]
+
+
+if __name__ == "__main__":
+ if not device_online():
+ print("[structure] DEVICE OFFLINE — the adb tunnel appears to be down; "
+ "records will read setup_failed rather than app defects.")
+ run_suite(TESTS, "structure")
diff --git a/android/v1tzor-timeplanner/tests/test_android_text.py b/android/v1tzor-timeplanner/tests/test_android_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab099ca5bee18bc3f75f091c81a8f8ee8623dd0b
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_android_text.py
@@ -0,0 +1,591 @@
+#!/usr/bin/env python3
+"""TEXT lane for TimePlanner (package from argv[1]).
+
+Owns CONTENT strings that an interaction PRODUCES, and is the sole owner of
+exact-string equality. Every test is TRIGGER (tap / navigate) -> OBSERVATION (a
+specific app-authored string that the running ORIGINAL rendered on that surface).
+Existence-on-a-dead-shell must FAIL: the strong tests assert a string that is
+ABSENT before the trigger and PRESENT only after it (transition), or that appears
+only after a real surface jump proven with and_reach (reach).
+
+Every expected string below was OBSERVED live on the original via a fresh ui()
+dump — never read from source, never a version/build constant (those are excluded
+on purpose: a faithful recreation cannot know them).
+
+Run:
+ ADB_PATH=... DEVICE_SERIAL=... python3 test_android_text.py
+"""
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from android_testgen_kit import * # noqa: F403,E402
+
+require_kit(1)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Onboarding + LeakCanary recovery (the two documented traps; helpers are the
+# exact idiom the other five lanes use).
+# (A) After clear_data() a notification-permission dialog is on screen
+# ("Allow" / "Don't allow" — curly apostrophe); ui() sees it, so dismiss it.
+# (B) The .debug build bundles a SECOND launcher activity in the SAME package;
+# monkey LAUNCHER may open the wrong screen and wait_for_foreground() LIES
+# (same package). Detect by the ABSENCE of a Home surface; recover with
+# force_stop + relaunch (NOT HOME).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def dismiss_onboarding(nodes=None):
+ nodes = nodes if nodes is not None else ui()
+ btn = next((n for n in nodes
+ if (n.get("text") or "") in ("Allow", "Don't allow", "Don’t allow")), None)
+ if btn is None:
+ return False
+ tap_node(btn)
+ return True
+
+
+def _home_ready(nodes):
+ return (find_node_ci(nodes, "Schedule") is not None
+ or find_node_ci(nodes, "Plan now") is not None
+ or find_node_ci(nodes, "Nothing planned yet") is not None)
+
+
+def ensure_home(max_tries=12):
+ for _ in range(max_tries):
+ nodes = ui()
+ if dismiss_onboarding(nodes):
+ settle("tap"); continue
+ if _home_ready(nodes):
+ settle("launch")
+ if _home_ready(ui()):
+ return True
+ continue
+ force_stop(); settle("key")
+ launch_app(); settle("launch")
+ return _home_ready(ui())
+
+
+def start_home_clean():
+ clear_data(); launch_app(); return ensure_home()
+
+
+def start_home():
+ restart_app(); return ensure_home()
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# Compose tap helpers — leaf labels report clickable="false"; tap the clickable
+# ancestor whose bounds enclose the label's centre (same idiom as the other lanes).
+# ══════════════════════════════════════════════════════════════════════════════
+
+def _clickable_ancestor(nodes, anchor):
+ if not anchor or "_center" not in anchor:
+ return None
+ cx, cy = anchor["_center"]
+ cands = [n for n in nodes
+ if n.get("clickable") == "true" and "_bounds" in n
+ and n["_bounds"][0] <= cx <= n["_bounds"][2]
+ and n["_bounds"][1] <= cy <= n["_bounds"][3]]
+ cands.sort(key=lambda n: (n["_bounds"][2] - n["_bounds"][0])
+ * (n["_bounds"][3] - n["_bounds"][1]))
+ return cands[0] if cands else None
+
+
+def _tap_anchor(nodes, anchor):
+ if anchor is None:
+ return False
+ anc = _clickable_ancestor(nodes, anchor)
+ return tap_node(anc) if anc else tap_node(anchor)
+
+
+# ── text-reading helpers ────────────────────────────────────────────────────────
+
+def all_text(nodes):
+ """Every visible text + content-desc, joined — one blob to search."""
+ parts = []
+ for n in nodes:
+ t = (n.get("text") or "").strip()
+ cd = (n.get("content-desc") or "").strip()
+ if t:
+ parts.append(t)
+ if cd:
+ parts.append(cd)
+ return " | ".join(parts)
+
+
+def has_ci(nodes, needle):
+ """Case-insensitive substring test over text + content-desc."""
+ return needle.strip().casefold() in all_text(nodes).casefold()
+
+
+def exact_text(nodes, value):
+ """True iff some node's text is EXACTLY `value` (after strip). This is the
+ exact-string equality this lane owns — no substring slack."""
+ v = value.strip()
+ return any((n.get("text") or "").strip() == v for n in nodes)
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# NAMED navigation helpers — the and_reach_*/and_enter_* NAME backs every depth>=1
+# and jump_kind="reach" claim (the depth audit looks for a call from this family,
+# directly or in a helper a test calls). Each returns bool and, on success, has
+# counted the surface it entered.
+#
+# The bottom-nav tab label collides with the top-bar title (both key
+# "TextView|Analytics"), so a tab's own name is useless as a reach target — we
+# target a screen-BODY element instead: Analytics -> "Category stats",
+# Settings -> "Appearance".
+# ══════════════════════════════════════════════════════════════════════════════
+
+def and_reach_analytics():
+ """Home -> tap the Analytics bottom tab -> Analytics screen. Proves the body
+ element 'Category stats' appeared and Home's 'Schedule' title left. Ensures the
+ Time sub-tab (donut + legend) is shown. Counts one surface."""
+ nodes = ui()
+ tab = find_node(nodes, content_desc="Analytics") or find_node(nodes, text="Analytics")
+ if tab is None:
+ return False
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, tab):
+ return False
+ settle("launch")
+ after = and_showing()
+ if not and_reach(before, after, "Category stats", "Schedule"):
+ return False
+ and_enter("analytics")
+ t = find_node(ui(), content_desc="Time")
+ if t is not None:
+ _tap_anchor(ui(), t)
+ settle("tap")
+ return True
+
+
+def and_reach_settings():
+ """Home -> tap the Settings bottom tab -> Settings screen. Proves the body
+ section 'Appearance' appeared and Home's 'Schedule' title left. Counts one
+ surface."""
+ nodes = ui()
+ tab = find_node(nodes, content_desc="Settings") or find_node(nodes, text="Settings")
+ if tab is None:
+ return False
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, tab):
+ return False
+ settle("launch")
+ after = and_showing()
+ if not and_reach(before, after, "Appearance", "Schedule"):
+ return False
+ and_enter("settings")
+ return True
+
+
+def and_reach_editor():
+ """Home -> (Plan now creates the day) -> tap the free 'Unassigned'/'Add a task'
+ row -> Editor. Proves Editor's 'Statistics' appeared and Home's 'Schedule'
+ left. Counts one surface."""
+ n = find_node_ci(ui(), "Plan now")
+ if n is not None:
+ tap_node(n) # creates the day's schedule
+ settle("tap")
+ row = find_node_ci(ui(), "Unassigned") or find_node_ci(ui(), "Add a task")
+ if row is None:
+ return False
+ nodes = ui()
+ before = and_showing(nodes)
+ if not _tap_anchor(nodes, row):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Statistics", "Schedule"):
+ return False
+ and_enter("editor")
+ return True
+
+
+def and_reach_category_sheet():
+ """Editor -> tap the Category card -> Category bottom sheet. 'Select' is the
+ sheet's confirm button (the Editor has 'Save', not 'Select'). Counts one
+ surface."""
+ nodes = ui()
+ card = _clickable_ancestor(nodes, find_node(nodes, text="Category"))
+ if card is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(card):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Select", "Save"):
+ return False
+ and_enter("category_sheet")
+ return True
+
+
+def and_reach_drawer():
+ """Home -> tap the hamburger ('Open menu') -> the navigation drawer. Proves the
+ drawer header 'Time Planner' appeared (Home never renders it). Counts one
+ surface."""
+ nodes = ui()
+ menu = find_node(nodes, content_desc="Open menu")
+ if menu is None:
+ return False
+ before = and_showing(nodes)
+ if not tap_node(menu):
+ return False
+ after = and_showing()
+ if not and_reach(before, after, "Time Planner"):
+ return False
+ and_enter("drawer")
+ return True
+
+
+def and_reach_templates():
+ """(drawer already open) tap 'Templates' -> Templates screen. Proves 'List is
+ empty' appeared and the drawer header 'Time Planner' left. Counts one surface."""
+ item = find_node(ui(), text="Templates")
+ if item is None:
+ return False
+ if not and_reach_surface(item, "List is empty", "Time Planner"):
+ return False
+ return True
+
+
+def and_reach_overview():
+ """Home -> tap the top-bar grid icon ('Overview') -> Overview screen. Proves
+ the 'Schedules' section appeared and Home's 'Compact view' toggle left. Counts
+ one surface."""
+ ov = find_node(ui(), content_desc="Overview")
+ if ov is None:
+ return False
+ return and_reach_surface(ov, "Schedules", "Compact view")
+
+
+# ══════════════════════════════════════════════════════════════════════════════
+# TESTS
+# ══════════════════════════════════════════════════════════════════════════════
+
+# 1) Home top-bar title. A depth-0 dump read of the app's own screen title.
+@and_test(expects=("text_home_title",))
+def test_home_title():
+ ok_home = start_home()
+ nodes = ui()
+ # The bottom-nav "Home" tab also exists; the top-bar TITLE is the exact
+ # "Schedule" TextView, which only the real Home surface renders.
+ ok = ok_home and exact_text(nodes, "Schedule")
+ record("text_home_title", ok,
+ "" if ok else "feature_missing: Home top-bar title 'Schedule' not shown",
+ depth=0, jump_kind="none", expect="top-bar title == 'Schedule'")
+
+
+# 2) Virgin-Home empty state. Only a genuinely empty schedule renders this prompt,
+# so it must be read on a freshly-cleared database.
+@and_test(expects=("text_empty_state",))
+def test_empty_state():
+ ok_home = start_home_clean()
+ nodes = ui()
+ ok = ok_home and exact_text(nodes, "Nothing planned yet") \
+ and exact_text(nodes, "Plan now")
+ record("text_empty_state", ok,
+ "" if ok else
+ "feature_missing: virgin-Home empty state 'Nothing planned yet' / 'Plan now' not shown",
+ depth=0, jump_kind="none",
+ expect="empty-state 'Nothing planned yet' + button 'Plan now'")
+
+
+# 3) Transition PRODUCED by tapping "Plan now": the free-time slot row labelled
+# "Unassigned" is ABSENT on the virgin day and appears only after the tap. This
+# is text an interaction produces, and it fails on a shell that renders no rows.
+@and_test(expects=("text_unassigned_after_plan",))
+def test_unassigned_after_plan():
+ if not start_home_clean():
+ record("text_unassigned_after_plan", False,
+ "setup_failed: could not reach virgin Home",
+ depth=1, jump_kind="transition",
+ expect="'Unassigned' absent before Plan now, present after")
+ return
+ absent_before = not has_ci(ui(), "Unassigned")
+ plan = find_node_ci(ui(), "Plan now")
+ if plan is None:
+ record("text_unassigned_after_plan", False,
+ "feature_missing: no 'Plan now' control on the empty Home",
+ depth=1, jump_kind="transition",
+ expect="'Unassigned' absent before Plan now, present after")
+ return
+ tap_node(plan)
+ and_enter("day_schedule") # tapping Plan now materialises the day's schedule
+ settle("tap")
+ present_after = exact_text(ui(), "Unassigned")
+ ok = absent_before and present_after
+ record("text_unassigned_after_plan", ok,
+ "" if ok else
+ ("behavior_wrong: free-slot 'Unassigned' row did not appear after Plan now"
+ if absent_before else
+ "behavior_wrong: 'Unassigned' already present before Plan now (bad baseline)"),
+ depth=1, jump_kind="transition",
+ expect="'Unassigned' absent before Plan now, present after")
+
+
+# 4) Analytics screen strings reached from the Analytics tab: the screen title
+# "Analytics" AND the section header "Category stats" (a body element that only
+# the reached screen shows). Plus the ONE VLM for this lane.
+@and_test(expects=("text_analytics_headers", "text_pie_center_total_vlm"))
+def test_analytics_headers():
+ ok_home = start_home()
+ reached = ok_home and and_reach_analytics()
+ if not reached:
+ record("text_analytics_headers", False,
+ "feature_missing: Analytics screen not reachable from the Analytics tab",
+ depth=1, jump_kind="reach",
+ expect="'Analytics' title + 'Category stats' / 'Planning stats' headers")
+ vlm_assert("text_pie_center_total",
+ "In the centre of the circular donut/ring chart under the "
+ "'Category stats' section, is a time total drawn as "
+ "'h m' (for example '0h 0m') positioned INSIDE "
+ "the ring's hole (surrounded by the coloured ring), rather than "
+ "off to the side in the legend?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none",
+ tag="position")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Analytics") \
+ and (has_ci(nodes, "Category stats") or has_ci(nodes, "Planning stats"))
+ record("text_analytics_headers", ok,
+ "" if ok else
+ "behavior_wrong: Analytics title / stats section headers not shown after reaching Analytics",
+ depth=1, jump_kind="reach",
+ expect="'Analytics' title + 'Category stats' / 'Planning stats' headers")
+
+ # THE lane's one VLM: the summed-time total is RENDERED centred inside the
+ # donut ring. Its exact position (inside the ring's hole, not in the flat
+ # legend list) is a rendered layout property the view-tree geometry does not
+ # make trivially checkable — a fine-grained POSITION question.
+ vlm_assert("text_pie_center_total",
+ "In the centre of the circular donut/ring chart under the "
+ "'Category stats' section, is a time total drawn as "
+ "'h m' (for example '0h 0m') positioned INSIDE the "
+ "ring's hole (surrounded by the coloured ring), rather than off to "
+ "the side in the legend?",
+ RESULTS_DIR, expect="YES", depth=1, jump_kind="none", tag="position")
+
+
+# 5) Analytics category-legend names reached via the tab: "Misc" and "Else" are
+# app-unique legend labels that only the reached Analytics Time tab renders.
+@and_test(expects=("text_analytics_legend",))
+def test_analytics_legend():
+ ok_home = start_home()
+ reached = ok_home and and_reach_analytics()
+ if not reached:
+ record("text_analytics_legend", False,
+ "setup_failed: could not reach the Analytics Time tab",
+ depth=1, jump_kind="reach",
+ expect="legend category names 'Misc' and 'Else'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Misc") and exact_text(nodes, "Else")
+ record("text_analytics_legend", ok,
+ "" if ok else
+ "behavior_wrong: Analytics category legend ('Misc'/'Else') not shown",
+ depth=1, jump_kind="reach",
+ expect="legend category names 'Misc' and 'Else'")
+
+
+# 6) Settings section headers reached from the Settings tab: "Appearance" (a body
+# header the reached screen shows and Home never does).
+@and_test(expects=("text_settings_appearance",))
+def test_settings_appearance():
+ ok_home = start_home()
+ reached = ok_home and and_reach_settings()
+ if not reached:
+ record("text_settings_appearance", False,
+ "feature_missing: Settings screen not reachable from the Settings tab",
+ depth=1, jump_kind="reach",
+ expect="Settings section header 'Appearance'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Appearance") and exact_text(nodes, "Theme")
+ record("text_settings_appearance", ok,
+ "" if ok else
+ "behavior_wrong: Settings 'Appearance' / 'Theme' headers not shown after reaching Settings",
+ depth=1, jump_kind="reach",
+ expect="Settings 'Appearance' section + 'Theme' row")
+
+
+# 7) Settings 'Developer' value — a concrete exact-string content assertion. The
+# "About the app" rows live below the fold, so scroll them into view. The VALUE
+# "Stanislav Aleshin" is an app-authored string (NOT a version/build constant).
+@and_test(expects=("text_settings_developer",))
+def test_settings_developer():
+ ok_home = start_home()
+ reached = ok_home and and_reach_settings()
+ if not reached:
+ record("text_settings_developer", False,
+ "setup_failed: could not reach Settings",
+ depth=1, jump_kind="reach",
+ expect="Developer value 'Stanislav Aleshin'")
+ return
+ row = scroll_into_view("Developer", max_swipes=5)
+ nodes = ui()
+ ok = row is not None and exact_text(nodes, "Developer") \
+ and exact_text(nodes, "Stanislav Aleshin")
+ record("text_settings_developer", ok,
+ "" if ok else
+ "behavior_wrong: 'Developer' row value 'Stanislav Aleshin' not shown in Settings > About",
+ depth=1, jump_kind="reach",
+ expect="Developer row value == 'Stanislav Aleshin'")
+
+
+# 8) Editor title + a field label PRODUCED by opening the Editor: "Editor" title,
+# "Statistics" field with its subtitle "Include in analytics".
+@and_test(expects=("text_editor_statistics",))
+def test_editor_statistics():
+ ok_home = start_home()
+ reached = ok_home and and_reach_editor()
+ if not reached:
+ record("text_editor_statistics", False,
+ "feature_missing: could not open the Editor from Home",
+ depth=1, jump_kind="reach",
+ expect="Editor 'Statistics' + subtitle 'Include in analytics'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Editor") and exact_text(nodes, "Statistics") \
+ and exact_text(nodes, "Include in analytics")
+ record("text_editor_statistics", ok,
+ "" if ok else
+ "behavior_wrong: Editor 'Statistics' / 'Include in analytics' text not shown",
+ depth=1, jump_kind="reach",
+ expect="Editor title 'Editor' + 'Statistics' / 'Include in analytics'")
+
+
+# 9) A second Editor field label pair: "Notifications" + subtitle "Set a reminder
+# for the task start" — proves the Editor renders its authored labels, not a
+# generic form.
+@and_test(expects=("text_editor_notifications",))
+def test_editor_notifications():
+ ok_home = start_home()
+ reached = ok_home and and_reach_editor()
+ if not reached:
+ record("text_editor_notifications", False,
+ "feature_missing: could not open the Editor from Home",
+ depth=1, jump_kind="reach",
+ expect="Editor 'Notifications' + 'Set a reminder for the task start'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Notifications") \
+ and exact_text(nodes, "Set a reminder for the task start")
+ record("text_editor_notifications", ok,
+ "" if ok else
+ "behavior_wrong: Editor 'Notifications' / reminder subtitle not shown",
+ depth=1, jump_kind="reach",
+ expect="Editor 'Notifications' + 'Set a reminder for the task start'")
+
+
+# 10) Category bottom-sheet (Editor -> Category card): sheet header "Category",
+# search placeholder "Select a category", and radio row "Study". Depth 2.
+@and_test(expects=("text_category_sheet",))
+def test_category_sheet():
+ ok_home = start_home()
+ in_editor = ok_home and and_reach_editor()
+ in_sheet = in_editor and and_reach_category_sheet()
+ if not in_sheet:
+ record("text_category_sheet", False,
+ "feature_missing: Category bottom sheet did not open from the Editor",
+ depth=2, jump_kind="reach",
+ expect="sheet 'Select a category' placeholder + 'Study' row")
+ return
+ nodes = ui()
+ ok = has_ci(nodes, "Select a category") \
+ and exact_text(nodes, "Study") and exact_text(nodes, "Shopping")
+ record("text_category_sheet", ok,
+ "" if ok else
+ "behavior_wrong: Category sheet placeholder / radio labels ('Study'/'Shopping') not shown",
+ depth=2, jump_kind="reach",
+ expect="'Select a category' + radio rows 'Study' / 'Shopping'")
+
+
+# 11) Drawer header + item PRODUCED by tapping the hamburger: header "Time Planner"
+# and item "Templates" (both absent on Home, present only in the open drawer).
+@and_test(expects=("text_drawer_header",))
+def test_drawer_header():
+ ok_home = start_home()
+ if not ok_home:
+ record("text_drawer_header", False,
+ "setup_failed: could not reach Home",
+ depth=1, jump_kind="reach",
+ expect="drawer header 'Time Planner' + item 'Templates'")
+ return
+ before_absent = not has_ci(ui(), "Time Planner")
+ opened = and_reach_drawer()
+ nodes = ui()
+ ok = before_absent and opened and exact_text(nodes, "Time Planner") \
+ and exact_text(nodes, "Templates") and exact_text(nodes, "Categories")
+ record("text_drawer_header", ok,
+ "" if ok else
+ "feature_missing: drawer header 'Time Planner' + items 'Templates'/'Categories' not shown",
+ depth=1, jump_kind="reach",
+ expect="drawer header 'Time Planner' + items 'Templates' / 'Categories'")
+
+
+# 12) Templates empty-state reached through the drawer (depth 2): the exact
+# "List is empty" string plus the "Sort" label. Only the reached Templates
+# screen renders these.
+@and_test(expects=("text_templates_empty",))
+def test_templates_empty():
+ ok_home = start_home()
+ opened = ok_home and and_reach_drawer()
+ reached = opened and and_reach_templates()
+ if not reached:
+ record("text_templates_empty", False,
+ "feature_missing: Templates screen not reachable from the drawer",
+ depth=2, jump_kind="reach",
+ expect="Templates 'List is empty' + 'Sort'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "List is empty") and exact_text(nodes, "Sort")
+ record("text_templates_empty", ok,
+ "" if ok else
+ "behavior_wrong: Templates 'List is empty' / 'Sort' text not shown",
+ depth=2, jump_kind="reach",
+ expect="Templates empty-state 'List is empty' + 'Sort'")
+
+
+# 13) Overview screen reached from the Home top-bar grid icon: section headers
+# "Schedules" and "Undistributed tasks", and a status chip "Planned".
+@and_test(expects=("text_overview_headers",))
+def test_overview_headers():
+ ok_home = start_home()
+ reached = ok_home and and_reach_overview()
+ if not reached:
+ record("text_overview_headers", False,
+ "feature_missing: Overview not reachable from the Home top bar",
+ depth=1, jump_kind="reach",
+ expect="Overview 'Schedules' + 'Undistributed tasks' + chip 'Planned'")
+ return
+ nodes = ui()
+ ok = exact_text(nodes, "Schedules") \
+ and exact_text(nodes, "Undistributed tasks") \
+ and (exact_text(nodes, "Planned") or exact_text(nodes, "Current"))
+ record("text_overview_headers", ok,
+ "" if ok else
+ "behavior_wrong: Overview headers ('Schedules'/'Undistributed tasks') / status chip not shown",
+ depth=1, jump_kind="reach",
+ expect="Overview 'Schedules' + 'Undistributed tasks' + status chip")
+
+
+TESTS = [
+ test_home_title,
+ test_empty_state,
+ test_unassigned_after_plan,
+ test_analytics_headers,
+ test_analytics_legend,
+ test_settings_appearance,
+ test_settings_developer,
+ test_editor_statistics,
+ test_editor_notifications,
+ test_category_sheet,
+ test_drawer_header,
+ test_templates_empty,
+ test_overview_headers,
+]
+
+
+if __name__ == "__main__":
+ run_suite(TESTS, "text")
diff --git a/android/v1tzor-timeplanner/tests/test_manifest.json b/android/v1tzor-timeplanner/tests/test_manifest.json
new file mode 100644
index 0000000000000000000000000000000000000000..cd4b7ec538db36dfc6c2112220e8d5f8e70de069
--- /dev/null
+++ b/android/v1tzor-timeplanner/tests/test_manifest.json
@@ -0,0 +1,802 @@
+{
+ "manifest_version": 1,
+ "kit_api_version": 1,
+ "task_id": "TimePlanner",
+ "baseline_model": "claude-opus-4-8",
+ "baseline_package": "",
+ "total": 112,
+ "manifest_sha": "84f2dbbb2fd3",
+ "tests": [
+ {
+ "name": "computation::computation_analytics_others_zero",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_analytics_study_pct",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_default_duration",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_donut_center_total",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_donut_full_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_duration_differential",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_duration_layout_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_duration_shrinks_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_end_3am",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_end_6am",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_legend_dots_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_legend_layout_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "computation::computation_workload_bars_vlm",
+ "module": "computation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_cancel_no_persist",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_persists",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_task",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_task_icon_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_create_task_running_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_edit_category",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_edit_icon_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_note_roundtrip",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_running_controls_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_running_expand",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_running_progress_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_schedule_grows",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_schedule_grows_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_second_task",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_sheet_selected_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "interaction::interaction_two_tasks_vlm",
+ "module": "interaction",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_editor_home",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_picker_editor",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_backstack_sheet_editor",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_deepchain_backstack",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_drawer",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_open_drawer_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_analytics",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_analytics_tabs_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_analytics_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_categories",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_category_sheet",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_category_sheet_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_date_picker",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_editor",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_editor_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_home_tab",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_overview",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_overview_drawer",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_overview_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_templates",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_time_picker",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "navigation::nav_reach_time_picker_vlm",
+ "module": "navigation",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_calendar_behavior",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_calendar_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_calendar_pick_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_category_radio",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_category_study_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_swatch_check_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_color_swatch_moved_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_compact_view_density_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_compact_view_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_dynamic_colors_on_track_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_dynamic_colors_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_notifications_off_track_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_notifications_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_priority_medium_check_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_priority_medium_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_priority_medium_max",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_priority_standard_medium",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_secure_screen_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_statistics_off_track_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_statistics_toggle",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_statistics_toggle_back",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_applied_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_highlight_vlm",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_dark_light",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_persists",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "states::states_theme_system_dark",
+ "module": "states",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_analytics_donut_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_analytics_heatmap_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_analytics_tab_switch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_bottom_nav_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_bottom_nav_three_tabs",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_category_sheet_position_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_category_sheet_radios",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_editor_cards_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_editor_field_cards",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_editor_priority_segmented_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_empty_state_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_home_layout_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_home_topbar",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_gate_launch",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_home_empty_to_planned",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_overview_shape",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_color_swatches_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_sections",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "structure::structure_settings_theme_segmented_vlm",
+ "module": "structure",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_analytics_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_analytics_legend",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_category_sheet",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_drawer_header",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_editor_notifications",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_editor_statistics",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_empty_state",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_home_title",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_overview_headers",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_pie_center_total_vlm",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_appearance",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_settings_developer",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_templates_empty",
+ "module": "text",
+ "baseline_status": "passed"
+ },
+ {
+ "name": "text::text_unassigned_after_plan",
+ "module": "text",
+ "baseline_status": "passed"
+ }
+ ],
+ "ignored": [],
+ "vlm_assertions": [
+ {
+ "name": "computation::computation_duration_layout_vlm",
+ "module": "computation",
+ "tag": "position"
+ },
+ {
+ "name": "computation::computation_duration_shrinks_vlm",
+ "module": "computation",
+ "tag": "content"
+ },
+ {
+ "name": "computation::computation_donut_full_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_legend_layout_vlm",
+ "module": "computation",
+ "tag": "layout"
+ },
+ {
+ "name": "computation::computation_workload_bars_vlm",
+ "module": "computation",
+ "tag": "shape"
+ },
+ {
+ "name": "computation::computation_legend_dots_vlm",
+ "module": "computation",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_create_task_running_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "interaction::interaction_create_task_icon_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_edit_icon_vlm",
+ "module": "interaction",
+ "tag": "shape"
+ },
+ {
+ "name": "interaction::interaction_schedule_grows_vlm",
+ "module": "interaction",
+ "tag": "layout"
+ },
+ {
+ "name": "interaction::interaction_two_tasks_vlm",
+ "module": "interaction",
+ "tag": "position"
+ },
+ {
+ "name": "interaction::interaction_running_progress_vlm",
+ "module": "interaction",
+ "tag": "size"
+ },
+ {
+ "name": "interaction::interaction_running_controls_vlm",
+ "module": "interaction",
+ "tag": "layout"
+ },
+ {
+ "name": "interaction::interaction_sheet_selected_vlm",
+ "module": "interaction",
+ "tag": "color"
+ },
+ {
+ "name": "navigation::nav_reach_analytics_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_analytics_tabs_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_settings_vlm",
+ "module": "navigation",
+ "tag": "shape"
+ },
+ {
+ "name": "navigation::nav_reach_editor_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_overview_vlm",
+ "module": "navigation",
+ "tag": "layout"
+ },
+ {
+ "name": "navigation::nav_open_drawer_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_category_sheet_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "navigation::nav_reach_time_picker_vlm",
+ "module": "navigation",
+ "tag": "position"
+ },
+ {
+ "name": "states::states_statistics_off_track_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_notifications_off_track_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_priority_medium_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_priority_medium_check_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_theme_dark_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_theme_dark_applied_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_calendar_pick_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_dynamic_colors_on_track_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_compact_view_density_vlm",
+ "module": "states",
+ "tag": "layout"
+ },
+ {
+ "name": "states::states_category_study_highlight_vlm",
+ "module": "states",
+ "tag": "color"
+ },
+ {
+ "name": "states::states_color_swatch_check_vlm",
+ "module": "states",
+ "tag": "shape"
+ },
+ {
+ "name": "states::states_color_swatch_moved_vlm",
+ "module": "states",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_gate_home_layout_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_bottom_nav_layout_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_empty_state_layout_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_editor_cards_layout_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "structure::structure_editor_priority_segmented_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_category_sheet_position_vlm",
+ "module": "structure",
+ "tag": "position"
+ },
+ {
+ "name": "structure::structure_settings_color_swatches_vlm",
+ "module": "structure",
+ "tag": "color"
+ },
+ {
+ "name": "structure::structure_settings_theme_segmented_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_analytics_donut_vlm",
+ "module": "structure",
+ "tag": "shape"
+ },
+ {
+ "name": "structure::structure_analytics_heatmap_vlm",
+ "module": "structure",
+ "tag": "layout"
+ },
+ {
+ "name": "text::text_pie_center_total_vlm",
+ "module": "text",
+ "tag": "position"
+ }
+ ],
+ "vlm_total": 45,
+ "n_vlm_unverified": 0,
+ "vlm_log_found": true
+}
\ No newline at end of file
diff --git a/android/v1tzor-timeplanner/vlm_assertions.json b/android/v1tzor-timeplanner/vlm_assertions.json
new file mode 100644
index 0000000000000000000000000000000000000000..99f79958ac9248d576a131094d7b5fb76b36004f
--- /dev/null
+++ b/android/v1tzor-timeplanner/vlm_assertions.json
@@ -0,0 +1,923 @@
+{
+ "schema_version": 2,
+ "instance_id": "android/v1tzor-timeplanner",
+ "grading": {
+ "mode": "inline",
+ "model": null,
+ "scored_separately": true
+ },
+ "totals": {
+ "assertions": 45,
+ "with_verdict": 45,
+ "calibrated": 0,
+ "usable": null,
+ "scored_records": 45,
+ "unbacked_records": 0
+ },
+ "assertions": [
+ {
+ "id": "computation_duration_layout_vlm",
+ "screenshot": "computation_duration_layout_vlm.png",
+ "assertion": "In this task editor, is there a duration label of the form '