diff --git a/.gitignore b/.gitignore index 316f31e9..455751dc 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ /captures .externalNativeBuild **/*.swp +/.agents/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..ad0a07b4 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,60 @@ +# AI Agent Harness for Android Browser Helper + +This page defines the rules, skills, and prompts for AI agents working on this project. + +## Rule Inheritance + +This harness inherits from: +- [common.md](_agents/prompts/common.md) + +## Common Directives + +Instructions that are useful for Android Browser Helper development. + +### Paths + +* All files in the project's source can be read relative to the workspace root. + +### Building + +* Do not attempt a build without first establishing the correct target. +* Build the project using Gradle: + * To build the entire project: `./gradlew build` + * To build a specific module (e.g., `androidbrowserhelper`): `./gradlew :androidbrowserhelper:assembleDebug` + +### Testing + +* Run tests using Gradle: + * To run all unit tests: `./gradlew test` + * To run unit tests for a specific module: `./gradlew :androidbrowserhelper:test` + * To run instrumentation tests (if emulator is available): `./gradlew connectedAndroidTest` + +### Coding + +* Stay on task: Do not address code health issues or TODOs in code unless it is required to achieve your given task. +* Add code comments sparingly: Focus on *why* something is done, not *what* is done. +* **Documentation**: Keep documentation fresh. Update Javadoc for public API changes, and update relevant markdown files (e.g., `README.md`, `docs/`) when changing behavior or APIs. + +### Git Operations + +* **Always branched:** Ensure you are not on the `main` branch if you are making commits. If you are, first do `git checkout -b {BRANCH_NAME}`. +* **Commit messages:** + * Use active voice and avoid passive voice. + * Use present tense or imperative mood (e.g., "Change foo" instead of "Changed foo"). + * Wrap the commit message at 72 characters when possible. + +--- + +## Canonical Documentation + +- [README.md](README.md) +- [docs/](docs/) + +## Project Rules + +Refer to the specific rules in `_agents/rules/`: +- [CODE_STRUCTURE.md](_agents/rules/CODE_STRUCTURE.md) +- [DEPENDENCIES.md](_agents/rules/DEPENDENCIES.md) +- [STYLE.md](_agents/rules/STYLE.md) +- [TESTING.md](_agents/rules/TESTING.md) +- [REVIEWS.md](_agents/rules/REVIEWS.md) diff --git a/_agents/INDEX.md b/_agents/INDEX.md new file mode 100644 index 00000000..dee224ec --- /dev/null +++ b/_agents/INDEX.md @@ -0,0 +1,25 @@ +# AI Agent Harness Catalog + +This directory contains the configuration, rules, and skills for AI agents working in this repository. + +## Directory Structure + +* **[prompts/](prompts/)**: Common system prompts and workflow templates. + * [`common.md`](prompts/common.md): Standard edit/fix workflow guidelines. +* **[rules/](rules/)**: Domain-specific coding and testing rules. + * [`CODE_STRUCTURE.md`](rules/CODE_STRUCTURE.md): Gradle modules and key classes. + * [`DEPENDENCIES.md`](rules/DEPENDENCIES.md): Dependency policies (small APK size, Java-only). + * [`STYLE.md`](rules/STYLE.md): Google Java Style and copyright requirements. + * [`TESTING.md`](rules/TESTING.md): Robolectric, Instrumentation, and manual TWA testing steps. + * [`REVIEWS.md`](rules/REVIEWS.md): Code review checklist. +* **[skills/](skills/)**: Custom agent workflows. + * [`doc-writer/`](skills/doc-writer/): GAN-based design and execution plan authoring. +* **[templates/](templates/)**: Templates for documents generated by skills. + * [`designs.md`](templates/designs.md): Technical Design Document template. + * [`plans.md`](templates/plans.md): Execution Plan template. +* **[designs/](designs/)**: Output directory for generated Technical Design Documents. + * [`index.md`](designs/index.md): Index registry for designs. +* **[plans/](plans/)**: Output directory for generated Execution Plans. + * [`index.md`](plans/index.md): Index registry for plans. +* **[`skills.json`](skills.json)**: Project skills registry. +* **[`agents.json`](agents.json)**: Project subagents registry. diff --git a/_agents/RULES.md b/_agents/RULES.md new file mode 100644 index 00000000..50d1d3ab --- /dev/null +++ b/_agents/RULES.md @@ -0,0 +1,12 @@ +# Agent Rules Routing Table + +Use this table to quickly find the relevant rules for your task. + +| If you are... | Refer to... | Description | +| :--- | :--- | :--- | +| **Exploring the codebase** | [`rules/CODE_STRUCTURE.md`](rules/CODE_STRUCTURE.md) | Maps Gradle modules and key entry-point classes. | +| **Writing or editing Java code** | [`rules/STYLE.md`](rules/STYLE.md) | Coding style (Google Java Style) and copyright headers. | +| **Adding or modifying dependencies** | [`rules/DEPENDENCIES.md`](rules/DEPENDENCIES.md) | Constraints on external libraries and Kotlin usage. | +| **Writing, running, or debugging tests** | [`rules/TESTING.md`](rules/TESTING.md) | Robolectric unit tests, Instrumentation tests, and TWA manual debugging (DAL bypass, Logcat). | +| **Reviewing code or designs** | [`rules/REVIEWS.md`](rules/REVIEWS.md) | Checklist for security, compatibility, and performance. | +| **Executing a task** | [`prompts/common.md`](prompts/common.md) | Standard Edit/Fix workflow guidelines. | diff --git a/_agents/agents.json b/_agents/agents.json new file mode 100644 index 00000000..e1c4273d --- /dev/null +++ b/_agents/agents.json @@ -0,0 +1,13 @@ +{ + "entries": [ + { + "path": "_agents/agents/design_reviewer" + }, + { + "path": "_agents/agents/reviewer" + }, + { + "path": "_agents/agents/android-browser-helper_agent" + } + ] +} diff --git a/_agents/agents/android-browser-helper_agent/agent.json b/_agents/agents/android-browser-helper_agent/agent.json new file mode 100644 index 00000000..fd351601 --- /dev/null +++ b/_agents/agents/android-browser-helper_agent/agent.json @@ -0,0 +1,7 @@ +{ + "name": "android-browser-helper_agent", + "description": "Specialized Agent for the Android Browser Helper project, tailored for Custom Tabs and TWA integrations.", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/_agents/agents/android-browser-helper_agent/config.yaml b/_agents/agents/android-browser-helper_agent/config.yaml new file mode 100644 index 00000000..77af26a3 --- /dev/null +++ b/_agents/agents/android-browser-helper_agent/config.yaml @@ -0,0 +1,13 @@ +coding_agent: + agentic_mode: true + +prompt_section_customization: + add_prompt_sections: + - prompt_section: + title: "Android Browser Helper Project Directives" + content: | + You are the Android Browser Helper agent. Your goal is to assist with workspace development in this repository. + You MUST ALWAYS consult the setup, rules, and routing in `@/AGENTS.md` first. + You also have access to a project-specific skill `harness`. You should use it to load project context and handle project-specific operations. + When invoking skills like `doc-writer`, infer the required parameters dynamically by inspecting the workspace structure (e.g., placing designs in `_agents/designs/` and plans in `_agents/plans/`) rather than asking the user to specify them directly. + insert_before_section: artifacts diff --git a/_agents/agents/design_reviewer/agent.json b/_agents/agents/design_reviewer/agent.json new file mode 100644 index 00000000..b7e1d338 --- /dev/null +++ b/_agents/agents/design_reviewer/agent.json @@ -0,0 +1,7 @@ +{ + "name": "adversarial_reviewer", + "description": "Specialized staff-level architect subagent that performs Skeptical Adversarial Design and Code Reviews following agents/rules/REVIEWS.md guidelines.", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/_agents/agents/design_reviewer/config.yaml b/_agents/agents/design_reviewer/config.yaml new file mode 100644 index 00000000..6bc1ec13 --- /dev/null +++ b/_agents/agents/design_reviewer/config.yaml @@ -0,0 +1,29 @@ +coding_agent: + agentic_mode: true + +prompt_section_customization: + add_prompt_sections: + - prompt_section: + title: "Core Mandates" + content: | + # Core Mandates (Universal Subagent Context) + You are a specialized subagent operating within the Jetski ecosystem. You have been delegated a specific task by the Orchestrator. + 1. Security & System Integrity: Never log, print, or commit secrets, API keys, or credentials. + 2. Context Efficiency: Combined search and read turns are highly preferred. Use grep_search or find_by_name before reading entire files. + 3. No Chitchat: Focus purely on intent, findings, and technical rationale. Do not narrate tool usage. + 4. Read-Only Protocol: You are a strictly read-only agent. You are forbidden from using any tools to modify files or configurations in this codebase. + 5. Messaging Protocol: ALWAYS return your final review report via the send_message tool to the Orchestrator's ID (the conversation ID that invoked you). + insert_before_section: "artifacts" + + - prompt_section: + title: "Role: The Skeptical Architect" + content: | + # Role: The Skeptical Architect + You are the **Design Reviewer** subagent, a senior staff-level architect focused on identifying hidden assumptions, architectural risks, and mismatches. + Your primary mandate is to flawlessly execute the standard design review operating procedure. + + Before proceeding, you MUST execute the `design-review` skill by reading its instructions at: + `_agents/skills/design-review/SKILL.md` + + You must strictly abide by grading rubrics, checks, and output formatting defined in that skill. + insert_after_section: "Core Mandates" diff --git a/_agents/agents/reviewer/agent.json b/_agents/agents/reviewer/agent.json new file mode 100644 index 00000000..a97d7aba --- /dev/null +++ b/_agents/agents/reviewer/agent.json @@ -0,0 +1,7 @@ +{ + "name": "reviewer", + "description": "Senior SWE subagent for identifying code issues, enforcing Android/Java standards, and producing Dashboard-First code review reports.", + "configPath": { + "relativePathToConfig": "config.yaml" + } +} diff --git a/_agents/agents/reviewer/config.yaml b/_agents/agents/reviewer/config.yaml new file mode 100644 index 00000000..5279bd77 --- /dev/null +++ b/_agents/agents/reviewer/config.yaml @@ -0,0 +1,27 @@ +coding_agent: + agentic_mode: true + +prompt_section_customization: + add_prompt_sections: + - prompt_section: + title: "Core Mandates" + content: | + # Core Mandates (Universal Subagent Context) + You are a specialized code review subagent operating within the Jetski ecosystem. You have been delegated a code review task by the Orchestrator. + 1. Security & System Integrity: Never log, print, or commit secrets, API keys, or credentials. + 2. Read-Only Protocol: You are a strictly read-only agent. You are forbidden from using any tools to modify files or configurations in this codebase. + 3. Messaging Protocol: ALWAYS return your final review report via the send_message tool to the Orchestrator's ID. + insert_before_section: "artifacts" + + - prompt_section: + title: "Role: Senior Staff SWE Reviewer" + content: | + # Role: Senior Staff SWE Reviewer + You are a Senior Staff Software Engineer reviewing code changes for the `android-browser-helper` project. + Your primary mandate is to flawlessly execute the standard code review operating procedure. + + Before proceeding, you MUST execute the `code-review` skill by reading its instructions at: + `_agents/skills/code-review/SKILL.md` + + You must strictly abide by grading rubrics, verification checklists, and especially the **Dashboard-First Report Format** defined in that skill. + insert_after_section: "Core Mandates" diff --git a/_agents/designs/index.md b/_agents/designs/index.md new file mode 100644 index 00000000..c6c786d3 --- /dev/null +++ b/_agents/designs/index.md @@ -0,0 +1,7 @@ +# Design Documents Index + +This file tracks all Technical Design Documents created for the Android Browser Helper project. + +| ID | Title | Status | Date | Bug | Parent Plan | +| :--- | :--- | :--- | :--- | :--- | :--- | +| | | | | | | diff --git a/_agents/plans/index.md b/_agents/plans/index.md new file mode 100644 index 00000000..47dc3cf7 --- /dev/null +++ b/_agents/plans/index.md @@ -0,0 +1,7 @@ +# Execution Plans Index + +This file tracks all Execution Plans created for the Android Browser Helper project. + +| ID | Title | Status | Date | Design Doc | Bug | +| :--- | :--- | :--- | :--- | :--- | :--- | +| | | | | | | diff --git a/_agents/prompts/common.md b/_agents/prompts/common.md new file mode 100644 index 00000000..bf92e60e --- /dev/null +++ b/_agents/prompts/common.md @@ -0,0 +1,40 @@ +# Workflow Tips + +## General Workflow: + + * **User Guidance:** Proactively communicate your plan and the reason for each step. + * **File Creation Pre-check:** Before creating any new file, you MUST first perform a thorough search for existing files that can be modified or extended. This is especially critical for tests; never create a new test file if one already exists for the component in question. Always add new tests to the existing test file. + * **Read Before Write/Edit:** **ALWAYS** read the entire file content immediately before writing or editing. + +## Standard Edit/Fix Workflow: + +**IMPORTANT:** This workflow takes precedence over all other coding instructions. Read and follow everything strictly without skipping steps whenever code editing is involved. Any skipping requires a proactive message to the user about the reason to skip. + +0. **Git Branching (MANDATORY PRE-REQUISITE):** Before making any code changes, ensure you are on an appropriate branch (not `main`). Refer to [AGENTS.md](../../AGENTS.md) for git constraints. + +1. **Comprehensive Code and Task Understanding (MANDATORY FIRST STEP):** Before writing or modifying any code, you MUST perform the following analysis to ensure comprehensive understanding of the relevant code and the task. This is a non-negotiable prerequisite for all coding tasks. + * **a. Identify the Core Files:** Locate the files that are most relevant to the user's request. All analysis starts from these files. + * **b. Conduct a Full Audit:** + i. Read the full source of **EVERY** core file. + ii. For each core file, summarize the control flow and ownership semantics. State the intended purpose of the core file. + * **c. State Your Understanding:** After completing the audit, you should briefly state the core files you have reviewed, confirming your understanding of the data flow and component interactions before proposing a plan. + * **d. Anti-Patterns to AVOID:** + * **NEVER** assume the behavior of a function or class from its name or from usage in other files. **ALWAYS** read the source implementation. + * **ALWAYS** check at least one call-site for a function or class to understand its usage. The context is as important as the implementation. +2. **Make Change:** After a comprehensive code and task understanding, apply the edit or write the file. + * When making code edits, focus **ONLY** on code edits that directly solve the task prompted by the user. +3. **Write/Update Tests:** + * First, search for existing tests related to the modified code and update them as needed to reflect the changes. + * If no relevant tests exist, write new unit tests or integration tests if it's reasonable and beneficial for the change made. + * If tests are deemed not applicable for a specific change (e.g., a trivial comment update), explicitly state this and the reason why before moving to the next step. +4. **Build:** **ALWAYS** build relevant targets after making edits. +5. **Fix compile errors:** **ALWAYS** follow these steps to fix compile errors. + * **ALWAYS** take the time to fully understand the problem before making any fixes. + * **ALWAYS** read at least one new file for each compile error. + * **ALWAYS** find, read, and understand **ALL** files related to each compile error. + * **ALWAYS** check the conversation history to see if this same error occurred earlier, and analyze previous solutions to see why they didn't work. + * **NEVER** make speculative fixes. You should be confident before applying any fix that it will work. If you are not confident, read more files. +6. **Test:** **ALWAYS** run relevant tests after a successful build. If you cannot find any relevant test files, you may prompt the user to ask how this change should be tested. +7. **Fix test errors**: + * **ALWAYS** take the time to fully understand the problem before making any fixes. +8. **Iterate:** Repeat building and testing using the above steps until all are successful. diff --git a/_agents/prompts/common.minimal.md b/_agents/prompts/common.minimal.md new file mode 100644 index 00000000..7d33d856 --- /dev/null +++ b/_agents/prompts/common.minimal.md @@ -0,0 +1,44 @@ +# Gemini-CLI Specific Directives + +Instructions that apply only to gemini-cli. + +* When using the `read_file` tool: + * Always set the 'limit' parameter to 20000 to prevent truncation. +* File Not Found Errors: + * If a file operation fails due to an incorrect path, do not retry with the same path. + * Inform the user and search for the correct path using parts of the path or filename. + +# Common Directives + +Instructions that are useful for Android Browser Helper development. + +## Paths + +* All files in the project's source can be read relative to the workspace root. + +## Building + +* Do not attempt a build without first establishing the correct target. +* Build the project using Gradle: + * To build the entire project: `./gradlew build` + * To build a specific module (e.g., `androidbrowserhelper`): `./gradlew :androidbrowserhelper:assembleDebug` + +## Testing + +* Run tests using Gradle: + * To run all unit tests: `./gradlew test` + * To run unit tests for a specific module: `./gradlew :androidbrowserhelper:test` + * To run instrumentation tests (if emulator is available): `./gradlew connectedAndroidTest` + +## Coding + +* Stay on task: Do not address code health issues or TODOs in code unless it is required to achieve your given task. +* Add code comments sparingly: Focus on *why* something is done, not *what* is done. + +## Git Operations + +* **Always branched:** Ensure you are not on the `main` branch if you are making commits. If you are, first do `git checkout -b {BRANCH_NAME}`. +* **Commit messages:** + * Use active voice and avoid passive voice. + * Use present tense or imperative mood (e.g., "Change foo" instead of "Changed foo"). + * Wrap the commit message at 72 characters when possible. diff --git a/_agents/rules/CODE_STRUCTURE.md b/_agents/rules/CODE_STRUCTURE.md new file mode 100644 index 00000000..e8d0616f --- /dev/null +++ b/_agents/rules/CODE_STRUCTURE.md @@ -0,0 +1,21 @@ +# Code Structure + +This document outlines the directory structure and modules of the Android Browser Helper project. + +## Modules + +The project is divided into the following modules: + +* **[:androidbrowserhelper](../../androidbrowserhelper)**: The core library containing helper classes for Custom Tabs and Trusted Web Activities (TWA). + * `src/main/java`: Source code for the core library. + * `src/test/java`: Robolectric unit tests. + * `src/androidTest/java`: Android instrumentation tests. +* **[:locationdelegation](../../locationdelegation)**: An optional library to delegate location permission requests from the TWA to the Android app. +* **[:playbilling](../../playbilling)**: An optional library to enable Google Play Billing inside TWAs. +* **[:demos](../../demos)**: A collection of demo applications demonstrating various features of the library. + +## Key Classes in `:androidbrowserhelper` + +* **[`LauncherActivity`](../../androidbrowserhelper/src/main/java/com/google/androidbrowserhelper/trusted/LauncherActivity.java)**: Entry point activity for launching a TWA. +* **[`TwaLauncher`](../../androidbrowserhelper/src/main/java/com/google/androidbrowserhelper/trusted/TwaLauncher.java)**: Handles the complexity of connecting to the Custom Tabs service and launching the TWA. +* **[`TwaProviderPicker`](../../androidbrowserhelper/src/main/java/com/google/androidbrowserhelper/trusted/TwaProviderPicker.java)**: Chooses the best browser on the device to launch the TWA. diff --git a/_agents/rules/DEPENDENCIES.md b/_agents/rules/DEPENDENCIES.md new file mode 100644 index 00000000..8cc735d2 --- /dev/null +++ b/_agents/rules/DEPENDENCIES.md @@ -0,0 +1,18 @@ +# Dependency Management + +This document outlines the policy for managing dependencies in the Android Browser Helper project. + +## Core Goal: Keep the Library Lightweight + +Android Browser Helper is a library that other Android applications depend on. To minimize the impact on the size of the consuming applications (the "app size"), we must keep our dependency footprint as small as possible. + +## Encouraged Dependencies + +* **AndroidX libraries**: Prefer using official AndroidX libraries (e.g., `androidx.core`, `androidx.browser`) for compatibility and standard functionality. +* **Existing dependencies**: Reuse existing dependencies listed in `gradle/libs.versions.toml` (e.g., Guava, though we should use it sparingly if standard Java alternatives exist). + +## Banned / Discouraged Dependencies + +* **No New External Libraries**: Do not add new external libraries (libraries not currently in `libs.versions.toml`) without a strong justification and approval from maintainers. +* **Kotlin (in core library)**: The core `:androidbrowserhelper` module is currently pure Java. Avoid adding Kotlin dependencies to the core library to prevent transitive dependency issues for pure Java apps using this library. (Kotlin is acceptable in demos or optional modules if justified, but currently not used). +* **Heavy Frameworks**: Avoid adding large frameworks that significantly increase the binary size. diff --git a/_agents/rules/REVIEWS.md b/_agents/rules/REVIEWS.md new file mode 100644 index 00000000..f100f177 --- /dev/null +++ b/_agents/rules/REVIEWS.md @@ -0,0 +1,25 @@ +# Code Review Checklist + +This document provides a checklist for reviewing code changes in the Android Browser Helper project. + +## Security & Privacy + +* **URL Validation**: Ensure any URLs passed to Custom Tabs or TWAs are validated and secure (e.g., HTTPS). +* **Data Sharing**: Be mindful of what data is shared with the browser. Refer to the data disclosure section in `README.md`. +* **Intent Spoofing**: Validate incoming intents if the app exposes activities that can be launched by other apps. + +## Architecture & Interoperability + +* **Browser Compatibility**: Verify that changes do not assume Chrome is the only browser on the device. Use `TwaProviderPicker` to select the provider. Refer to [TWA Browser Support](../../docs/trusted-web-activity-browser-support.md) for known browser compatibility. +* **AndroidX Browser Library**: Ensure compatibility with the version of `androidx.browser` being used. +* **Backward Compatibility**: The library has a `minSdkVersion` of 23. Ensure new APIs used are guarded by SDK version checks if they are not available on older versions. + +## Performance + +* **Warmup and MayLaunchUrl**: Use `CustomTabsClient.warmup` and `CustomTabsSession.mayLaunchUrl` where appropriate to improve launch performance. +* **Resource Leakage**: Ensure Custom Tabs sessions and service connections are properly released when no longer needed. + +## Testing & Quality + +* **Test coverage**: Ensure new code is covered by unit or instrumentation tests. +* **Documentation**: Update `README.md` or other documentation if public APIs are changed or added. diff --git a/_agents/rules/STYLE.md b/_agents/rules/STYLE.md new file mode 100644 index 00000000..43e5694f --- /dev/null +++ b/_agents/rules/STYLE.md @@ -0,0 +1,40 @@ +# Coding Style Guide + +This document outlines the coding style conventions for the Android Browser Helper project. + +## Language + +* This project is primarily written in **Java**. +* New code should be written in Java, matching the existing codebase. + +## Style Guide + +* Follow the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html). +* Use 4 spaces for indentation (standard for Android development). + +## Copyright Headers + +Every new or modified Java source file must include the Apache 2.0 copyright header using line comments, matching the existing codebase style: + +```java +// Copyright 2026 Google Inc. All Rights Reserved. +// +// 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. +``` + + +## Best Practices + +* **Imports**: Clean up unused imports. Do not use wildcard imports (e.g., `import java.util.*`). +* **Nullability**: Use `@NonNull` and `@Nullable` annotations from `androidx.annotation` to assist with static analysis. +* **Deprecation**: If using deprecated APIs, explain why in a comment and plan for migration if possible. diff --git a/_agents/rules/TESTING.md b/_agents/rules/TESTING.md new file mode 100644 index 00000000..de8cbc41 --- /dev/null +++ b/_agents/rules/TESTING.md @@ -0,0 +1,119 @@ +# Testing Guide + +This document explains how to run and write tests for the Android Browser Helper project. + +## Types of Tests + +The project contains two types of tests: + +1. **Unit Tests (Robolectric)**: Located in `src/test/`. These run on the JVM using Robolectric to simulate the Android environment. They are fast and should be used for testing business logic that doesn't require a real device. +2. **Instrumentation Tests (AndroidX Test)**: Located in `src/androidTest/`. These run on a physical device or emulator. They are slower but test real integration with the Android OS. + +## Running Tests + +### Unit Tests + +To run all unit tests in the project: + +```sh +./gradlew test +``` + +To run unit tests for a specific module (e.g., `:androidbrowserhelper`): + +```sh +./gradlew :androidbrowserhelper:test +``` + +### Instrumentation Tests + +To run instrumentation tests, you must have an Android emulator running or a physical device connected via ADB. + +To run all instrumentation tests: + +```sh +./gradlew connectedAndroidTest +``` + +To run instrumentation tests for a specific module: + +```sh +./gradlew :androidbrowserhelper:connectedAndroidTest +``` + +## Testing Frameworks + +* **JUnit 4**: The standard testing framework. +* **Robolectric**: For running Android tests on the JVM. +* **Mockito**: For mocking dependencies. + +## Best Practices + +* **Test Coverage**: New features and bug fixes MUST be accompanied by corresponding tests. +* **Modify Existing Tests**: If you modify existing code, check if there are existing tests for it and update them to cover the new behavior. +* **Fakes and Mocks**: Use Mockito to mock system services or external dependencies when writing unit tests. + +## Manual Testing & Debugging (TWAs) + +When testing Trusted Web Activities (TWA) manually on a device or emulator, you often need to bypass Digital Asset Link (DAL) verification and inspect logs. + +### Bypassing Digital Asset Link (DAL) Verification + +Chrome requires DAL verification to enable features like notification delegation. To bypass this for a test domain (e.g., `example.com`): + +1. **Enable command line on non-rooted devices:** + * Open Chrome on the device/emulator. + * Navigate to `chrome://flags/#enable-command-line-on-non-rooted-devices`. + * Set it to **Enabled** and relaunch Chrome. +2. **Set the bypass flag for your test domain:** + ```sh + adb shell "echo '_ --disable-digital-asset-link-verification-for-url=\"https://example.com\"' > /data/local/tmp/chrome-command-line" + adb shell am force-stop com.android.chrome + ``` +3. **Grant runtime permissions (if testing notifications):** + ```sh + adb shell pm grant android.permission.POST_NOTIFICATIONS + ``` + +### Checking App Links Verification Status + +To verify if the OS has verified your app links: + +```sh +# Get verification state +adb shell pm get-app-links + +# Force re-verification +adb shell pm verify-app-links --re-verify +``` + +### Resetting App State for Testing + +To ensure a clean state before running a test: + +```sh +# Clear app data +adb shell pm clear + +# Uninstall the app +adb uninstall + +# Clear Chrome data (to reset verification cache) +adb shell pm clear com.android.chrome +``` + +### Useful Logcat Filters + +Use these filters to debug TWA connection and delegation issues: + +```sh +# Stream TWA delegation and activity logs +adb logcat -s NotificationDelegation:V TWALauncherActivity:V + +# Stream TWA + Chrome logs together +adb logcat -s NotificationDelegation:V TWALauncherActivity:V chromium:V + +# Dump logs for a specific TWA process +adb logcat -d --pid=$(adb shell pidof ) +``` + diff --git a/_agents/skills.json b/_agents/skills.json new file mode 100644 index 00000000..fb79cccd --- /dev/null +++ b/_agents/skills.json @@ -0,0 +1,20 @@ +{ + "entries": [ + { + "path": "_agents/skills/doc-writer", + "description": "GAN-based workflow for authoring Technical Design Documents and Execution Plans." + }, + { + "path": "_agents/skills/code-review", + "description": "Standard Operating Procedure (SOP) for conducting Code Reviews in the project." + }, + { + "path": "_agents/skills/design-review", + "description": "Standard Operating Procedure (SOP) for conducting Skeptical Design Reviews." + }, + { + "path": "_agents/skills/harness", + "description": "Skill for loading context from the harness and managing rules." + } + ] +} diff --git a/_agents/skills/code-review/SKILL.md b/_agents/skills/code-review/SKILL.md new file mode 100644 index 00000000..8349db98 --- /dev/null +++ b/_agents/skills/code-review/SKILL.md @@ -0,0 +1,48 @@ +--- +name: code-review +description: >- + Standard Operating Procedure (SOP) for conducting Code Reviews in the android-browser-helper project. Defines criteria, rules, and the required Dashboard-First report format. +--- + +# Code Review Standard Operating Procedure + +Use this skill to perform high-precision code reviews of changes in the project. Any agent executing this skill (whether the main agent or the specialized `reviewer` subagent) must strictly follow these instructions. + + + +## 1. Context & Criteria + +You are acting as a Senior Staff Software Engineer reviewing code changes. +Your mission is to ensure high engineering standards, verify adherence to Google Java Style, check for threading bugs (Main thread blocking, background task execution, concurrency issues), audit security boundaries (Intent filters, data sharing with browsers), and ensure efficient resource usage. + +**Documentation & Harness Freshness**: You MUST verify that any change altering public APIs, TWA launch behavior, location/billing integration, or module boundaries also updates canonical documentation in markdown files (`docs/`, `README.md`), JavaDocs, as well as AI Agent Harness rules and architecture files (`AGENTS.md`, `_agents/`). + +## 2. Rule Checklist + +Before grading, you MUST review the project's standard rules: +- `_agents/rules/CODE_STRUCTURE.md` +- `_agents/rules/STYLE.md` +- `_agents/rules/TESTING.md` +- `_agents/rules/REVIEWS.md` + +## 3. Output Formatting: Dashboard-First Review Report + +You MUST structure your final review report in three distinct sections: + +### 1. Code Review Verdict +Provide an explicit verdict emoji and title: +- `🔴 Changes Requested` (if there is at least one Critical issue) +- `🟡 Approved with Suggestions` (if there are only Important or Suggestion issues) +- `🟢 Approved` (if flawless) + +### 2. Finding Summary Table +Provide a Markdown table summarizing all findings, sorted strictly by severity (`🔴 Critical` -> `🟡 Important` -> `🔵 Suggestion`). +Columns required: `ID` (`F1`, `F2`...), `Severity`, `Category` (Security, Threading, Memory, Style, Testing, Documentation), `Location` (`File.java:L123`), `Summary`. + +### 3. Detailed Findings +For each finding ID (`F1`, `F2`...): +- **Location**: Exact file and line range. +- **Why it matters**: Explain the technical risk or bug. +- **How to fix**: Provide a concrete Markdown code block showing the corrected Java code. + + diff --git a/_agents/skills/design-review/SKILL.md b/_agents/skills/design-review/SKILL.md new file mode 100644 index 00000000..dce34bd8 --- /dev/null +++ b/_agents/skills/design-review/SKILL.md @@ -0,0 +1,27 @@ +--- +name: design-review +description: >- + Standard Operating Procedure (SOP) for conducting Skeptical Design Reviews in the android-browser-helper project. Defines criteria, adversarial evaluation priorities, and reporting structure. +--- + +# Design Review Standard Operating Procedure + +Use this skill to perform high-precision, skeptical evaluations of technical proposals or design documents. Any agent executing this skill (whether the main agent or the specialized `design_reviewer` subagent) must strictly follow these instructions. + + + +## 1. Context & Criteria + +You are acting as a Senior Staff-Level Architect focused on identifying hidden assumptions, architectural risks, and mismatches between proposed changes and the existing codebase. +Your goal is intentionally skeptical: you evaluate technical proposals, or design documents to ensure they are robust, realistic, and constrained by the current system state. +Your objective is NOT to find faults in existing code, but to ensure the *new* proposal or changes are robust. + +## 2. Process & Guidelines + +1. **Load Rules First**: Your very first step MUST be to read the standard Design Review guidelines and checklists from the local rulebook: + `_agents/rules/REVIEWS.md` +2. **Additional Context Check**: Identify any other rules referenced (such as `_agents/rules/CODE_STRUCTURE.md`) that apply to the design. +3. **Strict Compliance**: You MUST strictly follow the critique criteria, evaluation checklists, and required output formatting defined in `REVIEWS.md` for your review findings and final verdict. +4. **Draft the Critique**: Compile your findings into a structured markdown report, clearly delineating blocking issues from architectural suggestions. + + diff --git a/_agents/skills/doc-writer/SKILL.md b/_agents/skills/doc-writer/SKILL.md new file mode 100644 index 00000000..b01a63dd --- /dev/null +++ b/_agents/skills/doc-writer/SKILL.md @@ -0,0 +1,116 @@ +--- +name: doc-writer +description: >- + GAN-based workflow for authoring Technical Design Documents and Execution Plans. Use when asked to "write a design", "author an execution plan", or execute GAN iterations for documentation in this project. +--- + +# Document Writer + +## Hydration Parameters + +The following parameters are used to configure the document writer. They can usually be inferred dynamically from the workspace structure: + +- `projectName`: Name of the project (default: `android-browser-helper`) +- `documentName`: The name of the document being created (Design or Execution Plan) +- `agentRulesDoc`: Path to the project's `AGENTS.md` (default: `AGENTS.md`) +- `agentHarnessDirectory`: Path to the agent folder (default: `_agents/`) +- `designDirectory`: Directory where new designs are saved (default: `_agents/designs/`) +- `executionPlanDirectory`: Directory where new execution plans are saved (default: `_agents/plans/`) + +Default Parameters: + +- `designNamingConvention`: `0001-feature-design.md` +- `executionPlanNamingConvention`: `0001-feature-plan.md` +- `designTemplate`: `_agents/templates/designs.md` +- `executionPlanTemplate`: `_agents/templates/plans.md` + +## Overview + +This skill provides a Generator-Discriminator (GAN) workflow designed to help write Technical Design Documents (Designs) and Execution Plans (Plans) for the Android Browser Helper project. It orchestrates collaboration between specialized subagents to produce high-quality, reviewable artifacts. + +--- + +## The Roles + +You are the **Orchestrator**. Coordinate between two specialized subagents: + +1. **The Planner (Generator):** Generates initial drafts for the design or execution plan. +2. **The Evaluator (Discriminator):** Reviews the drafts against project standards and rules. + +--- + +## Orchestration Workflow + +### Phase 1: Initialization + +1. **Identify The Flow**: Determine if the user wants to write a **Design Document** or an **Execution Plan**. + - If **Design Document**: Use `designTemplate` (`_agents/templates/designs.md`). + - If **Execution Plan**: Use `executionPlanTemplate` (`_agents/templates/plans.md`). +2. **Dynamic Parameter Inference**: If the calling agent or user did not specify directories, use defaults. +3. **Initialize State Tracking**: Create a Markdown file `_agents/gan_iteration_status.md` to track progress throughout the GAN loop. +4. **Invoke Planner (Generator)**: Spawn a Planner subagent with `Model="heavy"` and `Workspace="inherit"` using the appropriate prompt template below. +5. **Invoke Evaluator (Discriminator)**: Spawn an Evaluator subagent (e.g., using `adversarial_reviewer` persona if defined, or a self-configured evaluator) to critique the draft. + +#### Planner Prompt Template (Design Document Flow) + +```text +You are the Planner for the {{projectName}} project. + +1. ALWAYS read the project guidelines at `{{agentRulesDoc}}` before starting. +2. Reference the Design Document template and instructions at `{{designTemplate}}` when creating the draft. +3. Ensure your design strictly abides by project architecture, style, and dependency rules. +4. Provide your complete markdown output in your response to the Orchestrator. + +Your task is: [INSERT TASK DESCRIPTION HERE] +``` + +#### Planner Prompt Template (Execution Plan Flow) + +```text +You are the Planner for the {{projectName}} project. + +1. ALWAYS read the project guidelines at `{{agentRulesDoc}}` before starting. +2. Reference the Execution Plan template and instructions at `{{executionPlanTemplate}}` when creating the draft. +3. ALWAYS ensure each milestone maps to a single PR/CL and includes concrete `./gradlew` build and test commands. +4. Provide your complete markdown output in your response to the Orchestrator. + +Your task is: [INSERT TASK DESCRIPTION HERE] +``` + +#### Evaluator Prompt Template + +```text +You are the Skeptical Architect and Evaluator for the {{projectName}} project. + +1. ALWAYS read the project guidelines at `{{agentRulesDoc}}` before starting. +2. Evaluate the planner's draft against the template instructions (`{{designTemplate}}` or `{{executionPlanTemplate}}`). +3. Critique for hidden assumptions, security boundaries, and test coverage. +4. If the work is flawless, explicitly state "LGTM". +``` + +--- + +### Phase 2: Reactive Message Loop + +1. **Planner Draft Received**: Update `gan_iteration_status.md` and forward the draft to the Evaluator via `send_message`. +2. **Evaluator Critique Received**: + - If the Evaluator replies "LGTM" or you reach the iteration limit of **3 rounds**, proceed to Phase 3. + - Otherwise, forward the critique back to the Planner instructing them to apply adjustments. + +--- + +### Phase 3: Human Approval + +1. Present the draft to the user for approval using visible text. Ask them to reply with `Accept` or `Comment and Iterate`. +2. If **Accept**: Proceed to Phase 4. +3. If **Comment and Iterate**: Forward feedback to the Planner, reset iteration count, and loop back. + +--- + +### Phase 4: Finalization + +1. Write the approved document to the designated directory: + - Designs → `{{designDirectory}}0001-feature-design.md` + - Plans → `{{executionPlanDirectory}}0001-feature-plan.md` +2. Register the new document in the corresponding index file (`index.md`). +3. Notify the user that the document has been successfully saved. diff --git a/_agents/skills/harness/SKILL.md b/_agents/skills/harness/SKILL.md new file mode 100644 index 00000000..39da1917 --- /dev/null +++ b/_agents/skills/harness/SKILL.md @@ -0,0 +1,27 @@ +--- +name: harness +description: Skill for loading context from the harness and managing rules. +--- + +# Skill: Harness Management + +This skill allows loading context from the harness for any purpose. It knows how to update rules and propagate references throughout the harness when changes are needed. + +## Prompts + +### Modifying the Harness + +When you are asked to modify the harness, update rules, or add new skills, you must: + +1. ALWAYS reference the top-level [`AGENTS.md`](../../../AGENTS.md) file for guidance. +2. Ensure all files in the `_agents/` folder are referenced in the [`AGENTS.md`](../../../AGENTS.md) file or in [`_agents/INDEX.md`](../../INDEX.md) to maintain a complete catalog. +3. When adding new rules, update [`_agents/RULES.md`](../../RULES.md) and the specific rule file, and ensure they are linked from [`AGENTS.md`](../../../AGENTS.md). +4. If the user requests design, plan, or implementation, mention `doc-writer` if relevant. + +### Onboarding + +If the user asks to onboard themselves to the project, ensure their local config (in `.agents/`) points to the `_agents/` skills and agents registries. + +## Context Loading + +Load context from `_agents/` folder to understand rules, structure, and dependencies. diff --git a/_agents/templates/designs.md b/_agents/templates/designs.md new file mode 100644 index 00000000..9e24af8c --- /dev/null +++ b/_agents/templates/designs.md @@ -0,0 +1,129 @@ +# Technical Design Documents (Designs) + +**Agent Preamble:** + +> **CRITICAL:** Before reading this document or authoring a design, you MUST read the project's `AGENTS.md` file to understand the architecture, style, and boundaries. Also review the style guide at `_agents/rules/STYLE.md` and general coding workflow at `_agents/prompts/common.md`. + +This document describes the requirements for authoring a Technical Design Document for the Android Browser Helper project. + +## Purpose of a Design + +A Design document is strictly about **architecture**. Its purpose is to explore, define, and document the structure, data models, API surfaces, dependencies, and technical trade-offs of a proposed system *before* any implementation planning or coding begins. + +A Design document answers the questions: + +- "What problem are we solving?" +- "What is the shape of the data, Java classes, and Intent interfaces?" +- "What were the alternative approaches, and why were they rejected?" + +**A Design Document is NOT an Execution Plan.** It does not contain implementation steps, file editing instructions, or milestones. It focuses entirely on establishing agreement on the technical architecture. + +## Authoring a Design + +When asked to author or propose a technical design, conduct thorough research of the existing repository context and generate a comprehensive markdown document. Ensure your design is objective and addresses the constraints of the system. + +**Tailoring for Scale:** For smaller changes or refactors, many sections (e.g., Privacy, UI) may not apply. In such cases, do not delete the sections; instead, keep the headings and explicitly mark them as **N/A** (Not Applicable) with a brief, one-sentence explanation. + +### File Naming and Location + +All new design documents must be placed in the `_agents/designs/` subdirectory. They must be explicitly numbered, use lowercase letters, and use hyphens for separation. They must follow the naming convention: `0001-feature-design.md`. + +**Registration Requirement:** Before creating a new design document, you **must** register it in the index file (`_agents/designs/index.md`) to prevent ID conflicts. + +### Required Structure + +Your Design document must follow this format: + +```markdown +--- +id: "0001" +title: "Design: [Feature Name]" +project: "android-browser-helper" +author: "user@google.com" +status: "draft" +date: "2026-08-12" +bug: "b/123456789" # or GitHub Issue link +--- + + + +## 1. Context and Goals + +**Problem formulation:** What is the specific problem you are trying to solve? Describe the current state and its deficiencies. + +**Background:** Discuss motivation, link to screenshots, related features, etc. + +**Goals:** What are the objective requirements for a successful design? +* Goal 1 + +**Non-Goals:** Explicitly state what this design will *not* attempt to solve. +* Non-goal 1 + +## 2. Proposed Architecture + +High-level architecture overview. How does this align with the project boundaries (e.g., Core Library vs. Location/Billing extensions)? + +### Subsystems Affected +* [ ] Core Library (`androidbrowserhelper`) +* [ ] Location Delegation (`locationdelegation`) +* [ ] Play Billing (`playbilling`) +* [ ] Demos + +### Thread Model +* Does it perform work on the Main (UI) thread? If so, how do we avoid blocking it (e.g., using AsyncTask, Executors, or Coroutines if applicable)? +* Does it interact with background services? + +### Data Models & Schemas +Detail the shape of data. SharedPreferences structure, Bundle extras, or core domain classes. + +### API Surface & Public Interfaces +Define public Java classes, methods, Intent Actions, and Extra keys. + +## 3. Alternatives Considered +Explore at least one viable alternative. Describe approach and state trade-offs. + +## 4. Core Principle Considerations + +### Speed & Efficiency +* **Main Thread Impact:** Does this add work to the Android Main thread? +* **Startup & Critical Paths:** Is it on the critical path of TWA launch? +* **APK Size Impact:** Expected impact on the library size. + +### Security +* **Intent Security:** Are intents properly secured? Are we exposing components to unauthorized apps? +* **Data Sharing:** Are we safely sharing data with the browser provider? + +### Stability & Simplicity +* How do we handle cases where the preferred browser is not installed or doesn't support the required features? + +## 5. Privacy & Accessibility + +### Privacy +* Does it collect/transmit user data? +* What data is shared with the browser (URLs, location, billing info)? +* Does it respect the user's choices/permissions? + +### Accessibility (A11y) +* If introducing UI components (e.g., splash screens, permission dialogs), do they support TalkBack and standard accessibility features? + +## 6. Testing Plan +* Unit tests (Robolectric). +* Instrumentation tests (AndroidX Test). +* Manual testing steps (if physical device interaction is required). + +## 7. Detailed Implementation +Detailed architectural breakdown. Enumerate primary classes modified or created. + +## 8. Future Work & Technical Debt +* Deferred work or known limitations. +``` + +## Review and Approval + +Once the Design is authored, it must be reviewed and approved by the user. Only after architectural consensus is reached via the Design document should an Execution Plan (see `_agents/templates/plans.md`) be authored. diff --git a/_agents/templates/plans.md b/_agents/templates/plans.md new file mode 100644 index 00000000..28bfc57f --- /dev/null +++ b/_agents/templates/plans.md @@ -0,0 +1,85 @@ +# Execution Plans (ExecPlans) + +**Agent Preamble:** + +> **CRITICAL:** Before executing any milestone, you MUST read the project's `AGENTS.md` to understand operating procedures. Run tests and verify code quality before completing each milestone. Proceed to next milestone only after user confirmation. + +This document describes the requirements for authoring an Execution Plan (ExecPlan) for the Android Browser Helper project. + +## Purpose of an Execution Plan + +An Execution Plan is a **living, persistent markdown artifact** that tracks multi-day, multi-PR/CL projects. While a Design Document defines *what* to build and *why*, an Execution Plan defines *how* to execute the implementation step-by-step across reviewable Pull Requests (PRs) or Changelists (CLs). + +**Key Principles:** + +1. **Milestone = PR/CL Boundary:** Each milestone MUST correspond to exactly ONE PR/CL. Keep changes small and focused. +2. **Observable Verification:** Every milestone MUST list explicit build and test commands (using `./gradlew`) with expected outcomes. +3. **Idempotence:** Steps should be safe to re-run without breaking workspace state. +4. **Living State Tracking:** Keep the check-boxes up to date as milestones complete. Document surprises, bugs, and architectural decisions discovered along the way. + +## Authoring an Execution Plan + +### File Naming and Location + +All execution plans must be placed in the `_agents/plans/` subdirectory. They must be explicitly numbered and follow the naming convention: `0001-feature-plan.md`. + +**Registration Requirement:** Before creating a new plan, you **must** register it in the index file (`_agents/plans/index.md`) and link it back to its parent Design Document. + +### Required Structure + +```markdown +--- +id: "0001" +title: "Plan: [Feature Name]" +project: "android-browser-helper" +author: "user@google.com" +status: "in-progress" +date: "2026-08-12" +design_doc: "../designs/0001-feature-design.md" +bug: "b/123456789" # or GitHub Issue link +--- + + + +## 1. Purpose / Big Picture + +Explain in a few sentences what the user gains after this change and how they can see it working. State the user-visible behavior enabled. + +## 2. Context and Orientation + +Describe current state relevant to this task. Reference key files by relative path. Define any non-obvious terms. + +## 3. Progress + +- [ ] **Milestone 1: [Name]** +- [ ] **Milestone 2: [Name]** + +## 4. Surprises & Discoveries + +Document unexpected behaviors, optimizations, or bugs discovered during implementation. + +## 5. Decision Log + +Record decisions made while working on the plan, including rationale and date. + +## 6. Plan of Work (Milestones) + +### Milestone 1: [Milestone Name] + +* **Concrete Steps:** + - Edit files: `androidbrowserhelper/src/main/java/com/google/androidbrowserhelper/trusted/SomeFile.java` + - Build command: `./gradlew :androidbrowserhelper:assembleDebug` + - Test command: `./gradlew :androidbrowserhelper:test` (or `connectedAndroidTest` if needed) +* **Interfaces and Dependencies:** + - [List classes or methods created or modified] + - [Check dependency constraints] +* **Validation and Acceptance:** + - [State what to observe to confirm the milestone is successful] + - [Verify code formatting] + - [Verify documentation and harness freshness: ensure canonical documentation in markdown files (docs/, README.md), JavaDoc, as well as AI Agent Harness files is updated] +* **Idempotence and Recovery:** + - [State if steps can be safely re-run] +```