+
+# OpenCode Plugins by capyBearista
+
+A collection of plugins for the OpenCode AI coding agent. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
+
+## The Plugins
+
+### @capybearista/opencode-output-styles
+Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
+
+### @capybearista/opencode-agents-loader
+Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
+
+### @capybearista/opencode-double-tap-timeline
+A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse. ⌨️
+
+## Installation
+
+You can install any of these plugins globally or locally using the OpenCode CLI:
+
+```bash
+opencode plugin add -g @capybearista/opencode-output-styles
+```
+
+Alternatively, add them directly to your `opencode.json` configuration file:
+
+```json
+{
+ "plugin": [
+ "@capybearista/opencode-output-styles",
+ "@capybearista/opencode-agents-loader"
+ ]
+}
+```
+
+## Development
+
+This project is a monorepo managed with Bun and Turborepo.
+
+```bash
+# Install dependencies
+bun install
+
+# Build all plugins
+bun run build
+
+# Run tests
+bun run test
+```
+
+## Creating a New Plugin
+
+We use a standard template for new plugins.
+
+1. Run the scaffolding skill:
+ `init-plugin`
+2. Follow the prompts to generate the package.
+3. Build and test locally.
+
+## License
+
+MPL-2.0
diff --git a/packages/opencode-agents-loader/README.md b/packages/opencode-agents-loader/README.md
index e9f08c7..bc3f228 100644
--- a/packages/opencode-agents-loader/README.md
+++ b/packages/opencode-agents-loader/README.md
@@ -101,7 +101,11 @@ Place agent markdown files in `agent/` or `agents/` subdirectories:
project-expert.md
```
-## Precedence
+## Configuration
+
+This plugin requires no manual configuration. It works automatically by reading from `.agents/` directories.
+
+### Precedence
Existing config entries from `.opencode/` directories always take precedence over `.agents/` entries. The plugin only injects entries that **do not already exist**.
diff --git a/packages/opencode-double-tap-timeline/README.md b/packages/opencode-double-tap-timeline/README.md
index a317a5d..de585cc 100644
--- a/packages/opencode-double-tap-timeline/README.md
+++ b/packages/opencode-double-tap-timeline/README.md
@@ -49,14 +49,6 @@ Add the plugin to `tui.json` or `tui.jsonc`:
}
```
-Add the plugin to `opencode.json` or `opencode.jsonc`:
-
-```json
-{
- "plugin": ["@capybearista/opencode-double-tap-timeline"]
-}
-```
-
You can also install it through the CLI:
```bash
@@ -70,9 +62,11 @@ opencode plugin # project-local install
2. Double-tap `Escape` quickly (within 800ms)
3. The timeline modal opens
-## Notes
+**Note:** Hitting `Escape` two times in quick succession to interrupt a running prompt will also invoke the timeline modal. Hit `Escape` again to quickly exit.
+
+## Configuration
-Hitting `Escape` two times in quick succession to interrupt a running prompt will also invoke the timeline modal. Hit `Escape` again to quickly exit.
+This plugin requires no manual configuration.
## Troubleshooting
From 33e1f85c3d201e8f76b3fc8f3ad6329d5899232f Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 16:36:38 -0400
Subject: [PATCH 003/115] ci: skip workflows on docs-only changes
CI workflow now uses paths-ignore to skip on *.md, docs/,
.github/assets/, .changeset/, CONTRIBUTING.md, and LICENSE*
changes. Release workflow uses a paths allowlist so it only
runs when package source, changesets, lockfile, or workflow
files actually change.
---
.github/workflows/ci.yml | 14 ++++++++++++++
.github/workflows/release.yml | 8 ++++++++
2 files changed, 22 insertions(+)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 29a613a..103bee7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -3,8 +3,22 @@ name: CI
on:
push:
branches: [main]
+ paths-ignore:
+ - '**.md'
+ - 'docs/**'
+ - '.github/assets/**'
+ - '.changeset/**'
+ - 'CONTRIBUTING.md'
+ - 'LICENSE*'
pull_request:
branches: [main]
+ paths-ignore:
+ - '**.md'
+ - 'docs/**'
+ - '.github/assets/**'
+ - '.changeset/**'
+ - 'CONTRIBUTING.md'
+ - 'LICENSE*'
permissions:
contents: read
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 564e680..ef6bc3a 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -4,6 +4,14 @@ on:
push:
branches:
- main
+ paths:
+ - 'packages/**'
+ - '.changeset/**'
+ - 'bun.lock'
+ - 'package.json'
+ - 'turbo.json'
+ - 'tsconfig*.json'
+ - '.github/workflows/release.yml'
permissions:
contents: write
From e28f9ac5c7ce3cd6068ff7145e763d0f03c19328 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 16:43:29 -0400
Subject: [PATCH 004/115] chore: add light-mode version of logo
---
...-plugins.svg => opencode-plugins-dark.svg} | 0
.github/assets/opencode-plugins-light.svg | 38 +++++++++++++++++++
2 files changed, 38 insertions(+)
rename .github/assets/{opencode-plugins.svg => opencode-plugins-dark.svg} (100%)
create mode 100644 .github/assets/opencode-plugins-light.svg
diff --git a/.github/assets/opencode-plugins.svg b/.github/assets/opencode-plugins-dark.svg
similarity index 100%
rename from .github/assets/opencode-plugins.svg
rename to .github/assets/opencode-plugins-dark.svg
diff --git a/.github/assets/opencode-plugins-light.svg b/.github/assets/opencode-plugins-light.svg
new file mode 100644
index 0000000..6cf065f
--- /dev/null
+++ b/.github/assets/opencode-plugins-light.svg
@@ -0,0 +1,38 @@
+
From ac8778011bd7e1e1dfbdea99d424403264661dde Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sun, 3 May 2026 16:44:37 -0400
Subject: [PATCH 005/115] chore(README): replace static logo with responsive
picture element
Updated logo display in README with responsive images.
---
README.md | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/README.md b/README.md
index f9419e6..88be08f 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,11 @@
# OpenCode Plugins by capyBearista
From 881319c9874625efdc752d37ce924752abcaf7c6 Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sun, 3 May 2026 16:47:42 -0400
Subject: [PATCH 006/115] chore: add LICENSE to root
---
LICENSE.md | 373 +++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 373 insertions(+)
create mode 100644 LICENSE.md
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000..d0a1fa1
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
From 68b60a7a0b4887232419675f9dafacb4a4aeffa3 Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sun, 3 May 2026 17:19:45 -0400
Subject: [PATCH 007/115] chore: add funding.yml
---
.github/FUNDING.yml | 15 +++++++++++++++
1 file changed, 15 insertions(+)
create mode 100644 .github/FUNDING.yml
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
new file mode 100644
index 0000000..275eec7
--- /dev/null
+++ b/.github/FUNDING.yml
@@ -0,0 +1,15 @@
+# These are supported funding model platforms
+
+github: [capyBearista]
+patreon: # Replace with a single Patreon username
+open_collective: # Replace with a single Open Collective username
+ko_fi: # Replace with a single Ko-fi username
+tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+liberapay: # Replace with a single Liberapay username
+issuehunt: # Replace with a single IssueHunt username
+lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
+polar: # Replace with a single Polar username
+buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
+thanks_dev: # Replace with a single thanks.dev username
+custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
From ddbbb6bdf49492976a7ce069283132e68f792bb3 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 19:37:09 -0400
Subject: [PATCH 008/115] docs(readme, changelog): overhaul header, add
total-downloads badge
Clarify CONTRIBUTING.md
---
.github/assets/capybearista-watermark.svg | 11 +++++
.github/assets/capybearista-wordmark.svg | 15 +++++++
CONTRIBUTING.md | 19 ++++++---
README.md | 52 ++++++++++++++---------
tools/total-downloads-worker.js | 26 ++++++++++++
5 files changed, 99 insertions(+), 24 deletions(-)
create mode 100644 .github/assets/capybearista-watermark.svg
create mode 100644 .github/assets/capybearista-wordmark.svg
create mode 100644 tools/total-downloads-worker.js
diff --git a/.github/assets/capybearista-watermark.svg b/.github/assets/capybearista-watermark.svg
new file mode 100644
index 0000000..5b00f8a
--- /dev/null
+++ b/.github/assets/capybearista-watermark.svg
@@ -0,0 +1,11 @@
+
diff --git a/.github/assets/capybearista-wordmark.svg b/.github/assets/capybearista-wordmark.svg
new file mode 100644
index 0000000..3a95b68
--- /dev/null
+++ b/.github/assets/capybearista-wordmark.svg
@@ -0,0 +1,15 @@
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 02fab9b..6335f44 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -6,7 +6,7 @@ Thank you for your interest in contributing!
```bash
# Clone the monorepo
-git clone https://github.com/capyBearista/opencode-plugins
+git clone https://github.com/capybearista/opencode-plugins
cd opencode-plugins
# Install dependencies
@@ -18,13 +18,13 @@ bun install
Before opening a pull request, run the full quality gate:
```bash
-bun run typecheck && bun run lint && bun run test
+bun run build && bun run typecheck && bun run lint && bun run test
```
-Or use Turbo for parallel execution:
+Auto-format all code with Biome (`bun run check` runs `biome check --write` in every package):
```bash
-bun run build && bun run typecheck && bun run lint && bun test
+bun run check
```
## Commit Messages
@@ -66,11 +66,20 @@ A commit-msg hook will block commits that don't follow this format.
5. Commit with conventional commit format
6. Push and open a PR
+## Automation
+
+The repository uses **Husky** to enforce quality on every commit:
+
+- **Pre-commit** — runs `graphify update .` to keep the project knowledge graph current
+- **Commit-msg** — enforces conventional commits via `commitlint`
+
+**CI** runs on every push via GitHub Actions (typecheck, lint, test).
+
## Monorepo Structure
- `packages/` — published OpenCode plugins
+- `tools/` — auxiliary scripts and utilities (e.g., the Cloudflare Worker for the total-downloads badge)
- `docs/` — internal documentation and upstream prompt snapshots
-- `external/` — independent external projects (not part of workspace)
Each package in `packages/` is independently versioned and published via Changesets.
diff --git a/README.md b/README.md
index 88be08f..544b843 100644
--- a/README.md
+++ b/README.md
@@ -1,26 +1,39 @@
+
A collection of plugins for the OpenCode AI coding agent. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
-## The Plugins
+## Quick Start
-### @capybearista/opencode-output-styles
-Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
+```sh
+opencode plugin add -g \
+@capybearista/opencode-output-styles \
+@capybearista/opencode-agents-loader \
+@capybearista/opencode-double-tap-timeline
+```
-### @capybearista/opencode-agents-loader
-Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
+## Meet The Plugins
-### @capybearista/opencode-double-tap-timeline
+### [@capybearista/opencode-output-styles](./packages/opencode-output-styles/)
+Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session. 🗣️
+
+### [@capybearista/opencode-agents-loader](./packages/opencode-agents-loader/)
+Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized. 🛠️
+
+### [@capybearista/opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse. ⌨️
## Installation
@@ -42,6 +55,16 @@ Alternatively, add them directly to your `opencode.json` configuration file:
}
```
+## What Should I Build Next?
+
+Every plugin here started because someone hit a wall with OpenCode and thought *"there's gotta be a better way."*
+
+I usually browse through [Reddit](https://reddit.com/r/opencodecli) and the GitHub Issues section of the [OpenCode](https://github.com/anomalyco/opencode) repo, noticing people griping about their workflows. But if you've got a concrete idea and want to put it directly in front of me, I'm all ears :)
+
+↣ [GitHub Discussions](https://github.com/capybearista/opencode-plugins/discussions) for plugin brainstorms, OpenCode pain points, and "what if..." ideas.
+
+↣ Already using a plugin and something's off? Or maybe you've got an idea to enhance an existing plugin? [Open an issue](https://github.com/capybearista/opencode-plugins/issues).
+
## Development
This project is a monorepo managed with Bun and Turborepo.
@@ -57,15 +80,6 @@ bun run build
bun run test
```
-## Creating a New Plugin
-
-We use a standard template for new plugins.
-
-1. Run the scaffolding skill:
- `init-plugin`
-2. Follow the prompts to generate the package.
-3. Build and test locally.
-
## License
-MPL-2.0
+[MPL-2.0](./LICENSE.md)
diff --git a/tools/total-downloads-worker.js b/tools/total-downloads-worker.js
new file mode 100644
index 0000000..f370d0e
--- /dev/null
+++ b/tools/total-downloads-worker.js
@@ -0,0 +1,26 @@
+export default {
+ async fetch() {
+ const packages = [
+ "@capybearista/opencode-agents-loader",
+ "@capybearista/opencode-double-tap-timeline",
+ "@capybearista/opencode-output-styles",
+ ];
+ const results = await Promise.all(
+ packages.map((p) =>
+ fetch(`https://api.npmjs.org/downloads/point/last-month/${encodeURIComponent(p)}`).then(
+ (r) => r.json(),
+ ),
+ ),
+ );
+ const total = results.reduce((sum, r) => sum + r.downloads, 0);
+ return new Response(
+ JSON.stringify({
+ schemaVersion: 1,
+ label: "downloads",
+ message: total.toLocaleString() + "/month",
+ color: "brightgreen",
+ }),
+ { headers: { "Content-Type": "application/json" } },
+ );
+ },
+};
From 0b2b515697c17985aaed7c34561f76ea043145f7 Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sun, 3 May 2026 19:55:18 -0400
Subject: [PATCH 009/115] chore(output-styles): rename package title in
README.md
---
packages/opencode-output-styles/README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/opencode-output-styles/README.md b/packages/opencode-output-styles/README.md
index d020b88..ab00e31 100644
--- a/packages/opencode-output-styles/README.md
+++ b/packages/opencode-output-styles/README.md
@@ -1,4 +1,4 @@
-# @capybearista/opencode-output-styles
+# opencode-output-styles
Reusable response styles for OpenCode sessions
From f379609eb8f0656d8a8ea0e51db8363be6a5fda7 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 20:28:29 -0400
Subject: [PATCH 010/115] chore(docs): update installation commands in README
for clarity
---
README.md | 13 ++++++++++++-
packages/opencode-agents-loader/README.md | 4 ++--
packages/opencode-double-tap-timeline/README.md | 4 ++--
packages/opencode-output-styles/README.md | 4 ++--
4 files changed, 18 insertions(+), 7 deletions(-)
diff --git a/README.md b/README.md
index 544b843..9f73980 100644
--- a/README.md
+++ b/README.md
@@ -42,9 +42,10 @@ You can install any of these plugins globally or locally using the OpenCode CLI:
```bash
opencode plugin add -g @capybearista/opencode-output-styles
+opencode plugin add @capybearista/opencode-output-styles
```
-Alternatively, add them directly to your `opencode.json` configuration file:
+Alternatively, add them directly to your `opencode.json`/`opencode.jsonc` configuration file:
```json
{
@@ -55,6 +56,16 @@ Alternatively, add them directly to your `opencode.json` configuration file:
}
```
+For TUI-based plugins, add them directly to `tui.json`/`tui.jsonc`:
+
+```json
+{
+ "plugin": [
+ "@capybearista/opencode-double-tap-timeline"
+ ]
+}
+```
+
## What Should I Build Next?
Every plugin here started because someone hit a wall with OpenCode and thought *"there's gotta be a better way."*
diff --git a/packages/opencode-agents-loader/README.md b/packages/opencode-agents-loader/README.md
index bc3f228..82ead67 100644
--- a/packages/opencode-agents-loader/README.md
+++ b/packages/opencode-agents-loader/README.md
@@ -52,8 +52,8 @@ Add the plugin to `opencode.json` or `opencode.jsonc`:
You can also install it through the CLI:
```bash
-opencode plugin -g # global install
-opencode plugin # project-local install
+opencode plugin -g @capybearista/opencode-agents-loader # global install
+opencode plugin @capybearista/opencode-agents-loader # project-local install
```
## Usage
diff --git a/packages/opencode-double-tap-timeline/README.md b/packages/opencode-double-tap-timeline/README.md
index de585cc..adcc400 100644
--- a/packages/opencode-double-tap-timeline/README.md
+++ b/packages/opencode-double-tap-timeline/README.md
@@ -52,8 +52,8 @@ Add the plugin to `tui.json` or `tui.jsonc`:
You can also install it through the CLI:
```bash
-opencode plugin -g # global install
-opencode plugin # project-local install
+opencode plugin -g @capybearista/opencode-double-tap-timeline # global install
+opencode plugin @capybearista/opencode-double-tap-timeline # project-local install
```
## Usage
diff --git a/packages/opencode-output-styles/README.md b/packages/opencode-output-styles/README.md
index ab00e31..385f660 100644
--- a/packages/opencode-output-styles/README.md
+++ b/packages/opencode-output-styles/README.md
@@ -53,8 +53,8 @@ Add the plugin to `opencode.json` or `opencode.jsonc`:
You can also install it through the CLI:
```bash
-opencode plugin -g # global install
-opencode plugin # project-local install
+opencode plugin -g @capybearista/opencode-output-styles # global install
+opencode plugin @capybearista/opencode-output-styles # project-local install
```
## Usage
From 99c33c5160d0dea7424bff3f951dd65ee97e369d Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sun, 3 May 2026 20:33:55 -0400
Subject: [PATCH 011/115] chore(readme): update plugin titles
---
README.md | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/README.md b/README.md
index 9f73980..99fa8e0 100644
--- a/README.md
+++ b/README.md
@@ -27,14 +27,14 @@ opencode plugin add -g \
## Meet The Plugins
-### [@capybearista/opencode-output-styles](./packages/opencode-output-styles/)
-Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session. 🗣️
+### 🗣️ [@capybearista/opencode-output-styles](./packages/opencode-output-styles/)
+Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
-### [@capybearista/opencode-agents-loader](./packages/opencode-agents-loader/)
-Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized. 🛠️
+### 🛠️ [@capybearista/opencode-agents-loader](./packages/opencode-agents-loader/)
+Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
-### [@capybearista/opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
-A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse. ⌨️
+### ⏱️ [@capybearista/opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
+A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse.
## Installation
From 59abb33e441dc4418cd01d3dba1122b3feb450d1 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 20:37:20 -0400
Subject: [PATCH 012/115] chore(double-tap-timeline): add changeset for v1.0.0
---
.changeset/proud-pants-wave.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/proud-pants-wave.md
diff --git a/.changeset/proud-pants-wave.md b/.changeset/proud-pants-wave.md
new file mode 100644
index 0000000..4d76ee3
--- /dev/null
+++ b/.changeset/proud-pants-wave.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-double-tap-timeline": major
+---
+
+Inspired by Claude Code's double-tap-to-invoke-/rewind feature. Instead of typing /timeline or reaching for the mouse, just double-tap Escape while in a session to open the timeline modal instantly.
From 81dc183f91bf33860e669894c3c31ea762bbab51 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 20:38:55 -0400
Subject: [PATCH 013/115] chore(readme): update logo width
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index 99fa8e0..c70b85e 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-
From c55ec77ded5afa5e9b03bbda29de38c3d5a03776 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 22:00:14 -0400
Subject: [PATCH 018/115] fix(output-styles): revert included output styles to
original behavior
---
.../opencode-output-styles/built-in-styles/explanatory.md | 5 +----
packages/opencode-output-styles/built-in-styles/learning.md | 5 +----
2 files changed, 2 insertions(+), 8 deletions(-)
diff --git a/packages/opencode-output-styles/built-in-styles/explanatory.md b/packages/opencode-output-styles/built-in-styles/explanatory.md
index 4b7bdd8..a134df7 100644
--- a/packages/opencode-output-styles/built-in-styles/explanatory.md
+++ b/packages/opencode-output-styles/built-in-styles/explanatory.md
@@ -9,9 +9,6 @@ You should be clear and educational, providing helpful explanations while remain
## Insights
-In order to encourage learning, before and after writing code, always provide brief educational explanations about implementation choices using (with backticks):
-"`★ Insight ─────────────────────────────────────`
-[2-3 key educational points]
-`─────────────────────────────────────────────────`"
+In order to encourage learning, before and after writing code, always provide brief educational explanations about implementation choices using (with backticks):\n\"`★ Insight ─────────────────────────────────────`\n[2-3 key educational points]\n`─────────────────────────────────────────────────`\"
These insights should be included in the conversation, not in the codebase. You should generally focus on interesting insights that are specific to the codebase or the code you just wrote, rather than general programming concepts. Do not wait until the end to provide insights. Provide them as you write code.
diff --git a/packages/opencode-output-styles/built-in-styles/learning.md b/packages/opencode-output-styles/built-in-styles/learning.md
index 3eba420..70315f6 100644
--- a/packages/opencode-output-styles/built-in-styles/learning.md
+++ b/packages/opencode-output-styles/built-in-styles/learning.md
@@ -59,9 +59,6 @@ Additionally, provide educational insights about the codebase as you help with t
### Insights
-Provide brief educational explanations about implementation choices using (with backticks):
-"`★ Insight ─────────────────────────────────────`
-[2-3 key educational points]
-`─────────────────────────────────────────────────`"
+Provide brief educational explanations about implementation choices using (with backticks):\n\"`★ Insight ─────────────────────────────────────`\n[2-3 key educational points]\n`─────────────────────────────────────────────────`\"
These insights should be included in the conversation, not in the codebase. Focus on interesting insights specific to the codebase or the concepts the student is writing, rather than general programming concepts. Provide insights throughout the session, not just at the end.
From 1ae9e1a8217e9521bab0bbd10d1d343582bfb922 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 22:02:27 -0400
Subject: [PATCH 019/115] chore(output-styles): add changeset
---
.changeset/cyan-sheep-bow.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/cyan-sheep-bow.md
diff --git a/.changeset/cyan-sheep-bow.md b/.changeset/cyan-sheep-bow.md
new file mode 100644
index 0000000..4d99d53
--- /dev/null
+++ b/.changeset/cyan-sheep-bow.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-output-styles": patch
+---
+
+fix(output-styles): revert included output styles to original behavior
From f14999aff1750c466cd796a0cc8564244c4b1bf6 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 22:13:09 -0400
Subject: [PATCH 020/115] feat(ci): add Dependabot, CodeQL, and supply chain
hardening
Set up four layers of GitHub security scanning for this public monorepo:
Dependabot for automated dependency vulnerability alerts.
CodeQL for static analysis of TypeScript code.
SHA-pinned actions to prevent supply chain attacks via tag mutation.
Also fixes a pre-existing bug where the cache key referenced the old binary lockfile format (bun.lockb) that does not exist, causing every CI run to miss the cache and do a full install.
- .github/dependabot.yml: monitor bun + github-actions ecosystems with
weekly grouped updates to reduce PR fatigue
- .github/workflows/codeql.yml: security-and-quality query suite on
push/PR to main and weekly cron
- .github/workflows/ci.yml: SHA-pin all actions, fix bun.lockb cache key
- .github/workflows/release.yml: SHA-pin all actions, fix bun.lockb key
Secret scanning and push protection are UI-based settings that must be
enabled manually in the repo's Advanced Security settings.
---
.github/dependabot.yml | 43 +++++++++++++++++++++++++++++++
.github/workflows/ci.yml | 12 ++++-----
.github/workflows/codeql.yml | 48 +++++++++++++++++++++++++++++++++++
.github/workflows/release.yml | 14 +++++-----
4 files changed, 103 insertions(+), 14 deletions(-)
create mode 100644 .github/dependabot.yml
create mode 100644 .github/workflows/codeql.yml
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 0000000..0efec4f
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,43 @@
+version: 2
+
+updates:
+ - package-ecosystem: "bun"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ day: "monday"
+ time: "06:00"
+ timezone: "America/New_York"
+ groups:
+ production-dependencies:
+ dependency-type: "production"
+ update-types:
+ - "minor"
+ - "patch"
+ development-dependencies:
+ dependency-type: "development"
+ update-types:
+ - "minor"
+ - "patch"
+ major-updates:
+ update-types:
+ - "major"
+ open-pull-requests-limit: 10
+ labels:
+ - "dependencies"
+ - "bun"
+
+ - package-ecosystem: "github-actions"
+ directory: "/"
+ schedule:
+ interval: "weekly"
+ day: "monday"
+ time: "06:00"
+ timezone: "America/New_York"
+ groups:
+ actions:
+ patterns:
+ - "*"
+ labels:
+ - "dependencies"
+ - "github-actions"
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 103bee7..40b36ec 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -8,7 +8,6 @@ on:
- 'docs/**'
- '.github/assets/**'
- '.changeset/**'
- - 'CONTRIBUTING.md'
- 'LICENSE*'
pull_request:
branches: [main]
@@ -17,7 +16,6 @@ on:
- 'docs/**'
- '.github/assets/**'
- '.changeset/**'
- - 'CONTRIBUTING.md'
- 'LICENSE*'
permissions:
@@ -32,24 +30,24 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
fetch-depth: 0
- name: Setup Bun
- uses: oven-sh/setup-bun@v2
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.12
- name: Cache dependencies
- uses: actions/cache@v4
+ uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: |
~/.bun/install/cache
${{ github.workspace }}/.turbo
- key: ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lockb') }}-${{ github.sha }}
+ key: ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lock') }}-${{ github.sha }}
restore-keys: |
- ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lockb') }}-
+ ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lock') }}-
${{ runner.os }}-bun-turbo-
- name: Install dependencies
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
new file mode 100644
index 0000000..1bbfe3f
--- /dev/null
+++ b/.github/workflows/codeql.yml
@@ -0,0 +1,48 @@
+name: CodeQL
+
+on:
+ push:
+ branches: [main]
+ paths-ignore:
+ - '**.md'
+ - 'docs/**'
+ - '.github/assets/**'
+ - '.changeset/**'
+ - 'LICENSE*'
+ pull_request:
+ branches: [main]
+ paths-ignore:
+ - '**.md'
+ - 'docs/**'
+ - '.github/assets/**'
+ - '.changeset/**'
+ - 'LICENSE*'
+ schedule:
+ - cron: '0 6 * * 0'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ analyze:
+ name: Analyze
+ runs-on: ubuntu-latest
+ permissions:
+ actions: read
+ contents: read
+ security-events: write
+ strategy:
+ fail-fast: false
+ matrix:
+ language: [javascript-typescript]
+ steps:
+ - name: Checkout
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+ - name: Initialize CodeQL
+ uses: github/codeql-action/init@c3f298df8c1fea2fefe20c785e6aa00f32df8260 # v4.35.3
+ with:
+ languages: ${{ matrix.language }}
+ queries: security-and-quality
+ - name: Perform CodeQL Analysis
+ uses: github/codeql-action/analyze@c3f298df8c1fea2fefe20c785e6aa00f32df8260 # v4.35.3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index ef6bc3a..a43f7a9 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -29,30 +29,30 @@ jobs:
environment: npm-publish
steps:
- name: Checkout
- uses: actions/checkout@v4
+ uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
with:
fetch-depth: 0
- name: Setup Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 'lts/*'
registry-url: https://registry.npmjs.org/
- name: Setup Bun
- uses: oven-sh/setup-bun@v2
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: 1.3.12
- name: Cache dependencies
- uses: actions/cache@v4
+ uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
with:
path: |
~/.bun/install/cache
${{ github.workspace }}/.turbo
- key: ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lockb') }}-${{ github.sha }}
+ key: ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lock') }}-${{ github.sha }}
restore-keys: |
- ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lockb') }}-
+ ${{ runner.os }}-bun-turbo-${{ hashFiles('**/bun.lock') }}-
${{ runner.os }}-bun-turbo-
- name: Install dependencies
@@ -60,7 +60,7 @@ jobs:
- name: Create Release Pull Request or Publish to NPM
id: changesets
- uses: changesets/action@v1
+ uses: changesets/action@e87c8ed249971350e47fab7515075f44eb134e5b # v1.7.0
with:
# This expects a script named "changeset:publish" in root package.json
publish: bun run changeset:publish
From 31c965dab7318471902ab2310bc5468f6955b8bc Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 3 May 2026 22:24:07 -0400
Subject: [PATCH 021/115] fix(commit): remove commit message body character
limit
---
commitlint.config.ts | 3 +++
1 file changed, 3 insertions(+)
diff --git a/commitlint.config.ts b/commitlint.config.ts
index b29b5ae..6099623 100644
--- a/commitlint.config.ts
+++ b/commitlint.config.ts
@@ -1,3 +1,6 @@
export default {
extends: ["@commitlint/config-conventional"],
+ rules: {
+ "body-max-line-length": [0, "always"],
+ },
};
From fcd9a0c3c57fa1b99e5f6c9bffb13c727516778b Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
<41898282+github-actions[bot]@users.noreply.github.com>
Date: Mon, 4 May 2026 02:24:35 +0000
Subject: [PATCH 022/115] Version Packages
---
.changeset/cyan-sheep-bow.md | 5 -----
packages/opencode-output-styles/CHANGELOG.md | 6 ++++++
packages/opencode-output-styles/package.json | 2 +-
3 files changed, 7 insertions(+), 6 deletions(-)
delete mode 100644 .changeset/cyan-sheep-bow.md
diff --git a/.changeset/cyan-sheep-bow.md b/.changeset/cyan-sheep-bow.md
deleted file mode 100644
index 4d99d53..0000000
--- a/.changeset/cyan-sheep-bow.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@capybearista/opencode-output-styles": patch
----
-
-fix(output-styles): revert included output styles to original behavior
diff --git a/packages/opencode-output-styles/CHANGELOG.md b/packages/opencode-output-styles/CHANGELOG.md
index c625827..c36f07e 100644
--- a/packages/opencode-output-styles/CHANGELOG.md
+++ b/packages/opencode-output-styles/CHANGELOG.md
@@ -1,5 +1,11 @@
# @capybearista/opencode-output-styles
+## 1.0.1
+
+### Patch Changes
+
+- 1ae9e1a: fix(output-styles): revert included output styles to original behavior
+
## 1.0.0
### Major Changes
diff --git a/packages/opencode-output-styles/package.json b/packages/opencode-output-styles/package.json
index ed30ffa..047c74c 100644
--- a/packages/opencode-output-styles/package.json
+++ b/packages/opencode-output-styles/package.json
@@ -1,6 +1,6 @@
{
"name": "@capybearista/opencode-output-styles",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Output styles plugin for OpenCode",
"author": "capyBearista ",
"repository": {
From 8b5f30ba6de31954fb9271c65a6ee002c3869de4 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 4 May 2026 02:25:30 +0000
Subject: [PATCH 023/115] chore(deps): bump the actions group with 5 updates
Bumps the actions group with 5 updates:
| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4.3.1` | `6.0.2` |
| [actions/cache](https://github.com/actions/cache) | `4.3.0` | `5.0.5` |
| [github/codeql-action](https://github.com/github/codeql-action) | `c3f298df8c1fea2fefe20c785e6aa00f32df8260` | `e46ed2cbd01164d986452f91f178727624ae40d7` |
| [actions/setup-node](https://github.com/actions/setup-node) | `4.4.0` | `6.4.0` |
| [changesets/action](https://github.com/changesets/action) | `e87c8ed249971350e47fab7515075f44eb134e5b` | `6a0a831ff30acef54f2c6aa1cbbc1096b066edaf` |
Updates `actions/checkout` from 4.3.1 to 6.0.2
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/34e114876b0b11c390a56381ad16ebd13914f8d5...de0fac2e4500dabe0009e67214ff5f5447ce83dd)
Updates `actions/cache` from 4.3.0 to 5.0.5
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/0057852bfaa89a56745cba8c7296529d2fc39830...27d5ce7f107fe9357f9df03efb73ab90386fccae)
Updates `github/codeql-action` from c3f298df8c1fea2fefe20c785e6aa00f32df8260 to e46ed2cbd01164d986452f91f178727624ae40d7
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/c3f298df8c1fea2fefe20c785e6aa00f32df8260...e46ed2cbd01164d986452f91f178727624ae40d7)
Updates `actions/setup-node` from 4.4.0 to 6.4.0
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/49933ea5288caeca8642d1e84afbd3f7d6820020...48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e)
Updates `changesets/action` from e87c8ed249971350e47fab7515075f44eb134e5b to 6a0a831ff30acef54f2c6aa1cbbc1096b066edaf
- [Release notes](https://github.com/changesets/action/releases)
- [Changelog](https://github.com/changesets/action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/changesets/action/compare/e87c8ed249971350e47fab7515075f44eb134e5b...6a0a831ff30acef54f2c6aa1cbbc1096b066edaf)
---
updated-dependencies:
- dependency-name: actions/checkout
dependency-version: 6.0.2
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: actions
- dependency-name: actions/cache
dependency-version: 5.0.5
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: actions
- dependency-name: github/codeql-action
dependency-version: e46ed2cbd01164d986452f91f178727624ae40d7
dependency-type: direct:production
dependency-group: actions
- dependency-name: actions/setup-node
dependency-version: 6.4.0
dependency-type: direct:production
update-type: version-update:semver-major
dependency-group: actions
- dependency-name: changesets/action
dependency-version: 6a0a831ff30acef54f2c6aa1cbbc1096b066edaf
dependency-type: direct:production
dependency-group: actions
...
Signed-off-by: dependabot[bot]
---
.github/workflows/ci.yml | 4 ++--
.github/workflows/codeql.yml | 6 +++---
.github/workflows/release.yml | 8 ++++----
3 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 40b36ec..be5d2bb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -30,7 +30,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
@@ -40,7 +40,7 @@ jobs:
bun-version: 1.3.12
- name: Cache dependencies
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: |
~/.bun/install/cache
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 1bbfe3f..9be87c7 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -38,11 +38,11 @@ jobs:
language: [javascript-typescript]
steps:
- name: Checkout
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Initialize CodeQL
- uses: github/codeql-action/init@c3f298df8c1fea2fefe20c785e6aa00f32df8260 # v4.35.3
+ uses: github/codeql-action/init@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
with:
languages: ${{ matrix.language }}
queries: security-and-quality
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@c3f298df8c1fea2fefe20c785e6aa00f32df8260 # v4.35.3
+ uses: github/codeql-action/analyze@e46ed2cbd01164d986452f91f178727624ae40d7 # v4.35.3
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index a43f7a9..2f3c761 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -29,12 +29,12 @@ jobs:
environment: npm-publish
steps:
- name: Checkout
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
+ uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
- name: Setup Node.js
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: 'lts/*'
registry-url: https://registry.npmjs.org/
@@ -45,7 +45,7 @@ jobs:
bun-version: 1.3.12
- name: Cache dependencies
- uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0
+ uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
with:
path: |
~/.bun/install/cache
@@ -60,7 +60,7 @@ jobs:
- name: Create Release Pull Request or Publish to NPM
id: changesets
- uses: changesets/action@e87c8ed249971350e47fab7515075f44eb134e5b # v1.7.0
+ uses: changesets/action@6a0a831ff30acef54f2c6aa1cbbc1096b066edaf # v1.7.0
with:
# This expects a script named "changeset:publish" in root package.json
publish: bun run changeset:publish
From ff50c0a8aaeae12cc62ac6610ade0d9e4d5d797c Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 4 May 2026 02:25:32 +0000
Subject: [PATCH 024/115] chore(deps-dev): bump the development-dependencies
group with 2 updates
Bumps the development-dependencies group with 2 updates: [@biomejs/biome](https://github.com/biomejs/biome/tree/HEAD/packages/@biomejs/biome) and [turbo](https://github.com/vercel/turborepo).
Updates `@biomejs/biome` from 2.4.13 to 2.4.14
- [Release notes](https://github.com/biomejs/biome/releases)
- [Changelog](https://github.com/biomejs/biome/blob/main/packages/@biomejs/biome/CHANGELOG.md)
- [Commits](https://github.com/biomejs/biome/commits/@biomejs/biome@2.4.14/packages/@biomejs/biome)
Updates `turbo` from 2.9.7 to 2.9.8
- [Release notes](https://github.com/vercel/turborepo/releases)
- [Changelog](https://github.com/vercel/turborepo/blob/main/RELEASE.md)
- [Commits](https://github.com/vercel/turborepo/compare/v2.9.7...v2.9.8)
---
updated-dependencies:
- dependency-name: "@biomejs/biome"
dependency-version: 2.4.14
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: development-dependencies
- dependency-name: turbo
dependency-version: 2.9.8
dependency-type: direct:development
update-type: version-update:semver-patch
dependency-group: development-dependencies
...
Signed-off-by: dependabot[bot]
---
bun.lock | 40 ++++++++++++++++++++--------------------
package.json | 4 ++--
2 files changed, 22 insertions(+), 22 deletions(-)
diff --git a/bun.lock b/bun.lock
index e420e1e..08835d2 100644
--- a/bun.lock
+++ b/bun.lock
@@ -5,14 +5,14 @@
"": {
"name": "opencode-plugins",
"devDependencies": {
- "@biomejs/biome": "2.4.13",
+ "@biomejs/biome": "2.4.14",
"@changesets/cli": "^2.27.0",
"@commitlint/cli": "^20.5.0",
"@commitlint/config-conventional": "^20.5.0",
"@types/bun": "^1.3.13",
"@types/node": "^22.0.0",
"husky": "^9.1.7",
- "turbo": "^2.0.0",
+ "turbo": "^2.9.8",
"typescript": "^5.8.0",
},
},
@@ -31,7 +31,7 @@
},
"packages/opencode-double-tap-timeline": {
"name": "@capybearista/opencode-double-tap-timeline",
- "version": "0.1.1",
+ "version": "1.0.0",
"devDependencies": {
"@opencode-ai/plugin": ">=1.14.24",
"@opentui/core": ">=0.1.103",
@@ -46,7 +46,7 @@
},
"packages/opencode-output-styles": {
"name": "@capybearista/opencode-output-styles",
- "version": "0.0.0",
+ "version": "1.0.0",
"dependencies": {
"yaml": "^2.4.5",
},
@@ -119,23 +119,23 @@
"@babel/types": ["@babel/types@7.29.0", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.28.5" } }, "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A=="],
- "@biomejs/biome": ["@biomejs/biome@2.4.13", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.13", "@biomejs/cli-darwin-x64": "2.4.13", "@biomejs/cli-linux-arm64": "2.4.13", "@biomejs/cli-linux-arm64-musl": "2.4.13", "@biomejs/cli-linux-x64": "2.4.13", "@biomejs/cli-linux-x64-musl": "2.4.13", "@biomejs/cli-win32-arm64": "2.4.13", "@biomejs/cli-win32-x64": "2.4.13" }, "bin": { "biome": "bin/biome" } }, "sha512-gLXOwkOBBg0tr7bDsqlkIh4uFeKuMjxvqsrb1Tukww1iDmHcfr4Uu8MoQxp0Rcte+69+osRNWXwHsu/zxT6XqA=="],
+ "@biomejs/biome": ["@biomejs/biome@2.4.14", "", { "optionalDependencies": { "@biomejs/cli-darwin-arm64": "2.4.14", "@biomejs/cli-darwin-x64": "2.4.14", "@biomejs/cli-linux-arm64": "2.4.14", "@biomejs/cli-linux-arm64-musl": "2.4.14", "@biomejs/cli-linux-x64": "2.4.14", "@biomejs/cli-linux-x64-musl": "2.4.14", "@biomejs/cli-win32-arm64": "2.4.14", "@biomejs/cli-win32-x64": "2.4.14" }, "bin": { "biome": "bin/biome" } }, "sha512-TmAvxOEgrpLypzVGJ8FulIZnlyA9TxrO1hyqYrCz9r+bwma9xXxuLA5IuYnj55XQneFx460KjRbx6SWGLkg3bQ=="],
- "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.13", "", { "os": "darwin", "cpu": "arm64" }, "sha512-2KImO1jhNFBa2oWConyr0x6flxbQpGKv6902uGXpYM62Xyem8U80j441SyUJ8KyngsmKbQjeIv1q2CQfDkNnYg=="],
+ "@biomejs/cli-darwin-arm64": ["@biomejs/cli-darwin-arm64@2.4.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-XvgoE9XOawUOQPdmvs4J7wPhi/DLwSCGks3AlPJDmh34O0awRTqCED1HRcRDdpf1Zrp4us4MGOOdIxNpbqNF5Q=="],
- "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.13", "", { "os": "darwin", "cpu": "x64" }, "sha512-BKrJklbaFN4p1Ts4kPBczo+PkbsHQg57kmJ+vON9u2t6uN5okYHaSr7h/MutPCWQgg2lglaWoSmm+zhYW+oOkg=="],
+ "@biomejs/cli-darwin-x64": ["@biomejs/cli-darwin-x64@2.4.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-jE7hKBCFhOx3uUh+ZkWBfOHxAcILPfhFplNkuID/eZeSTLHzfZzoZxW8fbqY9xXRnPi7jGNAf1iPVR+0yWsM/Q=="],
- "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-NzkUDSqfvMBrPplKgVr3aXLHZ2NEELvvF4vZxXulEylKWIGqlvNEcwUcj9OLrn75TD3lJ/GIqCVlBwd1MZCuYQ=="],
+ "@biomejs/cli-linux-arm64": ["@biomejs/cli-linux-arm64@2.4.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-2TELhZnW5RSLL063l9rc5xLpA0ZIw0Ccwy/0q384rvNAgFw3yI76bd59547yxowdQr5MNPET/xDLrLuvgSeeWQ=="],
- "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.13", "", { "os": "linux", "cpu": "arm64" }, "sha512-U5MsuBQW25dXaYtqWWSPM3P96H6Y+fHuja3TQpMNnylocHW0tEbtFTDlUj6oM+YJLntvEkQy4grBvQNUD4+RCg=="],
+ "@biomejs/cli-linux-arm64-musl": ["@biomejs/cli-linux-arm64-musl@2.4.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-/z+6gqAqqUQTHazwStxSXKHg9b8UvqBmDFRp+c4wYbq2KXhELQDon9EoC9RpmQ8JWkqQx/lIUy/cs+MhzDZp6A=="],
- "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.13", "", { "os": "linux", "cpu": "x64" }, "sha512-Az3ZZedYRBo9EQzNnD9SxFcR1G5QsGo6VEc2hIyVPZ1rdKwee/7E9oeBBZFpE8Z44ekxsDQBqbiWGW5ShOhUSQ=="],
+ "@biomejs/cli-linux-x64": ["@biomejs/cli-linux-x64@2.4.14", "", { "os": "linux", "cpu": "x64" }, "sha512-zHrlQZDBDUz4OLAraYpWKcnLS6HOewBFWYOzY91d1ZjdqZwibOyb6BEu6WuWLugyo0P3riCmsbV9UqV1cSXwQg=="],
- "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.13", "", { "os": "linux", "cpu": "x64" }, "sha512-Z601MienRgTBDza/+u2CH3RSrWoXo9rtr8NK6A4KJzqGgfxx+H3VlyLgTJ4sRo40T3pIsqpTmiOQEvYzQvBRvQ=="],
+ "@biomejs/cli-linux-x64-musl": ["@biomejs/cli-linux-x64-musl@2.4.14", "", { "os": "linux", "cpu": "x64" }, "sha512-R6BWgJdQOwW9ulJatuTVrQkjnODjqHZkKNOqb1sz++3Noe5LYd0i3PchnOBUCYAPHoPWHhjJqbdZlHEu0hpjdA=="],
- "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.13", "", { "os": "win32", "cpu": "arm64" }, "sha512-Px9PS2B5/Q183bUwy/5VHqp3J2lzdOCeVGzMpphYfl8oSa7VDCqenBdqWpy6DCy/en4Rbf/Y1RieZF6dJPcc9A=="],
+ "@biomejs/cli-win32-arm64": ["@biomejs/cli-win32-arm64@2.4.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-M3EH5hqOI/F/FUA2u4xcLoUgmxd218mvuj/6JL7Hv2toQvr2/AdOvKSpGkoRuWFCtQPVa+ZqkEV3Q5xBA9+XSA=="],
- "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.13", "", { "os": "win32", "cpu": "x64" }, "sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ=="],
+ "@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.14", "", { "os": "win32", "cpu": "x64" }, "sha512-WL0EG5qE+EAKomGXbf2g6VnSKJhTL3tXC0QRzWRwA5VpjxNYa6H4P7ZWfymbGE4IhZZQi1KXQ2R0YjwInmz2fA=="],
"@capybearista/opencode-agents-loader": ["@capybearista/opencode-agents-loader@workspace:packages/opencode-agents-loader"],
@@ -271,17 +271,17 @@
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
- "@turbo/darwin-64": ["@turbo/darwin-64@2.9.7", "", { "os": "darwin", "cpu": "x64" }, "sha512-wnvOWuVWJ5EUHNKxExEWiGlTeVpLG1L0PCu5MUozyC1P2SHGiWsmpW6/yAuShH91Fa2TAHOvdCRBzriZh4j4Eg=="],
+ "@turbo/darwin-64": ["@turbo/darwin-64@2.9.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-zU1P95ygDpsQ+2QHh7CVTqvYwi9UBlhKWzoIyUnP3vUoge7H9SQEzrd8dj+XcTrslAp9Db3vIBcXtMVoTEYDnA=="],
- "@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.9.7", "", { "os": "darwin", "cpu": "arm64" }, "sha512-mA0FIPMwwN3lodDkQYaGxj6PeT7ZaN5aCEbkKn/WB+ZB9yJdVWA4J83GH7t43jqDc5dcnVluVN5UFx3plRiXhA=="],
+ "@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.9.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-nKRFI5ZhCGUi4eXNlrojzWcT/CehMj0raot1WE4lw5qf66ZxZHbRbBqcwNEy+ZLY7RkJJRY+TaU89fuj3BcgGg=="],
- "@turbo/linux-64": ["@turbo/linux-64@2.9.7", "", { "os": "linux", "cpu": "x64" }, "sha512-fEbUYpgb5l7P+q+5tsWF2gw+/GSjUsuUTcnfm+f0lozUjgcjLKyOat6PgtAChmIFcTPchCL/8rJ3TvkBy01gfA=="],
+ "@turbo/linux-64": ["@turbo/linux-64@2.9.8", "", { "os": "linux", "cpu": "x64" }, "sha512-Wf/kQpVDCaWM3P5d6lKvJnqjYn/ofUBGbT4h4vRFrdC4N6B/nsun03S2kQNJJMXpXg39woeS4CI367RMU3/OAg=="],
- "@turbo/linux-arm64": ["@turbo/linux-arm64@2.9.7", "", { "os": "linux", "cpu": "arm64" }, "sha512-VkUjulo9ytfHKUHOS5gy0XPoh4CTKPXWCL8nLdrlHVi9fSut31ECeUqnm/dAbETP5D4xo9mH9XkJ+qMzGe/zmg=="],
+ "@turbo/linux-arm64": ["@turbo/linux-arm64@2.9.8", "", { "os": "linux", "cpu": "arm64" }, "sha512-v6S3HuKVoa9CEx16IxKj1i/+crxXx22A9O80zW1350zyUlcX0T/zLOxVf1k+ruK/7ssXnDJVg8uSYOxlYRedlA=="],
- "@turbo/windows-64": ["@turbo/windows-64@2.9.7", "", { "os": "win32", "cpu": "x64" }, "sha512-/GWdY6/x4aIHqkYJq596Rpdk1x0MkpRPkJcLAoB3yGRwyUms0+u2F1GnV54IbyAZTeKLRWSJKzNC+QwVGdYchA=="],
+ "@turbo/windows-64": ["@turbo/windows-64@2.9.8", "", { "os": "win32", "cpu": "x64" }, "sha512-JaefWOJNBazDylAn3f+lLB34XMNu8nEBbgPRP/Ewysg81cBubGfcyyyzpQOGVuMwfaqdNAE/kitG7w3AbJn9/g=="],
- "@turbo/windows-arm64": ["@turbo/windows-arm64@2.9.7", "", { "os": "win32", "cpu": "arm64" }, "sha512-xBBgxCC5PK2+WZ1PPRZdp+aJ0bMBcEbweXWux3RUHJvX9ZodcoQySkrW6qt+ahb+uk8ZjyQodLfDwtVSoYds1w=="],
+ "@turbo/windows-arm64": ["@turbo/windows-arm64@2.9.8", "", { "os": "win32", "cpu": "arm64" }, "sha512-Or6ljjB4TiiwCdVKDYWew0SokQ9kep5zruL8P3nbum9WdkH5XA41rQID4Ulc215Z+R3DrB+qXSHPsJjU3/n2ng=="],
"@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],
@@ -639,7 +639,7 @@
"toml": ["toml@4.1.1", "", {}, "sha512-EBJnVBr3dTXdA89WVFoAIPUqkBjxPMwRqsfuo1r240tKFHXv3zgca4+NJib/h6TyvGF7vOawz0jGuryJCdNHrw=="],
- "turbo": ["turbo@2.9.7", "", { "optionalDependencies": { "@turbo/darwin-64": "2.9.7", "@turbo/darwin-arm64": "2.9.7", "@turbo/linux-64": "2.9.7", "@turbo/linux-arm64": "2.9.7", "@turbo/windows-64": "2.9.7", "@turbo/windows-arm64": "2.9.7" }, "bin": { "turbo": "bin/turbo" } }, "sha512-epxzqVO2s0IxcSWcgb+qKrtco8isfe7g3VtiS6hkYnEK4A9XQDZbrtavQ6MtWR1KoQn+1fUomaQth2rfRHlUlg=="],
+ "turbo": ["turbo@2.9.8", "", { "optionalDependencies": { "@turbo/darwin-64": "2.9.8", "@turbo/darwin-arm64": "2.9.8", "@turbo/linux-64": "2.9.8", "@turbo/linux-arm64": "2.9.8", "@turbo/windows-64": "2.9.8", "@turbo/windows-arm64": "2.9.8" }, "bin": { "turbo": "bin/turbo" } }, "sha512-REEB2rVTVDTf4hav1gJ5dIsGylWZrNonvjXFtk1dCi8gND3PhZtnYkyry1bra/Fo+iP6ctTEZbg6vWfdfHq/1A=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
diff --git a/package.json b/package.json
index 2b2e546..bc1bc95 100644
--- a/package.json
+++ b/package.json
@@ -17,14 +17,14 @@
"prepare": "husky"
},
"devDependencies": {
- "@biomejs/biome": "2.4.13",
+ "@biomejs/biome": "2.4.14",
"@changesets/cli": "^2.27.0",
"@commitlint/cli": "^20.5.0",
"@commitlint/config-conventional": "^20.5.0",
"@types/bun": "^1.3.13",
"@types/node": "^22.0.0",
"husky": "^9.1.7",
- "turbo": "^2.0.0",
+ "turbo": "^2.9.8",
"typescript": "^5.8.0"
}
}
From c12504b9f64768c8bd5d61ddea1fd913e04bb010 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 4 May 2026 02:53:37 +0000
Subject: [PATCH 025/115] chore(deps-dev): bump the major-updates group across
1 directory with 2 updates
Bumps the major-updates group with 2 updates in the / directory: [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) and [typescript](https://github.com/microsoft/TypeScript).
Updates `@types/node` from 22.19.17 to 25.6.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)
Updates `typescript` from 5.9.3 to 6.0.3
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.9.3...v6.0.3)
---
updated-dependencies:
- dependency-name: "@types/node"
dependency-version: 25.6.0
dependency-type: direct:development
update-type: version-update:semver-major
dependency-group: major-updates
- dependency-name: typescript
dependency-version: 6.0.3
dependency-type: direct:development
update-type: version-update:semver-major
dependency-group: major-updates
...
Signed-off-by: dependabot[bot]
---
bun.lock | 12 ++++++------
package.json | 4 ++--
2 files changed, 8 insertions(+), 8 deletions(-)
diff --git a/bun.lock b/bun.lock
index 08835d2..360c3d9 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10,10 +10,10 @@
"@commitlint/cli": "^20.5.0",
"@commitlint/config-conventional": "^20.5.0",
"@types/bun": "^1.3.13",
- "@types/node": "^22.0.0",
+ "@types/node": "^25.6.0",
"husky": "^9.1.7",
"turbo": "^2.9.8",
- "typescript": "^5.8.0",
+ "typescript": "^6.0.3",
},
},
"packages/opencode-agents-loader": {
@@ -46,7 +46,7 @@
},
"packages/opencode-output-styles": {
"name": "@capybearista/opencode-output-styles",
- "version": "1.0.0",
+ "version": "1.0.1",
"dependencies": {
"yaml": "^2.4.5",
},
@@ -285,7 +285,7 @@
"@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],
- "@types/node": ["@types/node@22.19.17", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-wGdMcf+vPYM6jikpS/qhg6WiqSV/OhG+jeeHT/KlVqxYfD40iYJf9/AE1uQxVWFvU7MipKRkRv8NSHiCGgPr8Q=="],
+ "@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
@@ -641,9 +641,9 @@
"turbo": ["turbo@2.9.8", "", { "optionalDependencies": { "@turbo/darwin-64": "2.9.8", "@turbo/darwin-arm64": "2.9.8", "@turbo/linux-64": "2.9.8", "@turbo/linux-arm64": "2.9.8", "@turbo/windows-64": "2.9.8", "@turbo/windows-arm64": "2.9.8" }, "bin": { "turbo": "bin/turbo" } }, "sha512-REEB2rVTVDTf4hav1gJ5dIsGylWZrNonvjXFtk1dCi8gND3PhZtnYkyry1bra/Fo+iP6ctTEZbg6vWfdfHq/1A=="],
- "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+ "typescript": ["typescript@6.0.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw=="],
- "undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
+ "undici-types": ["undici-types@7.19.2", "", {}, "sha512-qYVnV5OEm2AW8cJMCpdV20CDyaN3g0AjDlOGf1OW4iaDEx8MwdtChUp4zu4H0VP3nDRF/8RKWH+IPp9uW0YGZg=="],
"universalify": ["universalify@0.1.2", "", {}, "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg=="],
diff --git a/package.json b/package.json
index bc1bc95..b821667 100644
--- a/package.json
+++ b/package.json
@@ -22,9 +22,9 @@
"@commitlint/cli": "^20.5.0",
"@commitlint/config-conventional": "^20.5.0",
"@types/bun": "^1.3.13",
- "@types/node": "^22.0.0",
+ "@types/node": "^25.6.0",
"husky": "^9.1.7",
"turbo": "^2.9.8",
- "typescript": "^5.8.0"
+ "typescript": "^6.0.3"
}
}
From 056d05b4d11dbef0e17ed997fa812d8faf09f1f6 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Mon, 4 May 2026 01:50:59 -0400
Subject: [PATCH 026/115] docs(readme): add shoutouts section and improve
formatting
---
README.md | 23 +++++++++++++++++++----
1 file changed, 19 insertions(+), 4 deletions(-)
diff --git a/README.md b/README.md
index f116545..75deb9f 100644
--- a/README.md
+++ b/README.md
@@ -29,12 +29,15 @@ opencode plugin add -g \
## Meet The Plugins
### 🗣️ [@capybearista/opencode-output-styles](./packages/opencode-output-styles/)
+
Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
### 🛠️ [@capybearista/opencode-agents-loader](./packages/opencode-agents-loader/)
+
Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
### ⏱️ [@capybearista/opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
+
A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse.
## Installation
@@ -61,15 +64,13 @@ For TUI-based plugins, add them directly to `tui.json`/`tui.jsonc`:
```json
{
- "plugin": [
- "@capybearista/opencode-double-tap-timeline"
- ]
+ "plugin": ["@capybearista/opencode-double-tap-timeline"]
}
```
## What Should I Build Next?
-Every plugin here started because someone hit a wall with OpenCode and thought *"there's gotta be a better way."*
+Every plugin here started because someone hit a wall with OpenCode and thought _"there's gotta be a better way."_
I usually browse through [Reddit](https://reddit.com/r/opencodecli) and the GitHub Issues section of the [OpenCode](https://github.com/anomalyco/opencode) repo, noticing people griping about their workflows. But if you've got a concrete idea and want to put it directly in front of me, I'm all ears :)
@@ -77,6 +78,20 @@ I usually browse through [Reddit](https://reddit.com/r/opencodecli) and the GitH
↣ Already using a plugin and something's off? Or maybe you've got an idea to enhance an existing plugin? [Open an issue](https://github.com/capybearista/opencode-plugins/issues).
+## Shoutouts
+
+Plugins I've personally used and highly recommend! Some of these are genuinely underrated and have massive potential.
+
+| Name | Use case | Description |
+| -------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [opencode-quota](https://github.com/slkiser/opencode-quota) | Keep track of your provider subscriptions _in_ OpenCode | Token usage and quota tracking for Anthropic, OpenAI, Copilot, and more—reports in terminal with zero context pollution. |
+| [opencode-snippets](https://github.com/JosXa/opencode-snippets) | Expand `#tags` into text anywhere, instantly | Hashtag-based snippet expansion. Just type `#name` to inject pre-defined code blocks, configs, or prompts inline. You can even put them in commands. |
+| [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning) | Caps token waste from stale context | Context-aware compression intelligently prunes old tool outputs to keep context lean and reduce token burn. |
+| [cc-safety-net](https://github.com/kenryu42/claude-code-safety-net) | Prevents dangerous commands like `rm -rf` and `git reset --hard` | Intercepts destructive git and filesystem commands before they execute, giving you a chance to abort before your agent deletes your entire project. |
+| [opencode-command-hooks](https://github.com/shanebishop1/opencode-command-hooks) | Run scripts on session events without writing a plugin | Declarative event hooks for shell commands via YAML/JSON. You can even attach scripts to lifecycle events like `tool.execute.after`. |
+| [opencode-agent-identity](https://github.com/gotgenes/opencode-agent-identity) | Distinguish which sub-agent said what in multi-agent sessions | Per-message attribution so each agent knows its role and which message came from which source. |
+| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Know when sessions finish without watching the terminal | Highly customizable desktop notifications and sounds for permission prompts, completion, and errors so you never miss a beat. |
+
## Development
This project is a monorepo managed with Bun and Turborepo.
From 33fab779c75cd4ae915924ee9b3aa589e6431251 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Mon, 4 May 2026 02:55:30 -0400
Subject: [PATCH 027/115] docs(workflows): update contributing guidelines and
templates
Updated issue templates to remove the 'Code of Conduct' checkbox from bug reports and replace it with a 'Contributing Guidelines' checkbox in feature requests. Also added a reference to the guidelines in the README to improve contributor onboarding.
---
.github/ISSUE_TEMPLATE/bug_report.yml | 8 --------
.github/ISSUE_TEMPLATE/feature_request.yml | 6 +++---
README.md | 2 ++
3 files changed, 5 insertions(+), 11 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index 568c182..aabe91b 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -41,11 +41,3 @@ body:
placeholder: e.g., 1.0.0
validations:
required: true
- - type: checkboxes
- id: terms
- attributes:
- label: Code of Conduct
- description: By submitting this issue, you agree to follow our Code of Conduct.
- options:
- - label: I agree to follow this project's Code of Conduct
- required: true
\ No newline at end of file
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index 6cc8491..c2d094e 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -30,8 +30,8 @@ body:
- type: checkboxes
id: terms
attributes:
- label: Code of Conduct
- description: By submitting this issue, you agree to follow our Code of Conduct.
+ label: Contributing Guidelines
+ description: By submitting this issue, you agree to follow our Contributing Guidelines (CONTRIBUTING.md).
options:
- - label: I agree to follow this project's Code of Conduct
+ - label: I have read this project's Contributing Guidelines
required: true
\ No newline at end of file
diff --git a/README.md b/README.md
index 75deb9f..add2010 100644
--- a/README.md
+++ b/README.md
@@ -107,6 +107,8 @@ bun run build
bun run test
```
+Please review the [contribution guidelines](./CONTRIBUTING.md) before contributing :)
+
## License
[MPL-2.0](./LICENSE.md)
From 0106aee43e6efa38b530847ec3f065ef3bc9fcca Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Mon, 4 May 2026 04:17:15 -0400
Subject: [PATCH 028/115] docs(workflows): overhaul issue and PR templates
using GitHub Forms schema
Replaced basic issue templates with GitHub Forms (YAML schema):
- Added bug and feature type frontmatter for org-level filtering
- Added plugin selector dropdowns targeting specific packages
- Added pre-flight checklists (duplicate search, version check, etc.)
- Added environment fields (plugin version, OpenCode version, OS)
- Added file upload support for screenshots and mockups
Replaced PR template with structured sections:
- Summary, Linked Issue, Plugin(s) Affected, Type of Change
- OpenCode Validation, Quality Checklist, Screenshots
- Aligned quality checks with bun toolchain commands
Updated config.yml: replaced docs link with GitHub Discussions link
Removed Changesets section from CONTRIBUTING.md (sole maintainer)
---
.github/ISSUE_TEMPLATE/bug_report.yml | 66 +++++++++++++++--
.github/ISSUE_TEMPLATE/config.yml | 6 +-
.github/ISSUE_TEMPLATE/feature_request.yml | 82 +++++++++++++++++++---
.github/PULL_REQUEST_TEMPLATE.md | 31 --------
.github/pull_request_template.md | 47 +++++++++++++
CONTRIBUTING.md | 10 ---
6 files changed, 181 insertions(+), 61 deletions(-)
delete mode 100644 .github/PULL_REQUEST_TEMPLATE.md
create mode 100644 .github/pull_request_template.md
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index aabe91b..c6d10a8 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -2,27 +2,51 @@ name: Bug Report
description: File a bug report
title: "[Bug]: "
labels: ["bug"]
+type: bug
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
+ - type: checkboxes
+ id: preflight
+ attributes:
+ label: Pre-flight checklist
+ options:
+ - label: I have searched existing issues to avoid duplicates
+ required: true
+ - label: I have provided clear steps to reproduce (in the field below)
+ required: false
+ - type: dropdown
+ id: plugin
+ attributes:
+ label: Which plugin is affected?
+ description: Select the plugin you're reporting a bug for.
+ options:
+ - Select
+ - opencode-agents-loader
+ - opencode-double-tap-timeline
+ - opencode-output-styles
+ - opencode-plugins (this monorepo itself)
+ - Other
+ validations:
+ required: true
- type: textarea
id: what-happened
attributes:
label: What happened?
- description: Also tell us what you expected to happen.
- placeholder: Tell us what you see!
+ description: Outline the unexpected behavior or error you encountered.
+ placeholder: I keep running into...
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Steps to reproduce
- description: How can we reproduce the issue?
+ description: How can the issue be reproduced?
placeholder: |
- 1. Go to '...'
- 2. Click on '....'
+ 1. Run OpenCode...
+ 2. Run the command '....'
3. Scroll down to '....'
4. See error
validations:
@@ -34,10 +58,38 @@ body:
description: Please copy and paste any relevant log output. This will be automatically formatted into code.
render: shell
- type: input
- id: version
+ id: plugin-version
attributes:
- label: Version
+ label: Plugin Version
description: What version of the plugin are you running?
placeholder: e.g., 1.0.0
validations:
required: true
+ - type: input
+ id: opencode-version
+ attributes:
+ label: OpenCode Version
+ description: What version of OpenCode are you using?
+ placeholder: e.g., 1.14.33
+ validations:
+ required: true
+ - type: dropdown
+ id: os
+ attributes:
+ label: Operating System
+ description: What OS are you running?
+ options:
+ - Select
+ - Linux
+ - macOS
+ - Windows
+ - Other
+ validations:
+ required: true
+ - type: upload
+ id: uploads
+ attributes:
+ label: Upload screenshots or logs
+ description: Add images or log files to help explain the issue.
+ validations:
+ required: false
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 1975d22..889cc16 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -1,5 +1,5 @@
blank_issues_enabled: false
contact_links:
- - name: OpenCode Plugins Documentation
- url: https://github.com/capyBearista/opencode-plugins#readme
- about: Please read the documentation before opening an issue.
\ No newline at end of file
+ - name: GitHub Discussions
+ url: https://github.com/capybearista/opencode-plugins/discussions
+ about: Ask questions, brainstorm new plugin ideas, or share feedback here!
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index c2d094e..e95cd98 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -1,18 +1,52 @@
name: Feature Request
-description: Suggest an idea for this project
+description: Suggest an idea for an existing plugin or this monorepo itself
title: "[Feature]: "
labels: ["enhancement"]
+type: feature
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to suggest a feature!
+ - type: checkboxes
+ id: preflight
+ attributes:
+ label: Pre-flight checklist
+ options:
+ - label: I have searched existing issues to avoid duplicates
+ required: true
+ - label: I have checked the plugin's README for existing capabilities
+ required: true
+ - type: dropdown
+ id: plugin
+ attributes:
+ label: Which plugin is this for?
+ description: Select the plugin you'd like to see enhanced.
+ options:
+ - Select
+ - opencode-agents-loader
+ - opencode-double-tap-timeline
+ - opencode-output-styles
+ - opencode-plugins (this monorepo itself)
+ - Other
+ validations:
+ required: true
+ - type: dropdown
+ id: request-type
+ attributes:
+ label: Is your feature request related to a problem with the selected option above?
+ options:
+ - "No — I have an idea for a new capability"
+ - "Yes — something is broken, frustrating, or missing"
+ default: 0
+ validations:
+ required: true
- type: textarea
id: problem
attributes:
- label: Is your feature request related to a problem?
- description: A clear and concise description of what the problem is.
- placeholder: I'm always frustrated when...
+ label: If No — What would you like to see? || If Yes — What's the problem?
+ description: Describe the new capability or enhancement you'd like added. || A clear and concise description of the issue you're facing.
+ placeholder: I'd love to be able to... || I'm always frustrated when...
validations:
required: true
- type: textarea
@@ -27,11 +61,39 @@ body:
attributes:
label: Describe alternatives you've considered
description: A clear and concise description of any alternative solutions or features you've considered.
- - type: checkboxes
- id: terms
+ - type: input
+ id: plugin-version
attributes:
- label: Contributing Guidelines
- description: By submitting this issue, you agree to follow our Contributing Guidelines (CONTRIBUTING.md).
+ label: Plugin Version
+ description: What version of the plugin are you running?
+ placeholder: e.g., 1.0.0
+ validations:
+ required: false
+ - type: input
+ id: opencode-version
+ attributes:
+ label: OpenCode Version
+ description: What version of OpenCode are you using?
+ placeholder: e.g., 1.14.33
+ validations:
+ required: false
+ - type: dropdown
+ id: os
+ attributes:
+ label: Operating System
+ description: What OS are you running?
options:
- - label: I have read this project's Contributing Guidelines
- required: true
\ No newline at end of file
+ - Select
+ - Linux
+ - macOS
+ - Windows
+ - Other
+ validations:
+ required: false
+ - type: upload
+ id: mockups
+ attributes:
+ label: Upload mockups or examples
+ description: Add images or reference files to help illustrate your idea.
+ validations:
+ required: false
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
deleted file mode 100644
index e9518f8..0000000
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ /dev/null
@@ -1,31 +0,0 @@
-## Description
-
-
-
-Fixes # (issue)
-
-## Type of Change
-
-
-
-- [ ] Bug fix (non-breaking change which fixes an issue)
-- [ ] New feature (non-breaking change which adds functionality)
-- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
-- [ ] Documentation update
-- [ ] Refactoring (no functional changes)
-- [ ] Performance improvement
-- [ ] Test changes
-
-## Checklist
-
-
-
-- [ ] I have run `bun run typecheck && bun run lint && bun run test` and all checks pass
-- [ ] I have added tests that prove my fix is effective or that my feature works
-- [ ] I have updated the documentation accordingly (if applicable)
-- [ ] My changes generate no new warnings
-- [ ] I have read the [Contributing Guidelines](../CONTRIBUTING.md)
-
-## Additional Context
-
-
\ No newline at end of file
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
new file mode 100644
index 0000000..52ed24b
--- /dev/null
+++ b/.github/pull_request_template.md
@@ -0,0 +1,47 @@
+## Summary
+
+
+
+## Linked Issue
+
+
+
+## Plugin(s) Affected
+
+- [ ] opencode-agents-loader
+- [ ] opencode-double-tap-timeline
+- [ ] opencode-output-styles
+- [ ] opencode-plugins (this monorepo itself)
+- [ ] Other: _______
+
+## Type of Change
+
+
+
+- [ ] Bug fix (non-breaking change which fixes an issue)
+- [ ] New feature (non-breaking change which adds functionality)
+- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
+- [ ] Documentation update
+- [ ] Refactoring (no functional changes)
+- [ ] Other: _______
+
+## OpenCode Validation
+
+- OpenCode version tested:
+
+## Quality Checklist
+
+- [ ] I ran `bun run typecheck && bun run lint && bun run test`
+- [ ] I ran `bun run build`
+- [ ] This is the smallest safe root-cause fix (no unnecessary logic changes)
+- [ ] I preserved behavioral invariants and added/updated tests as needed
+- [ ] I updated docs for user-facing changes
+- [ ] I have read the [Contributing Guidelines](../CONTRIBUTING.md)
+
+## Screenshots
+
+
+
+## Additional Context
+
+
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6335f44..f3f6b6f 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -83,16 +83,6 @@ The repository uses **Husky** to enforce quality on every commit:
Each package in `packages/` is independently versioned and published via Changesets.
-## Changesets
-
-For changes that should be released, add a changeset:
-
-```bash
-bun changeset
-```
-
-This creates a changeset file describing your change. The changeset will be consumed during the next release cycle.
-
## Code Style
- **TypeScript strict mode** is required
From e7dc90a2b2fe003dc2449053a8e843b84834b283 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Mon, 4 May 2026 04:48:32 -0400
Subject: [PATCH 029/115] fix(workflows): remove type frontmatter from issue
templates
The type key requires org-level issue type configuration.
Without it, GitHub rejects the template with 'type is not a permitted key'.
---
.github/ISSUE_TEMPLATE/bug_report.yml | 1 -
.github/ISSUE_TEMPLATE/feature_request.yml | 1 -
2 files changed, 2 deletions(-)
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml
index c6d10a8..41d27f4 100644
--- a/.github/ISSUE_TEMPLATE/bug_report.yml
+++ b/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -2,7 +2,6 @@ name: Bug Report
description: File a bug report
title: "[Bug]: "
labels: ["bug"]
-type: bug
body:
- type: markdown
attributes:
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index e95cd98..7e7f8a4 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -2,7 +2,6 @@ name: Feature Request
description: Suggest an idea for an existing plugin or this monorepo itself
title: "[Feature]: "
labels: ["enhancement"]
-type: feature
body:
- type: markdown
attributes:
From be0caa1ee200030e2277edf20f11d5402e99ce97 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Mon, 4 May 2026 15:07:12 -0400
Subject: [PATCH 030/115] chore(license): change file format to fix preview
rendering issue
---
LICENSE.md => LICENSE | 0
packages/opencode-agents-loader/{LICENSE.md => LICENSE} | 0
packages/opencode-double-tap-timeline/{LICENSE.md => LICENSE} | 0
packages/opencode-output-styles/{LICENSE.md => LICENSE} | 0
4 files changed, 0 insertions(+), 0 deletions(-)
rename LICENSE.md => LICENSE (100%)
rename packages/opencode-agents-loader/{LICENSE.md => LICENSE} (100%)
rename packages/opencode-double-tap-timeline/{LICENSE.md => LICENSE} (100%)
rename packages/opencode-output-styles/{LICENSE.md => LICENSE} (100%)
diff --git a/LICENSE.md b/LICENSE
similarity index 100%
rename from LICENSE.md
rename to LICENSE
diff --git a/packages/opencode-agents-loader/LICENSE.md b/packages/opencode-agents-loader/LICENSE
similarity index 100%
rename from packages/opencode-agents-loader/LICENSE.md
rename to packages/opencode-agents-loader/LICENSE
diff --git a/packages/opencode-double-tap-timeline/LICENSE.md b/packages/opencode-double-tap-timeline/LICENSE
similarity index 100%
rename from packages/opencode-double-tap-timeline/LICENSE.md
rename to packages/opencode-double-tap-timeline/LICENSE
diff --git a/packages/opencode-output-styles/LICENSE.md b/packages/opencode-output-styles/LICENSE
similarity index 100%
rename from packages/opencode-output-styles/LICENSE.md
rename to packages/opencode-output-styles/LICENSE
From bc09a3633f1f8af827de9bd02211026a9c293e38 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 07:39:15 -0400
Subject: [PATCH 031/115] docs(github): refine issue templates and README
guidance
Separate brand-new plugin proposals from existing-plugin feature requests and update the README intake links accordingly.
---
.github/ISSUE_TEMPLATE/feature_request.yml | 21 ++++---
.../ISSUE_TEMPLATE/new_plugin_proposal.yml | 59 +++++++++++++++++++
README.md | 23 ++++----
3 files changed, 81 insertions(+), 22 deletions(-)
create mode 100644 .github/ISSUE_TEMPLATE/new_plugin_proposal.yml
diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml
index 7e7f8a4..553dbff 100644
--- a/.github/ISSUE_TEMPLATE/feature_request.yml
+++ b/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -1,12 +1,12 @@
name: Feature Request
-description: Suggest an idea for an existing plugin or this monorepo itself
+description: Suggest an enhancement for an existing plugin or this monorepo itself
title: "[Feature]: "
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
- Thanks for taking the time to suggest a feature!
+ Thanks for taking the time to suggest an enhancement!
- type: checkboxes
id: preflight
attributes:
@@ -14,7 +14,7 @@ body:
options:
- label: I have searched existing issues to avoid duplicates
required: true
- - label: I have checked the plugin's README for existing capabilities
+ - label: I have checked the relevant README for existing capabilities
required: true
- type: dropdown
id: plugin
@@ -27,25 +27,24 @@ body:
- opencode-double-tap-timeline
- opencode-output-styles
- opencode-plugins (this monorepo itself)
- - Other
validations:
required: true
- type: dropdown
id: request-type
attributes:
- label: Is your feature request related to a problem with the selected option above?
+ label: Is your request related to a problem or bug with the selected option?
options:
- "No — I have an idea for a new capability"
- - "Yes — something is broken, frustrating, or missing"
+ - "Yes — please open a bug report issue :)"
default: 0
validations:
required: true
- type: textarea
id: problem
attributes:
- label: If No — What would you like to see? || If Yes — What's the problem?
- description: Describe the new capability or enhancement you'd like added. || A clear and concise description of the issue you're facing.
- placeholder: I'd love to be able to... || I'm always frustrated when...
+ label: What would you like to see?
+ description: Describe the enhancement you'd like added.
+ placeholder: I'd love to be able to...
validations:
required: true
- type: textarea
@@ -59,12 +58,12 @@ body:
id: alternatives
attributes:
label: Describe alternatives you've considered
- description: A clear and concise description of any alternative solutions or features you've considered.
+ description: Share any other approaches, workarounds, plugins, and tools you considered.
- type: input
id: plugin-version
attributes:
label: Plugin Version
- description: What version of the plugin are you running?
+ description: What version of the plugin are you running? Leave blank if this is about the monorepo.
placeholder: e.g., 1.0.0
validations:
required: false
diff --git a/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml b/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml
new file mode 100644
index 0000000..1a6902e
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml
@@ -0,0 +1,59 @@
+name: New Plugin Proposal
+description: Propose a brand-new plugin for this monorepo
+title: "[Plugin]: "
+labels: ["enhancement"]
+body:
+ - type: markdown
+ attributes:
+ value: |
+ Thanks for taking the time to propose a new plugin idea.
+
+ You can keep this high-level, but if you want to sketch additional details, feel free to add them in the optional sections below or in a follow-up comment.
+ - type: checkboxes
+ id: preflight
+ attributes:
+ label: Pre-flight checklist
+ options:
+ - label: I have searched existing issues to avoid duplicates
+ required: true
+ - label: I have checked the README and existing plugin docs for overlap
+ required: true
+ - type: input
+ id: plugin-archetype
+ attributes:
+ label: Proposed plugin archetype
+ description: In a few words, what problem does this plugin solve?
+ placeholder: e.g., It solves ... in one prompt
+ validations:
+ required: true
+ - type: textarea
+ id: problem
+ attributes:
+ label: What problem does this plugin solve?
+ description: Describe the user pain point or workflow gap at a high level.
+ placeholder: I keep running into...
+ validations:
+ required: true
+ - type: textarea
+ id: idea
+ attributes:
+ label: Describe the plugin idea
+ description: Outline the core behavior you want. Keep it focused on the user experience.
+ placeholder: The plugin should...
+ validations:
+ required: true
+ - type: textarea
+ id: details
+ attributes:
+ label: Extra details & alternatives
+ description: Add any extra context, examples, constraints, related plugins, or likely hooks if you want to sketch the idea further. Share any other approaches, workarounds, plugins, and tools you considered.
+ placeholder: Potential integrations, edge cases, examples, notes...
+ validations:
+ required: false
+ - type: upload
+ id: mockups
+ attributes:
+ label: Upload mockups or examples
+ description: Add images or reference files to help illustrate your idea.
+ validations:
+ required: false
diff --git a/README.md b/README.md
index add2010..c3871d3 100644
--- a/README.md
+++ b/README.md
@@ -74,23 +74,24 @@ Every plugin here started because someone hit a wall with OpenCode and thought _
I usually browse through [Reddit](https://reddit.com/r/opencodecli) and the GitHub Issues section of the [OpenCode](https://github.com/anomalyco/opencode) repo, noticing people griping about their workflows. But if you've got a concrete idea and want to put it directly in front of me, I'm all ears :)
-↣ [GitHub Discussions](https://github.com/capybearista/opencode-plugins/discussions) for plugin brainstorms, OpenCode pain points, and "what if..." ideas.
+↣ Got a brand-new plugin idea? [Open a plugin proposal issue](https://github.com/capybearista/opencode-plugins/issues/new?template=new_plugin_proposal.yml).
-↣ Already using a plugin and something's off? Or maybe you've got an idea to enhance an existing plugin? [Open an issue](https://github.com/capybearista/opencode-plugins/issues).
+↣ Already using a plugin and something's off? Or maybe you've got an idea to enhance an existing plugin or the monorepo itself? [Open a feature request issue](https://github.com/capybearista/opencode-plugins/issues/new?template=feature_request.yml).
## Shoutouts
Plugins I've personally used and highly recommend! Some of these are genuinely underrated and have massive potential.
-| Name | Use case | Description |
-| -------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
-| [opencode-quota](https://github.com/slkiser/opencode-quota) | Keep track of your provider subscriptions _in_ OpenCode | Token usage and quota tracking for Anthropic, OpenAI, Copilot, and more—reports in terminal with zero context pollution. |
-| [opencode-snippets](https://github.com/JosXa/opencode-snippets) | Expand `#tags` into text anywhere, instantly | Hashtag-based snippet expansion. Just type `#name` to inject pre-defined code blocks, configs, or prompts inline. You can even put them in commands. |
-| [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning) | Caps token waste from stale context | Context-aware compression intelligently prunes old tool outputs to keep context lean and reduce token burn. |
-| [cc-safety-net](https://github.com/kenryu42/claude-code-safety-net) | Prevents dangerous commands like `rm -rf` and `git reset --hard` | Intercepts destructive git and filesystem commands before they execute, giving you a chance to abort before your agent deletes your entire project. |
-| [opencode-command-hooks](https://github.com/shanebishop1/opencode-command-hooks) | Run scripts on session events without writing a plugin | Declarative event hooks for shell commands via YAML/JSON. You can even attach scripts to lifecycle events like `tool.execute.after`. |
-| [opencode-agent-identity](https://github.com/gotgenes/opencode-agent-identity) | Distinguish which sub-agent said what in multi-agent sessions | Per-message attribution so each agent knows its role and which message came from which source. |
-| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Know when sessions finish without watching the terminal | Highly customizable desktop notifications and sounds for permission prompts, completion, and errors so you never miss a beat. |
+| Name | Use case | Description |
+| -------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| [opencode-quota](https://github.com/slkiser/opencode-quota) | Keep track of your provider subscriptions _in_ OpenCode | Token usage and quota tracking for Anthropic, OpenAI, Copilot, and more—reports in terminal with zero context pollution. |
+| [opencode-snippets](https://github.com/JosXa/opencode-snippets) | Expand `#tags` into text anywhere, instantly | Hashtag-based snippet expansion. Just type `#name` to inject pre-defined code blocks, configs, or prompts inline. You can even put them in commands. |
+| [opencode-dcp](https://github.com/Opencode-DCP/opencode-dynamic-context-pruning) | Caps token waste from stale context | Context-aware compression intelligently prunes old tool outputs to keep context lean and reduce token burn. |
+| [cc-safety-net](https://github.com/kenryu42/claude-code-safety-net) | Prevents dangerous commands like `rm -rf` and `git reset --hard` | Intercepts destructive git and filesystem commands before they execute, giving you a chance to abort before your agent deletes your entire project. |
+| [opencode-command-hooks](https://github.com/shanebishop1/opencode-command-hooks) | Run scripts on session events without writing a plugin | Declarative event hooks for shell commands via YAML/JSON. You can even attach scripts to lifecycle events like `tool.execute.after`. |
+| [opencode-agent-identity](https://github.com/gotgenes/opencode-agent-identity) | Distinguish which sub-agent said what in multi-agent sessions | Per-message attribution so each agent knows its role and which message came from which source. |
+| [opencode-mem](https://github.com/tickernelz/opencode-mem) | Retain long-term context across sessions | Persistent memory for AI coding agents with SQLite + USearch indexing, automatic user profile learning, and a visual web UI. It's even got a nice web UI to check stored memories! |
+| [opencode-notifier](https://github.com/mohak34/opencode-notifier) | Know when sessions finish without watching the terminal | Highly customizable desktop notifications and sounds for permission prompts, completion, and errors so you never miss a beat. |
## Development
From febecf415f9e2d6355c36102a40a0580cd8960f3 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 07:41:46 -0400
Subject: [PATCH 032/115] docs(issue-template): update placeholder
---
.github/ISSUE_TEMPLATE/new_plugin_proposal.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml b/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml
index 1a6902e..c05e41c 100644
--- a/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml
+++ b/.github/ISSUE_TEMPLATE/new_plugin_proposal.yml
@@ -23,7 +23,7 @@ body:
attributes:
label: Proposed plugin archetype
description: In a few words, what problem does this plugin solve?
- placeholder: e.g., It solves ... in one prompt
+ placeholder: e.g., It single-handedly achieves AGI...
validations:
required: true
- type: textarea
From c87d3bedd3fce3c2ee9f4d0260bdd833bf69e061 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 10:56:43 -0400
Subject: [PATCH 033/115] chore(readme): clean up and prettify
---
README.md | 13 +++++++----
packages/opencode-agents-loader/README.md | 21 +++++++++--------
.../opencode-double-tap-timeline/README.md | 23 +++++++------------
packages/opencode-output-styles/README.md | 23 +++++++++++--------
4 files changed, 42 insertions(+), 38 deletions(-)
diff --git a/README.md b/README.md
index c3871d3..5397481 100644
--- a/README.md
+++ b/README.md
@@ -9,10 +9,15 @@
-
-
+
+
+
+
+
+
+
-
A collection of plugins for the OpenCode AI coding agent. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
@@ -112,4 +117,4 @@ Please review the [contribution guidelines](./CONTRIBUTING.md) before contributi
## License
-[MPL-2.0](./LICENSE.md)
+[MPL-2.0](./LICENSE)
diff --git a/packages/opencode-agents-loader/README.md b/packages/opencode-agents-loader/README.md
index 82ead67..0045d17 100644
--- a/packages/opencode-agents-loader/README.md
+++ b/packages/opencode-agents-loader/README.md
@@ -2,10 +2,11 @@
Extend agent discovery to the .agents/ directory standard
-
-
-
-
+
+
+
+
---
@@ -101,10 +102,6 @@ Place agent markdown files in `agent/` or `agents/` subdirectories:
project-expert.md
```
-## Configuration
-
-This plugin requires no manual configuration. It works automatically by reading from `.agents/` directories.
-
### Precedence
Existing config entries from `.opencode/` directories always take precedence over `.agents/` entries. The plugin only injects entries that **do not already exist**.
@@ -117,11 +114,15 @@ Within `.agents/` directories, the closest directory to your project wins. Prece
4. `~/.config/opencode/` (global)
5. `~/.agents/` (global)
+## Configuration
+
+This plugin requires no manual configuration. It works automatically by reading from `.agents/` directories.
+
## Troubleshooting
- If commands or agents don't appear, verify your files end in `.md` and include valid YAML frontmatter
- Confirm the directory naming is `commands/` or `command/`, `agents/` or `agent/`
-- `.opencode/` entries always take priority — remove or rename conflicts there first
+- `.opencode/` entries always take priority—remove or rename conflicts there first
## Contributing
@@ -135,4 +136,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE.md)
+[MPL-2.0](LICENSE)
diff --git a/packages/opencode-double-tap-timeline/README.md b/packages/opencode-double-tap-timeline/README.md
index adcc400..b12aa80 100644
--- a/packages/opencode-double-tap-timeline/README.md
+++ b/packages/opencode-double-tap-timeline/README.md
@@ -2,10 +2,11 @@
Double-tap Escape to open the timeline modal
-
-
-
-
+
+
+
+
---
@@ -49,13 +50,6 @@ Add the plugin to `tui.json` or `tui.jsonc`:
}
```
-You can also install it through the CLI:
-
-```bash
-opencode plugin -g @capybearista/opencode-double-tap-timeline # global install
-opencode plugin @capybearista/opencode-double-tap-timeline # project-local install
-```
-
## Usage
1. Open a session in OpenCode
@@ -70,9 +64,8 @@ This plugin requires no manual configuration.
## Troubleshooting
-- If double-tap doesn't work, ensure you're in a session screen (not the home screen)
-- If a dialog is open, the timeline won't trigger — close any open dialogs first
-- The plugin uses OpenTUI's `useKeyboard` hook, which requires `@opentui/solid` installed
+- If double-tap doesn't work, ensure you're in a session screen (not the home screen with the opencode logo)
+- If a dialog is open, the timeline won't trigger. Close any open dialogs first
## Contributing
@@ -86,4 +79,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE.md)
+[MPL-2.0](LICENSE)
diff --git a/packages/opencode-output-styles/README.md b/packages/opencode-output-styles/README.md
index 385f660..f53a857 100644
--- a/packages/opencode-output-styles/README.md
+++ b/packages/opencode-output-styles/README.md
@@ -2,10 +2,11 @@
Reusable response styles for OpenCode sessions
-
-
-
-
+
+
+
+
---
@@ -31,7 +32,7 @@ src/
## Features
-- Ships built-in styles inspired by Claude Code (`explanatory`, `learning`) out of the box
+- Ships built-in styles *inspired* by Claude Code (`explanatory`, `learning`) out of the box
- Discovers global styles from `~/.config/opencode/output-styles/`
- Discovers project-local styles from `.opencode/output-styles/`
- Activates styles with `/output-style `
@@ -102,7 +103,7 @@ For example, to override `explanatory` with a custom version, create `~/.config/
| `/output-style ` | Activates the specified style |
| `/output-style clear` | Removes the active style |
-## Configuration
+### Contract
Style files support the following frontmatter:
@@ -125,11 +126,15 @@ The plugin also writes one project-local state file:
| --- | --- |
| `.opencode/active-style.json` | Stores the currently selected style id for the project. |
+## Configuration
+
+This plugin requires no manual configuration.
+
## Troubleshooting
- If `/output-style` shows no results, confirm your style files end in `.md` and include YAML frontmatter.
- If two styles share the same filename, the project-local version takes precedence over the global one, which takes precedence over the built-in.
-- The `/output-style` command currently uses a plugin API workaround that throws a handled error to short-circuit the command pipeline, because the plugin API does not yet expose a clean command short-circuit path.
+- The `/output-style` command currently uses a plugin API workaround that throws a handled error to short-circuit the command pipeline.
## Contributing
@@ -137,10 +142,10 @@ This package lives in the `opencode-plugins` monorepo.
- Run `bun run build`, `bun run typecheck`, `bun run lint`, and `bun test` before opening a PR.
- Keep the plugin focused on style discovery, persistence, and prompt appending.
-- Prefer small, direct changes over expanding the plugin into broader prompt-rewriting behavior.
+- Prefer small, direct changes.
Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE.md)
+[MPL-2.0](LICENSE)
From c3a0fd828f889e84a75a7aaa02cd557ac338eed9 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 11:21:07 -0400
Subject: [PATCH 034/115] chore(readme): fix opencode plugins badge
---
README.md | 3 +--
packages/opencode-agents-loader/README.md | 3 +--
packages/opencode-double-tap-timeline/README.md | 3 +--
packages/opencode-output-styles/README.md | 3 +--
4 files changed, 4 insertions(+), 8 deletions(-)
diff --git a/README.md b/README.md
index 5397481..073585e 100644
--- a/README.md
+++ b/README.md
@@ -11,8 +11,7 @@
From 3dcf158d0dd95876df2fecb55f4650dcb88ac22e Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 18:57:52 -0400
Subject: [PATCH 035/115] feat(new): init commit for opencode-ram-monitor
---
bun.lock | 25 ++
packages/opencode-ram-monitor/LICENSE | 373 ++++++++++++++++++
packages/opencode-ram-monitor/README.md | 69 ++++
packages/opencode-ram-monitor/bunfig.toml | 1 +
packages/opencode-ram-monitor/package.json | 45 +++
.../opencode-ram-monitor/src/index.test.ts | 22 ++
packages/opencode-ram-monitor/src/index.ts | 61 +++
packages/opencode-ram-monitor/src/memory.ts | 222 +++++++++++
packages/opencode-ram-monitor/src/tui.tsx | 42 ++
.../opencode-ram-monitor/tsconfig.build.json | 12 +
packages/opencode-ram-monitor/tsconfig.json | 12 +
11 files changed, 884 insertions(+)
create mode 100644 packages/opencode-ram-monitor/LICENSE
create mode 100644 packages/opencode-ram-monitor/README.md
create mode 100644 packages/opencode-ram-monitor/bunfig.toml
create mode 100644 packages/opencode-ram-monitor/package.json
create mode 100644 packages/opencode-ram-monitor/src/index.test.ts
create mode 100644 packages/opencode-ram-monitor/src/index.ts
create mode 100644 packages/opencode-ram-monitor/src/memory.ts
create mode 100644 packages/opencode-ram-monitor/src/tui.tsx
create mode 100644 packages/opencode-ram-monitor/tsconfig.build.json
create mode 100644 packages/opencode-ram-monitor/tsconfig.json
diff --git a/bun.lock b/bun.lock
index 360c3d9..4a12847 100644
--- a/bun.lock
+++ b/bun.lock
@@ -57,6 +57,25 @@
"@opencode-ai/plugin": ">=1.14.0",
},
},
+ "packages/opencode-ram-monitor": {
+ "name": "@capybearista/opencode-ram-monitor",
+ "version": "0.0.0",
+ "devDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0",
+ "@opentui/core": ">=0.1.0",
+ "@opentui/solid": ">=0.1.103",
+ "@tsconfig/node22": "^22.0.0",
+ "@types/bun": "latest",
+ "@types/node": "^25.6.0",
+ "solid-js": ">=1.9.0",
+ "typescript": "^5.8.0",
+ },
+ "peerDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0",
+ "@opentui/solid": ">=0.1.103",
+ "solid-js": ">=1.9.0",
+ },
+ },
},
"packages": {
"@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="],
@@ -143,6 +162,8 @@
"@capybearista/opencode-output-styles": ["@capybearista/opencode-output-styles@workspace:packages/opencode-output-styles"],
+ "@capybearista/opencode-ram-monitor": ["@capybearista/opencode-ram-monitor@workspace:packages/opencode-ram-monitor"],
+
"@changesets/apply-release-plan": ["@changesets/apply-release-plan@7.1.1", "", { "dependencies": { "@changesets/config": "^3.1.4", "@changesets/get-version-range-type": "^0.4.0", "@changesets/git": "^3.0.4", "@changesets/should-skip-package": "^0.1.2", "@changesets/types": "^6.1.0", "@manypkg/get-packages": "^1.1.3", "detect-indent": "^6.0.0", "fs-extra": "^7.0.1", "lodash.startcase": "^4.4.0", "outdent": "^0.5.0", "prettier": "^2.7.1", "resolve-from": "^5.0.0", "semver": "^7.5.3" } }, "sha512-9qPCm/rLx/xoOFXIHGB229+4GOL76S4MC+7tyOuTsR6+1jYlfFDQORdvwR5hDA6y4FL2BPt3qpbcQIS+dW85LA=="],
"@changesets/assemble-release-plan": ["@changesets/assemble-release-plan@6.0.10", "", { "dependencies": { "@changesets/errors": "^0.2.0", "@changesets/get-dependents-graph": "^2.1.4", "@changesets/should-skip-package": "^0.1.2", "@changesets/types": "^6.1.0", "@manypkg/get-packages": "^1.1.3", "semver": "^7.5.3" } }, "sha512-rSDcqdJ9KbVyjpBIuCidhvZNIiVt1XaIYp73ycVQRIA5n/j6wQaEk0ChRLMUQ1vkxZe51PTQ9OIhbg6HQMW45A=="],
@@ -271,6 +292,8 @@
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
+ "@tsconfig/node22": ["@tsconfig/node22@22.0.5", "", {}, "sha512-hLf2ld+sYN/BtOJjHUWOk568dvjFQkHnLNa6zce25GIH+vxKfvTgm3qpaH6ToF5tu/NN0IH66s+Bb5wElHrLcw=="],
+
"@turbo/darwin-64": ["@turbo/darwin-64@2.9.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-zU1P95ygDpsQ+2QHh7CVTqvYwi9UBlhKWzoIyUnP3vUoge7H9SQEzrd8dj+XcTrslAp9Db3vIBcXtMVoTEYDnA=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.9.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-nKRFI5ZhCGUi4eXNlrojzWcT/CehMj0raot1WE4lw5qf66ZxZHbRbBqcwNEy+ZLY7RkJJRY+TaU89fuj3BcgGg=="],
@@ -677,6 +700,8 @@
"@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+ "@capybearista/opencode-ram-monitor/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
"@changesets/parse/js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"@manypkg/find-root/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="],
diff --git a/packages/opencode-ram-monitor/LICENSE b/packages/opencode-ram-monitor/LICENSE
new file mode 100644
index 0000000..dbdb0fa
--- /dev/null
+++ b/packages/opencode-ram-monitor/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
\ No newline at end of file
diff --git a/packages/opencode-ram-monitor/README.md b/packages/opencode-ram-monitor/README.md
new file mode 100644
index 0000000..b47ae9b
--- /dev/null
+++ b/packages/opencode-ram-monitor/README.md
@@ -0,0 +1,69 @@
+# opencode-ram-monitor
+
+
Zero-dependency RAM monitoring for OpenCode sessions
+
+
+
+
+
+
+---
+
+## Why?
+
+> This plugin gives developers real-time, zero-dependency insights into the memory usage of all their active OpenCode sessions and child processes.
+
+## Philosophy: Extending OpenCode
+
+OpenCode is designed to be highly extensible. This plugin hooks into the OpenCode lifecycle to provide additional functionality seamlessly into your workflows.
+
+## Features
+
+
+
+## Install
+
+Add the plugin to `opencode.json` or `opencode.jsonc`:
+```json
+{
+ "plugin": ["@capybearista/opencode-ram-monitor"]
+}
+```
+
+Also, add the plugin to `tui.json` or `tui.jsonc`:
+```json
+{
+ "plugin": ["@capybearista/opencode-ram-monitor"]
+}
+```
+
+## Usage
+
+
+
+## Configuration
+
+
+
+## Troubleshooting
+
+
+
+## Contributing
+
+This package lives in the `opencode-plugins` monorepo.
+
+- Run `bun run build`, `bun run typecheck`, `bun run lint`, and `bun test` before opening a PR.
+- Keep the plugin focused on RAM monitoring logic.
+- Prefer small, direct changes.
+
+Please open an issue or check for existing ones before creating a pull request.
+
+## License
+
+[MPL-2.0](LICENSE)
\ No newline at end of file
diff --git a/packages/opencode-ram-monitor/bunfig.toml b/packages/opencode-ram-monitor/bunfig.toml
new file mode 100644
index 0000000..7693482
--- /dev/null
+++ b/packages/opencode-ram-monitor/bunfig.toml
@@ -0,0 +1 @@
+preload = ["@opentui/solid/preload"]
diff --git a/packages/opencode-ram-monitor/package.json b/packages/opencode-ram-monitor/package.json
new file mode 100644
index 0000000..955a4aa
--- /dev/null
+++ b/packages/opencode-ram-monitor/package.json
@@ -0,0 +1,45 @@
+{
+ "name": "@capybearista/opencode-ram-monitor",
+ "version": "0.0.0",
+ "description": "Monitor RAM usage of OpenCode sessions",
+ "author": "capyBearista ",
+ "license": "MPL-2.0",
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/index.ts --outdir=dist --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && [ -f dist/src/index.js ] && mv dist/src/index.js dist/index.js && rm -rf dist/src || true",
+ "typecheck": "tsc --noEmit",
+ "check": "bunx @biomejs/biome check --write .",
+ "lint": "bunx @biomejs/biome check .",
+ "ci": "bunx @biomejs/biome ci .",
+ "test": "bun test"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ },
+ "./tui": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ }
+ },
+ "peerDependencies": {
+ "@opencode-ai/plugin": ">=1.14.24",
+ "@opentui/solid": ">=0.1.103",
+ "solid-js": ">=1.9.0"
+ },
+ "devDependencies": {
+ "@opencode-ai/plugin": ">=1.14.24",
+ "@opentui/core": ">=0.1.103",
+ "@opentui/solid": ">=0.1.103",
+ "@types/bun": "latest",
+ "@types/node": "^25.6.0",
+ "solid-js": ">=1.9.0",
+ "typescript": "^5.8.0"
+ }
+}
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
new file mode 100644
index 0000000..bbd0f35
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -0,0 +1,22 @@
+import "@opentui/solid/preload";
+import { describe, expect, test } from "bun:test";
+import plugin from "./index.js";
+
+describe("@capybearista/opencode-ram-monitor", () => {
+ test("has an id", () => {
+ expect(plugin.id).toBeString();
+ expect(plugin.id).toBe("capybearista.opencode-ram-monitor");
+ });
+
+ test("exports a default object", () => {
+ expect(plugin).toBeObject();
+ });
+
+ test("exports server hooks", () => {
+ expect(plugin.server).toBeFunction();
+ });
+
+ test("exports tui hooks", () => {
+ expect(plugin.tui).toBeFunction();
+ });
+});
diff --git a/packages/opencode-ram-monitor/src/index.ts b/packages/opencode-ram-monitor/src/index.ts
new file mode 100644
index 0000000..52a67b7
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/index.ts
@@ -0,0 +1,61 @@
+import type { Plugin } from "@opencode-ai/plugin";
+import type { TuiPlugin } from "@opencode-ai/plugin/tui";
+import { getHeavyProcessTree } from "./memory.js";
+
+export const RamMonitorPlugin: Plugin = async (ctx) => {
+ return {
+ config: async (opencodeConfig) => {
+ opencodeConfig.command ??= {};
+ opencodeConfig.command.ram = {
+ template: "",
+ description: "Show a detailed process tree and RAM usage",
+ };
+ },
+ "command.execute.before": async (input) => {
+ if (input.command !== "ram") return;
+
+ let treeText: string;
+ try {
+ treeText = await getHeavyProcessTree();
+ } catch {
+ treeText = "Unable to generate RAM usage tree. Please try again.";
+ }
+
+ try {
+ await ctx.client.session.prompt({
+ path: { id: input.sessionID },
+ body: {
+ noReply: true,
+ parts: [
+ {
+ type: "text",
+ text: treeText,
+ ignored: true,
+ },
+ ],
+ },
+ });
+ } catch {
+ // swallow prompt errors
+ }
+
+ throw new Error("__STYLE_COMMAND_HANDLED__");
+ },
+ };
+};
+
+export const tui: TuiPlugin = async (api) => {
+ const { RamWidget } = await import("./tui.js");
+ api.slots.register({
+ slots: {
+ home_footer: RamWidget,
+ sidebar_footer: RamWidget,
+ },
+ });
+};
+
+export default {
+ id: "capybearista.opencode-ram-monitor",
+ server: RamMonitorPlugin,
+ tui,
+};
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
new file mode 100644
index 0000000..5f0de2e
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -0,0 +1,222 @@
+import { exec } from "node:child_process";
+import { readdir, readFile } from "node:fs/promises";
+import { homedir, platform } from "node:os";
+import { join } from "node:path";
+import { promisify } from "node:util";
+
+const EXEC_OPTS = { timeout: 5000, windowsHide: true };
+const execAsync = promisify(exec);
+
+export async function getActiveSessions(): Promise {
+ const pids: number[] = [process.pid]; // Always include current process
+ const stateDirs = [
+ join(homedir(), ".opencode", "state"),
+ join(homedir(), ".cache", "opencode", "state"), // Fallback
+ ];
+
+ for (const dir of stateDirs) {
+ try {
+ const files = await readdir(dir);
+ for (const file of files) {
+ if (file.endsWith(".lock")) {
+ const content = await readFile(join(dir, file), "utf-8");
+ try {
+ const data = JSON.parse(content);
+ if (data.pid && typeof data.pid === "number") {
+ pids.push(data.pid);
+ }
+ } catch {
+ // fallback: maybe the filename has PID or the lockfile is just the PID
+ const pid = parseInt(content.trim(), 10);
+ if (!Number.isNaN(pid)) {
+ pids.push(pid);
+ }
+ }
+ }
+ }
+ } catch {
+ // Directory doesn't exist or is unreadable, ignore
+ }
+ }
+
+ // Deduplicate PIDs
+ return [...new Set(pids)];
+}
+
+export async function getLightweightRam(): Promise {
+ const pids = await getActiveSessions();
+ if (pids.length === 0) return 0;
+
+ const osPlatform = platform();
+ let totalRss = 0;
+
+ if (osPlatform === "linux") {
+ // Fast path for Linux/WSL - read VmRSS from /proc//status (kB)
+ for (const pid of pids) {
+ try {
+ const status = await readFile(`/proc/${pid}/status`, "utf-8");
+ const match = status.match(/VmRSS:\s+(\d+)\s+kB/);
+ if (match) {
+ totalRss += parseInt(match[1], 10) * 1024;
+ }
+ } catch {
+ // Process might have exited or permission denied
+ }
+ }
+ } else if (osPlatform === "darwin") {
+ // macOS: query each PID individually to avoid total failure if one PID is stale
+ for (const pid of pids) {
+ try {
+ const { stdout } = await execAsync(`ps -o rss= -p ${pid}`, EXEC_OPTS);
+ const rssKb = parseInt(stdout.trim(), 10);
+ if (!Number.isNaN(rssKb)) totalRss += rssKb * 1024;
+ } catch {
+ // Process might have exited
+ }
+ }
+ } else if (osPlatform === "win32") {
+ // Windows: query each PID individually for reliability
+ for (const pid of pids) {
+ try {
+ const { stdout } = await execAsync(
+ `wmic process where "ProcessId=${pid}" get WorkingSetSize`,
+ );
+ const lines = stdout.trim().split("\n").slice(1); // skip header
+ for (const line of lines) {
+ const rssBytes = parseInt(line.trim(), 10);
+ if (!Number.isNaN(rssBytes)) totalRss += rssBytes;
+ }
+ } catch {
+ // Process might have exited
+ }
+ }
+ } else {
+ // Fallback: just current process
+ totalRss = process.memoryUsage().rss;
+ }
+
+ return totalRss;
+}
+
+export interface ProcessNode {
+ pid: number;
+ ppid: number;
+ rss: number; // bytes
+ command: string;
+ children: ProcessNode[];
+}
+
+export async function getHeavyProcessTree(): Promise {
+ const pids = await getActiveSessions();
+ const osPlatform = platform();
+
+ let processes: ProcessNode[] = [];
+
+ if (osPlatform === "linux" || osPlatform === "darwin") {
+ try {
+ // Get all processes to build tree
+ const { stdout } = await execAsync(`ps -e -o pid=,ppid=,rss=,comm=`, EXEC_OPTS);
+ const lines = stdout.trim().split("\n");
+ processes = lines
+ .map((line) => {
+ const parts = line.trim().split(/\s+/);
+ const pid = parseInt(parts[0], 10);
+ const ppid = parseInt(parts[1], 10);
+ const rss = parseInt(parts[2], 10) * 1024; // KB to Bytes
+ const command = parts.slice(3).join(" ");
+ return { pid, ppid, rss, command, children: [] };
+ })
+ .filter((p) => !Number.isNaN(p.pid));
+ } catch {
+ // Error running ps
+ }
+ } else if (osPlatform === "win32") {
+ try {
+ // Use VALUE format (Key=Value pairs) to avoid CSV comma issues
+ const { stdout } = await execAsync(
+ `wmic process get Name,ParentProcessId,ProcessId,WorkingSetSize /format:value`,
+ EXEC_OPTS,
+ );
+ const normalized = stdout.replace(/\r\n/g, "\n").trim();
+ const blocks = normalized.split(/\n\n/);
+
+ for (const block of blocks) {
+ const lines = block.trim().split("\n");
+ const entry: Record = {};
+ for (const line of lines) {
+ const eq = line.indexOf("=");
+ if (eq !== -1) {
+ const key = line.slice(0, eq).trim();
+ const value = line.slice(eq + 1).trim();
+ entry[key] = value;
+ }
+ }
+ const pid = parseInt(entry.ProcessId, 10);
+ const ppid = parseInt(entry.ParentProcessId, 10);
+ const rss = parseInt(entry.WorkingSetSize, 10);
+ const command = entry.Name || "";
+ if (!Number.isNaN(pid)) {
+ processes.push({ pid, ppid, rss, command, children: [] });
+ }
+ }
+ } catch {
+ // Error
+ }
+ }
+
+ // Build tree
+ const procMap = new Map();
+ for (const p of processes) {
+ procMap.set(p.pid, p);
+ }
+
+ for (const p of processes) {
+ if (procMap.has(p.ppid)) {
+ procMap.get(p.ppid)?.children.push(p);
+ }
+ }
+
+ const rootPids = new Set(pids);
+ const targetRoots = processes.filter((p) => rootPids.has(p.pid));
+
+ if (targetRoots.length === 0) {
+ // Fallback if ps parsing failed or OS is unsupported
+ return `### OpenCode RAM Usage Tree\n\nNo detailed process tree could be generated. Current process PID is ${process.pid}.`;
+ }
+
+ let markdown = "### OpenCode RAM Usage Tree\n\n";
+
+ const formatSize = (bytes: number) => {
+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
+ };
+
+ const buildTreeString = (node: ProcessNode, prefix: string, isLast: boolean): string => {
+ let result = `${prefix}${isLast ? "└──" : "├──"} [${node.command}] (PID ${node.pid}) - ${formatSize(node.rss)}\n`;
+
+ const childPrefix = prefix + (isLast ? " " : "│ ");
+ for (let i = 0; i < node.children.length; i++) {
+ result += buildTreeString(node.children[i], childPrefix, i === node.children.length - 1);
+ }
+ return result;
+ };
+
+ const getTreeSum = (node: ProcessNode): number => {
+ return node.rss + node.children.reduce((acc, child) => acc + getTreeSum(child), 0);
+ };
+
+ for (const root of targetRoots) {
+ const totalMem = getTreeSum(root);
+ markdown += `**Session (PID ${root.pid}) - Total: ${formatSize(totalMem)}**\n`;
+ markdown += `\`\`\`text\n`;
+ markdown += buildTreeString(root, "", true);
+ markdown += `\`\`\`\n\n`;
+ }
+
+ return markdown.trim();
+}
+
+export function formatBytes(bytes: number): string {
+ if (bytes === 0) return "0 MB";
+ const mb = bytes / 1024 / 1024;
+ return `${mb.toFixed(1)} MB`;
+}
diff --git a/packages/opencode-ram-monitor/src/tui.tsx b/packages/opencode-ram-monitor/src/tui.tsx
new file mode 100644
index 0000000..ab913db
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/tui.tsx
@@ -0,0 +1,42 @@
+import { createElement, createTextNode, insert, insertNode } from "@opentui/solid";
+import { createSignal, onCleanup, onMount } from "solid-js";
+import { formatBytes, getLightweightRam } from "./memory.js";
+
+// biome-ignore lint/suspicious/noExplicitAny: TUI slot types are too restrictive
+export function RamWidget(): any {
+ const [ram, setRam] = createSignal(0);
+
+ onMount(() => {
+ let timeout: ReturnType | undefined;
+ let disposed = false;
+
+ const poll = async () => {
+ try {
+ const currentRam = await getLightweightRam();
+ if (!disposed) setRam(currentRam);
+ } catch {
+ // Ignore transient errors (e.g. permission denied on /proc)
+ }
+
+ if (!disposed) {
+ timeout = setTimeout(poll, 3000);
+ }
+ };
+
+ void poll();
+
+ onCleanup(() => {
+ disposed = true;
+ if (timeout) clearTimeout(timeout);
+ });
+ });
+
+ // Manually construct the TUI element to avoid JSX transformation issues
+ return (() => {
+ const el = createElement("span");
+ const textNode = createTextNode("RAM: ");
+ insertNode(el, textNode);
+ insert(el, () => formatBytes(ram()), null);
+ return el;
+ })();
+}
diff --git a/packages/opencode-ram-monitor/tsconfig.build.json b/packages/opencode-ram-monitor/tsconfig.build.json
new file mode 100644
index 0000000..b4f0389
--- /dev/null
+++ b/packages/opencode-ram-monitor/tsconfig.build.json
@@ -0,0 +1,12 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "jsx": "preserve",
+ "noImplicitAny": false,
+ "types": ["bun"]
+ },
+ "include": ["src"],
+ "exclude": ["dist", "node_modules", "src/**/*.test.ts"]
+}
diff --git a/packages/opencode-ram-monitor/tsconfig.json b/packages/opencode-ram-monitor/tsconfig.json
new file mode 100644
index 0000000..3886f22
--- /dev/null
+++ b/packages/opencode-ram-monitor/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "extends": "../../tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "outDir": "dist",
+ "jsx": "preserve",
+ "jsxImportSource": "@opentui/solid",
+ "types": ["bun"]
+ },
+ "include": ["src"],
+ "exclude": ["dist", "node_modules", "src/**/*.test.ts"]
+}
From 358761e9fae32a0dbb92d855cf8cb8de8d4a9c9e Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Tue, 5 May 2026 18:59:08 -0400
Subject: [PATCH 036/115] docs(readme): remove quick start section and update
plugin names
---
README.md | 15 +++------------
1 file changed, 3 insertions(+), 12 deletions(-)
diff --git a/README.md b/README.md
index 073585e..4d674a2 100644
--- a/README.md
+++ b/README.md
@@ -21,26 +21,17 @@
A collection of plugins for the OpenCode AI coding agent. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
-## Quick Start
-
-```sh
-opencode plugin add -g \
-@capybearista/opencode-output-styles \
-@capybearista/opencode-agents-loader \
-@capybearista/opencode-double-tap-timeline
-```
-
## Meet The Plugins
-### 🗣️ [@capybearista/opencode-output-styles](./packages/opencode-output-styles/)
+### 🗣️ [opencode-output-styles](./packages/opencode-output-styles/)
Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
-### 🛠️ [@capybearista/opencode-agents-loader](./packages/opencode-agents-loader/)
+### 🛠️ [opencode-agents-loader](./packages/opencode-agents-loader/)
Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
-### ⏱️ [@capybearista/opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
+### ⏱️ [opencode-double-tap-timeline](./packages/opencode-double-tap-timeline/)
A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse.
From 4c424e409dc417f58d6d20959af4aae69b8fde33 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 02:00:17 -0400
Subject: [PATCH 037/115] feat(ram-monitor): overhaul architecture and add
multi-session tracking
- Split plugin into server/tui modules for OpenCode compatibility
- Implement live process-based session discovery in memory.ts
- Add configurable sidebar widget with current and total RAM metrics
- Address startup deadlock by deferring async config loading
---
packages/opencode-ram-monitor/package.json | 22 +++-
.../opencode-ram-monitor/src/index.test.ts | 14 +-
packages/opencode-ram-monitor/src/index.ts | 62 +--------
packages/opencode-ram-monitor/src/memory.ts | 123 ++++++++++++++++--
packages/opencode-ram-monitor/src/server.ts | 52 ++++++++
packages/opencode-ram-monitor/src/sidebar.tsx | 93 +++++++++++++
packages/opencode-ram-monitor/src/tui.tsx | 42 ------
7 files changed, 275 insertions(+), 133 deletions(-)
create mode 100644 packages/opencode-ram-monitor/src/server.ts
create mode 100644 packages/opencode-ram-monitor/src/sidebar.tsx
delete mode 100644 packages/opencode-ram-monitor/src/tui.tsx
diff --git a/packages/opencode-ram-monitor/package.json b/packages/opencode-ram-monitor/package.json
index 955a4aa..ca30776 100644
--- a/packages/opencode-ram-monitor/package.json
+++ b/packages/opencode-ram-monitor/package.json
@@ -5,13 +5,13 @@
"author": "capyBearista ",
"license": "MPL-2.0",
"type": "module",
- "main": "./dist/index.js",
- "types": "./dist/index.d.ts",
+ "main": "./dist/server.js",
+ "types": "./dist/server.d.ts",
"files": [
"dist"
],
"scripts": {
- "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/index.ts --outdir=dist --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && [ -f dist/src/index.js ] && mv dist/src/index.js dist/index.js && rm -rf dist/src || true",
+ "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/server.ts --outfile=dist/server.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && bun build src/memory.ts --outfile=dist/memory.js --target=bun && cp src/sidebar.tsx dist/sidebar.tsx",
"typecheck": "tsc --noEmit",
"check": "bunx @biomejs/biome check --write .",
"lint": "bunx @biomejs/biome check .",
@@ -20,14 +20,22 @@
},
"exports": {
".": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
+ "types": "./dist/server.d.ts",
+ "default": "./dist/server.js"
+ },
+ "./server": {
+ "types": "./dist/server.d.ts",
+ "default": "./dist/server.js"
},
"./tui": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
+ "types": "./dist/sidebar.d.ts",
+ "default": "./dist/sidebar.tsx"
}
},
+ "oc-plugin": [
+ "server",
+ "tui"
+ ],
"peerDependencies": {
"@opencode-ai/plugin": ">=1.14.24",
"@opentui/solid": ">=0.1.103",
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
index bbd0f35..5b11772 100644
--- a/packages/opencode-ram-monitor/src/index.test.ts
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -1,22 +1,18 @@
import "@opentui/solid/preload";
import { describe, expect, test } from "bun:test";
-import plugin from "./index.js";
+import serverModule from "./server.js";
describe("@capybearista/opencode-ram-monitor", () => {
test("has an id", () => {
- expect(plugin.id).toBeString();
- expect(plugin.id).toBe("capybearista.opencode-ram-monitor");
+ expect(serverModule.id).toBeString();
+ expect(serverModule.id).toBe("capybearista.opencode-ram-monitor");
});
test("exports a default object", () => {
- expect(plugin).toBeObject();
+ expect(serverModule).toBeObject();
});
test("exports server hooks", () => {
- expect(plugin.server).toBeFunction();
- });
-
- test("exports tui hooks", () => {
- expect(plugin.tui).toBeFunction();
+ expect(serverModule.server).toBeFunction();
});
});
diff --git a/packages/opencode-ram-monitor/src/index.ts b/packages/opencode-ram-monitor/src/index.ts
index 52a67b7..5f3a71f 100644
--- a/packages/opencode-ram-monitor/src/index.ts
+++ b/packages/opencode-ram-monitor/src/index.ts
@@ -1,61 +1 @@
-import type { Plugin } from "@opencode-ai/plugin";
-import type { TuiPlugin } from "@opencode-ai/plugin/tui";
-import { getHeavyProcessTree } from "./memory.js";
-
-export const RamMonitorPlugin: Plugin = async (ctx) => {
- return {
- config: async (opencodeConfig) => {
- opencodeConfig.command ??= {};
- opencodeConfig.command.ram = {
- template: "",
- description: "Show a detailed process tree and RAM usage",
- };
- },
- "command.execute.before": async (input) => {
- if (input.command !== "ram") return;
-
- let treeText: string;
- try {
- treeText = await getHeavyProcessTree();
- } catch {
- treeText = "Unable to generate RAM usage tree. Please try again.";
- }
-
- try {
- await ctx.client.session.prompt({
- path: { id: input.sessionID },
- body: {
- noReply: true,
- parts: [
- {
- type: "text",
- text: treeText,
- ignored: true,
- },
- ],
- },
- });
- } catch {
- // swallow prompt errors
- }
-
- throw new Error("__STYLE_COMMAND_HANDLED__");
- },
- };
-};
-
-export const tui: TuiPlugin = async (api) => {
- const { RamWidget } = await import("./tui.js");
- api.slots.register({
- slots: {
- home_footer: RamWidget,
- sidebar_footer: RamWidget,
- },
- });
-};
-
-export default {
- id: "capybearista.opencode-ram-monitor",
- server: RamMonitorPlugin,
- tui,
-};
+export { default } from "./server.js";
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
index 5f0de2e..72b21f1 100644
--- a/packages/opencode-ram-monitor/src/memory.ts
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -7,11 +7,82 @@ import { promisify } from "node:util";
const EXEC_OPTS = { timeout: 5000, windowsHide: true };
const execAsync = promisify(exec);
+async function getRuntimeSessionPids(): Promise {
+ const osPlatform = platform();
+
+ if (osPlatform === "linux" || osPlatform === "darwin") {
+ try {
+ const { stdout } = await execAsync("ps -eo pid=,args=", EXEC_OPTS);
+ const corePids: number[] = [];
+ const launcherPids: number[] = [];
+
+ for (const line of stdout.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ const firstSpace = trimmed.indexOf(" ");
+ if (firstSpace === -1) continue;
+
+ const pid = parseInt(trimmed.slice(0, firstSpace), 10);
+ if (Number.isNaN(pid)) continue;
+
+ const args = trimmed.slice(firstSpace + 1).toLowerCase();
+ if (args.includes("/bin/.opencode")) {
+ corePids.push(pid);
+ } else if (args.includes("/bin/opencode")) {
+ launcherPids.push(pid);
+ }
+ }
+
+ return corePids.length > 0 ? corePids : launcherPids;
+ } catch {
+ return [];
+ }
+ }
+
+ if (osPlatform === "win32") {
+ try {
+ const { stdout } = await execAsync(
+ "wmic process get ProcessId,CommandLine /format:csv",
+ EXEC_OPTS,
+ );
+ const corePids: number[] = [];
+ const launcherPids: number[] = [];
+
+ for (const line of stdout.replace(/\r\n/g, "\n").split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed?.includes(",")) continue;
+
+ const columns = trimmed.split(",");
+ if (columns.length < 3) continue;
+
+ const pid = parseInt(columns[columns.length - 1], 10);
+ if (Number.isNaN(pid)) continue;
+
+ const commandLine = columns.slice(1, -1).join(",").toLowerCase();
+ if (commandLine.includes("\\.opencode")) {
+ corePids.push(pid);
+ } else if (commandLine.includes("\\opencode") || commandLine.includes("/opencode")) {
+ launcherPids.push(pid);
+ }
+ }
+
+ return corePids.length > 0 ? corePids : launcherPids;
+ } catch {
+ return [];
+ }
+ }
+
+ return [];
+}
+
export async function getActiveSessions(): Promise {
- const pids: number[] = [process.pid]; // Always include current process
+ const pids: number[] = [process.pid];
const stateDirs = [
join(homedir(), ".opencode", "state"),
- join(homedir(), ".cache", "opencode", "state"), // Fallback
+ join(homedir(), ".cache", "opencode", "state"),
+ join(homedir(), ".local", "state", "opencode"),
+ join(homedir(), ".local", "state", "opencode", "locks"),
];
for (const dir of stateDirs) {
@@ -26,7 +97,6 @@ export async function getActiveSessions(): Promise {
pids.push(data.pid);
}
} catch {
- // fallback: maybe the filename has PID or the lockfile is just the PID
const pid = parseInt(content.trim(), 10);
if (!Number.isNaN(pid)) {
pids.push(pid);
@@ -34,21 +104,28 @@ export async function getActiveSessions(): Promise {
}
}
}
- } catch {
- // Directory doesn't exist or is unreadable, ignore
- }
+ } catch {}
}
- // Deduplicate PIDs
+ const runtimePids = await getRuntimeSessionPids();
+ pids.push(...runtimePids);
+
return [...new Set(pids)];
}
-export async function getLightweightRam(): Promise {
+export interface LightweightRamResult {
+ current: number;
+ total: number;
+ count: number;
+}
+
+export async function getLightweightRam(): Promise {
const pids = await getActiveSessions();
- if (pids.length === 0) return 0;
+ if (pids.length === 0) return { current: 0, total: 0, count: 0 };
const osPlatform = platform();
let totalRss = 0;
+ let currentRss = 0;
if (osPlatform === "linux") {
// Fast path for Linux/WSL - read VmRSS from /proc//status (kB)
@@ -57,7 +134,9 @@ export async function getLightweightRam(): Promise {
const status = await readFile(`/proc/${pid}/status`, "utf-8");
const match = status.match(/VmRSS:\s+(\d+)\s+kB/);
if (match) {
- totalRss += parseInt(match[1], 10) * 1024;
+ const rss = parseInt(match[1], 10) * 1024;
+ totalRss += rss;
+ if (pid === process.pid) currentRss = rss;
}
} catch {
// Process might have exited or permission denied
@@ -69,7 +148,11 @@ export async function getLightweightRam(): Promise {
try {
const { stdout } = await execAsync(`ps -o rss= -p ${pid}`, EXEC_OPTS);
const rssKb = parseInt(stdout.trim(), 10);
- if (!Number.isNaN(rssKb)) totalRss += rssKb * 1024;
+ if (!Number.isNaN(rssKb)) {
+ const rss = rssKb * 1024;
+ totalRss += rss;
+ if (pid === process.pid) currentRss = rss;
+ }
} catch {
// Process might have exited
}
@@ -84,7 +167,10 @@ export async function getLightweightRam(): Promise {
const lines = stdout.trim().split("\n").slice(1); // skip header
for (const line of lines) {
const rssBytes = parseInt(line.trim(), 10);
- if (!Number.isNaN(rssBytes)) totalRss += rssBytes;
+ if (!Number.isNaN(rssBytes)) {
+ totalRss += rssBytes;
+ if (pid === process.pid) currentRss = rssBytes;
+ }
}
} catch {
// Process might have exited
@@ -92,10 +178,19 @@ export async function getLightweightRam(): Promise {
}
} else {
// Fallback: just current process
- totalRss = process.memoryUsage().rss;
+ currentRss = process.memoryUsage().rss;
+ totalRss = currentRss;
}
- return totalRss;
+ if (currentRss === 0 && totalRss > 0) {
+ currentRss = process.memoryUsage().rss;
+ }
+
+ return {
+ current: currentRss,
+ total: totalRss,
+ count: pids.length,
+ };
}
export interface ProcessNode {
diff --git a/packages/opencode-ram-monitor/src/server.ts b/packages/opencode-ram-monitor/src/server.ts
new file mode 100644
index 0000000..e3efd74
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/server.ts
@@ -0,0 +1,52 @@
+import type { Plugin } from "@opencode-ai/plugin";
+import { getHeavyProcessTree } from "./memory.js";
+
+const COMMAND_HANDLED_SENTINEL = "__RAM_COMMAND_HANDLED__";
+
+function handled(): never {
+ throw new Error(COMMAND_HANDLED_SENTINEL);
+}
+
+const RamMonitorServer: Plugin = async ({ client }) => {
+ async function injectRawOutput(sessionID: string, output: string): Promise {
+ try {
+ await client.session.prompt({
+ path: { id: sessionID },
+ body: {
+ noReply: true,
+ parts: [{ type: "text", text: output, ignored: true }],
+ },
+ });
+ } catch {
+ // swallow prompt errors
+ }
+ }
+
+ return {
+ config: async (cfg) => {
+ cfg.command ??= {};
+ cfg.command.ram = {
+ template: "",
+ description: "Show a detailed process tree and RAM usage",
+ };
+ },
+ "command.execute.before": async (input, _output) => {
+ if (input.command !== "ram") return;
+
+ let treeText: string;
+ try {
+ treeText = await getHeavyProcessTree();
+ } catch {
+ treeText = "Unable to generate RAM usage tree. Please try again.";
+ }
+
+ await injectRawOutput(input.sessionID, treeText);
+ handled();
+ },
+ };
+};
+
+export default {
+ id: "capybearista.opencode-ram-monitor",
+ server: RamMonitorServer,
+};
diff --git a/packages/opencode-ram-monitor/src/sidebar.tsx b/packages/opencode-ram-monitor/src/sidebar.tsx
new file mode 100644
index 0000000..80ea092
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/sidebar.tsx
@@ -0,0 +1,93 @@
+/** @jsxImportSource @opentui/solid */
+import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
+import { createSignal, onCleanup } from "solid-js";
+import { formatBytes, getLightweightRam, type LightweightRamResult } from "./memory.js";
+
+function RamWidget(props: { api: TuiPluginApi }) {
+ const [ram, setRam] = createSignal({ current: 0, total: 0, count: 0 });
+ const [error, setError] = createSignal(null);
+ const [intervalMs, setIntervalMs] = createSignal(5000);
+
+ let disposed = false;
+ let timeout: ReturnType | undefined;
+
+ // Fetch config once on mount
+ const loadConfig = async () => {
+ try {
+ const response = await props.api.client.config.get();
+ const rawConfig = (
+ response.data as unknown as { experimental?: { ramMonitor?: Record } }
+ )?.experimental?.ramMonitor;
+ if (rawConfig?.refreshIntervalMs) {
+ setIntervalMs(Number(rawConfig.refreshIntervalMs) || 5000);
+ }
+ } catch {
+ // fallback to 5000
+ }
+ };
+ void loadConfig();
+
+ const poll = async () => {
+ try {
+ const currentRam = await getLightweightRam();
+ if (!disposed) {
+ setRam(currentRam);
+ setError(null);
+ }
+ } catch (err: unknown) {
+ if (!disposed) {
+ setError((err as Error).message || "RAM error");
+ console.error("RAM Monitor Poll Error:", err);
+ }
+ }
+
+ if (!disposed) {
+ timeout = setTimeout(poll, intervalMs());
+ }
+ };
+
+ void poll();
+
+ onCleanup(() => {
+ disposed = true;
+ if (timeout) clearTimeout(timeout);
+ });
+
+ return (
+
+
+ RAM Usage
+
+
+ {error() ? `Error: ${error()}` : `Current: ${formatBytes(ram().current)}`}
+
+ {!error() && ram().count > 0 && (
+
+ {`Total: ${formatBytes(ram().total)} (${ram().count} active)`}
+
+ )}
+
+ );
+}
+
+const SIDEBAR_ORDER = 150;
+
+const tui: TuiPlugin = async (api) => {
+ console.log("RamMonitor TUI plugin loading with ID: capybearista.opencode-ram-monitor");
+
+ api.slots.register({
+ order: SIDEBAR_ORDER,
+ slots: {
+ sidebar_content() {
+ return ;
+ },
+ },
+ });
+};
+
+const pluginModule: TuiPluginModule & { id: string } = {
+ id: "capybearista.opencode-ram-monitor",
+ tui,
+};
+
+export default pluginModule;
diff --git a/packages/opencode-ram-monitor/src/tui.tsx b/packages/opencode-ram-monitor/src/tui.tsx
deleted file mode 100644
index ab913db..0000000
--- a/packages/opencode-ram-monitor/src/tui.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { createElement, createTextNode, insert, insertNode } from "@opentui/solid";
-import { createSignal, onCleanup, onMount } from "solid-js";
-import { formatBytes, getLightweightRam } from "./memory.js";
-
-// biome-ignore lint/suspicious/noExplicitAny: TUI slot types are too restrictive
-export function RamWidget(): any {
- const [ram, setRam] = createSignal(0);
-
- onMount(() => {
- let timeout: ReturnType | undefined;
- let disposed = false;
-
- const poll = async () => {
- try {
- const currentRam = await getLightweightRam();
- if (!disposed) setRam(currentRam);
- } catch {
- // Ignore transient errors (e.g. permission denied on /proc)
- }
-
- if (!disposed) {
- timeout = setTimeout(poll, 3000);
- }
- };
-
- void poll();
-
- onCleanup(() => {
- disposed = true;
- if (timeout) clearTimeout(timeout);
- });
- });
-
- // Manually construct the TUI element to avoid JSX transformation issues
- return (() => {
- const el = createElement("span");
- const textNode = createTextNode("RAM: ");
- insertNode(el, textNode);
- insert(el, () => formatBytes(ram()), null);
- return el;
- })();
-}
From 441a5f0a4d384b14295ddd4526a75a54f5ebf954 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 03:31:49 -0400
Subject: [PATCH 038/115] feat(ram-monitor): overhaul with config support and
multi-session tracking
- Added refreshIntervalMs configuration support via .opencode/opencode.json
- Implemented real-time PID discovery for active OpenCode sessions
- Hardened process classification to prevent false positives using token-based matching
- Added cycle protection and timeout safety for process tree generation
- Cleaned up TUI lifecycle and removed debug logs
---
packages/opencode-ram-monitor/README.md | 49 +++++-
packages/opencode-ram-monitor/package.json | 2 +-
.../opencode-ram-monitor/src/index.test.ts | 40 +++++
packages/opencode-ram-monitor/src/memory.ts | 162 ++++++++++++++----
.../src/sidebar-config.ts | 19 ++
packages/opencode-ram-monitor/src/sidebar.tsx | 51 ++++--
6 files changed, 270 insertions(+), 53 deletions(-)
create mode 100644 packages/opencode-ram-monitor/src/sidebar-config.ts
diff --git a/packages/opencode-ram-monitor/README.md b/packages/opencode-ram-monitor/README.md
index b47ae9b..1f1bbd0 100644
--- a/packages/opencode-ram-monitor/README.md
+++ b/packages/opencode-ram-monitor/README.md
@@ -16,15 +16,33 @@
## Philosophy: Extending OpenCode
-OpenCode is designed to be highly extensible. This plugin hooks into the OpenCode lifecycle to provide additional functionality seamlessly into your workflows.
+```text
+Host Architecture
+├── Server Plugin (src/server.ts)
+│ ├── command.execute.before hook
+│ │ └── Intercepts `/ram`
+│ └── Injects raw heavy process tree into the active session
+│
+└── TUI Plugin (src/sidebar.tsx)
+ ├── sidebar_content slot
+ │ └── Renders `RamWidget` in the TUI sidebar
+ ├── Poller
+ │ └── Calls `getLightweightRam()` at `refreshIntervalMs`
+ └── Process Sampler (src/memory.ts)
+ └── Discovers `opencode` PIDs via `ps`/`wmic` to get total session count
+```
## Features
-
+- **Real-time Sidebar Widget**: View your current and total RAM usage natively in the OpenCode TUI sidebar.
+- **Active Session Tracking**: Automatically discovers all running OpenCode sessions and aggregates their RAM.
+- **Cross-Platform**: Uses native commands (`ps` on Unix, `wmic` on Windows) for lightweight zero-dependency metrics.
+- **`/ram` Command**: Intercepts the `/ram` command to provide a detailed, heavy process-tree breakdown of the current session right in the chat.
+- **Configurable**: Polling intervals can be customized via `.opencode/opencode.json`.
## Install
@@ -44,15 +62,34 @@ Also, add the plugin to `tui.json` or `tui.jsonc`:
## Usage
-
+Once installed, the RAM monitor will automatically appear in your OpenCode TUI sidebar, polling your system to display the memory usage of your current session and the aggregate total across all active sessions.
+
+To get a detailed heavy process tree of your current session's memory usage, simply type `/ram` in your OpenCode chat.
## Configuration
-
+Add the following to your `.opencode/opencode.json` to configure the plugin:
+
+| Property | Type | Default | Description |
+| :--- | :--- | :--- | :--- |
+| `experimental.ramMonitor.refreshIntervalMs` | `number` | `5000` | Polling interval for the sidebar widget in milliseconds. Clamped between `1000` and `60000`. |
+
+Example:
+```json
+{
+ "experimental": {
+ "ramMonitor": {
+ "refreshIntervalMs": 2000
+ }
+ }
+}
+```
## Troubleshooting
-
+- **Widget missing from sidebar**: Ensure both the server and TUI plugins are registered in `opencode.json` and `tui.json` respectively. If `refreshIntervalMs` is configured, ensure your `opencode.json` is valid, as comments can cause the config reader to fail or fallback.
+- **Active count seems off**: The plugin tokenizes command lines to find active `opencode` processes. Deeply nested wrappers or complex invocation aliases might not be matched.
+- **Total RAM shows `0`**: If sampling fails completely (e.g. `ps` is missing), the plugin falls back to using `process.memoryUsage().rss` of the current process. Ensure standard process utilities are available.
## Contributing
diff --git a/packages/opencode-ram-monitor/package.json b/packages/opencode-ram-monitor/package.json
index ca30776..34dbc3b 100644
--- a/packages/opencode-ram-monitor/package.json
+++ b/packages/opencode-ram-monitor/package.json
@@ -11,7 +11,7 @@
"dist"
],
"scripts": {
- "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/server.ts --outfile=dist/server.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && bun build src/memory.ts --outfile=dist/memory.js --target=bun && cp src/sidebar.tsx dist/sidebar.tsx",
+ "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/server.ts --outfile=dist/server.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && bun build src/memory.ts --outfile=dist/memory.js --target=bun && bun build src/sidebar-config.ts --outfile=dist/sidebar-config.js --target=bun && cp src/sidebar.tsx dist/sidebar.tsx",
"typecheck": "tsc --noEmit",
"check": "bunx @biomejs/biome check --write .",
"lint": "bunx @biomejs/biome check .",
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
index 5b11772..79a8e17 100644
--- a/packages/opencode-ram-monitor/src/index.test.ts
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -1,6 +1,8 @@
import "@opentui/solid/preload";
import { describe, expect, test } from "bun:test";
+import { classifyOpencodeProcess } from "./memory.js";
import serverModule from "./server.js";
+import { getErrorMessage, normalizeRefreshIntervalMs } from "./sidebar-config.js";
describe("@capybearista/opencode-ram-monitor", () => {
test("has an id", () => {
@@ -15,4 +17,42 @@ describe("@capybearista/opencode-ram-monitor", () => {
test("exports server hooks", () => {
expect(serverModule.server).toBeFunction();
});
+
+ test("classifies direct core and launcher commands", () => {
+ expect(classifyOpencodeProcess("/usr/local/bin/.opencode -c")).toBe("core");
+ expect(classifyOpencodeProcess("/usr/local/bin/opencode -c")).toBe("launcher");
+ });
+
+ test("classifies node-wrapped opencode commands with flags", () => {
+ expect(
+ classifyOpencodeProcess('node --require /tmp/bootstrap.js "/opt/opencode/bin/.opencode" -c'),
+ ).toBe("core");
+ expect(
+ classifyOpencodeProcess("node --loader ts-node/esm /opt/opencode/bin/opencode --foo"),
+ ).toBe("launcher");
+ });
+
+ test("does not misclassify non-script opencode args", () => {
+ expect(classifyOpencodeProcess("node /srv/app.js --name opencode")).toBeNull();
+ expect(classifyOpencodeProcess("node --require opencode /srv/app.js")).toBeNull();
+ });
+
+ test("ignores non-opencode commands", () => {
+ expect(classifyOpencodeProcess("node /usr/bin/tsserver --stdio")).toBeNull();
+ expect(classifyOpencodeProcess("/bin/sh -c 'echo hello'")).toBeNull();
+ });
+
+ test("normalizes refresh interval to safe bounds", () => {
+ expect(normalizeRefreshIntervalMs("200")).toBe(1000);
+ expect(normalizeRefreshIntervalMs(0)).toBe(1000);
+ expect(normalizeRefreshIntervalMs(1500)).toBe(1500);
+ expect(normalizeRefreshIntervalMs(999999)).toBe(60_000);
+ expect(normalizeRefreshIntervalMs("bad")).toBe(5000);
+ });
+
+ test("derives stable error messages from unknown throws", () => {
+ expect(getErrorMessage(new Error("boom"))).toBe("boom");
+ expect(getErrorMessage("failure")).toBe("failure");
+ expect(getErrorMessage({ reason: "unknown" })).toBe("RAM error");
+ });
});
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
index 72b21f1..16f28f9 100644
--- a/packages/opencode-ram-monitor/src/memory.ts
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -7,6 +7,76 @@ import { promisify } from "node:util";
const EXEC_OPTS = { timeout: 5000, windowsHide: true };
const execAsync = promisify(exec);
+function splitCommandTokens(commandLine: string): string[] {
+ const matches = commandLine.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);
+ if (!matches) return [];
+ return matches.map((token) => token.replace(/^['"]|['"]$/g, ""));
+}
+
+function getTokenBaseName(token: string): string {
+ const parts = token
+ .toLowerCase()
+ .split(/[\\/]+/)
+ .filter(Boolean);
+ return parts.length > 0 ? parts[parts.length - 1] : "";
+}
+
+function classifyOpencodeBinary(token: string): "core" | "launcher" | null {
+ const baseName = getTokenBaseName(token);
+ if (baseName === ".opencode" || baseName === ".opencode.exe") return "core";
+ if (baseName === "opencode" || baseName === "opencode.exe") return "launcher";
+ return null;
+}
+
+function nodeOrBunOptionConsumesNextToken(token: string): boolean {
+ if (token === "-r" || token === "--require") return true;
+ if (token === "--loader" || token === "--import") return true;
+ if (token === "-e" || token === "--eval") return true;
+ if (token === "-p" || token === "--print") return true;
+ if (token === "--env-file") return true;
+ return false;
+}
+
+export function classifyOpencodeProcess(commandLine: string): "core" | "launcher" | null {
+ const tokens = splitCommandTokens(commandLine);
+ if (tokens.length === 0) return null;
+
+ const first = getTokenBaseName(tokens[0]);
+ const firstClassification = classifyOpencodeBinary(tokens[0]);
+ if (firstClassification) return firstClassification;
+
+ if (first === "node" || first === "node.exe" || first === "bun" || first === "bun.exe") {
+ let skipNextToken = false;
+ for (let index = 1; index < tokens.length; index++) {
+ const token = tokens[index];
+ if (!token) continue;
+
+ if (skipNextToken) {
+ skipNextToken = false;
+ continue;
+ }
+
+ if (token === "--") {
+ if (index + 1 < tokens.length) {
+ return classifyOpencodeBinary(tokens[index + 1]);
+ }
+ return null;
+ }
+
+ if (token.startsWith("-")) {
+ if (nodeOrBunOptionConsumesNextToken(token)) {
+ skipNextToken = !token.includes("=");
+ }
+ continue;
+ }
+
+ return classifyOpencodeBinary(token);
+ }
+ }
+
+ return null;
+}
+
async function getRuntimeSessionPids(): Promise {
const osPlatform = platform();
@@ -26,12 +96,10 @@ async function getRuntimeSessionPids(): Promise {
const pid = parseInt(trimmed.slice(0, firstSpace), 10);
if (Number.isNaN(pid)) continue;
- const args = trimmed.slice(firstSpace + 1).toLowerCase();
- if (args.includes("/bin/.opencode")) {
- corePids.push(pid);
- } else if (args.includes("/bin/opencode")) {
- launcherPids.push(pid);
- }
+ const args = trimmed.slice(firstSpace + 1);
+ const processKind = classifyOpencodeProcess(args);
+ if (processKind === "core") corePids.push(pid);
+ if (processKind === "launcher") launcherPids.push(pid);
}
return corePids.length > 0 ? corePids : launcherPids;
@@ -43,28 +111,31 @@ async function getRuntimeSessionPids(): Promise {
if (osPlatform === "win32") {
try {
const { stdout } = await execAsync(
- "wmic process get ProcessId,CommandLine /format:csv",
+ "wmic process get CommandLine,ProcessId /format:value",
EXEC_OPTS,
);
const corePids: number[] = [];
const launcherPids: number[] = [];
- for (const line of stdout.replace(/\r\n/g, "\n").split("\n")) {
- const trimmed = line.trim();
- if (!trimmed?.includes(",")) continue;
-
- const columns = trimmed.split(",");
- if (columns.length < 3) continue;
+ const normalized = stdout.replace(/\r\n/g, "\n").trim();
+ const blocks = normalized.split(/\n\n+/);
+ for (const block of blocks) {
+ const lines = block.trim().split("\n");
+ const entry: Record = {};
+ for (const line of lines) {
+ const separatorIndex = line.indexOf("=");
+ if (separatorIndex === -1) continue;
+ const key = line.slice(0, separatorIndex).trim();
+ const value = line.slice(separatorIndex + 1).trim();
+ entry[key] = value;
+ }
- const pid = parseInt(columns[columns.length - 1], 10);
+ const pid = parseInt(entry.ProcessId, 10);
if (Number.isNaN(pid)) continue;
- const commandLine = columns.slice(1, -1).join(",").toLowerCase();
- if (commandLine.includes("\\.opencode")) {
- corePids.push(pid);
- } else if (commandLine.includes("\\opencode") || commandLine.includes("/opencode")) {
- launcherPids.push(pid);
- }
+ const processKind = classifyOpencodeProcess(entry.CommandLine || "");
+ if (processKind === "core") corePids.push(pid);
+ if (processKind === "launcher") launcherPids.push(pid);
}
return corePids.length > 0 ? corePids : launcherPids;
@@ -126,6 +197,7 @@ export async function getLightweightRam(): Promise {
const osPlatform = platform();
let totalRss = 0;
let currentRss = 0;
+ const sampledPids = new Set();
if (osPlatform === "linux") {
// Fast path for Linux/WSL - read VmRSS from /proc//status (kB)
@@ -136,6 +208,7 @@ export async function getLightweightRam(): Promise {
if (match) {
const rss = parseInt(match[1], 10) * 1024;
totalRss += rss;
+ sampledPids.add(pid);
if (pid === process.pid) currentRss = rss;
}
} catch {
@@ -151,6 +224,7 @@ export async function getLightweightRam(): Promise {
if (!Number.isNaN(rssKb)) {
const rss = rssKb * 1024;
totalRss += rss;
+ sampledPids.add(pid);
if (pid === process.pid) currentRss = rss;
}
} catch {
@@ -163,12 +237,14 @@ export async function getLightweightRam(): Promise {
try {
const { stdout } = await execAsync(
`wmic process where "ProcessId=${pid}" get WorkingSetSize`,
+ EXEC_OPTS,
);
const lines = stdout.trim().split("\n").slice(1); // skip header
for (const line of lines) {
const rssBytes = parseInt(line.trim(), 10);
if (!Number.isNaN(rssBytes)) {
totalRss += rssBytes;
+ sampledPids.add(pid);
if (pid === process.pid) currentRss = rssBytes;
}
}
@@ -180,16 +256,22 @@ export async function getLightweightRam(): Promise {
// Fallback: just current process
currentRss = process.memoryUsage().rss;
totalRss = currentRss;
+ sampledPids.add(process.pid);
}
- if (currentRss === 0 && totalRss > 0) {
- currentRss = process.memoryUsage().rss;
+ if (currentRss === 0) {
+ const fallbackCurrentRss = process.memoryUsage().rss;
+ currentRss = fallbackCurrentRss;
+ if (!sampledPids.has(process.pid)) {
+ totalRss += fallbackCurrentRss;
+ sampledPids.add(process.pid);
+ }
}
return {
current: currentRss,
total: totalRss,
- count: pids.length,
+ count: sampledPids.size,
};
}
@@ -266,7 +348,7 @@ export async function getHeavyProcessTree(): Promise {
}
for (const p of processes) {
- if (procMap.has(p.ppid)) {
+ if (p.ppid !== p.pid && procMap.has(p.ppid)) {
procMap.get(p.ppid)?.children.push(p);
}
}
@@ -285,25 +367,45 @@ export async function getHeavyProcessTree(): Promise {
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
};
- const buildTreeString = (node: ProcessNode, prefix: string, isLast: boolean): string => {
+ const buildTreeString = (
+ node: ProcessNode,
+ prefix: string,
+ isLast: boolean,
+ visited: Set,
+ ): string => {
+ if (visited.has(node.pid)) {
+ return `${prefix}${isLast ? "└──" : "├──"} [${node.command}] (PID ${node.pid}) - cycle detected\n`;
+ }
+
+ const nextVisited = new Set(visited);
+ nextVisited.add(node.pid);
+
let result = `${prefix}${isLast ? "└──" : "├──"} [${node.command}] (PID ${node.pid}) - ${formatSize(node.rss)}\n`;
const childPrefix = prefix + (isLast ? " " : "│ ");
for (let i = 0; i < node.children.length; i++) {
- result += buildTreeString(node.children[i], childPrefix, i === node.children.length - 1);
+ result += buildTreeString(
+ node.children[i],
+ childPrefix,
+ i === node.children.length - 1,
+ nextVisited,
+ );
}
return result;
};
- const getTreeSum = (node: ProcessNode): number => {
- return node.rss + node.children.reduce((acc, child) => acc + getTreeSum(child), 0);
+ const getTreeSum = (node: ProcessNode, visited: Set): number => {
+ if (visited.has(node.pid)) return 0;
+ const nextVisited = new Set(visited);
+ nextVisited.add(node.pid);
+ return node.rss + node.children.reduce((acc, child) => acc + getTreeSum(child, nextVisited), 0);
};
for (const root of targetRoots) {
- const totalMem = getTreeSum(root);
+ const totalMem = getTreeSum(root, new Set());
markdown += `**Session (PID ${root.pid}) - Total: ${formatSize(totalMem)}**\n`;
markdown += `\`\`\`text\n`;
- markdown += buildTreeString(root, "", true);
+ markdown += buildTreeString(root, "", true, new Set());
markdown += `\`\`\`\n\n`;
}
diff --git a/packages/opencode-ram-monitor/src/sidebar-config.ts b/packages/opencode-ram-monitor/src/sidebar-config.ts
new file mode 100644
index 0000000..ebcf90a
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/sidebar-config.ts
@@ -0,0 +1,19 @@
+const DEFAULT_REFRESH_INTERVAL_MS = 5000;
+const MIN_REFRESH_INTERVAL_MS = 1000;
+const MAX_REFRESH_INTERVAL_MS = 60_000;
+
+export function getDefaultRefreshIntervalMs(): number {
+ return DEFAULT_REFRESH_INTERVAL_MS;
+}
+
+export function normalizeRefreshIntervalMs(value: unknown): number {
+ const parsed = typeof value === "number" ? value : Number(value);
+ if (!Number.isFinite(parsed)) return DEFAULT_REFRESH_INTERVAL_MS;
+ return Math.min(MAX_REFRESH_INTERVAL_MS, Math.max(MIN_REFRESH_INTERVAL_MS, Math.floor(parsed)));
+}
+
+export function getErrorMessage(error: unknown): string {
+ if (error instanceof Error && error.message) return error.message;
+ if (typeof error === "string" && error.trim().length > 0) return error;
+ return "RAM error";
+}
diff --git a/packages/opencode-ram-monitor/src/sidebar.tsx b/packages/opencode-ram-monitor/src/sidebar.tsx
index 80ea092..52a977e 100644
--- a/packages/opencode-ram-monitor/src/sidebar.tsx
+++ b/packages/opencode-ram-monitor/src/sidebar.tsx
@@ -1,12 +1,21 @@
/** @jsxImportSource @opentui/solid */
+
+import * as fs from "node:fs/promises";
+import * as path from "node:path";
import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
-import { createSignal, onCleanup } from "solid-js";
+import { createSignal, onCleanup, onMount } from "solid-js";
import { formatBytes, getLightweightRam, type LightweightRamResult } from "./memory.js";
+import {
+ getDefaultRefreshIntervalMs,
+ getErrorMessage,
+ normalizeRefreshIntervalMs,
+} from "./sidebar-config.js";
function RamWidget(props: { api: TuiPluginApi }) {
const [ram, setRam] = createSignal({ current: 0, total: 0, count: 0 });
const [error, setError] = createSignal(null);
- const [intervalMs, setIntervalMs] = createSignal(5000);
+ const [intervalMs, setIntervalMs] = createSignal(getDefaultRefreshIntervalMs());
+ const [tick, setTick] = createSignal(0);
let disposed = false;
let timeout: ReturnType | undefined;
@@ -14,18 +23,23 @@ function RamWidget(props: { api: TuiPluginApi }) {
// Fetch config once on mount
const loadConfig = async () => {
try {
- const response = await props.api.client.config.get();
- const rawConfig = (
- response.data as unknown as { experimental?: { ramMonitor?: Record } }
- )?.experimental?.ramMonitor;
- if (rawConfig?.refreshIntervalMs) {
- setIntervalMs(Number(rawConfig.refreshIntervalMs) || 5000);
+ const worktree = props.api.state.path?.worktree || process.cwd();
+ const configPath = path.join(worktree, ".opencode", "opencode.json");
+ const configContent = await fs.readFile(configPath, "utf8");
+
+ // Basic JSON parsing. Real parser would strip comments, but since
+ // comments break strict JSON anyway, we just try parse.
+ const parsed = JSON.parse(configContent);
+ const rawConfig = parsed?.experimental?.ramMonitor;
+
+ if (rawConfig && "refreshIntervalMs" in rawConfig) {
+ const nextInterval = normalizeRefreshIntervalMs(rawConfig.refreshIntervalMs);
+ setIntervalMs(nextInterval);
}
} catch {
- // fallback to 5000
+ // Keep default interval if file missing or invalid.
}
};
- void loadConfig();
const poll = async () => {
try {
@@ -33,11 +47,11 @@ function RamWidget(props: { api: TuiPluginApi }) {
if (!disposed) {
setRam(currentRam);
setError(null);
+ setTick((t) => t + 1);
}
} catch (err: unknown) {
if (!disposed) {
- setError((err as Error).message || "RAM error");
- console.error("RAM Monitor Poll Error:", err);
+ setError(getErrorMessage(err));
}
}
@@ -46,7 +60,14 @@ function RamWidget(props: { api: TuiPluginApi }) {
}
};
- void poll();
+ onMount(() => {
+ void (async () => {
+ await loadConfig();
+ if (!disposed) {
+ void poll();
+ }
+ })();
+ });
onCleanup(() => {
disposed = true;
@@ -56,7 +77,7 @@ function RamWidget(props: { api: TuiPluginApi }) {
return (
- RAM Usage
+ RAM Usage {tick() % 2 === 0 ? "●" : "○"}
{error() ? `Error: ${error()}` : `Current: ${formatBytes(ram().current)}`}
@@ -73,8 +94,6 @@ function RamWidget(props: { api: TuiPluginApi }) {
const SIDEBAR_ORDER = 150;
const tui: TuiPlugin = async (api) => {
- console.log("RamMonitor TUI plugin loading with ID: capybearista.opencode-ram-monitor");
-
api.slots.register({
order: SIDEBAR_ORDER,
slots: {
From 914322a9374565426a14f61ade728663a8cc93bd Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 03:33:17 -0400
Subject: [PATCH 039/115] chore(changeset): remove outdated changeset
management documentation
---
.agents/commands/changeset.md | 27 ---------------------------
1 file changed, 27 deletions(-)
delete mode 100644 .agents/commands/changeset.md
diff --git a/.agents/commands/changeset.md b/.agents/commands/changeset.md
deleted file mode 100644
index 4c2159e..0000000
--- a/.agents/commands/changeset.md
+++ /dev/null
@@ -1,27 +0,0 @@
----
-description: Manage project versioning and changelogs using Changesets
-agent: build
-subtask: true
----
-
-# Changeset Management
-
-This command helps you manage versions and changelogs for this monorepo.
-
-## Usage
-
-- `/changeset` — Interactively create a new changeset
-- `/changeset status` — View pending changesets
-- `/changeset version` — Apply changesets to bump versions
-- `/changeset ` — Pass arbitrary arguments to the changeset CLI
-
-## Argument Contract
-ARGUMENTS=$ARGUMENTS
-
-If ARGUMENTS is empty, I will run `bun changeset`.
-Otherwise, I will run `bun changeset $ARGUMENTS`.
-
-## Steps
-1. Execute `bun changeset $ARGUMENTS`
-2. Follow interactive prompts if required
-3. Verify the generated `.changeset/*.md` file
From 04e41dc4322fd73e2d9452960377ad6081964215 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 04:13:16 -0400
Subject: [PATCH 040/115] docs(ram-monitor): add v1.0.0 post-mortem and general
plugin patterns
---
docs/opencode-plugin-ipc-and-os-patterns.md | 88 +++++++++++++++++++++
docs/ram-monitor/post-mortem-v1.0.0.md | 23 ++++++
2 files changed, 111 insertions(+)
create mode 100644 docs/opencode-plugin-ipc-and-os-patterns.md
create mode 100644 docs/ram-monitor/post-mortem-v1.0.0.md
diff --git a/docs/opencode-plugin-ipc-and-os-patterns.md b/docs/opencode-plugin-ipc-and-os-patterns.md
new file mode 100644
index 0000000..0bcc5a8
--- /dev/null
+++ b/docs/opencode-plugin-ipc-and-os-patterns.md
@@ -0,0 +1,88 @@
+# OpenCode Plugin IPC and OS Interaction Patterns
+
+This guide captures architectural principles and cross-platform interaction patterns derived from the development of ecosystem plugins (such as `opencode-ram-monitor`). It serves as a reference for plugin authors to ensure stability, responsiveness, and broad platform compatibility.
+
+## 1. IPC and Asynchronous Initialization Constraints
+
+OpenCode plugins operate across an IPC (Inter-Process Communication) boundary. When the OpenCode host boots, it synchronously queries registered plugins to build the UI and establish the plugin registry.
+
+### The Top-Level `await` Trap
+**Do not block the plugin factory with top-level `await`.**
+
+When exporting a TUI plugin module, the factory function must return immediately. If you place a top-level `await` (e.g., fetching a configuration file or making an external API call) before returning the `api.slots.register` call, you block the IPC channel.
+
+**Symptoms of a blocked IPC:**
+- The OpenCode terminal renders a black screen or hangs indefinitely.
+- The host is unable to proceed with rendering other widgets.
+
+**The Solution:**
+Defer asynchronous data loading to the UI lifecycle layer. Use SolidJS's `onMount` (or equivalent React hooks if using React) inside the actual widget component.
+
+```tsx
+// ❌ BAD: Blocks IPC during host boot
+const tui: TuiPlugin = async (api) => {
+ const config = await readConfig(); // DANGER: Host hangs waiting for this
+ api.slots.register({ /* ... */ });
+};
+
+// ✅ GOOD: Returns immediately, loads async
+const tui: TuiPlugin = async (api) => {
+ api.slots.register({
+ order: 100,
+ slots: {
+ sidebar_content() {
+ const [data, setData] = createSignal(null);
+ onMount(async () => {
+ const config = await readConfig();
+ setData(config);
+ });
+ return ;
+ }
+ }
+ });
+};
+```
+
+## 2. Platform-Specific OS Interaction Patterns
+
+When a plugin needs to interact with the underlying OS (e.g., reading system metrics, managing processes, file system queries), relying on Node.js standard libraries alone is often insufficient. Below are proven patterns for robust cross-platform interactions.
+
+### Linux and WSL: The `/proc` Fast Path
+For system-level metrics on Linux and WSL environments, reading directly from the virtual `/proc` filesystem is highly performant and requires zero subprocess overhead.
+
+- **Pattern:** Read `/proc/[pid]/status` directly.
+- **Why:** Avoids `ps` command invocation overhead during rapid polling cycles. Perfectly maps over into WSL environments without requiring Windows interop bridging.
+
+### macOS (Darwin): Command-Line Execution
+macOS does not expose a `/proc` filesystem. To get similar metrics, you must shell out to BSD commands.
+
+- **Pattern:** `ps -o rss= -p [pid]`
+- **Safety:** Always wrap the `exec` call in a `try...catch` and execute isolated per-PID queries. Shelling out for a large batch of PIDs simultaneously can fail entirely if a single PID in the query string exits before execution completes.
+
+### Windows (Pwsh/CMD): `wmic` and CSV Hazards
+Windows querying using `wmic` or PowerShell introduces text-parsing hazards, particularly with command lines that include commas or nested quotes.
+
+- **The CSV Bug:** Never use `wmic /format:csv`. If a process command line contains a comma, it breaks the CSV column alignment, leading to NaN errors and logic failures.
+- **Pattern:** Use `wmic process get ... /format:value`.
+- **Implementation:** This outputs `Key=Value` blocks separated by blank lines. It is vastly more resilient to commas in the data.
+
+```ts
+// Executing wmic with /format:value
+const { stdout } = await execAsync(
+ "wmic process get CommandLine,ProcessId /format:value",
+ { windowsHide: true, timeout: 5000 }
+);
+
+// Splitting securely by block
+const blocks = stdout.replace(/\r\n/g, "\n").trim().split(/\n\n+/);
+// Parsing Key=Value inside the block
+```
+
+- **Hidden Windows:** Always pass `windowsHide: true` to `exec` or `spawn` options on Windows to prevent console windows from flashing dynamically when polling the system.
+
+## 3. Polling and Process Lifecycle Hygiene
+
+For plugins that implement continuous polling:
+
+1. **Avoid `setInterval` Overlap:** Use recursive `setTimeout` instead of `setInterval`. If the asynchronous payload takes longer than the interval (e.g., a slow disk or CPU spike), `setInterval` will queue overlapping executions. Recursive `setTimeout` ensures the next tick only queues after the previous one finishes.
+2. **Deterministic Cleanup:** Plugins can be unloaded or the TUI can be re-mounted. Always track a `disposed` boolean flag and clear timeouts inside `onCleanup` hooks to prevent memory leaks and zombie loops.
\ No newline at end of file
diff --git a/docs/ram-monitor/post-mortem-v1.0.0.md b/docs/ram-monitor/post-mortem-v1.0.0.md
new file mode 100644
index 0000000..6ee0a05
--- /dev/null
+++ b/docs/ram-monitor/post-mortem-v1.0.0.md
@@ -0,0 +1,23 @@
+# `opencode-ram-monitor` v1.0.0 Post-Mortem
+
+This document summarizes the architectural challenges and bug fixes encountered during the stabilization and v1.0.0 preparation of the `@capybearista/opencode-ram-monitor` plugin.
+
+## 1. IPC Boot Deadlock
+**The Issue:** The initial plugin implementation attempted to perform a top-level `await` to read configuration before registering the TUI slots (`tui: TuiPlugin = async (api) => { await config(); api.slots.register(...) }`). Because the OpenCode host boots synchronously and awaits the module export, this blocked the IPC channel and caused the UI to hang on a black screen.
+**The Fix:** Deferred configuration loading to SolidJS's `onMount` hook inside the Solid component (`sidebar.tsx`). The plugin factory now registers its slots immediately, and the widget loads the config and starts polling asynchronously after mounting.
+
+## 2. Strict Host Schema Stripping
+**The Issue:** We attempted to read our configuration (`experimental.ramMonitor.refreshIntervalMs`) using `api.client.config.get()`. However, the host uses strict Zod schema validation for its config object and silently strips any unknown "experimental" keys.
+**The Fix:** Bypassed the API client entirely for custom plugin config. The widget now uses `node:fs/promises` to manually read `.opencode/opencode.json` from disk using the resolved worktree path (`api.state.path.worktree`).
+
+## 3. Active Session Discovery (Tokenization Bugs)
+**The Issue:** Originally, active session discovery used stale `.lock` files or naive substring matching on command lines. If a user had `node_modules/.bin/opencode` running or a similarly named directory, false positives occurred.
+**The Fix:** Built a robust token classifier (`classifyOpencodeProcess` in `memory.ts`). It explicitly strips quotes, splits command line arguments, handles `node` and `bun` executable wrappers, skips standard Node flags (`-r`, `--eval`), and correctly identifies whether the active script is `opencode` (launcher) or `.opencode` (core process).
+
+## 4. Windows Commas & CSV Parser Failure
+**The Issue:** Windows process querying was using `wmic /format:csv`. If a process executable path or arguments contained a comma, it destroyed the CSV column alignment, returning `NaN` for memory values and breaking the parser.
+**The Fix:** Switched to `wmic ... /format:value`, which outputs `Key=Value` blocks separated by blank lines (`\r\n\r\n`). This entirely avoids comma conflict hazards.
+
+## 5. Heavy Process Tree Infinite Loops
+**The Issue:** The heavy process tree traversal (`getHeavyProcessTree`) recursively mapped child processes to their parents. In edge cases where a process reported itself as its own parent or circular adoption occurred, the plugin threw a Maximum Call Stack Exceeded exception.
+**The Fix:** Implemented graph cycle detection using a `visited` Set during tree traversal. If a PID attempts to loop, it renders `- cycle detected` and safely terminates that branch.
\ No newline at end of file
From 6a34f4a43fef7d91c28ad915bf01c6a24e06c6a7 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 04:30:51 -0400
Subject: [PATCH 041/115] chore(pr-template): add opencode-ram-monitor to
affected plugins list
---
.github/pull_request_template.md | 1 +
1 file changed, 1 insertion(+)
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 52ed24b..6ef0fdc 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -11,6 +11,7 @@
- [ ] opencode-agents-loader
- [ ] opencode-double-tap-timeline
- [ ] opencode-output-styles
+- [ ] opencode-ram-monitor
- [ ] opencode-plugins (this monorepo itself)
- [ ] Other: _______
From fc8ad850a0ec5ea6c5f2eaea5a076895d577436d Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 04:31:00 -0400
Subject: [PATCH 042/115] chore(ram-monitor): add changeset
---
.changeset/ram-monitor-v1.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/ram-monitor-v1.md
diff --git a/.changeset/ram-monitor-v1.md b/.changeset/ram-monitor-v1.md
new file mode 100644
index 0000000..aba7794
--- /dev/null
+++ b/.changeset/ram-monitor-v1.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-ram-monitor": major
+---
+
+Initial v1.0.0 release. RAM Monitor with configuration support, real-time PID discovery, and active session counting.
\ No newline at end of file
From c36e022abe10558d1add233f90bd81c5f6667d4d Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 13:49:26 -0400
Subject: [PATCH 043/115] chore(ai-tools): add new agents for analyzing PR test
coverage quality and failure hunting
---
.agents/agents/pr-test-analyzer.md | 133 ++++++++++++++++++++++
.agents/agents/silent-failure-hunter.md | 142 ++++++++++++++++++++++++
2 files changed, 275 insertions(+)
create mode 100644 .agents/agents/pr-test-analyzer.md
create mode 100644 .agents/agents/silent-failure-hunter.md
diff --git a/.agents/agents/pr-test-analyzer.md b/.agents/agents/pr-test-analyzer.md
new file mode 100644
index 0000000..6cda71d
--- /dev/null
+++ b/.agents/agents/pr-test-analyzer.md
@@ -0,0 +1,133 @@
+---
+name: pr-test-analyzer
+description: Analyzes PR test coverage for quality and completeness. Focuses on behavioral coverage, not line metrics. Identifies critical gaps, evaluates test quality, and rates recommendations by criticality (1-10). Use after PR creation or before marking ready.
+model: opencode-go/qwen3.6-plus
+temperature: 0.2
+mode: subagent
+---
+
+You are an expert test coverage analyst. Your job is to ensure PRs have adequate test coverage for critical functionality, focusing on tests that catch real bugs rather than achieving metrics.
+
+## CRITICAL: Pragmatic Coverage Analysis
+
+Your ONLY job is to analyze test coverage quality:
+
+- **DO NOT** demand 100% line coverage
+- **DO NOT** suggest tests for trivial getters/setters
+- **DO NOT** recommend tests that test implementation details
+- **DO NOT** ignore existing integration test coverage
+- **DO NOT** be pedantic about edge cases that won't happen
+- **ONLY** focus on tests that prevent real bugs and regressions
+
+Pragmatic over academic. Value over metrics.
+
+## Analysis Scope
+
+**Default**: PR diff and associated test files
+
+**What to Analyze**:
+- New functionality added in the PR
+- Modified code paths
+- Test files added or changed
+- Integration points affected
+
+## Analysis Process
+
+### Step 1: Understand the Changes
+
+| Change Type | What to Look For |
+|-------------|------------------|
+| **New features** | Core functionality requiring coverage |
+| **Modified logic** | Changed behavior needing test updates |
+| **New APIs** | Contracts that must be verified |
+| **Error handling** | Failure paths added or changed |
+| **Edge cases** | Boundary conditions introduced |
+
+### Step 2: Map Test Coverage
+
+For each significant change, identify:
+- Which test file covers it (if any)
+- What scenarios are tested
+- What scenarios are missing
+- Whether tests are behavioral or implementation-coupled
+
+### Step 3: Identify Critical Gaps
+
+| Gap Type | Risk Level |
+|----------|------------|
+| **Error handling** | High - uncaught exceptions |
+| **Validation logic** | High - invalid input accepted |
+| **Business logic branches** | High - critical paths untested |
+| **Boundary conditions** | Medium - off-by-one, nulls |
+| **Async behavior** | Medium - race conditions |
+| **Integration points** | Medium - API contracts |
+
+### Step 4: Evaluate Test Quality
+
+| Quality Aspect | Good Sign | Bad Sign |
+|----------------|-----------|----------|
+| **Focus** | Tests behavior/contracts | Tests implementation details |
+| **Resilience** | Survives refactoring | Breaks on internal changes |
+| **Clarity** | DAMP (Descriptive and Meaningful) | Cryptic or over-DRY |
+| **Assertions** | Verifies outcomes | Just checks no errors |
+| **Independence** | Isolated, no order dependency | Relies on other test state |
+
+### Step 5: Rate and Prioritize
+
+| Rating | Criticality | Action |
+|--------|-------------|--------|
+| **9-10** | Critical - data loss, security, system failure | Must add |
+| **7-8** | Important - user-facing errors, business logic | Should add |
+| **5-6** | Moderate - edge cases, minor issues | Consider |
+| **3-4** | Low - completeness, nice-to-have | Optional |
+| **1-2** | Minimal - trivial | Skip |
+
+**Focus recommendations on ratings 5+**
+
+## Output Format
+
+```markdown
+## Test Coverage Analysis: [PR Title/Number]
+
+### Scope
+- **Files changed**: [N]
+- **Test files**: [N added/modified]
+
+### Summary
+[2-3 sentence overview]
+**Overall Assessment**: [GOOD / ADEQUATE / NEEDS WORK / CRITICAL GAPS]
+
+---
+
+### Critical Gaps (Rating 8-10)
+
+#### Gap 1: [Title]
+**Rating**: 9/10
+**Location**: `path/to/file.ts:45-60`
+**Risk**: [What could break]
+**Suggested Test**: [test outline]
+
+### Important Improvements (Rating 5-7)
+[same format]
+
+### Test Quality Issues
+[existing tests needing improvement]
+
+### Positive Observations
+[what's well-tested]
+
+---
+
+### Recommended Priority
+1. [highest impact test to add]
+2. [second]
+3. [third]
+```
+
+## Key Principles
+
+- **Behavior over implementation** - Tests should survive refactoring
+- **Critical paths first** - Focus on what can cause real damage
+- **Cost/benefit analysis** - Every suggestion should justify its value
+- **Existing coverage awareness** - Check integration tests before flagging gaps
+- **Specific recommendations** - Include test outlines, not vague suggestions
diff --git a/.agents/agents/silent-failure-hunter.md b/.agents/agents/silent-failure-hunter.md
new file mode 100644
index 0000000..3fcea16
--- /dev/null
+++ b/.agents/agents/silent-failure-hunter.md
@@ -0,0 +1,142 @@
+---
+name: silent-failure-hunter
+description: Hunts for silent failures, inadequate error handling, and inappropriate fallbacks in code changes. Zero tolerance for swallowed errors. Use after implementing error handling, catch blocks, or fallback logic.
+model: opencode-go/qwen3.6-plus
+temperature: 0.2
+mode: subagent
+---
+
+You are an elite error handling auditor with zero tolerance for silent failures. Your job is to protect users from obscure, hard-to-debug issues by ensuring every error is properly surfaced, logged, and actionable.
+
+## CRITICAL: Zero Tolerance for Silent Failures
+
+These rules are non-negotiable:
+
+- **DO NOT** accept empty catch blocks - ever
+- **DO NOT** accept errors logged without user feedback
+- **DO NOT** accept broad exception catching that hides unrelated errors
+- **DO NOT** accept fallbacks without explicit user awareness
+- **DO NOT** accept mock/fake implementations in production code
+- **EVERY** error must be logged with context
+- **EVERY** user-facing error must be actionable
+
+Silent failures are critical defects. Period.
+
+## Analysis Scope
+
+**Default**: Error handling code in PR diff or unstaged changes
+
+**What to Hunt**:
+- Try-catch blocks (or language equivalents)
+- Error callbacks and event handlers
+- Conditional branches handling error states
+- Fallback logic and default values on failure
+- Optional chaining that might hide errors
+- Retry logic that exhausts silently
+
+## Hunting Process
+
+### Step 1: Locate All Error Handling
+
+Find every error handling location in scope.
+
+### Step 2: Scrutinize Each Handler
+
+For every error handling location, evaluate:
+
+#### Logging Quality
+
+| Question | Pass | Fail |
+|----------|------|------|
+| Is error logged with appropriate severity? | Structured logger with context | `console.log()` or nothing |
+| Does log include sufficient context? | Operation, IDs, state | Just error message |
+| Would this help debug in 6 months? | Clear breadcrumb trail | Cryptic or missing |
+
+#### User Feedback
+
+| Question | Pass | Fail |
+|----------|------|------|
+| Does user receive feedback? | Clear error shown | Silent failure |
+| Is message actionable? | Tells user what to do | "Something went wrong" |
+
+#### Catch Block Specificity
+
+| Question | Pass | Fail |
+|----------|------|------|
+| Catches only expected errors? | Specific error types | `catch (e)` catches all |
+| Could hide unrelated errors? | No | Yes |
+
+#### Fallback Behavior
+
+| Question | Pass | Fail |
+|----------|------|------|
+| Is fallback explicit? | Documented/intentional | Silent substitution |
+| Does it mask the real problem? | No, logs original error | Hides underlying issue |
+
+### Step 3: Hunt Hidden Failures
+
+| Anti-Pattern | Severity |
+|--------------|----------|
+| Empty catch block | CRITICAL |
+| Log and continue (no user awareness) | HIGH |
+| Return null/default silently | HIGH |
+| Optional chaining hiding errors | MEDIUM |
+| Retry exhaustion without notice | HIGH |
+| Fallback chain without explanation | MEDIUM |
+
+## Output Format
+
+```markdown
+## Silent Failure Hunt: [Scope Description]
+
+### Scope
+- **Reviewing**: [PR diff / specific files]
+- **Error handlers found**: [N locations]
+
+---
+
+### Critical Issues (Must Fix)
+
+#### Issue 1: [Brief Title]
+**Severity**: CRITICAL
+**Location**: `path/to/file.ts:45-52`
+**Pattern**: [type]
+
+**Current Code**: [snippet]
+**Hidden Errors**: [what could be silently swallowed]
+**User Impact**: [how this affects users]
+**Required Fix**: [snippet]
+
+---
+
+### High Severity Issues
+[same format]
+
+### Medium Severity Issues
+[same format]
+
+### Positive Findings
+[good error handling patterns observed]
+
+---
+
+### Summary
+
+| Severity | Count | Action |
+|----------|-------|--------|
+| CRITICAL | X | Must fix before merge |
+| HIGH | Y | Should fix before merge |
+| MEDIUM | Z | Improve when possible |
+
+### Verdict: [PASS / NEEDS FIXES / CRITICAL ISSUES]
+```
+
+## Key Principles
+
+- **Zero tolerance** - Silent failures are critical defects, not style issues
+- **User-first** - Every error must give users actionable information
+- **Debug-friendly** - Logs must help someone debug in 6 months
+- **Specific catches** - Broad catches hide unrelated errors
+- **Visible fallbacks** - Users must know when fallback behavior activates
+
+Every silent failure you catch prevents hours of debugging frustration.
From c8befbfabdb34ae7e7ff7c9ab6e583c3a580fa64 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Thu, 7 May 2026 13:51:20 -0400
Subject: [PATCH 044/115] feat(new): init commit for
opencode-adversarial-review
---
bun.lock | 19 +
packages/opencode-adversarial-review/LICENSE | 373 ++++++++++++++++++
.../opencode-adversarial-review/README.md | 72 ++++
.../opencode-adversarial-review/package.json | 36 ++
.../src/index.test.ts | 17 +
.../opencode-adversarial-review/src/index.ts | 46 +++
.../opencode-adversarial-review/tsconfig.json | 13 +
7 files changed, 576 insertions(+)
create mode 100644 packages/opencode-adversarial-review/LICENSE
create mode 100644 packages/opencode-adversarial-review/README.md
create mode 100644 packages/opencode-adversarial-review/package.json
create mode 100644 packages/opencode-adversarial-review/src/index.test.ts
create mode 100644 packages/opencode-adversarial-review/src/index.ts
create mode 100644 packages/opencode-adversarial-review/tsconfig.json
diff --git a/bun.lock b/bun.lock
index 360c3d9..350ae84 100644
--- a/bun.lock
+++ b/bun.lock
@@ -16,6 +16,19 @@
"typescript": "^6.0.3",
},
},
+ "packages/opencode-adversarial-review": {
+ "name": "@capybearista/opencode-adversarial-review",
+ "version": "0.0.0",
+ "devDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0",
+ "@tsconfig/node22": "^22.0.0",
+ "@types/bun": "latest",
+ "typescript": "^5.8.0",
+ },
+ "peerDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0",
+ },
+ },
"packages/opencode-agents-loader": {
"name": "@capybearista/opencode-agents-loader",
"version": "1.0.0",
@@ -137,6 +150,8 @@
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.14", "", { "os": "win32", "cpu": "x64" }, "sha512-WL0EG5qE+EAKomGXbf2g6VnSKJhTL3tXC0QRzWRwA5VpjxNYa6H4P7ZWfymbGE4IhZZQi1KXQ2R0YjwInmz2fA=="],
+ "@capybearista/opencode-adversarial-review": ["@capybearista/opencode-adversarial-review@workspace:packages/opencode-adversarial-review"],
+
"@capybearista/opencode-agents-loader": ["@capybearista/opencode-agents-loader@workspace:packages/opencode-agents-loader"],
"@capybearista/opencode-double-tap-timeline": ["@capybearista/opencode-double-tap-timeline@workspace:packages/opencode-double-tap-timeline"],
@@ -271,6 +286,8 @@
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
+ "@tsconfig/node22": ["@tsconfig/node22@22.0.5", "", {}, "sha512-hLf2ld+sYN/BtOJjHUWOk568dvjFQkHnLNa6zce25GIH+vxKfvTgm3qpaH6ToF5tu/NN0IH66s+Bb5wElHrLcw=="],
+
"@turbo/darwin-64": ["@turbo/darwin-64@2.9.8", "", { "os": "darwin", "cpu": "x64" }, "sha512-zU1P95ygDpsQ+2QHh7CVTqvYwi9UBlhKWzoIyUnP3vUoge7H9SQEzrd8dj+XcTrslAp9Db3vIBcXtMVoTEYDnA=="],
"@turbo/darwin-arm64": ["@turbo/darwin-arm64@2.9.8", "", { "os": "darwin", "cpu": "arm64" }, "sha512-nKRFI5ZhCGUi4eXNlrojzWcT/CehMj0raot1WE4lw5qf66ZxZHbRbBqcwNEy+ZLY7RkJJRY+TaU89fuj3BcgGg=="],
@@ -677,6 +694,8 @@
"@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
+ "@capybearista/opencode-adversarial-review/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
+
"@changesets/parse/js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"@manypkg/find-root/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="],
diff --git a/packages/opencode-adversarial-review/LICENSE b/packages/opencode-adversarial-review/LICENSE
new file mode 100644
index 0000000..dbdb0fa
--- /dev/null
+++ b/packages/opencode-adversarial-review/LICENSE
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
\ No newline at end of file
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
new file mode 100644
index 0000000..f724bf0
--- /dev/null
+++ b/packages/opencode-adversarial-review/README.md
@@ -0,0 +1,72 @@
+# opencode-adversarial-review
+
+
Challenge code with adversarial review
+
+
+
+
+
+
+---
+
+## Why?
+
+> Provides an adversarial code review agent that challenges implementation approach and design choices, not just finding bugs. Uses a clean-context subagent so the review is unbiased by conversation history.
+
+## Philosophy: Extending OpenCode
+
+OpenCode is designed to be highly extensible. This plugin hooks into the OpenCode lifecycle to provide additional functionality seamlessly into your workflows.
+
+## Features
+
+
+
+## Install
+
+
+
+
+Add the plugin to `opencode.json` or `opencode.jsonc`:
+```json
+{
+ "plugin": ["@capybearista/opencode-adversarial-review"]
+}
+```
+
+You can also install it through the CLI:
+
+```bash
+opencode plugin -g @capybearista/opencode-adversarial-review # global install
+opencode plugin @capybearista/opencode-adversarial-review # project-local install
+```
+
+## Usage
+
+
+
+## Configuration
+
+
+
+## Troubleshooting
+
+
+
+## Contributing
+
+This package lives in the `opencode-plugins` monorepo.
+
+- Run `bun run build`, `bun run typecheck`, `bun run lint`, and `bun test` before opening a PR.
+- Keep the plugin focused on adversarial code review.
+- Prefer small, direct changes.
+
+Please open an issue or check for existing ones before creating a pull request.
+
+## License
+
+[MPL-2.0](LICENSE)
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
new file mode 100644
index 0000000..e37fe1c
--- /dev/null
+++ b/packages/opencode-adversarial-review/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@capybearista/opencode-adversarial-review",
+ "version": "0.0.0",
+ "description": "Adversarial code review plugin",
+ "author": "capyBearista ",
+ "license": "MPL-2.0",
+ "type": "module",
+ "main": "./dist/index.js",
+ "types": "./dist/index.d.ts",
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "build": "tsc",
+ "typecheck": "tsc --noEmit",
+ "check": "bunx @biomejs/biome check --write .",
+ "lint": "bunx @biomejs/biome check .",
+ "ci": "bunx @biomejs/biome ci .",
+ "test": "bun test"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ }
+ },
+ "peerDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0"
+ },
+ "devDependencies": {
+ "@opencode-ai/plugin": ">=1.14.0",
+ "@tsconfig/node22": "^22.0.0",
+ "@types/bun": "latest",
+ "typescript": "^5.8.0"
+ }
+}
diff --git a/packages/opencode-adversarial-review/src/index.test.ts b/packages/opencode-adversarial-review/src/index.test.ts
new file mode 100644
index 0000000..4609bc6
--- /dev/null
+++ b/packages/opencode-adversarial-review/src/index.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, test } from "bun:test";
+import plugin from "./index";
+
+describe("@capybearista/opencode-adversarial-review", () => {
+ test("has an id", () => {
+ expect(plugin.id).toBeString();
+ expect(plugin.id).toBe("capybearista.opencode-adversarial-review");
+ });
+
+ test("exports a default object", () => {
+ expect(plugin).toBeObject();
+ });
+
+ test("exports server hooks", () => {
+ expect(plugin.server).toBeFunction();
+ });
+});
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
new file mode 100644
index 0000000..6332946
--- /dev/null
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -0,0 +1,46 @@
+import type { Plugin } from "@opencode-ai/plugin";
+
+export const AdversarialReviewPlugin: Plugin = async () => {
+ return {
+ config: async (cfg) => {
+ if (!cfg.agent) cfg.agent = {};
+ if (!cfg.agent["adversarial-review"]) {
+ cfg.agent["adversarial-review"] = {
+ description:
+ "Adversarial code review — challenges implementation approach and design choices",
+ mode: "subagent",
+ model: "openai/gpt-5.4",
+ temperature: 0.1,
+ color: "warning",
+ permission: {
+ edit: "deny",
+ bash: {
+ "git *": "allow",
+ "*": "deny",
+ },
+ read: "allow",
+ glob: "allow",
+ grep: "allow",
+ },
+ prompt: "",
+ };
+ }
+
+ if (!cfg.command) cfg.command = {};
+ if (!cfg.command["adversarial-review"]) {
+ cfg.command["adversarial-review"] = {
+ description: "Run an adversarial code review that challenges the implementation",
+ argumentHint: "[--base ] [--scope auto|working-tree|branch] [focus ...]",
+ agent: "adversarial-review",
+ subtask: true,
+ template: "",
+ };
+ }
+ },
+ };
+};
+
+export default {
+ id: "capybearista.opencode-adversarial-review",
+ server: AdversarialReviewPlugin,
+};
diff --git a/packages/opencode-adversarial-review/tsconfig.json b/packages/opencode-adversarial-review/tsconfig.json
new file mode 100644
index 0000000..89ac3f4
--- /dev/null
+++ b/packages/opencode-adversarial-review/tsconfig.json
@@ -0,0 +1,13 @@
+{
+ "extends": "@tsconfig/node22/tsconfig.json",
+ "compilerOptions": {
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "rootDir": "src",
+ "outDir": "dist",
+ "declaration": true,
+ "sourceMap": true
+ },
+ "include": ["src"],
+ "exclude": ["dist", "node_modules", "src/**/*.test.ts"]
+}
From 781cd8d2e6686079a8e08d1cfe09317929cd0d9c Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Fri, 8 May 2026 11:46:43 -0400
Subject: [PATCH 045/115] feat(adversarial-review): implement review gate and
convergence with Codex
- Inline diff mode for small changes (2 files full diff, >2 stat only)
- Untracked file contents in command template with space-safe reading
- --scope and --base argument handling in subagent prompt
- Permission whitelist with 11 read-only git subcommand patterns
- Review gate via tool.execute.after edit detection (replaces summary.diffs)
- Partial config merge with ??= pattern for agent and command registrations
- import.meta.dirname-based paths for cross-cwd test reliability
- agent.edit forced to deny with hard assignment to prevent user override
---
.../src/index.test.ts | 376 +++++++++++++++++-
.../opencode-adversarial-review/src/index.ts | 237 +++++++++--
.../src/prompts/adversarial-review.md | 102 +++++
.../src/schemas/review-output.schema.json | 50 +++
4 files changed, 731 insertions(+), 34 deletions(-)
create mode 100644 packages/opencode-adversarial-review/src/prompts/adversarial-review.md
create mode 100644 packages/opencode-adversarial-review/src/schemas/review-output.schema.json
diff --git a/packages/opencode-adversarial-review/src/index.test.ts b/packages/opencode-adversarial-review/src/index.test.ts
index 4609bc6..ef2053e 100644
--- a/packages/opencode-adversarial-review/src/index.test.ts
+++ b/packages/opencode-adversarial-review/src/index.test.ts
@@ -1,8 +1,9 @@
-import { describe, expect, test } from "bun:test";
-import plugin from "./index";
+import { describe, expect, mock, test } from "bun:test";
+import { join } from "path";
+import plugin from "./index.js";
describe("@capybearista/opencode-adversarial-review", () => {
- test("has an id", () => {
+ test("has a plugin id", () => {
expect(plugin.id).toBeString();
expect(plugin.id).toBe("capybearista.opencode-adversarial-review");
});
@@ -14,4 +15,373 @@ describe("@capybearista/opencode-adversarial-review", () => {
test("exports server hooks", () => {
expect(plugin.server).toBeFunction();
});
+
+ test("config hook registers adversarial-review agent when not present", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent).toBeDefined();
+ expect(cfg.agent["adversarial-review"]).toBeDefined();
+ expect(cfg.agent["adversarial-review"].mode).toBe("subagent");
+ expect(cfg.agent["adversarial-review"].model).toBe("openai/gpt-5.4");
+ expect(cfg.agent["adversarial-review"].prompt).toBeTruthy();
+ expect(cfg.agent["adversarial-review"].prompt).toInclude("break confidence in the change");
+ expect(cfg.agent["adversarial-review"].permission.edit).toBe("deny");
+ expect(cfg.agent["adversarial-review"].permission.bash["git diff*"]).toBe("allow");
+ expect(cfg.agent["adversarial-review"].permission.webfetch).toBe("deny");
+ });
+
+ test("config hook registers adversarial-review command when not present", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.command).toBeDefined();
+ expect(cfg.command["adversarial-review"]).toBeDefined();
+ expect(cfg.command["adversarial-review"].agent).toBe("adversarial-review");
+ expect(cfg.command["adversarial-review"].subtask).toBe(true);
+ expect(cfg.command["adversarial-review"].template).toBeTruthy();
+ expect(cfg.command["adversarial-review"].template).toInclude("$ARGUMENTS");
+ expect(cfg.command["adversarial-review"].template).toInclude("git branch");
+ });
+
+ test("config hook does not overwrite existing agent", async () => {
+ const cfg: Record = {
+ agent: {
+ "adversarial-review": {
+ description: "custom agent",
+ mode: "subagent",
+ model: "anthropic/claude-haiku-4-20250514",
+ prompt: "custom prompt",
+ },
+ },
+ };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent["adversarial-review"].model).toBe("anthropic/claude-haiku-4-20250514");
+ expect(cfg.agent["adversarial-review"].prompt).toBe("custom prompt");
+ });
+
+ test("config hook fills in missing fields when user provides partial agent config", async () => {
+ const cfg: Record = {
+ agent: {
+ "adversarial-review": {
+ model: "openrouter/openai/gpt-5-mini",
+ },
+ },
+ };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ const agent = cfg.agent["adversarial-review"];
+ expect(agent.model).toBe("openrouter/openai/gpt-5-mini");
+ expect(agent.prompt).toInclude("break confidence in the change");
+ expect(agent.mode).toBe("subagent");
+ expect(agent.description).toBeTruthy();
+ expect(agent.temperature).toBe(0.1);
+ expect(agent.color).toBe("warning");
+ expect(agent.permission.edit).toBe("deny");
+ expect(agent.permission.bash["git diff*"]).toBe("allow");
+ expect(agent.permission.bash["*"]).toBe("deny");
+ expect(agent.permission.webfetch).toBe("deny");
+ });
+
+ test("config hook does not overwrite existing command", async () => {
+ const cfg: Record = {
+ command: {
+ "adversarial-review": {
+ template: "custom template",
+ agent: "custom-agent",
+ },
+ },
+ };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.command["adversarial-review"].template).toBe("custom template");
+ expect(cfg.command["adversarial-review"].agent).toBe("custom-agent");
+ });
+
+ test("config hook preserves unrelated user agents and commands", async () => {
+ const cfg: Record = {
+ agent: {
+ "existing-agent": {
+ mode: "primary",
+ model: "openai/gpt-5.4",
+ },
+ },
+ command: {
+ "existing-cmd": {
+ template: "do something",
+ },
+ },
+ };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent["existing-agent"]).toBeDefined();
+ expect(cfg.command["existing-cmd"]).toBeDefined();
+ expect(cfg.agent["adversarial-review"]).toBeDefined();
+ expect(cfg.command["adversarial-review"]).toBeDefined();
+ });
+
+ test("config hook is idempotent — calling twice preserves user override", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+
+ await hooks.config(cfg);
+ cfg.agent["adversarial-review"].model = "anthropic/claude-sonnet-4-20250514";
+
+ await hooks.config(cfg);
+ expect(cfg.agent["adversarial-review"].model).toBe("anthropic/claude-sonnet-4-20250514");
+ });
+
+ test("config hook handles null agent gracefully", async () => {
+ const cfg: Record = { agent: null };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent).toBeDefined();
+ expect(cfg.agent["adversarial-review"]).toBeDefined();
+ });
+
+ test("config hook handles null command gracefully", async () => {
+ const cfg: Record = { command: null };
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.command).toBeDefined();
+ expect(cfg.command["adversarial-review"]).toBeDefined();
+ });
+
+ test("config hook initializes agent and command objects if absent", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent).toBeDefined();
+ expect(cfg.command).toBeDefined();
+ });
+
+ test("agent prompt contains structured output contract", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ const prompt = cfg.agent["adversarial-review"].prompt;
+ expect(prompt).toInclude("structured_output_contract");
+ expect(prompt).toInclude("verdict");
+ expect(prompt).toInclude("needs-attention");
+ expect(prompt).toInclude("severity");
+ expect(prompt).toInclude("line_start");
+ expect(prompt).toInclude("line_end");
+ });
+
+ test("command template includes shell injection markers", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ const template = cfg.command["adversarial-review"].template;
+ expect(template).toInclude("Arguments: $ARGUMENTS");
+ expect(template).toInclude("git log");
+ expect(template).toInclude("git status");
+ expect(template).toInclude("git diff");
+ });
+
+ test("agent permission denies edit and restricts bash to read-only git subcommands", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ const permission = cfg.agent["adversarial-review"].permission;
+ expect(permission.edit).toBe("deny");
+
+ const allowed = permission.bash;
+ expect(allowed["git diff*"]).toBe("allow");
+ expect(allowed["git log*"]).toBe("allow");
+ expect(allowed["git status*"]).toBe("allow");
+ expect(allowed["git show*"]).toBe("allow");
+ expect(allowed["git rev-parse*"]).toBe("allow");
+ expect(allowed["git branch"]).toBe("allow");
+ expect(allowed["git ls-files*"]).toBe("allow");
+ expect(allowed["git merge-base*"]).toBe("allow");
+ expect(allowed["git rev-list*"]).toBe("allow");
+ expect(allowed["git stash list*"]).toBe("allow");
+ expect(allowed["git stash show*"]).toBe("allow");
+ expect(allowed["git blame*"]).toBe("allow");
+ expect(allowed["*"]).toBe("deny");
+ expect(permission.webfetch).toBe("deny");
+ });
+
+ test("agent has temperature and color configured", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+
+ expect(cfg.agent["adversarial-review"].temperature).toBe(0.1);
+ expect(cfg.agent["adversarial-review"].color).toBe("warning");
+ });
+
+ test("embedded prompt matches reference prompt file", async () => {
+ const cfg: Record = {};
+ const hooks = await plugin.server({} as any);
+ await hooks.config(cfg);
+ const embedded = cfg.agent["adversarial-review"].prompt;
+
+ const reference = await Bun.file(
+ join(import.meta.dirname, "prompts", "adversarial-review.md"),
+ ).text();
+ expect(embedded.trim()).toBe(reference.trim());
+ });
+
+ test("output schema is valid JSON with required fields", async () => {
+ const text = await Bun.file(
+ join(import.meta.dirname, "schemas", "review-output.schema.json"),
+ ).text();
+ const schema = JSON.parse(text);
+
+ expect(schema.required).toContain("verdict");
+ expect(schema.required).toContain("findings");
+ expect(schema.properties.verdict.enum).toEqual(["approve", "needs-attention"]);
+
+ const findingProps = schema.properties.findings.items.properties;
+ expect(findingProps.severity.enum).toEqual(["critical", "high", "medium", "low"]);
+ expect(findingProps.confidence.minimum).toBe(0);
+ expect(findingProps.confidence.maximum).toBe(1);
+ expect(findingProps.line_start.minimum).toBe(1);
+ expect(findingProps.line_end.minimum).toBe(1);
+ });
+
+ test("hooks are registered", async () => {
+ const hooks = await plugin.server({} as any);
+ expect(hooks["chat.message"]).toBeFunction();
+ expect(hooks["tool.execute.after"]).toBeFunction();
+ });
+
+ test("chat.message hook no-ops when reviewGate is not enabled (default)", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "primary" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(0);
+ });
+
+ test("chat.message hook no-ops when config is null (no experimental set)", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks.config({ agent: null, command: null } as any);
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "primary" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(0);
+ });
+
+ test("chat.message hook skips when agent is adversarial-review (prevents loop)", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks.config({
+ experimental: { reviewGate: { enabled: true } },
+ agent: {},
+ command: {},
+ } as any);
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "adversarial-review" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(0);
+ });
+
+ test("chat.message hook skips when no tool edits were detected", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks.config({
+ experimental: { reviewGate: { enabled: true } },
+ agent: {},
+ command: {},
+ } as any);
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "primary" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(0);
+ });
+
+ test("tool.execute.after does not set pendingReview for non-edit tools", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks.config({
+ experimental: { reviewGate: { enabled: true } },
+ agent: {},
+ command: {},
+ } as any);
+
+ await hooks["tool.execute.after"](
+ { tool: "read", sessionID: "s1", callID: "c1", args: {} } as any,
+ { title: "", output: "", metadata: {} } as any,
+ );
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "primary" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(0);
+ });
+
+ test("chat.message hook calls session.command when tool.execute.after detected edits and gate enabled", async () => {
+ const commandSpy = mock(async () => {});
+ const hooks = await plugin.server({
+ client: { session: { command: commandSpy } },
+ } as any);
+
+ await hooks.config({
+ experimental: { reviewGate: { enabled: true } },
+ agent: {},
+ command: {},
+ } as any);
+
+ await hooks["tool.execute.after"](
+ { tool: "edit", sessionID: "s1", callID: "c1", args: {} } as any,
+ { title: "", output: "", metadata: {} } as any,
+ );
+
+ await hooks["chat.message"](
+ { sessionID: "s1", agent: "primary" } as any,
+ { message: {}, parts: [] } as any,
+ );
+
+ expect(commandSpy).toHaveBeenCalledTimes(1);
+ expect(commandSpy).toHaveBeenCalledWith({
+ path: { id: "s1" },
+ body: { command: "adversarial-review", arguments: "" },
+ });
+ });
});
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
index 6332946..0dc1139 100644
--- a/packages/opencode-adversarial-review/src/index.ts
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -1,46 +1,221 @@
import type { Plugin } from "@opencode-ai/plugin";
-export const AdversarialReviewPlugin: Plugin = async () => {
+const PLUGIN_ID = "capybearista.opencode-adversarial-review";
+
+const ADVERSARIAL_REVIEW_PROMPT = `
+You are an adversarial code review agent.
+Your job is to break confidence in the change, not to validate it.
+
+
+
+Review the provided repository context as if you are trying to find the strongest reasons this change should not ship yet.
+The user's focus and target arguments are in the message below.
+
+If the arguments include \`--scope auto\`, review using the broadest context the provided information supports (default).
+If \`--scope working-tree\`, review staged and unstaged changes against HEAD.
+If \`--scope branch\`, collect the diff for all changes on the current branch. Determine the fork point by running \`git merge-base HEAD \` where \`\` is the tracking branch of HEAD, or \`origin/main\`, or \`main\` (in order of preference). Then run \`git diff ...HEAD\`.
+If \`--base \` is provided without \`--scope\`, treat it as \`--scope branch --base \`.
+If \`--base \` is provided alongside \`--scope branch\`, use that ref as the base in \`git diff ...HEAD\`.
+
+
+
+Default to skepticism.
+Assume the change can fail in subtle, high-cost, or user-visible ways until the evidence says otherwise.
+Do not give credit for good intent, partial fixes, or likely follow-up work.
+If something only works on the happy path, treat that as a real weakness.
+
+
+
+Prioritize the kinds of failures that are expensive, dangerous, or hard to detect:
+- auth, permissions, tenant isolation, and trust boundaries
+- data loss, corruption, duplication, and irreversible state changes
+- rollback safety, retries, partial failure, and idempotency gaps
+- race conditions, ordering assumptions, stale state, and re-entrancy
+- empty-state, null, timeout, and degraded dependency behavior
+- version skew, schema drift, migration hazards, and compatibility regressions
+- observability gaps that would hide failure or make recovery harder
+
+
+
+Actively try to disprove the change.
+Look for violated invariants, missing guards, unhandled failure paths, and assumptions that stop being true under stress.
+Trace how bad inputs, retries, concurrent actions, or partially completed operations move through the code.
+If the user supplied a focus area, weight it heavily, but still report any other material issue you can defend.
+If the diff context is limited (only stat, no full diff), use the available tools (read, grep, glob) to inspect specific files before finalizing.
+
+
+
+The diff context either contains a full inline diff (for changes to 1-2 files) or a summary stat only (for larger changes). If you see a stat-only section without a full inline diff, use your tools to inspect the changed files directly. If you see a full inline diff, use it as primary evidence and supplement with tools as needed.
+
+
+
+Report only material findings.
+Do not include style feedback, naming feedback, low-value cleanup, or speculative concerns without evidence.
+A finding should answer:
+1. What can go wrong?
+2. Why is this code path vulnerable?
+3. What is the likely impact?
+4. What concrete change would reduce the risk?
+
+
+
+Output valid JSON matching this schema:
+
+{
+ "verdict": "approve" | "needs-attention",
+ "summary": "terse ship/no-ship assessment",
+ "findings": [
+ {
+ "severity": "critical" | "high" | "medium" | "low",
+ "title": "short finding title",
+ "body": "detailed explanation",
+ "file": "relative file path",
+ "line_start": 1,
+ "line_end": 1,
+ "confidence": 0.0-1.0,
+ "recommendation": "concrete fix suggestion"
+ }
+ ],
+ "next_steps": ["actionable next step"]
+}
+
+Use \`needs-attention\` if there is any material risk worth blocking on.
+Use \`approve\` only if you cannot support any substantive adversarial finding from the provided context.
+Keep the output compact and specific.
+
+
+
+Be aggressive, but stay grounded.
+Every finding must be defensible from the provided repository context or tool outputs.
+Do not invent files, lines, code paths, incidents, attack chains, or runtime behavior you cannot support.
+If a conclusion depends on an inference, state that explicitly in the finding body and keep the confidence honest.
+
+
+
+Prefer one strong finding over several weak ones.
+Do not dilute serious issues with filler.
+If the change looks safe, say so directly and return no findings.
+
+
+
+Before finalizing, check that each finding is:
+- adversarial rather than stylistic
+- tied to a concrete code location
+- plausible under a real failure scenario
+- actionable for an engineer fixing the issue
+`;
+
+const COMMAND_TEMPLATE = `## Adversarial Review
+
+Arguments: $ARGUMENTS
+Target: working tree diff
+
+## Git Context
+
+!\`echo "=== Branch ===" && git branch --show-current\`
+!\`echo "=== Status ===" && git status --short --untracked-files=all\`
+!\`echo "=== Recent Commits ===" && git log --oneline -3\`
+!\`echo "=== Changed Files ===" && git diff HEAD --name-only\`
+!\`echo "=== Untracked File Contents ==="; git ls-files --others --exclude-standard | head -5 | while IFS= read -r f; do echo "--- $f ---" && cat -- "$f" 2>/dev/null | head -c 16384 && echo; done\`
+!\`FILES=$(git diff HEAD --name-only | wc -l); if [ "$FILES" -gt 0 ] && [ "$FILES" -le 2 ]; then echo "=== Full Diff ===" && git diff HEAD; else echo "=== Diff Stat ===" && git diff HEAD --stat; fi\``;
+
+const AGENT_NAME = "adversarial-review";
+const CMD_NAME = "adversarial-review";
+
+export const AdversarialReviewPlugin: Plugin = async (ctx) => {
+ const client = ctx.client;
+ let reviewGateEnabled = false;
+ let pendingReview = false;
+
return {
config: async (cfg) => {
- if (!cfg.agent) cfg.agent = {};
- if (!cfg.agent["adversarial-review"]) {
- cfg.agent["adversarial-review"] = {
- description:
- "Adversarial code review — challenges implementation approach and design choices",
- mode: "subagent",
- model: "openai/gpt-5.4",
- temperature: 0.1,
- color: "warning",
- permission: {
- edit: "deny",
- bash: {
- "git *": "allow",
- "*": "deny",
- },
- read: "allow",
- glob: "allow",
- grep: "allow",
- },
- prompt: "",
+ try {
+ cfg.agent ??= {};
+ cfg.agent[AGENT_NAME] ??= {};
+
+ const agent = cfg.agent[AGENT_NAME];
+ agent.description ??=
+ "Adversarial code review — challenges implementation approach and design choices";
+ agent.mode ??= "subagent";
+ agent.model ??= "openai/gpt-5.4";
+ agent.temperature ??= 0.1;
+ agent.color ??= "warning";
+ (agent as any).permission ??= {};
+ const agentPerm = (agent as any).permission;
+ agentPerm.edit = "deny";
+ agentPerm.bash ??= {
+ "git blame*": "allow",
+ "git branch": "allow",
+ "git diff*": "allow",
+ "git log*": "allow",
+ "git ls-files*": "allow",
+ "git merge-base*": "allow",
+ "git rev-list*": "allow",
+ "git rev-parse*": "allow",
+ "git show*": "allow",
+ "git stash list*": "allow",
+ "git stash show*": "allow",
+ "git status*": "allow",
+ "*": "deny",
};
+ agentPerm.read ??= "allow";
+ agentPerm.glob ??= "allow";
+ agentPerm.grep ??= "allow";
+ agentPerm.webfetch ??= "deny";
+ agentPerm.websearch ??= "deny";
+ agent.prompt ??= ADVERSARIAL_REVIEW_PROMPT;
+
+ cfg.command ??= {};
+ cfg.command[CMD_NAME] ??= {} as any;
+ const cmd = cfg.command[CMD_NAME] as any;
+ cmd.description ??= "Run an adversarial code review that challenges the implementation";
+ cmd.argumentHint ??= "[--base ] [--scope auto|working-tree|branch] [focus ...]";
+ cmd.agent ??= AGENT_NAME;
+ cmd.subtask ??= true;
+ cmd.template ??= COMMAND_TEMPLATE;
+
+ reviewGateEnabled = (cfg as any).experimental?.reviewGate?.enabled === true;
+ } catch (err) {
+ console.error(
+ `[${PLUGIN_ID}] Failed to register agent and command:`,
+ err instanceof Error ? err.message : String(err),
+ );
+ throw err;
}
+ },
- if (!cfg.command) cfg.command = {};
- if (!cfg.command["adversarial-review"]) {
- cfg.command["adversarial-review"] = {
- description: "Run an adversarial code review that challenges the implementation",
- argumentHint: "[--base ] [--scope auto|working-tree|branch] [focus ...]",
- agent: "adversarial-review",
- subtask: true,
- template: "",
- };
+ "tool.execute.after": async (input, _output) => {
+ if (!reviewGateEnabled || !client) return;
+ if (["edit", "write", "patch"].includes(input.tool)) {
+ pendingReview = true;
+ }
+ },
+
+ "chat.message": async (input, _output) => {
+ if (!reviewGateEnabled || !client) return;
+ if (input.agent === AGENT_NAME) {
+ pendingReview = false;
+ return;
+ }
+ if (!pendingReview) return;
+ pendingReview = false;
+
+ try {
+ await client.session.command({
+ path: { id: input.sessionID },
+ body: { command: CMD_NAME, arguments: "" },
+ });
+ } catch (err) {
+ console.error(
+ `[${PLUGIN_ID}] Review gate failed:`,
+ err instanceof Error ? err.message : String(err),
+ );
}
},
};
};
export default {
- id: "capybearista.opencode-adversarial-review",
+ id: PLUGIN_ID,
server: AdversarialReviewPlugin,
};
diff --git a/packages/opencode-adversarial-review/src/prompts/adversarial-review.md b/packages/opencode-adversarial-review/src/prompts/adversarial-review.md
new file mode 100644
index 0000000..07aea81
--- /dev/null
+++ b/packages/opencode-adversarial-review/src/prompts/adversarial-review.md
@@ -0,0 +1,102 @@
+
+You are an adversarial code review agent.
+Your job is to break confidence in the change, not to validate it.
+
+
+
+Review the provided repository context as if you are trying to find the strongest reasons this change should not ship yet.
+The user's focus and target arguments are in the message below.
+
+If the arguments include `--scope auto`, review using the broadest context the provided information supports (default).
+If `--scope working-tree`, review staged and unstaged changes against HEAD.
+If `--scope branch`, collect the diff for all changes on the current branch. Determine the fork point by running `git merge-base HEAD ` where `` is the tracking branch of HEAD, or `origin/main`, or `main` (in order of preference). Then run `git diff ...HEAD`.
+If `--base ` is provided without `--scope`, treat it as `--scope branch --base `.
+If `--base ` is provided alongside `--scope branch`, use that ref as the base in `git diff ...HEAD`.
+
+
+
+Default to skepticism.
+Assume the change can fail in subtle, high-cost, or user-visible ways until the evidence says otherwise.
+Do not give credit for good intent, partial fixes, or likely follow-up work.
+If something only works on the happy path, treat that as a real weakness.
+
+
+
+Prioritize the kinds of failures that are expensive, dangerous, or hard to detect:
+- auth, permissions, tenant isolation, and trust boundaries
+- data loss, corruption, duplication, and irreversible state changes
+- rollback safety, retries, partial failure, and idempotency gaps
+- race conditions, ordering assumptions, stale state, and re-entrancy
+- empty-state, null, timeout, and degraded dependency behavior
+- version skew, schema drift, migration hazards, and compatibility regressions
+- observability gaps that would hide failure or make recovery harder
+
+
+
+Actively try to disprove the change.
+Look for violated invariants, missing guards, unhandled failure paths, and assumptions that stop being true under stress.
+Trace how bad inputs, retries, concurrent actions, or partially completed operations move through the code.
+If the user supplied a focus area, weight it heavily, but still report any other material issue you can defend.
+If the diff context is limited (only stat, no full diff), use the available tools (read, grep, glob) to inspect specific files before finalizing.
+
+
+
+The diff context either contains a full inline diff (for changes to 1-2 files) or a summary stat only (for larger changes). If you see a stat-only section without a full inline diff, use your tools to inspect the changed files directly. If you see a full inline diff, use it as primary evidence and supplement with tools as needed.
+
+
+
+Report only material findings.
+Do not include style feedback, naming feedback, low-value cleanup, or speculative concerns without evidence.
+A finding should answer:
+1. What can go wrong?
+2. Why is this code path vulnerable?
+3. What is the likely impact?
+4. What concrete change would reduce the risk?
+
+
+
+Output valid JSON matching this schema:
+
+{
+ "verdict": "approve" | "needs-attention",
+ "summary": "terse ship/no-ship assessment",
+ "findings": [
+ {
+ "severity": "critical" | "high" | "medium" | "low",
+ "title": "short finding title",
+ "body": "detailed explanation",
+ "file": "relative file path",
+ "line_start": 1,
+ "line_end": 1,
+ "confidence": 0.0-1.0,
+ "recommendation": "concrete fix suggestion"
+ }
+ ],
+ "next_steps": ["actionable next step"]
+}
+
+Use `needs-attention` if there is any material risk worth blocking on.
+Use `approve` only if you cannot support any substantive adversarial finding from the provided context.
+Keep the output compact and specific.
+
+
+
+Be aggressive, but stay grounded.
+Every finding must be defensible from the provided repository context or tool outputs.
+Do not invent files, lines, code paths, incidents, attack chains, or runtime behavior you cannot support.
+If a conclusion depends on an inference, state that explicitly in the finding body and keep the confidence honest.
+
+
+
+Prefer one strong finding over several weak ones.
+Do not dilute serious issues with filler.
+If the change looks safe, say so directly and return no findings.
+
+
+
+Before finalizing, check that each finding is:
+- adversarial rather than stylistic
+- tied to a concrete code location
+- plausible under a real failure scenario
+- actionable for an engineer fixing the issue
+
diff --git a/packages/opencode-adversarial-review/src/schemas/review-output.schema.json b/packages/opencode-adversarial-review/src/schemas/review-output.schema.json
new file mode 100644
index 0000000..f7f5119
--- /dev/null
+++ b/packages/opencode-adversarial-review/src/schemas/review-output.schema.json
@@ -0,0 +1,50 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["verdict", "summary", "findings", "next_steps"],
+ "properties": {
+ "verdict": {
+ "type": "string",
+ "enum": ["approve", "needs-attention"]
+ },
+ "summary": {
+ "type": "string",
+ "minLength": 1
+ },
+ "findings": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "severity",
+ "title",
+ "body",
+ "file",
+ "line_start",
+ "line_end",
+ "confidence",
+ "recommendation"
+ ],
+ "properties": {
+ "severity": {
+ "type": "string",
+ "enum": ["critical", "high", "medium", "low"]
+ },
+ "title": { "type": "string", "minLength": 1 },
+ "body": { "type": "string", "minLength": 1 },
+ "file": { "type": "string", "minLength": 1 },
+ "line_start": { "type": "integer", "minimum": 1 },
+ "line_end": { "type": "integer", "minimum": 1 },
+ "confidence": { "type": "number", "minimum": 0, "maximum": 1 },
+ "recommendation": { "type": "string" }
+ }
+ }
+ },
+ "next_steps": {
+ "type": "array",
+ "items": { "type": "string", "minLength": 1 }
+ }
+ }
+}
From ebe85459af271d8771d4a627d47c5874b7c449a0 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Fri, 8 May 2026 16:18:40 -0400
Subject: [PATCH 046/115] feat(adversarial-review): remove auto-trigger gate
and restore manual-only flow
Rollback hook implementation after discovering OpenCode turn lifecycle gaps.
The chat.message hook only fires on user messages, making turn-end triggering impossible without delayed or mid-turn side effects.
- Remove tool.execute.after and chat.message hooks
- Remove separate config file read (.opencode/adversarial-review.json)
- Restore 19-test baseline with mkdtempSync for isolation
---
docs/ram-monitor/codex-comparison.md | 119 ++++++++++++++++
.../src/index.test.ts | 132 +-----------------
.../opencode-adversarial-review/src/index.ts | 37 +----
3 files changed, 121 insertions(+), 167 deletions(-)
create mode 100644 docs/ram-monitor/codex-comparison.md
diff --git a/docs/ram-monitor/codex-comparison.md b/docs/ram-monitor/codex-comparison.md
new file mode 100644
index 0000000..0ea1d66
--- /dev/null
+++ b/docs/ram-monitor/codex-comparison.md
@@ -0,0 +1,119 @@
+# Comparison to the Official Codex-to-Claude-Code Plugin
+
+## Prompt Structure
+
+| Aspect | Codex | Ours |
+| --------------------- | ------------------------------------------------------------------------- | -------------------------------------------------- |
+| Template style | `{{PLACEHOLDER}}` interpolated at runtime | Embedded string constant, no interpolation |
+| `TARGET_LABEL` | Yes ("working tree diff", "branch diff vs main") | Yes ("Target: working tree diff" in template) |
+| `USER_FOCUS` | Injects focus text, fallback "No extra focus..." | Passes through `$ARGUMENTS`, no fallback |
+| `COLLECTION_GUIDANCE` | Two modes: "Use context below" vs "Lightweight summary, inspect yourself" | Yes — `` section tells subagent what to expect |
+| Core prompt | 84 lines, almost identical to ours | ~100 lines, ported from Codex with `` added |
+| 11 XML sections | Same 11 sections (role→final_check) | Same 11 sections |
+
+**Verdict:** Near-identical core prompt. Previously missing `TARGET_LABEL` and `COLLECTION_GUIDANCE` — now implemented via static template label and `` section.
+
+---
+
+## Context Collection
+
+| Aspect | Codex | Ours |
+| ------------------------- | -------------------------------------------------------------------- | --------------------------------------------------- |
+| **Mode** | Dual: inline-diff (≤2 files, ≤256KB) vs self-collect (large) | Dual: inline-diff (≤2 files → full diff) vs stat-only (larger) |
+| **Inline diff trigger** | Yes — full `git diff --binary --cached` + unstaged for small changes | Yes — full `git diff HEAD` for ≤2 files (no --separate staged) |
+| **Untracked files** | Contents included (up to 24KB each) | Included (up to 16KB each, space-safe `while read` loop) |
+| **Commit history** | Not included | 3 recent commits included |
+| **Diff size measurement** | Estimates files+bytes before running | File count via `wc -l` on `--name-only`, conditional inline |
+| **Staged vs unstaged** | Separates `--cached` (staged) from unstaged | Uses `git diff HEAD` (merged) |
+
+**Key gap:** Inline-diff mode gap closed. Remaining: staged vs unstaged separation (currently merged via `git diff HEAD`).
+
+---
+
+## Architecture
+
+| Aspect | Codex | Ours |
+| ----------------- | ----------------------------------------------------------------- | ------------------------------------------ |
+| Command structure | `.md` slash-command, `disable-model-invocation: true` | Shell-injected command template |
+| Execution | Companion Node.js script (git + Codex API) | Subagent with bash permission |
+| LLM role | Claude = thin pipe (no review work) | OpenCode = dispatcher, subagent = reviewer |
+| Model call | Direct JSON-RPC to Codex app server (stdin/stdout or Unix socket) | Via OpenCode's provider routing |
+| `outputSchema` | Server-side enforced by Codex (`turn/start` param) | Prompt instruction only — no enforcement |
+| Background mode | `--background` with async job tracking, AskUserQuestion prompt | Not supported — sync only |
+| Job persistence | Job files + `state.json` tracking | None — stateless |
+| Model reuse | Broker pattern (lazy-start Unix socket proxy, warm model) | OpenCode session management |
+| Stop-gate hook | `Stop` hook triggers fresh adversarial review on session end | Not implemented (auto-trigger model doesn't align) |
+
+**Key gap:** No output schema enforcement at runtime. Codex's `outputSchema` parameter forces structured JSON server-side. If our model returns invalid JSON, there's no parsing or error surfacing.
+
+---
+
+## Permission & Security
+
+| Aspect | Codex | Ours |
+| ----------------- | --------------------------------------------------- | ------------------------------------------------- |
+| Model sandbox | `sandbox: "read-only"` (Codex server) | No server sandbox — permission-based via OpenCode |
+| Model bash access | None — Codex can't run bash | Restricted git whitelist (12 patterns) |
+| Command-level | `allowed-tools: Bash(git:*)` (Claude, for preamble) | N/A (command template does it) |
+| Mutability guard | read-only sandbox = server-enforced | `edit: deny` = framework-enforced |
+| Hook execution | Not applicable (no bash for Codex) | No hook disable flag on our git commands |
+
+---
+
+## Output Handling
+
+| Aspect | Codex | Ours |
+| --------------------- | ---------------------------------------------------- | --------------------------------------------------------- |
+| Format enforcement | `outputSchema` on `turn/start` (server-side) | Prompt instruction only ("Output valid JSON...") |
+| Parsing | `JSON.parse()` on final message | None |
+| Validation | `validateReviewResultShape()` checks required fields | None |
+| Error rendering | "Did not return valid structured JSON" + raw output | N/A — user sees raw subagent response as-is |
+| Reference schema file | `review-output.schema.json` (used at test time only) | `review-output.schema.json` (test + reference, identical) |
+
+**Key gap:** Inline-diff, TARGET_LABEL, COLLECTION_GUIDANCE, untracked files, and `--scope` all addressed. Remaining gaps: output validation, background execution, job persistence, stop-gate — none critical for the subagent-based architecture.
+
+---
+
+## Testing
+
+| Aspect | Codex | Ours |
+| -------------- | ------------------------------------------------- | ------------------------------------------------------------------ |
+| Runner | Native Node `node --test` | Bun `bun test` |
+| E2E test | Yes — fake Codex fixture returns structured JSON | No — only unit tests against config hook |
+| Test count | 10 (commands, runtime, git, render, fake fixture) | 19 (config registration, idempotency, permissions, prompt sync) |
+| Coverage areas | Full flow, modes, scope, status, validation | Registration, idempotency, permissions, prompt sync, partial merge |
+
+---
+
+## Feature Inventory
+
+| Feature | Codex | Ours |
+| ------------------------------------ | ----- | -------------------------------- |
+| Inline diff (small changes) | ✅ | ✅ |
+| Self-collect (large changes) | ✅ | ✅ |
+| `--base ` | ✅ | ✅ |
+| Focus text | ✅ | ✅ |
+| `TARGET_LABEL` runtime variable | ✅ | ✅ |
+| `REVIEW_COLLECTION_GUIDANCE` | ✅ | ✅ |
+| Structured JSON output | ✅ | ✅ |
+| Server-side schema enforcement | ✅ | ❌ |
+| Runtime output validation | ✅ | ❌ |
+| Background execution | ✅ | ❌ |
+| Job tracking / status | ✅ | ❌ |
+| Stop-gate (auto-trigger on Stop) | ✅ | ❌ |
+| Untracked file context | ✅ | ✅ |
+| Staged vs unstaged separation | ✅ | Partial (`git diff HEAD` merges) |
+| `--scope` working-tree/branch/auto | ✅ | ✅ |
+| Read-only git permission whitelist | N/A | ✅ |
+| Idempotent config registration | N/A | ✅ |
+| Partial config merge (`??=` pattern) | N/A | ✅ |
+
+---
+
+## Architecture Divergences (intentional)
+
+1. **Subagent vs companion script**: We decided against a custom tool/script for context collection because OpenCode's `!`command`` shell injection + `subtask: true` is cleaner. The subagent handles everything.
+2. **No Codex dependency**: We don't need Codex — the subagent IS the reviewer, using OpenCode's model routing.
+3. **Permission-based security**: Codex uses server-side `sandbox: "read-only"`. We use OpenCode's permission system. Both achieve the same goal.
+4. **No broker**: OpenCode manages model sessions internally.
+5. **Stateless**: No job tracking needed — OpenCode's conversation history IS the review history.
diff --git a/packages/opencode-adversarial-review/src/index.test.ts b/packages/opencode-adversarial-review/src/index.test.ts
index ef2053e..85e7402 100644
--- a/packages/opencode-adversarial-review/src/index.test.ts
+++ b/packages/opencode-adversarial-review/src/index.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, mock, test } from "bun:test";
+import { describe, expect, test } from "bun:test";
import { join } from "path";
import plugin from "./index.js";
@@ -254,134 +254,4 @@ describe("@capybearista/opencode-adversarial-review", () => {
expect(findingProps.line_start.minimum).toBe(1);
expect(findingProps.line_end.minimum).toBe(1);
});
-
- test("hooks are registered", async () => {
- const hooks = await plugin.server({} as any);
- expect(hooks["chat.message"]).toBeFunction();
- expect(hooks["tool.execute.after"]).toBeFunction();
- });
-
- test("chat.message hook no-ops when reviewGate is not enabled (default)", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "primary" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(0);
- });
-
- test("chat.message hook no-ops when config is null (no experimental set)", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks.config({ agent: null, command: null } as any);
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "primary" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(0);
- });
-
- test("chat.message hook skips when agent is adversarial-review (prevents loop)", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks.config({
- experimental: { reviewGate: { enabled: true } },
- agent: {},
- command: {},
- } as any);
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "adversarial-review" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(0);
- });
-
- test("chat.message hook skips when no tool edits were detected", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks.config({
- experimental: { reviewGate: { enabled: true } },
- agent: {},
- command: {},
- } as any);
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "primary" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(0);
- });
-
- test("tool.execute.after does not set pendingReview for non-edit tools", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks.config({
- experimental: { reviewGate: { enabled: true } },
- agent: {},
- command: {},
- } as any);
-
- await hooks["tool.execute.after"](
- { tool: "read", sessionID: "s1", callID: "c1", args: {} } as any,
- { title: "", output: "", metadata: {} } as any,
- );
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "primary" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(0);
- });
-
- test("chat.message hook calls session.command when tool.execute.after detected edits and gate enabled", async () => {
- const commandSpy = mock(async () => {});
- const hooks = await plugin.server({
- client: { session: { command: commandSpy } },
- } as any);
-
- await hooks.config({
- experimental: { reviewGate: { enabled: true } },
- agent: {},
- command: {},
- } as any);
-
- await hooks["tool.execute.after"](
- { tool: "edit", sessionID: "s1", callID: "c1", args: {} } as any,
- { title: "", output: "", metadata: {} } as any,
- );
-
- await hooks["chat.message"](
- { sessionID: "s1", agent: "primary" } as any,
- { message: {}, parts: [] } as any,
- );
-
- expect(commandSpy).toHaveBeenCalledTimes(1);
- expect(commandSpy).toHaveBeenCalledWith({
- path: { id: "s1" },
- body: { command: "adversarial-review", arguments: "" },
- });
- });
});
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
index 0dc1139..0d63cae 100644
--- a/packages/opencode-adversarial-review/src/index.ts
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -122,11 +122,7 @@ Target: working tree diff
const AGENT_NAME = "adversarial-review";
const CMD_NAME = "adversarial-review";
-export const AdversarialReviewPlugin: Plugin = async (ctx) => {
- const client = ctx.client;
- let reviewGateEnabled = false;
- let pendingReview = false;
-
+export const AdversarialReviewPlugin: Plugin = async () => {
return {
config: async (cfg) => {
try {
@@ -173,8 +169,6 @@ export const AdversarialReviewPlugin: Plugin = async (ctx) => {
cmd.agent ??= AGENT_NAME;
cmd.subtask ??= true;
cmd.template ??= COMMAND_TEMPLATE;
-
- reviewGateEnabled = (cfg as any).experimental?.reviewGate?.enabled === true;
} catch (err) {
console.error(
`[${PLUGIN_ID}] Failed to register agent and command:`,
@@ -183,35 +177,6 @@ export const AdversarialReviewPlugin: Plugin = async (ctx) => {
throw err;
}
},
-
- "tool.execute.after": async (input, _output) => {
- if (!reviewGateEnabled || !client) return;
- if (["edit", "write", "patch"].includes(input.tool)) {
- pendingReview = true;
- }
- },
-
- "chat.message": async (input, _output) => {
- if (!reviewGateEnabled || !client) return;
- if (input.agent === AGENT_NAME) {
- pendingReview = false;
- return;
- }
- if (!pendingReview) return;
- pendingReview = false;
-
- try {
- await client.session.command({
- path: { id: input.sessionID },
- body: { command: CMD_NAME, arguments: "" },
- });
- } catch (err) {
- console.error(
- `[${PLUGIN_ID}] Review gate failed:`,
- err instanceof Error ? err.message : String(err),
- );
- }
- },
};
};
From 5a9e3856c43e6c78598b64f8533ef26da5ffc4f1 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Fri, 8 May 2026 16:38:26 -0400
Subject: [PATCH 047/115] docs(adversarial-review): align with monorepo
standards and complete documentation
- Update tsconfig.json to extend the monorepo base config
- Align typescript version to ^6.0.3 across package.json and bun.lock
- Complete the README.md with architecture diagrams, feature lists, usage examples, and configuration details
- Document --scope and --base arguments
Context:
- Updated packages/opencode-adversarial-review/README.md with adversarial review conventions
---
bun.lock | 4 +-
.../opencode-adversarial-review/README.md | 102 ++++++++++++++++--
.../opencode-adversarial-review/package.json | 2 +-
.../opencode-adversarial-review/tsconfig.json | 8 +-
4 files changed, 95 insertions(+), 21 deletions(-)
diff --git a/bun.lock b/bun.lock
index 350ae84..28eed0e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -23,7 +23,7 @@
"@opencode-ai/plugin": ">=1.14.0",
"@tsconfig/node22": "^22.0.0",
"@types/bun": "latest",
- "typescript": "^5.8.0",
+ "typescript": "^6.0.3",
},
"peerDependencies": {
"@opencode-ai/plugin": ">=1.14.0",
@@ -694,8 +694,6 @@
"@babel/helper-create-class-features-plugin/semver": ["semver@6.3.1", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA=="],
- "@capybearista/opencode-adversarial-review/typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
-
"@changesets/parse/js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="],
"@manypkg/find-root/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="],
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
index f724bf0..1ba2d72 100644
--- a/packages/opencode-adversarial-review/README.md
+++ b/packages/opencode-adversarial-review/README.md
@@ -16,21 +16,56 @@
## Philosophy: Extending OpenCode
-OpenCode is designed to be highly extensible. This plugin hooks into the OpenCode lifecycle to provide additional functionality seamlessly into your workflows.
+```mermaid
+graph TB
+ subgraph Host [OpenCode Host]
+ User([User]) -->|/adversarial-review| Command[Command Template]
+ end
+
+ subgraph Injection [Context Injection]
+ direction LR
+ Command -->|!git status| S[Status]
+ Command -->|!git log| L[Commits]
+ Command -->|!git diff| D[Diff Summary]
+ Command -->|!cat| U[Untracked]
+ end
+
+ subgraph Adversary [Adversarial Subagent]
+ direction TB
+ Reviewer{Adversarial Reviewer}
+ S & L & D & U --> Reviewer
+
+ Reviewer -->|Self-Collect| Tools[Explorer Tools]
+ Tools -->|Source Code| Reviewer
+ end
+
+ Reviewer -->|Structured JSON| User
+
+ classDef host fill:#bbf,stroke:#333,stroke-width:2px;
+ classDef collection fill:#dfd,stroke:#333,stroke-width:1px,stroke-dasharray: 5 5;
+ classDef adversary fill:#f9f,stroke:#333,stroke-width:2px;
+
+ class Host host;
+ class Collection collection;
+ class Adversary adversary;
+```
+
+The plugin uses a **stateless subagent architecture**. When the command is invoked, a deterministic shell script collects git metadata (diff stat, untracked files, recent commits) and injects it into a fresh subagent session. This ensures the review is unbiased by the primary agent's conversation history.
## Features
-
+- **Adversarial Persona**: A specialized subagent prompted to find reasons *not* to ship, prioritizing auth gaps, race conditions, and data loss.
+- **Dynamic Context Collection**: Automatically switches between full-inline diff (for 1-2 files) and high-level stat (for larger changes).
+- **Subagent Self-Collection**: The subagent uses whitelisted git and file tools to "pull" the specific file contents it needs based on the initial diff summary.
+- **Structured JSON Output**: Returns findings with severity, file locations, confidence scores, and concrete recommendations.
+- **Configurable Scope**: Support for `--base `, `--scope branch`, and `--scope working-tree`.
## Install
-
-
-
Add the plugin to `opencode.json` or `opencode.jsonc`:
```json
{
@@ -42,27 +77,72 @@ You can also install it through the CLI:
```bash
opencode plugin -g @capybearista/opencode-adversarial-review # global install
-opencode plugin @capybearista/opencode-adversarial-review # project-local install
+opencode plugin @capybearista/opencode-adversarial-review # project-local install
```
## Usage
-
+Run a review on your current working tree changes:
+```bash
+/adversarial-review
+```
+
+### Arguments
+
+| Argument | Values | Description |
+| :--- | :--- | :--- |
+| `--scope` | `auto`, `working-tree`, `branch` | The range of changes to review. Defaults to `auto`. |
+| `--base` | `` | The base reference (branch or commit) to compare against when using `branch` scope. |
+
+- **`auto`**: Reviews using the broadest context the provided information supports.
+- **`working-tree`**: Reviews staged and unstaged changes against `HEAD`.
+- **`branch`**: Reviews all changes on the current branch since it diverged from the upstream or main branch.
+- **`focus ...`**: Any trailing text is treated as a focus area for the review.
+
+### Examples
+
+Force review of only working tree changes (ignoring branch history):
+```bash
+/adversarial-review --scope working-tree
+```
+
+Review all changes on the current branch (automatically finds the fork point):
+```bash
+/adversarial-review --scope branch
+```
+
+Review a specific branch against its fork point from `main`:
+```bash
+/adversarial-review --base main
+```
+
+Review with a specific focus area:
+```bash
+/adversarial-review --base main focus on race conditions in the auth middleware
+```
## Configuration
-
+| Property | Type | Description |
+| :--- | :--- | :--- |
+| `agent.adversarial-review.model` | `string` | The model to use for the subagent (defaults to `openai/gpt-5.4`). |
+| `agent.adversarial-review.temperature` | `number` | Sampling temperature (defaults to `0.1` for deterministic review). |
+| `command.adversarial-review.template` | `string` | The shell-injected template used to gather git context. |
+
+This plugin requires no manual configuration out of the box, but you can override the subagent model in your local `opencode.json`.
## Troubleshooting
-
+- **"No changes to review"**: Ensure you have staged or unstaged changes, or use `--base` to review a committed branch.
+- **Model timeouts**: Large diffs may require a model with a larger context window or more time. The subagent is whitelisted to `read` files if the diff stat is too long to include.
+- **Git errors**: Ensure you are running within a git repository. The command relies on `git` being available in your PATH.
## Contributing
This package lives in the `opencode-plugins` monorepo.
- Run `bun run build`, `bun run typecheck`, `bun run lint`, and `bun test` before opening a PR.
-- Keep the plugin focused on adversarial code review.
+- Keep the plugin focused on the adversarial code review function.
- Prefer small, direct changes.
Please open an issue or check for existing ones before creating a pull request.
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
index e37fe1c..0d16526 100644
--- a/packages/opencode-adversarial-review/package.json
+++ b/packages/opencode-adversarial-review/package.json
@@ -31,6 +31,6 @@
"@opencode-ai/plugin": ">=1.14.0",
"@tsconfig/node22": "^22.0.0",
"@types/bun": "latest",
- "typescript": "^5.8.0"
+ "typescript": "^6.0.3"
}
}
diff --git a/packages/opencode-adversarial-review/tsconfig.json b/packages/opencode-adversarial-review/tsconfig.json
index 89ac3f4..55fc2bb 100644
--- a/packages/opencode-adversarial-review/tsconfig.json
+++ b/packages/opencode-adversarial-review/tsconfig.json
@@ -1,12 +1,8 @@
{
- "extends": "@tsconfig/node22/tsconfig.json",
+ "extends": "../../tsconfig.base.json",
"compilerOptions": {
- "module": "nodenext",
- "moduleResolution": "nodenext",
"rootDir": "src",
- "outDir": "dist",
- "declaration": true,
- "sourceMap": true
+ "outDir": "dist"
},
"include": ["src"],
"exclude": ["dist", "node_modules", "src/**/*.test.ts"]
From cb28b095165eb711985e5156bf24bd6650a1d104 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Fri, 8 May 2026 16:48:50 -0400
Subject: [PATCH 048/115] chore(adversarial-review): add changeset
---
.changeset/cool-bears-review.md | 5 +++++
packages/opencode-adversarial-review/tsconfig.json | 3 ++-
2 files changed, 7 insertions(+), 1 deletion(-)
create mode 100644 .changeset/cool-bears-review.md
diff --git a/.changeset/cool-bears-review.md b/.changeset/cool-bears-review.md
new file mode 100644
index 0000000..fc161de
--- /dev/null
+++ b/.changeset/cool-bears-review.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-adversarial-review": minor
+---
+
+Initial release of the adversarial code review plugin. Adds the `/adversarial-review` command and specialized subagent for zero-trust code auditing.
diff --git a/packages/opencode-adversarial-review/tsconfig.json b/packages/opencode-adversarial-review/tsconfig.json
index 55fc2bb..168da08 100644
--- a/packages/opencode-adversarial-review/tsconfig.json
+++ b/packages/opencode-adversarial-review/tsconfig.json
@@ -2,7 +2,8 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
- "outDir": "dist"
+ "outDir": "dist",
+ "types": ["bun", "node"]
},
"include": ["src"],
"exclude": ["dist", "node_modules", "src/**/*.test.ts"]
From 6d005dd6c7fbfa1172d126594951d975c342d65e Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 12:48:52 -0400
Subject: [PATCH 049/115] refactor(adversarial-review): enhance shell safety
and documentation
Standardized the command template with printf for robust headers and normalized wc -l output to ensure cross-platform numeric comparisons. Increased the full diff threshold to 5 files and added whitelisted git operations for the adversarial subagent. Documented the security model in the README.
Context:
- Added Permissions & Security section to README.md
- Added Roadmap note for configurable threshold in codex-comparison.md
- Updated index.test.ts assertions for simplified template matching
---
docs/ram-monitor/codex-comparison.md | 7 +++++++
packages/opencode-adversarial-review/README.md | 9 +++++++++
.../opencode-adversarial-review/src/index.test.ts | 4 ++--
packages/opencode-adversarial-review/src/index.ts | 12 ++++++------
4 files changed, 24 insertions(+), 8 deletions(-)
diff --git a/docs/ram-monitor/codex-comparison.md b/docs/ram-monitor/codex-comparison.md
index 0ea1d66..52891e2 100644
--- a/docs/ram-monitor/codex-comparison.md
+++ b/docs/ram-monitor/codex-comparison.md
@@ -117,3 +117,10 @@
3. **Permission-based security**: Codex uses server-side `sandbox: "read-only"`. We use OpenCode's permission system. Both achieve the same goal.
4. **No broker**: OpenCode manages model sessions internally.
5. **Stateless**: No job tracking needed — OpenCode's conversation history IS the review history.
+
+---
+
+## Future Considerations
+
+> [!NOTE]
+> **Configurable Diff Threshold**: Currently, the plugin uses a hardcoded threshold (5 files) to decide between a `full diff` and a `stat-only` summary. To improve flexibility, we should consider moving this to a configuration option (e.g., `command.adversarial-review.fullDiffThreshold`). This would allow users with larger context window models to opt-in to fuller context by default.
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
index 1ba2d72..d10bd5c 100644
--- a/packages/opencode-adversarial-review/README.md
+++ b/packages/opencode-adversarial-review/README.md
@@ -131,6 +131,15 @@ Review with a specific focus area:
This plugin requires no manual configuration out of the box, but you can override the subagent model in your local `opencode.json`.
+## Permissions & Security
+
+This plugin is designed with a "least privilege" security model. The adversarial subagent is strictly sandboxed to prevent accidental or malicious modifications to your codebase:
+
+- **Edit**: Explicitly denied (`edit: deny`).
+- **Bash**: Restricted to a read-only whitelist of 12 Git patterns (e.g., `git diff`, `git log`, `git status`). All other shell commands are blocked.
+- **Read/Grep/Glob**: Allowed (read-only) to enable code inspection.
+- **Network**: Web fetch and search are disabled to ensure the review remains focused on the files at hand.
+
## Troubleshooting
- **"No changes to review"**: Ensure you have staged or unstaged changes, or use `--base` to review a committed branch.
diff --git a/packages/opencode-adversarial-review/src/index.test.ts b/packages/opencode-adversarial-review/src/index.test.ts
index 85e7402..4c9cc1e 100644
--- a/packages/opencode-adversarial-review/src/index.test.ts
+++ b/packages/opencode-adversarial-review/src/index.test.ts
@@ -187,8 +187,8 @@ describe("@capybearista/opencode-adversarial-review", () => {
const template = cfg.command["adversarial-review"].template;
expect(template).toInclude("Arguments: $ARGUMENTS");
expect(template).toInclude("git log");
- expect(template).toInclude("git status");
- expect(template).toInclude("git diff");
+ expect(template).toInclude("status");
+ expect(template).toInclude("diff");
});
test("agent permission denies edit and restricts bash to read-only git subcommands", async () => {
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
index 0d63cae..8756a59 100644
--- a/packages/opencode-adversarial-review/src/index.ts
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -112,12 +112,12 @@ Target: working tree diff
## Git Context
-!\`echo "=== Branch ===" && git branch --show-current\`
-!\`echo "=== Status ===" && git status --short --untracked-files=all\`
-!\`echo "=== Recent Commits ===" && git log --oneline -3\`
-!\`echo "=== Changed Files ===" && git diff HEAD --name-only\`
-!\`echo "=== Untracked File Contents ==="; git ls-files --others --exclude-standard | head -5 | while IFS= read -r f; do echo "--- $f ---" && cat -- "$f" 2>/dev/null | head -c 16384 && echo; done\`
-!\`FILES=$(git diff HEAD --name-only | wc -l); if [ "$FILES" -gt 0 ] && [ "$FILES" -le 2 ]; then echo "=== Full Diff ===" && git diff HEAD; else echo "=== Diff Stat ===" && git diff HEAD --stat; fi\``;
+!\`printf "=== Branch ===\\n" && git branch --show-current\`
+!\`printf "=== Status ===\\n" && git status --short --untracked-files=all\`
+!\`printf "=== Recent Commits ===\\n" && git log --oneline -3\`
+!\`printf "=== Changed Files ===\\n" && git diff HEAD --name-only\`
+!\`printf "=== Untracked File Contents ===\\n"; git ls-files --others --exclude-standard | head -5 | while IFS= read -r f; do printf "--- %s ---\\n" "$f" && cat -- "$f" 2>/dev/null | head -c 16384 && printf "\\n"; done\`
+!\`FILES=\$(git diff HEAD --name-only | wc -l | tr -d ' '); if [ "\$FILES" -gt 0 ] && [ "\$FILES" -le 5 ]; then printf "=== Full Diff ===\\n" && git diff HEAD; else printf "=== Diff Stat ===\\n" && git diff HEAD --stat; fi\``;
const AGENT_NAME = "adversarial-review";
const CMD_NAME = "adversarial-review";
From 11d318a34c1fed59fbb5d09c2c510b0f5d905f68 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 14:31:54 -0400
Subject: [PATCH 050/115] fix(double-tap-timeline): use keymap.dispatchCommand
for v1.14.42 compatibility
The double-tap Escape feature stopped working after OpenCode v1.14.42 due to the keymap API refactor. Changed from the removed api.command.trigger() to api.keymap.dispatchCommand().
---
packages/opencode-double-tap-timeline/src/index.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/opencode-double-tap-timeline/src/index.ts b/packages/opencode-double-tap-timeline/src/index.ts
index c5abf12..949ce04 100644
--- a/packages/opencode-double-tap-timeline/src/index.ts
+++ b/packages/opencode-double-tap-timeline/src/index.ts
@@ -32,7 +32,7 @@ export const tui: TuiPlugin = async (api) => {
const sessionID = api.route.current.params?.sessionID as string | undefined;
if (!sessionID) return;
- api.command.trigger("session.timeline");
+ (api as any).keymap.dispatchCommand("session.timeline");
return;
}
From 9a98d68f5d685af2bcefc105029cabe16a3aaad2 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 14:33:08 -0400
Subject: [PATCH 051/115] chore(double-tap-timeline): add changeset
---
.changeset/flat-facts-read.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/flat-facts-read.md
diff --git a/.changeset/flat-facts-read.md b/.changeset/flat-facts-read.md
new file mode 100644
index 0000000..da6e7bd
--- /dev/null
+++ b/.changeset/flat-facts-read.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-double-tap-timeline": patch
+---
+
+Fix for OpenCode v1.14.42 keymap API change
From 8118f5f08f8391ecb2427aa1102b243358e1c80e Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sat, 9 May 2026 14:37:46 -0400
Subject: [PATCH 052/115] fix(adversarial-review): protect against git
quotepath failures
By default, git ls-files may output quoted paths if filenames contain special characters (such as spaces or quotes). These quotes will cause the subsequent cat command to fail. Using git -c core.quotepath=false ensures that paths are output literally, making the context collection loop more robust.
---
packages/opencode-adversarial-review/src/index.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
index 8756a59..0f5cc7f 100644
--- a/packages/opencode-adversarial-review/src/index.ts
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -116,7 +116,7 @@ Target: working tree diff
!\`printf "=== Status ===\\n" && git status --short --untracked-files=all\`
!\`printf "=== Recent Commits ===\\n" && git log --oneline -3\`
!\`printf "=== Changed Files ===\\n" && git diff HEAD --name-only\`
-!\`printf "=== Untracked File Contents ===\\n"; git ls-files --others --exclude-standard | head -5 | while IFS= read -r f; do printf "--- %s ---\\n" "$f" && cat -- "$f" 2>/dev/null | head -c 16384 && printf "\\n"; done\`
+!\`printf "=== Untracked File Contents ===\\n"; git -c core.quotepath=false ls-files --others --exclude-standard | head -5 | while IFS= read -r f; do printf "--- %s ---\\n" "$f" && cat -- "$f" 2>/dev/null | head -c 16384 && printf "\\n"; done\`
!\`FILES=\$(git diff HEAD --name-only | wc -l | tr -d ' '); if [ "\$FILES" -gt 0 ] && [ "\$FILES" -le 5 ]; then printf "=== Full Diff ===\\n" && git diff HEAD; else printf "=== Diff Stat ===\\n" && git diff HEAD --stat; fi\``;
const AGENT_NAME = "adversarial-review";
From 8895e67e2328a99028a5512414c194006545c79c Mon Sep 17 00:00:00 2001
From: Arjun Pramanik
Date: Sat, 9 May 2026 14:38:50 -0400
Subject: [PATCH 053/115] fix(adversarial-review): clarify wording
---
packages/opencode-adversarial-review/src/index.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/opencode-adversarial-review/src/index.ts b/packages/opencode-adversarial-review/src/index.ts
index 0f5cc7f..b05b10c 100644
--- a/packages/opencode-adversarial-review/src/index.ts
+++ b/packages/opencode-adversarial-review/src/index.ts
@@ -108,7 +108,7 @@ Before finalizing, check that each finding is:
const COMMAND_TEMPLATE = `## Adversarial Review
Arguments: $ARGUMENTS
-Target: working tree diff
+Target: code changes
## Git Context
From ebd924b426bda11b3caf42e06b803d8490a0423f Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 15:35:27 -0400
Subject: [PATCH 054/115] chore(double-tap-timeline): update peer dep to
>=1.14.42
The keymap API was introduced in v1.14.42. Updating peer dependency
to accurately reflect the plugin's requirements.
---
packages/opencode-double-tap-timeline/package.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/opencode-double-tap-timeline/package.json b/packages/opencode-double-tap-timeline/package.json
index fbacdb5..5d3a3f8 100644
--- a/packages/opencode-double-tap-timeline/package.json
+++ b/packages/opencode-double-tap-timeline/package.json
@@ -34,12 +34,12 @@
"test": "bun test"
},
"peerDependencies": {
- "@opencode-ai/plugin": ">=1.14.24",
+ "@opencode-ai/plugin": ">=1.14.42",
"@opentui/solid": ">=0.1.103",
"solid-js": ">=1.9.0"
},
"devDependencies": {
- "@opencode-ai/plugin": ">=1.14.24",
+ "@opencode-ai/plugin": ">=1.14.42",
"@opentui/solid": ">=0.1.103",
"@opentui/core": ">=0.1.103",
"solid-js": ">=1.9.0"
From cf34d9f95e54cbc0f6f256814cb977397654017d Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 15:37:49 -0400
Subject: [PATCH 055/115] Revert "chore(double-tap-timeline): update peer dep
to >=1.14.42"
This reverts commit ebd924b426bda11b3caf42e06b803d8490a0423f.
---
packages/opencode-double-tap-timeline/package.json | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/opencode-double-tap-timeline/package.json b/packages/opencode-double-tap-timeline/package.json
index 5d3a3f8..fbacdb5 100644
--- a/packages/opencode-double-tap-timeline/package.json
+++ b/packages/opencode-double-tap-timeline/package.json
@@ -34,12 +34,12 @@
"test": "bun test"
},
"peerDependencies": {
- "@opencode-ai/plugin": ">=1.14.42",
+ "@opencode-ai/plugin": ">=1.14.24",
"@opentui/solid": ">=0.1.103",
"solid-js": ">=1.9.0"
},
"devDependencies": {
- "@opencode-ai/plugin": ">=1.14.42",
+ "@opencode-ai/plugin": ">=1.14.24",
"@opentui/solid": ">=0.1.103",
"@opentui/core": ">=0.1.103",
"solid-js": ">=1.9.0"
From 254b7f970694e7d1c580bb90849675f04098eebb Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 15:49:43 -0400
Subject: [PATCH 056/115] fix(double-tap-timeline): update peerDependency to
>=1.14.42
Reflects minimum required OpenCode version after keymap API change.
---
packages/opencode-double-tap-timeline/package.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/opencode-double-tap-timeline/package.json b/packages/opencode-double-tap-timeline/package.json
index fbacdb5..98e9311 100644
--- a/packages/opencode-double-tap-timeline/package.json
+++ b/packages/opencode-double-tap-timeline/package.json
@@ -34,7 +34,7 @@
"test": "bun test"
},
"peerDependencies": {
- "@opencode-ai/plugin": ">=1.14.24",
+ "@opencode-ai/plugin": ">=1.14.42",
"@opentui/solid": ">=0.1.103",
"solid-js": ">=1.9.0"
},
From 7e5b6c2a4e957798b53d8c1d9b64bc3c7b3eb522 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
<41898282+github-actions[bot]@users.noreply.github.com>
Date: Sat, 9 May 2026 19:52:55 +0000
Subject: [PATCH 057/115] Version Packages
---
.changeset/cool-bears-review.md | 5 -----
packages/opencode-adversarial-review/CHANGELOG.md | 7 +++++++
packages/opencode-adversarial-review/package.json | 2 +-
3 files changed, 8 insertions(+), 6 deletions(-)
delete mode 100644 .changeset/cool-bears-review.md
create mode 100644 packages/opencode-adversarial-review/CHANGELOG.md
diff --git a/.changeset/cool-bears-review.md b/.changeset/cool-bears-review.md
deleted file mode 100644
index fc161de..0000000
--- a/.changeset/cool-bears-review.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@capybearista/opencode-adversarial-review": minor
----
-
-Initial release of the adversarial code review plugin. Adds the `/adversarial-review` command and specialized subagent for zero-trust code auditing.
diff --git a/packages/opencode-adversarial-review/CHANGELOG.md b/packages/opencode-adversarial-review/CHANGELOG.md
new file mode 100644
index 0000000..4534d06
--- /dev/null
+++ b/packages/opencode-adversarial-review/CHANGELOG.md
@@ -0,0 +1,7 @@
+# @capybearista/opencode-adversarial-review
+
+## 0.1.0
+
+### Minor Changes
+
+- cb28b09: Initial release of the adversarial code review plugin. Adds the `/adversarial-review` command and specialized subagent for zero-trust code auditing.
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
index 0d16526..72d7204 100644
--- a/packages/opencode-adversarial-review/package.json
+++ b/packages/opencode-adversarial-review/package.json
@@ -1,6 +1,6 @@
{
"name": "@capybearista/opencode-adversarial-review",
- "version": "0.0.0",
+ "version": "0.1.0",
"description": "Adversarial code review plugin",
"author": "capyBearista ",
"license": "MPL-2.0",
From 65e9779e5931afbfa8c78053574b0d8cc1fa1893 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 16:07:24 -0400
Subject: [PATCH 058/115] chore(adversarial-review): add changeset
---
.changeset/sixty-hotels-shine.md | 5 +++++
1 file changed, 5 insertions(+)
create mode 100644 .changeset/sixty-hotels-shine.md
diff --git a/.changeset/sixty-hotels-shine.md b/.changeset/sixty-hotels-shine.md
new file mode 100644
index 0000000..7a4ed32
--- /dev/null
+++ b/.changeset/sixty-hotels-shine.md
@@ -0,0 +1,5 @@
+---
+"@capybearista/opencode-adversarial-review": major
+---
+
+bump to v1.0.0
From 6d44870d6b23005a63db06923e99b0f0b2f13532 Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
<41898282+github-actions[bot]@users.noreply.github.com>
Date: Sat, 9 May 2026 20:07:51 +0000
Subject: [PATCH 059/115] Version Packages
---
.changeset/sixty-hotels-shine.md | 5 -----
packages/opencode-adversarial-review/CHANGELOG.md | 6 ++++++
packages/opencode-adversarial-review/package.json | 2 +-
3 files changed, 7 insertions(+), 6 deletions(-)
delete mode 100644 .changeset/sixty-hotels-shine.md
diff --git a/.changeset/sixty-hotels-shine.md b/.changeset/sixty-hotels-shine.md
deleted file mode 100644
index 7a4ed32..0000000
--- a/.changeset/sixty-hotels-shine.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@capybearista/opencode-adversarial-review": major
----
-
-bump to v1.0.0
diff --git a/packages/opencode-adversarial-review/CHANGELOG.md b/packages/opencode-adversarial-review/CHANGELOG.md
index 4534d06..ed9af4a 100644
--- a/packages/opencode-adversarial-review/CHANGELOG.md
+++ b/packages/opencode-adversarial-review/CHANGELOG.md
@@ -1,5 +1,11 @@
# @capybearista/opencode-adversarial-review
+## 1.0.0
+
+### Major Changes
+
+- 65e9779: bump to v1.0.0
+
## 0.1.0
### Minor Changes
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
index 72d7204..50ecbe1 100644
--- a/packages/opencode-adversarial-review/package.json
+++ b/packages/opencode-adversarial-review/package.json
@@ -1,6 +1,6 @@
{
"name": "@capybearista/opencode-adversarial-review",
- "version": "0.1.0",
+ "version": "1.0.0",
"description": "Adversarial code review plugin",
"author": "capyBearista ",
"license": "MPL-2.0",
From c2563726086ccd8422d9a4686e16934f2c8b45dd Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 16:19:46 -0400
Subject: [PATCH 060/115] chore(adversarial-review): add repository metadata to
package.json
---
packages/opencode-adversarial-review/package.json | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
index 72d7204..6987096 100644
--- a/packages/opencode-adversarial-review/package.json
+++ b/packages/opencode-adversarial-review/package.json
@@ -3,8 +3,13 @@
"version": "0.1.0",
"description": "Adversarial code review plugin",
"author": "capyBearista ",
- "license": "MPL-2.0",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/capyBearista/opencode-plugins.git",
+ "directory": "packages/opencode-adversarial-review"
+ },
"type": "module",
+ "license": "MPL-2.0",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"files": [
From 3414d94cbda276392ba1d2c4b5449976686a566d Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 16:58:11 -0400
Subject: [PATCH 061/115] chore(repo): add plugin to README, update license
links
---
LICENSE => LICENSE.txt | 0
README.md | 42 +++++++++++++++----
.../{LICENSE => LICENSE.txt} | 0
.../opencode-adversarial-review/README.md | 8 ++--
.../{LICENSE => LICENSE.txt} | 0
packages/opencode-agents-loader/README.md | 8 ++--
.../{LICENSE => LICENSE.txt} | 0
.../opencode-double-tap-timeline/README.md | 4 +-
.../{LICENSE => LICENSE.txt} | 0
packages/opencode-output-styles/README.md | 8 ++--
10 files changed, 47 insertions(+), 23 deletions(-)
rename LICENSE => LICENSE.txt (100%)
rename packages/opencode-adversarial-review/{LICENSE => LICENSE.txt} (100%)
rename packages/opencode-agents-loader/{LICENSE => LICENSE.txt} (100%)
rename packages/opencode-double-tap-timeline/{LICENSE => LICENSE.txt} (100%)
rename packages/opencode-output-styles/{LICENSE => LICENSE.txt} (100%)
diff --git a/LICENSE b/LICENSE.txt
similarity index 100%
rename from LICENSE
rename to LICENSE.txt
diff --git a/README.md b/README.md
index 4d674a2..3e07371 100644
--- a/README.md
+++ b/README.md
@@ -19,14 +19,22 @@
-A collection of plugins for the OpenCode AI coding agent. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
+A collection of plugins for the OpenCode AI harness. These extensions add quality-of-life improvements, user interface features, and new configuration standards.
## Meet The Plugins
+### 🤺 [opencode-adversarial-review](./packages/opencode-adversarial-review/)
+
+Adversarial code review that challenges your implementation approach and design choices, not just finding bugs. Uses a clean-context subagent so the review stays unbiased by conversation history, prioritizing auth gaps, data loss, etc. Returns structured JSON findings with severity, confidence scores, and recommendations.
+
+*Inspired by Codex*
+
### 🗣️ [opencode-output-styles](./packages/opencode-output-styles/)
Persistent response styles for OpenCode sessions. This plugin injects selected guidelines (like "explanatory" or "learning" modes) into the system prompt so they stay active across your session.
+*Inspired by Claude Code*
+
### 🛠️ [opencode-agents-loader](./packages/opencode-agents-loader/)
Extends command and agent discovery to the `.agents/` directory standard. This enables interoperability with other AI tools and keeps project configuration organized.
@@ -35,13 +43,15 @@ Extends command and agent discovery to the `.agents/` directory standard. This e
A keyboard-driven UI extension. Double-tap the Escape key to instantly open the session timeline modal without typing commands or using a mouse.
+*Inspired by Claude Code*
+
## Installation
-You can install any of these plugins globally or locally using the OpenCode CLI:
+You can install any of these plugins globally or project-locally using the OpenCode CLI:
```bash
-opencode plugin add -g @capybearista/opencode-output-styles
-opencode plugin add @capybearista/opencode-output-styles
+opencode plugin add -g @capybearista/opencode-adversarial-review@latest # global install
+opencode plugin add @capybearista/opencode-adversarial-review@latest # project-local install
```
Alternatively, add them directly to your `opencode.json`/`opencode.jsonc` configuration file:
@@ -49,20 +59,30 @@ Alternatively, add them directly to your `opencode.json`/`opencode.jsonc` config
```json
{
"plugin": [
- "@capybearista/opencode-output-styles",
- "@capybearista/opencode-agents-loader"
+ "@capybearista/opencode-adversarial-review@latest",
+ "@capybearista/opencode-output-styles@latest",
+ "@capybearista/opencode-agents-loader@latest"
]
}
```
-For TUI-based plugins, add them directly to `tui.json`/`tui.jsonc`:
+For **TUI-based plugins**, add them directly to `tui.json`/`tui.jsonc`:
```json
{
- "plugin": ["@capybearista/opencode-double-tap-timeline"]
+ "plugin": ["@capybearista/opencode-double-tap-timeline@latest"]
}
```
+### Updating
+
+OpenCode does NOT care about the `@latest` tag after initial installation of a plugin. Instead, you must either manually set and change the tag (e.g., `@1.0.0` to `@2.0.0`) or simply run this command:
+
+```bash
+rm -rf ~/.cache/opencode/packages/@latest/
+opencode plugin @latest --global
+```
+
## What Should I Build Next?
Every plugin here started because someone hit a wall with OpenCode and thought _"there's gotta be a better way."_
@@ -105,6 +125,10 @@ bun run test
Please review the [contribution guidelines](./CONTRIBUTING.md) before contributing :)
+## Disclaimer
+
+This project is not affiliated with the anomalyco/opencode team in any way. These plugins are independently developed and maintained. I do this for the love of the game ¯\\_(ツ)_/¯
+
## License
-[MPL-2.0](./LICENSE)
+[MPL-2.0](./LICENSE.txt)
diff --git a/packages/opencode-adversarial-review/LICENSE b/packages/opencode-adversarial-review/LICENSE.txt
similarity index 100%
rename from packages/opencode-adversarial-review/LICENSE
rename to packages/opencode-adversarial-review/LICENSE.txt
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
index d10bd5c..2848958 100644
--- a/packages/opencode-adversarial-review/README.md
+++ b/packages/opencode-adversarial-review/README.md
@@ -69,15 +69,15 @@ The plugin uses a **stateless subagent architecture**. When the command is invok
Add the plugin to `opencode.json` or `opencode.jsonc`:
```json
{
- "plugin": ["@capybearista/opencode-adversarial-review"]
+ "plugin": ["@capybearista/opencode-adversarial-review@latest"]
}
```
You can also install it through the CLI:
```bash
-opencode plugin -g @capybearista/opencode-adversarial-review # global install
-opencode plugin @capybearista/opencode-adversarial-review # project-local install
+opencode plugin -g @capybearista/opencode-adversarial-review@latest # global install
+opencode plugin @capybearista/opencode-adversarial-review@latest # project-local install
```
## Usage
@@ -158,4 +158,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE)
+[MPL-2.0](./LICENSE.txt)
diff --git a/packages/opencode-agents-loader/LICENSE b/packages/opencode-agents-loader/LICENSE.txt
similarity index 100%
rename from packages/opencode-agents-loader/LICENSE
rename to packages/opencode-agents-loader/LICENSE.txt
diff --git a/packages/opencode-agents-loader/README.md b/packages/opencode-agents-loader/README.md
index 650ef02..345bb4b 100644
--- a/packages/opencode-agents-loader/README.md
+++ b/packages/opencode-agents-loader/README.md
@@ -45,15 +45,15 @@ Add the plugin to `opencode.json` or `opencode.jsonc`:
```json
{
- "plugin": ["@capybearista/opencode-agents-loader"]
+ "plugin": ["@capybearista/opencode-agents-loader@latest"]
}
```
You can also install it through the CLI:
```bash
-opencode plugin -g @capybearista/opencode-agents-loader # global install
-opencode plugin @capybearista/opencode-agents-loader # project-local install
+opencode plugin -g @capybearista/opencode-agents-loader@latest # global install
+opencode plugin @capybearista/opencode-agents-loader@latest # project-local install
```
## Usage
@@ -135,4 +135,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE)
+[MPL-2.0](./LICENSE.txt)
diff --git a/packages/opencode-double-tap-timeline/LICENSE b/packages/opencode-double-tap-timeline/LICENSE.txt
similarity index 100%
rename from packages/opencode-double-tap-timeline/LICENSE
rename to packages/opencode-double-tap-timeline/LICENSE.txt
diff --git a/packages/opencode-double-tap-timeline/README.md b/packages/opencode-double-tap-timeline/README.md
index 67f1261..9aab41b 100644
--- a/packages/opencode-double-tap-timeline/README.md
+++ b/packages/opencode-double-tap-timeline/README.md
@@ -45,7 +45,7 @@ Add the plugin to `tui.json` or `tui.jsonc`:
```json
{
- "plugin": ["@capybearista/opencode-double-tap-timeline"]
+ "plugin": ["@capybearista/opencode-double-tap-timeline@latest"]
}
```
@@ -78,4 +78,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE)
+[MPL-2.0](./LICENSE.txt)
diff --git a/packages/opencode-output-styles/LICENSE b/packages/opencode-output-styles/LICENSE.txt
similarity index 100%
rename from packages/opencode-output-styles/LICENSE
rename to packages/opencode-output-styles/LICENSE.txt
diff --git a/packages/opencode-output-styles/README.md b/packages/opencode-output-styles/README.md
index c046d4c..1f379b0 100644
--- a/packages/opencode-output-styles/README.md
+++ b/packages/opencode-output-styles/README.md
@@ -46,15 +46,15 @@ Add the plugin to `opencode.json` or `opencode.jsonc`:
```json
{
- "plugin": ["@capybearista/opencode-output-styles"]
+ "plugin": ["@capybearista/opencode-output-styles@latest"]
}
```
You can also install it through the CLI:
```bash
-opencode plugin -g @capybearista/opencode-output-styles # global install
-opencode plugin @capybearista/opencode-output-styles # project-local install
+opencode plugin -g @capybearista/opencode-output-styles@latest # global install
+opencode plugin @capybearista/opencode-output-styles@latest # project-local install
```
## Usage
@@ -147,4 +147,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE)
+[MPL-2.0](./LICENSE.txt)
From d57245991d0b2bd560c38942fb09fdb068c8c5c7 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 17:00:44 -0400
Subject: [PATCH 062/115] chore(package): update descriptions for adversarial
review and output styles plugins
---
packages/opencode-adversarial-review/package.json | 2 +-
packages/opencode-output-styles/package.json | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/opencode-adversarial-review/package.json b/packages/opencode-adversarial-review/package.json
index f332c50..37544ac 100644
--- a/packages/opencode-adversarial-review/package.json
+++ b/packages/opencode-adversarial-review/package.json
@@ -1,7 +1,7 @@
{
"name": "@capybearista/opencode-adversarial-review",
"version": "1.0.0",
- "description": "Adversarial code review plugin",
+ "description": "Adversarial code review for OpenCode — challenges implementation approach, finds auth gaps, race conditions, and data loss",
"author": "capyBearista ",
"repository": {
"type": "git",
diff --git a/packages/opencode-output-styles/package.json b/packages/opencode-output-styles/package.json
index 047c74c..9fa3da6 100644
--- a/packages/opencode-output-styles/package.json
+++ b/packages/opencode-output-styles/package.json
@@ -1,7 +1,7 @@
{
"name": "@capybearista/opencode-output-styles",
"version": "1.0.1",
- "description": "Output styles plugin for OpenCode",
+ "description": "Persistent response style guidelines for OpenCode sessions — explanatory, learning, and custom modes that survive restarts",
"author": "capyBearista ",
"repository": {
"type": "git",
From 72fe20de17b5b512abb6d6dd62b3f25d58e4000d Mon Sep 17 00:00:00 2001
From: "github-actions[bot]"
<41898282+github-actions[bot]@users.noreply.github.com>
Date: Sat, 9 May 2026 21:05:30 +0000
Subject: [PATCH 063/115] Version Packages
---
.changeset/flat-facts-read.md | 5 -----
packages/opencode-double-tap-timeline/CHANGELOG.md | 6 ++++++
packages/opencode-double-tap-timeline/package.json | 2 +-
3 files changed, 7 insertions(+), 6 deletions(-)
delete mode 100644 .changeset/flat-facts-read.md
diff --git a/.changeset/flat-facts-read.md b/.changeset/flat-facts-read.md
deleted file mode 100644
index da6e7bd..0000000
--- a/.changeset/flat-facts-read.md
+++ /dev/null
@@ -1,5 +0,0 @@
----
-"@capybearista/opencode-double-tap-timeline": patch
----
-
-Fix for OpenCode v1.14.42 keymap API change
diff --git a/packages/opencode-double-tap-timeline/CHANGELOG.md b/packages/opencode-double-tap-timeline/CHANGELOG.md
index 4c56a51..ee5e2d7 100644
--- a/packages/opencode-double-tap-timeline/CHANGELOG.md
+++ b/packages/opencode-double-tap-timeline/CHANGELOG.md
@@ -1,5 +1,11 @@
# @capybearista/opencode-double-tap-timeline
+## 1.0.1
+
+### Patch Changes
+
+- 9a98d68: Fix for OpenCode v1.14.42 keymap API change
+
## 1.0.0
### Major Changes
diff --git a/packages/opencode-double-tap-timeline/package.json b/packages/opencode-double-tap-timeline/package.json
index 98e9311..b044b85 100644
--- a/packages/opencode-double-tap-timeline/package.json
+++ b/packages/opencode-double-tap-timeline/package.json
@@ -1,6 +1,6 @@
{
"name": "@capybearista/opencode-double-tap-timeline",
- "version": "1.0.0",
+ "version": "1.0.1",
"description": "Double-tap Escape key to open the timeline modal, inspired by Claude Code's /rewind feature",
"author": "capyBearista ",
"repository": {
From 964be020b1f5229d32a89d36908ec9c1cfa11c76 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 18:18:56 -0400
Subject: [PATCH 064/115] chore(tools): add adversarial review package to
download tracking
---
tools/total-downloads-worker.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/tools/total-downloads-worker.js b/tools/total-downloads-worker.js
index f370d0e..8249e19 100644
--- a/tools/total-downloads-worker.js
+++ b/tools/total-downloads-worker.js
@@ -1,6 +1,7 @@
export default {
async fetch() {
const packages = [
+ "@capybearista/opencode-adversarial-review",
"@capybearista/opencode-agents-loader",
"@capybearista/opencode-double-tap-timeline",
"@capybearista/opencode-output-styles",
From 78c6086ea4e23c686d0283cefc1027cd834a4ceb Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 18:43:23 -0400
Subject: [PATCH 065/115] chore(README): add update instructions
---
packages/opencode-adversarial-review/README.md | 10 ++++++++++
packages/opencode-agents-loader/README.md | 10 ++++++++++
packages/opencode-double-tap-timeline/README.md | 10 ++++++++++
packages/opencode-output-styles/README.md | 10 ++++++++++
4 files changed, 40 insertions(+)
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
index 2848958..c8bc9d5 100644
--- a/packages/opencode-adversarial-review/README.md
+++ b/packages/opencode-adversarial-review/README.md
@@ -80,6 +80,16 @@ opencode plugin -g @capybearista/opencode-adversarial-review@latest # global
opencode plugin @capybearista/opencode-adversarial-review@latest # project-local install
```
+## Updating
+
+Simply run the following command while no active OpenCode sessions are running:
+
+```bash
+rm -rf ~/.cache/opencode/packages/'opencode-adversarial-review@latest'/
+```
+
+The next time you open OpenCode, the new version will be installed!
+
## Usage
Run a review on your current working tree changes:
diff --git a/packages/opencode-agents-loader/README.md b/packages/opencode-agents-loader/README.md
index 345bb4b..4bc6251 100644
--- a/packages/opencode-agents-loader/README.md
+++ b/packages/opencode-agents-loader/README.md
@@ -56,6 +56,16 @@ opencode plugin -g @capybearista/opencode-agents-loader@latest # global insta
opencode plugin @capybearista/opencode-agents-loader@latest # project-local install
```
+## Updating
+
+Simply run the following command while no active OpenCode sessions are running:
+
+```bash
+rm -rf ~/.cache/opencode/packages/'opencode-agents-loader@latest'/
+```
+
+The next time you open OpenCode, the new version will be installed!
+
## Usage
Create markdown files with YAML frontmatter:
diff --git a/packages/opencode-double-tap-timeline/README.md b/packages/opencode-double-tap-timeline/README.md
index 9aab41b..9d91e15 100644
--- a/packages/opencode-double-tap-timeline/README.md
+++ b/packages/opencode-double-tap-timeline/README.md
@@ -49,6 +49,16 @@ Add the plugin to `tui.json` or `tui.jsonc`:
}
```
+## Updating
+
+Simply run the following command while no active OpenCode sessions are running:
+
+```bash
+rm -rf ~/.cache/opencode/packages/'opencode-double-tap-timeline@latest'/
+```
+
+The next time you open OpenCode, the new version will be installed!
+
## Usage
1. Open a session in OpenCode
diff --git a/packages/opencode-output-styles/README.md b/packages/opencode-output-styles/README.md
index 1f379b0..eb1008e 100644
--- a/packages/opencode-output-styles/README.md
+++ b/packages/opencode-output-styles/README.md
@@ -57,6 +57,16 @@ opencode plugin -g @capybearista/opencode-output-styles@latest # global insta
opencode plugin @capybearista/opencode-output-styles@latest # project-local install
```
+## Updating
+
+Simply run the following command while no active OpenCode sessions are running:
+
+```bash
+rm -rf ~/.cache/opencode/packages/'opencode-output-styles@latest'/
+```
+
+The next time you open OpenCode, the new version will be installed!
+
## Usage
### Built-in styles
From 203e30f6fe1039bb1a028008a4b3b99ce36257b6 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 18:51:19 -0400
Subject: [PATCH 066/115] chore(adversarial-review): fix README formatting
---
packages/opencode-adversarial-review/README.md | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/packages/opencode-adversarial-review/README.md b/packages/opencode-adversarial-review/README.md
index c8bc9d5..645386c 100644
--- a/packages/opencode-adversarial-review/README.md
+++ b/packages/opencode-adversarial-review/README.md
@@ -1,13 +1,13 @@
# opencode-adversarial-review
-
Challenge code with adversarial review
+
Unbiased challenges and reviews for your code
-
+
+
---
## Why?
From 78ac6da8692a9dde4a424ab863b8fcd50814fe40 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 22:05:29 -0400
Subject: [PATCH 067/115] fix(ram-monitor): harden session tracking and /ram
failure handling
Validate lockfile-derived PIDs against the preferred live OpenCode process set to avoid stale/reused PID attribution and launcher/core overlap double-counting.\n\nAlso make /ram command interception resilient by only marking handled after successful prompt injection, while keeping diagnostics opt-in through OPENCODE_RAM_MONITOR_DEBUG and documenting global /ram semantics.
---
packages/opencode-ram-monitor/README.md | 16 +-
packages/opencode-ram-monitor/src/debug.ts | 32 +++
.../opencode-ram-monitor/src/index.test.ts | 119 ++++++++-
packages/opencode-ram-monitor/src/memory.ts | 233 ++++++++++++------
packages/opencode-ram-monitor/src/server.ts | 21 +-
packages/opencode-ram-monitor/src/sidebar.tsx | 13 +-
.../opencode-ram-monitor/tsconfig.build.json | 1 -
7 files changed, 339 insertions(+), 96 deletions(-)
create mode 100644 packages/opencode-ram-monitor/src/debug.ts
diff --git a/packages/opencode-ram-monitor/README.md b/packages/opencode-ram-monitor/README.md
index 1f1bbd0..95a7ea2 100644
--- a/packages/opencode-ram-monitor/README.md
+++ b/packages/opencode-ram-monitor/README.md
@@ -41,7 +41,7 @@ Host Architecture
- **Real-time Sidebar Widget**: View your current and total RAM usage natively in the OpenCode TUI sidebar.
- **Active Session Tracking**: Automatically discovers all running OpenCode sessions and aggregates their RAM.
- **Cross-Platform**: Uses native commands (`ps` on Unix, `wmic` on Windows) for lightweight zero-dependency metrics.
-- **`/ram` Command**: Intercepts the `/ram` command to provide a detailed, heavy process-tree breakdown of the current session right in the chat.
+- **`/ram` Command**: Intercepts the `/ram` command to provide a detailed, heavy process-tree breakdown across all active OpenCode sessions right in the chat.
- **Configurable**: Polling intervals can be customized via `.opencode/opencode.json`.
## Install
@@ -64,7 +64,7 @@ Also, add the plugin to `tui.json` or `tui.jsonc`:
Once installed, the RAM monitor will automatically appear in your OpenCode TUI sidebar, polling your system to display the memory usage of your current session and the aggregate total across all active sessions.
-To get a detailed heavy process tree of your current session's memory usage, simply type `/ram` in your OpenCode chat.
+To get a detailed heavy process tree of memory usage across all currently active OpenCode sessions, type `/ram` in your OpenCode chat.
## Configuration
@@ -91,6 +91,16 @@ Example:
- **Active count seems off**: The plugin tokenizes command lines to find active `opencode` processes. Deeply nested wrappers or complex invocation aliases might not be matched.
- **Total RAM shows `0`**: If sampling fails completely (e.g. `ps` is missing), the plugin falls back to using `process.memoryUsage().rss` of the current process. Ensure standard process utilities are available.
+## Debug Logging
+
+Debug logging is disabled by default. To enable diagnostic logs during development:
+
+```bash
+OPENCODE_RAM_MONITOR_DEBUG=1 opencode
+```
+
+When enabled, the plugin appends structured JSON log lines to `.opencode-ram-monitor.log` in the current working directory.
+
## Contributing
This package lives in the `opencode-plugins` monorepo.
@@ -103,4 +113,4 @@ Please open an issue or check for existing ones before creating a pull request.
## License
-[MPL-2.0](LICENSE)
\ No newline at end of file
+[MPL-2.0](LICENSE)
diff --git a/packages/opencode-ram-monitor/src/debug.ts b/packages/opencode-ram-monitor/src/debug.ts
new file mode 100644
index 0000000..42835aa
--- /dev/null
+++ b/packages/opencode-ram-monitor/src/debug.ts
@@ -0,0 +1,32 @@
+import { appendFile } from "node:fs/promises";
+import { join } from "node:path";
+
+const DEBUG_ENV_KEY = "OPENCODE_RAM_MONITOR_DEBUG";
+const DEBUG_LOG_FILE = ".opencode-ram-monitor.log";
+
+export function isRamMonitorDebugEnabled(): boolean {
+ return process.env[DEBUG_ENV_KEY] === "1";
+}
+
+export function getRamMonitorDebugLogPath(cwd: string = process.cwd()): string {
+ return join(cwd, DEBUG_LOG_FILE);
+}
+
+export async function debugLog(
+ event: string,
+ details: Record = {},
+): Promise {
+ if (!isRamMonitorDebugEnabled()) return;
+
+ const payload = {
+ time: new Date().toISOString(),
+ event,
+ ...details,
+ };
+
+ try {
+ await appendFile(getRamMonitorDebugLogPath(), `${JSON.stringify(payload)}\n`, "utf8");
+ } catch {
+ // Keep debug logging best-effort and non-disruptive.
+ }
+}
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
index 79a8e17..6a777f7 100644
--- a/packages/opencode-ram-monitor/src/index.test.ts
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -1,21 +1,28 @@
import "@opentui/solid/preload";
-import { describe, expect, test } from "bun:test";
-import { classifyOpencodeProcess } from "./memory.js";
-import serverModule from "./server.js";
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
+import { getRamMonitorDebugLogPath, isRamMonitorDebugEnabled } from "./debug.js";
+import { classifyOpencodeProcess, selectValidatedSessionPids } from "./memory.js";
import { getErrorMessage, normalizeRefreshIntervalMs } from "./sidebar-config.js";
describe("@capybearista/opencode-ram-monitor", () => {
- test("has an id", () => {
- expect(serverModule.id).toBeString();
- expect(serverModule.id).toBe("capybearista.opencode-ram-monitor");
- });
+ const initialDebugValue = process.env.OPENCODE_RAM_MONITOR_DEBUG;
- test("exports a default object", () => {
- expect(serverModule).toBeObject();
+ beforeEach(() => {
+ mock.restore();
+ if (initialDebugValue === undefined) {
+ delete process.env.OPENCODE_RAM_MONITOR_DEBUG;
+ return;
+ }
+ process.env.OPENCODE_RAM_MONITOR_DEBUG = initialDebugValue;
});
- test("exports server hooks", () => {
- expect(serverModule.server).toBeFunction();
+ afterEach(() => {
+ mock.restore();
+ if (initialDebugValue === undefined) {
+ delete process.env.OPENCODE_RAM_MONITOR_DEBUG;
+ return;
+ }
+ process.env.OPENCODE_RAM_MONITOR_DEBUG = initialDebugValue;
});
test("classifies direct core and launcher commands", () => {
@@ -42,6 +49,33 @@ describe("@capybearista/opencode-ram-monitor", () => {
expect(classifyOpencodeProcess("/bin/sh -c 'echo hello'")).toBeNull();
});
+ test("validates candidate PIDs against live opencode set", () => {
+ const selected = selectValidatedSessionPids([100, 200, 300, process.pid], new Set([100, 300]));
+ expect(selected).toContain(process.pid);
+ expect(selected).toContain(100);
+ expect(selected).toContain(300);
+ expect(selected).not.toContain(200);
+ });
+
+ test("keeps current PID even when not in live set", () => {
+ const currentPid = 777;
+ const selected = selectValidatedSessionPids([111, 222], new Set([111]), currentPid);
+ expect(selected).toEqual([currentPid, 111]);
+ });
+
+ test("excludes lockfile launcher PID when runtime core set is preferred", () => {
+ const currentPid = 900;
+ const lockfileLauncherPid = 120;
+ const runtimeCorePid = 121;
+ const selected = selectValidatedSessionPids(
+ [lockfileLauncherPid, runtimeCorePid],
+ new Set([runtimeCorePid]),
+ currentPid,
+ );
+
+ expect(selected).toEqual([currentPid, runtimeCorePid]);
+ });
+
test("normalizes refresh interval to safe bounds", () => {
expect(normalizeRefreshIntervalMs("200")).toBe(1000);
expect(normalizeRefreshIntervalMs(0)).toBe(1000);
@@ -55,4 +89,67 @@ describe("@capybearista/opencode-ram-monitor", () => {
expect(getErrorMessage("failure")).toBe("failure");
expect(getErrorMessage({ reason: "unknown" })).toBe("RAM error");
});
+
+ test("debug mode env gating works", () => {
+ delete process.env.OPENCODE_RAM_MONITOR_DEBUG;
+ expect(isRamMonitorDebugEnabled()).toBeFalse();
+ process.env.OPENCODE_RAM_MONITOR_DEBUG = "1";
+ expect(isRamMonitorDebugEnabled()).toBeTrue();
+ });
+
+ test("debug log path is cwd-local", () => {
+ expect(getRamMonitorDebugLogPath("/tmp/project")).toBe(
+ "/tmp/project/.opencode-ram-monitor.log",
+ );
+ });
+
+ test("/ram command is handled only after prompt injection succeeds", async () => {
+ mock.module("./memory.js", () => ({
+ getHeavyProcessTree: async () => "tree",
+ }));
+
+ const module = await import("./server.js");
+ const prompts: unknown[] = [];
+
+ const plugin = await module.default.server({
+ client: {
+ session: {
+ prompt: async (payload: unknown) => {
+ prompts.push(payload);
+ },
+ },
+ },
+ } as never);
+
+ const beforeExecute = plugin["command.execute.before"];
+ expect(beforeExecute).toBeFunction();
+ await expect(
+ beforeExecute?.({ command: "ram", sessionID: "s-1" } as never, {} as never),
+ ).rejects.toThrow("__RAM_COMMAND_HANDLED__");
+ expect(prompts.length).toBe(1);
+ });
+
+ test("/ram command falls through when prompt injection fails", async () => {
+ mock.module("./memory.js", () => ({
+ getHeavyProcessTree: async () => "tree",
+ }));
+
+ const module = await import("./server.js");
+
+ const plugin = await module.default.server({
+ client: {
+ session: {
+ prompt: async () => {
+ throw new Error("injection failed");
+ },
+ },
+ },
+ } as never);
+
+ const beforeExecute = plugin["command.execute.before"];
+ expect(beforeExecute).toBeFunction();
+ await expect(
+ beforeExecute?.({ command: "ram", sessionID: "s-1" } as never, {} as never),
+ ).resolves.toBeUndefined();
+ });
});
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
index 16f28f9..e62efd4 100644
--- a/packages/opencode-ram-monitor/src/memory.ts
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -3,6 +3,7 @@ import { readdir, readFile } from "node:fs/promises";
import { homedir, platform } from "node:os";
import { join } from "node:path";
import { promisify } from "node:util";
+import { debugLog } from "./debug.js";
const EXEC_OPTS = { timeout: 5000, windowsHide: true };
const execAsync = promisify(exec);
@@ -77,14 +78,32 @@ export function classifyOpencodeProcess(commandLine: string): "core" | "launcher
return null;
}
-async function getRuntimeSessionPids(): Promise {
+type OpenCodePidSets = {
+ core: Set;
+ launcher: Set;
+ all: Set;
+};
+
+function parseLockfilePid(content: string): number | null {
+ try {
+ const data = JSON.parse(content);
+ if (typeof data?.pid === "number") return data.pid;
+ } catch {
+ const pid = parseInt(content.trim(), 10);
+ if (!Number.isNaN(pid)) return pid;
+ }
+
+ return null;
+}
+
+async function getLiveOpencodePidSets(): Promise {
const osPlatform = platform();
+ const core = new Set();
+ const launcher = new Set();
if (osPlatform === "linux" || osPlatform === "darwin") {
try {
const { stdout } = await execAsync("ps -eo pid=,args=", EXEC_OPTS);
- const corePids: number[] = [];
- const launcherPids: number[] = [];
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
@@ -98,13 +117,15 @@ async function getRuntimeSessionPids(): Promise {
const args = trimmed.slice(firstSpace + 1);
const processKind = classifyOpencodeProcess(args);
- if (processKind === "core") corePids.push(pid);
- if (processKind === "launcher") launcherPids.push(pid);
+ if (processKind === "core") core.add(pid);
+ if (processKind === "launcher") launcher.add(pid);
}
-
- return corePids.length > 0 ? corePids : launcherPids;
- } catch {
- return [];
+ } catch (error) {
+ await debugLog("live-opencode-pids-failed", {
+ platform: osPlatform,
+ source: "ps",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
@@ -114,11 +135,10 @@ async function getRuntimeSessionPids(): Promise {
"wmic process get CommandLine,ProcessId /format:value",
EXEC_OPTS,
);
- const corePids: number[] = [];
- const launcherPids: number[] = [];
const normalized = stdout.replace(/\r\n/g, "\n").trim();
const blocks = normalized.split(/\n\n+/);
+
for (const block of blocks) {
const lines = block.trim().split("\n");
const entry: Record = {};
@@ -134,21 +154,46 @@ async function getRuntimeSessionPids(): Promise {
if (Number.isNaN(pid)) continue;
const processKind = classifyOpencodeProcess(entry.CommandLine || "");
- if (processKind === "core") corePids.push(pid);
- if (processKind === "launcher") launcherPids.push(pid);
+ if (processKind === "core") core.add(pid);
+ if (processKind === "launcher") launcher.add(pid);
}
+ } catch (error) {
+ await debugLog("live-opencode-pids-failed", {
+ platform: osPlatform,
+ source: "wmic",
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+
+ const all = new Set([...core, ...launcher]);
+ return { core, launcher, all };
+}
- return corePids.length > 0 ? corePids : launcherPids;
- } catch {
- return [];
+export function selectValidatedSessionPids(
+ candidates: number[],
+ liveOpencodePids: Set,
+ currentPid: number = process.pid,
+): number[] {
+ const selected = new Set();
+ selected.add(currentPid);
+
+ for (const pid of candidates) {
+ if (!Number.isInteger(pid) || pid <= 0) continue;
+ if (pid === currentPid) {
+ selected.add(pid);
+ continue;
+ }
+ if (liveOpencodePids.has(pid)) {
+ selected.add(pid);
}
}
- return [];
+ return [...selected];
}
-export async function getActiveSessions(): Promise {
- const pids: number[] = [process.pid];
+async function readLockfileCandidates(): Promise {
+ const candidates: number[] = [];
const stateDirs = [
join(homedir(), ".opencode", "state"),
join(homedir(), ".cache", "opencode", "state"),
@@ -160,28 +205,49 @@ export async function getActiveSessions(): Promise {
try {
const files = await readdir(dir);
for (const file of files) {
- if (file.endsWith(".lock")) {
- const content = await readFile(join(dir, file), "utf-8");
- try {
- const data = JSON.parse(content);
- if (data.pid && typeof data.pid === "number") {
- pids.push(data.pid);
- }
- } catch {
- const pid = parseInt(content.trim(), 10);
- if (!Number.isNaN(pid)) {
- pids.push(pid);
- }
- }
+ if (!file.endsWith(".lock")) continue;
+ const filePath = join(dir, file);
+ try {
+ const content = await readFile(filePath, "utf-8");
+ const pid = parseLockfilePid(content);
+ if (pid !== null) candidates.push(pid);
+ } catch (error) {
+ await debugLog("lockfile-read-failed", {
+ file: filePath,
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
- } catch {}
+ } catch (error) {
+ await debugLog("state-dir-read-failed", {
+ dir,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
}
- const runtimePids = await getRuntimeSessionPids();
- pids.push(...runtimePids);
+ return candidates;
+}
- return [...new Set(pids)];
+export async function getActiveSessions(): Promise {
+ const [liveSets, lockfileCandidates] = await Promise.all([
+ getLiveOpencodePidSets(),
+ readLockfileCandidates(),
+ ]);
+
+ const preferredLiveSet = liveSets.core.size > 0 ? liveSets.core : liveSets.launcher;
+ const runtimeCandidates = [...preferredLiveSet];
+ const allCandidates = [process.pid, ...lockfileCandidates, ...runtimeCandidates];
+ const validated = selectValidatedSessionPids(allCandidates, preferredLiveSet, process.pid);
+
+ await debugLog("active-sessions-resolved", {
+ candidates: allCandidates.length,
+ lockfileCandidates: lockfileCandidates.length,
+ runtimeCandidates: runtimeCandidates.length,
+ validated: validated.length,
+ });
+
+ return validated;
}
export interface LightweightRamResult {
@@ -200,7 +266,6 @@ export async function getLightweightRam(): Promise {
const sampledPids = new Set();
if (osPlatform === "linux") {
- // Fast path for Linux/WSL - read VmRSS from /proc//status (kB)
for (const pid of pids) {
try {
const status = await readFile(`/proc/${pid}/status`, "utf-8");
@@ -211,12 +276,16 @@ export async function getLightweightRam(): Promise {
sampledPids.add(pid);
if (pid === process.pid) currentRss = rss;
}
- } catch {
- // Process might have exited or permission denied
+ } catch (error) {
+ await debugLog("rss-sample-failed", {
+ platform: osPlatform,
+ pid,
+ source: "/proc",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
} else if (osPlatform === "darwin") {
- // macOS: query each PID individually to avoid total failure if one PID is stale
for (const pid of pids) {
try {
const { stdout } = await execAsync(`ps -o rss= -p ${pid}`, EXEC_OPTS);
@@ -227,19 +296,23 @@ export async function getLightweightRam(): Promise {
sampledPids.add(pid);
if (pid === process.pid) currentRss = rss;
}
- } catch {
- // Process might have exited
+ } catch (error) {
+ await debugLog("rss-sample-failed", {
+ platform: osPlatform,
+ pid,
+ source: "ps",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
} else if (osPlatform === "win32") {
- // Windows: query each PID individually for reliability
for (const pid of pids) {
try {
const { stdout } = await execAsync(
`wmic process where "ProcessId=${pid}" get WorkingSetSize`,
EXEC_OPTS,
);
- const lines = stdout.trim().split("\n").slice(1); // skip header
+ const lines = stdout.trim().split("\n").slice(1);
for (const line of lines) {
const rssBytes = parseInt(line.trim(), 10);
if (!Number.isNaN(rssBytes)) {
@@ -248,12 +321,16 @@ export async function getLightweightRam(): Promise {
if (pid === process.pid) currentRss = rssBytes;
}
}
- } catch {
- // Process might have exited
+ } catch (error) {
+ await debugLog("rss-sample-failed", {
+ platform: osPlatform,
+ pid,
+ source: "wmic",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
} else {
- // Fallback: just current process
currentRss = process.memoryUsage().rss;
totalRss = currentRss;
sampledPids.add(process.pid);
@@ -266,6 +343,10 @@ export async function getLightweightRam(): Promise {
totalRss += fallbackCurrentRss;
sampledPids.add(process.pid);
}
+ await debugLog("current-rss-fallback-used", {
+ fallbackCurrentRss,
+ sampledCount: sampledPids.size,
+ });
}
return {
@@ -278,7 +359,7 @@ export async function getLightweightRam(): Promise {
export interface ProcessNode {
pid: number;
ppid: number;
- rss: number; // bytes
+ rss: number;
command: string;
children: ProcessNode[];
}
@@ -291,7 +372,6 @@ export async function getHeavyProcessTree(): Promise {
if (osPlatform === "linux" || osPlatform === "darwin") {
try {
- // Get all processes to build tree
const { stdout } = await execAsync(`ps -e -o pid=,ppid=,rss=,comm=`, EXEC_OPTS);
const lines = stdout.trim().split("\n");
processes = lines
@@ -299,17 +379,20 @@ export async function getHeavyProcessTree(): Promise {
const parts = line.trim().split(/\s+/);
const pid = parseInt(parts[0], 10);
const ppid = parseInt(parts[1], 10);
- const rss = parseInt(parts[2], 10) * 1024; // KB to Bytes
+ const rss = parseInt(parts[2], 10) * 1024;
const command = parts.slice(3).join(" ");
return { pid, ppid, rss, command, children: [] };
})
.filter((p) => !Number.isNaN(p.pid));
- } catch {
- // Error running ps
+ } catch (error) {
+ await debugLog("heavy-tree-process-snapshot-failed", {
+ platform: osPlatform,
+ source: "ps",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
} else if (osPlatform === "win32") {
try {
- // Use VALUE format (Key=Value pairs) to avoid CSV comma issues
const { stdout } = await execAsync(
`wmic process get Name,ParentProcessId,ProcessId,WorkingSetSize /format:value`,
EXEC_OPTS,
@@ -322,11 +405,10 @@ export async function getHeavyProcessTree(): Promise {
const entry: Record = {};
for (const line of lines) {
const eq = line.indexOf("=");
- if (eq !== -1) {
- const key = line.slice(0, eq).trim();
- const value = line.slice(eq + 1).trim();
- entry[key] = value;
- }
+ if (eq === -1) continue;
+ const key = line.slice(0, eq).trim();
+ const value = line.slice(eq + 1).trim();
+ entry[key] = value;
}
const pid = parseInt(entry.ProcessId, 10);
const ppid = parseInt(entry.ParentProcessId, 10);
@@ -336,20 +418,23 @@ export async function getHeavyProcessTree(): Promise {
processes.push({ pid, ppid, rss, command, children: [] });
}
}
- } catch {
- // Error
+ } catch (error) {
+ await debugLog("heavy-tree-process-snapshot-failed", {
+ platform: osPlatform,
+ source: "wmic",
+ error: error instanceof Error ? error.message : String(error),
+ });
}
}
- // Build tree
const procMap = new Map();
- for (const p of processes) {
- procMap.set(p.pid, p);
+ for (const processNode of processes) {
+ procMap.set(processNode.pid, processNode);
}
- for (const p of processes) {
- if (p.ppid !== p.pid && procMap.has(p.ppid)) {
- procMap.get(p.ppid)?.children.push(p);
+ for (const processNode of processes) {
+ if (processNode.ppid !== processNode.pid && procMap.has(processNode.ppid)) {
+ procMap.get(processNode.ppid)?.children.push(processNode);
}
}
@@ -357,15 +442,16 @@ export async function getHeavyProcessTree(): Promise {
const targetRoots = processes.filter((p) => rootPids.has(p.pid));
if (targetRoots.length === 0) {
- // Fallback if ps parsing failed or OS is unsupported
+ await debugLog("heavy-tree-no-target-roots", {
+ discoveredProcesses: processes.length,
+ requestedRoots: pids.length,
+ currentPid: process.pid,
+ });
return `### OpenCode RAM Usage Tree\n\nNo detailed process tree could be generated. Current process PID is ${process.pid}.`;
}
let markdown = "### OpenCode RAM Usage Tree\n\n";
-
- const formatSize = (bytes: number) => {
- return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
- };
+ const formatSize = (bytes: number) => `${(bytes / 1024 / 1024).toFixed(2)} MB`;
const buildTreeString = (
node: ProcessNode,
@@ -379,7 +465,6 @@ export async function getHeavyProcessTree(): Promise {
const nextVisited = new Set(visited);
nextVisited.add(node.pid);
-
let result = `${prefix}${isLast ? "└──" : "├──"} [${node.command}] (PID ${node.pid}) - ${formatSize(node.rss)}\n`;
const childPrefix = prefix + (isLast ? " " : "│ ");
@@ -404,9 +489,9 @@ export async function getHeavyProcessTree(): Promise {
for (const root of targetRoots) {
const totalMem = getTreeSum(root, new Set());
markdown += `**Session (PID ${root.pid}) - Total: ${formatSize(totalMem)}**\n`;
- markdown += `\`\`\`text\n`;
+ markdown += "```text\n";
markdown += buildTreeString(root, "", true, new Set());
- markdown += `\`\`\`\n\n`;
+ markdown += "```\n\n";
}
return markdown.trim();
diff --git a/packages/opencode-ram-monitor/src/server.ts b/packages/opencode-ram-monitor/src/server.ts
index e3efd74..ed031fe 100644
--- a/packages/opencode-ram-monitor/src/server.ts
+++ b/packages/opencode-ram-monitor/src/server.ts
@@ -1,4 +1,5 @@
import type { Plugin } from "@opencode-ai/plugin";
+import { debugLog } from "./debug.js";
import { getHeavyProcessTree } from "./memory.js";
const COMMAND_HANDLED_SENTINEL = "__RAM_COMMAND_HANDLED__";
@@ -8,7 +9,7 @@ function handled(): never {
}
const RamMonitorServer: Plugin = async ({ client }) => {
- async function injectRawOutput(sessionID: string, output: string): Promise {
+ async function injectRawOutput(sessionID: string, output: string): Promise {
try {
await client.session.prompt({
path: { id: sessionID },
@@ -17,8 +18,13 @@ const RamMonitorServer: Plugin = async ({ client }) => {
parts: [{ type: "text", text: output, ignored: true }],
},
});
- } catch {
- // swallow prompt errors
+ return true;
+ } catch (error) {
+ await debugLog("prompt-inject-failed", {
+ sessionID,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return false;
}
}
@@ -36,11 +42,16 @@ const RamMonitorServer: Plugin = async ({ client }) => {
let treeText: string;
try {
treeText = await getHeavyProcessTree();
- } catch {
+ } catch (error) {
+ await debugLog("heavy-tree-failed", {
+ sessionID: input.sessionID,
+ error: error instanceof Error ? error.message : String(error),
+ });
treeText = "Unable to generate RAM usage tree. Please try again.";
}
- await injectRawOutput(input.sessionID, treeText);
+ const injected = await injectRawOutput(input.sessionID, treeText);
+ if (!injected) return;
handled();
},
};
diff --git a/packages/opencode-ram-monitor/src/sidebar.tsx b/packages/opencode-ram-monitor/src/sidebar.tsx
index 52a977e..4883d91 100644
--- a/packages/opencode-ram-monitor/src/sidebar.tsx
+++ b/packages/opencode-ram-monitor/src/sidebar.tsx
@@ -4,6 +4,7 @@ import * as fs from "node:fs/promises";
import * as path from "node:path";
import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
import { createSignal, onCleanup, onMount } from "solid-js";
+import { debugLog } from "./debug.js";
import { formatBytes, getLightweightRam, type LightweightRamResult } from "./memory.js";
import {
getDefaultRefreshIntervalMs,
@@ -36,8 +37,16 @@ function RamWidget(props: { api: TuiPluginApi }) {
const nextInterval = normalizeRefreshIntervalMs(rawConfig.refreshIntervalMs);
setIntervalMs(nextInterval);
}
- } catch {
- // Keep default interval if file missing or invalid.
+ } catch (error) {
+ await debugLog("sidebar-config-fallback", {
+ configPath: path.join(
+ props.api.state.path?.worktree || process.cwd(),
+ ".opencode",
+ "opencode.json",
+ ),
+ error: getErrorMessage(error),
+ fallbackIntervalMs: intervalMs(),
+ });
}
};
diff --git a/packages/opencode-ram-monitor/tsconfig.build.json b/packages/opencode-ram-monitor/tsconfig.build.json
index b4f0389..394c835 100644
--- a/packages/opencode-ram-monitor/tsconfig.build.json
+++ b/packages/opencode-ram-monitor/tsconfig.build.json
@@ -4,7 +4,6 @@
"rootDir": "src",
"outDir": "dist",
"jsx": "preserve",
- "noImplicitAny": false,
"types": ["bun"]
},
"include": ["src"],
From 22ddff1e2604e6f0b5bb0b995302dad460ada606 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sat, 9 May 2026 23:29:03 -0400
Subject: [PATCH 068/115] feat(ram-monitor): add JSONC config support and fix
session/build bugs
- Support opencode.json, opencode.jsonc, tui.json, tui.jsonc, and .opencode/ variants
- Add JSONC comment/trailing comma parsing and deterministic precedence order
- Fix session undercounting by unioning live core and launcher PIDs
- Fix duplicate nested roots in /ram tree by filtering ancestor roots
- Fix build: emit debug.js, build sidebar.tsx to JS, export ./tui to built artifact
- Fix observability: /ram injection failure now throws, debug write fails fall back to stderr
- Add config fallback warning and poll failure logging with context
- Fix warningPath bookkeeping to distinguish applied vs failed config in debug logs
- Fix macOS portability by using portable ps column syntax
Tests added for config loading, build/export contract, session union, root dedup, debug fallback, /ram error handling.
---
packages/opencode-ram-monitor/README.md | 30 ++-
packages/opencode-ram-monitor/package.json | 4 +-
packages/opencode-ram-monitor/src/debug.ts | 8 +-
.../opencode-ram-monitor/src/index.test.ts | 230 +++++++++++++++++-
packages/opencode-ram-monitor/src/memory.ts | 48 +++-
packages/opencode-ram-monitor/src/server.ts | 5 +-
.../src/sidebar-config.ts | 187 ++++++++++++++
packages/opencode-ram-monitor/src/sidebar.tsx | 99 ++++----
8 files changed, 549 insertions(+), 62 deletions(-)
diff --git a/packages/opencode-ram-monitor/README.md b/packages/opencode-ram-monitor/README.md
index 95a7ea2..1ab57a1 100644
--- a/packages/opencode-ram-monitor/README.md
+++ b/packages/opencode-ram-monitor/README.md
@@ -42,7 +42,7 @@ Host Architecture
- **Active Session Tracking**: Automatically discovers all running OpenCode sessions and aggregates their RAM.
- **Cross-Platform**: Uses native commands (`ps` on Unix, `wmic` on Windows) for lightweight zero-dependency metrics.
- **`/ram` Command**: Intercepts the `/ram` command to provide a detailed, heavy process-tree breakdown across all active OpenCode sessions right in the chat.
-- **Configurable**: Polling intervals can be customized via `.opencode/opencode.json`.
+- **Configurable**: Polling intervals can be customized via `opencode.json`, `opencode.jsonc`, `tui.json`, `tui.jsonc`, and their `.opencode/` variants.
## Install
@@ -68,7 +68,29 @@ To get a detailed heavy process tree of memory usage across all currently active
## Configuration
-Add the following to your `.opencode/opencode.json` to configure the plugin:
+Add the following to any supported OpenCode config file to configure the plugin:
+
+- `opencode.json`
+- `opencode.jsonc`
+- `.opencode/opencode.json`
+- `.opencode/opencode.jsonc`
+- `tui.json`
+- `tui.jsonc`
+- `.opencode/tui.json`
+- `.opencode/tui.jsonc`
+
+When multiple files define `experimental.ramMonitor.refreshIntervalMs`, the plugin applies them in this order and lets later files win:
+
+1. `opencode.json`
+2. `opencode.jsonc`
+3. `.opencode/opencode.json`
+4. `.opencode/opencode.jsonc`
+5. `tui.json`
+6. `tui.jsonc`
+7. `.opencode/tui.json`
+8. `.opencode/tui.jsonc`
+
+JSONC comments and trailing commas are supported.
| Property | Type | Default | Description |
| :--- | :--- | :--- | :--- |
@@ -87,7 +109,9 @@ Example:
## Troubleshooting
-- **Widget missing from sidebar**: Ensure both the server and TUI plugins are registered in `opencode.json` and `tui.json` respectively. If `refreshIntervalMs` is configured, ensure your `opencode.json` is valid, as comments can cause the config reader to fail or fallback.
+- **Widget missing from sidebar**: Ensure both the server and TUI plugins are registered in your OpenCode server and TUI config files.
+- **Refresh interval did not change**: The widget reads `experimental.ramMonitor.refreshIntervalMs` from all supported `opencode.*` and `tui.*` config files, including `.opencode/` variants. Later files override earlier ones.
+- **Config warning shown in the sidebar**: A supported config file could not be parsed, so the widget is using the last valid value it found or the default `5000ms` interval.
- **Active count seems off**: The plugin tokenizes command lines to find active `opencode` processes. Deeply nested wrappers or complex invocation aliases might not be matched.
- **Total RAM shows `0`**: If sampling fails completely (e.g. `ps` is missing), the plugin falls back to using `process.memoryUsage().rss` of the current process. Ensure standard process utilities are available.
diff --git a/packages/opencode-ram-monitor/package.json b/packages/opencode-ram-monitor/package.json
index 34dbc3b..719a039 100644
--- a/packages/opencode-ram-monitor/package.json
+++ b/packages/opencode-ram-monitor/package.json
@@ -11,7 +11,7 @@
"dist"
],
"scripts": {
- "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/server.ts --outfile=dist/server.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && bun build src/memory.ts --outfile=dist/memory.js --target=bun && bun build src/sidebar-config.ts --outfile=dist/sidebar-config.js --target=bun && cp src/sidebar.tsx dist/sidebar.tsx",
+ "build": "rm -rf dist && tsc --project tsconfig.build.json --emitDeclarationOnly && bun build src/server.ts --outfile=dist/server.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*' && bun build src/memory.ts --outfile=dist/memory.js --target=bun && bun build src/sidebar-config.ts --outfile=dist/sidebar-config.js --target=bun && bun build src/debug.ts --outfile=dist/debug.js --target=bun && bun build src/sidebar.tsx --outfile=dist/sidebar.js --target=bun --external '@opentui/*' --external 'solid-js' --external 'tree-sitter*'",
"typecheck": "tsc --noEmit",
"check": "bunx @biomejs/biome check --write .",
"lint": "bunx @biomejs/biome check .",
@@ -29,7 +29,7 @@
},
"./tui": {
"types": "./dist/sidebar.d.ts",
- "default": "./dist/sidebar.tsx"
+ "default": "./dist/sidebar.js"
}
},
"oc-plugin": [
diff --git a/packages/opencode-ram-monitor/src/debug.ts b/packages/opencode-ram-monitor/src/debug.ts
index 42835aa..2ffa668 100644
--- a/packages/opencode-ram-monitor/src/debug.ts
+++ b/packages/opencode-ram-monitor/src/debug.ts
@@ -26,7 +26,11 @@ export async function debugLog(
try {
await appendFile(getRamMonitorDebugLogPath(), `${JSON.stringify(payload)}\n`, "utf8");
- } catch {
- // Keep debug logging best-effort and non-disruptive.
+ } catch (error) {
+ try {
+ process.stderr.write(
+ `[opencode-ram-monitor] debug log write failed: ${error instanceof Error ? error.message : String(error)}\n`,
+ );
+ } catch {}
}
}
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
index 6a777f7..24a7cff 100644
--- a/packages/opencode-ram-monitor/src/index.test.ts
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -1,9 +1,58 @@
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import "@opentui/solid/preload";
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { getRamMonitorDebugLogPath, isRamMonitorDebugEnabled } from "./debug.js";
+import * as MemoryModule from "./memory.js";
import { classifyOpencodeProcess, selectValidatedSessionPids } from "./memory.js";
+import * as SidebarConfig from "./sidebar-config.js";
import { getErrorMessage, normalizeRefreshIntervalMs } from "./sidebar-config.js";
+type LoadRamMonitorWidgetConfig = (worktree: string) => Promise<{
+ intervalMs: number;
+ sourcePath: string | null;
+ warning: string | null;
+ warningPath: string | null;
+}>;
+
+function getLoadRamMonitorWidgetConfig(): LoadRamMonitorWidgetConfig {
+ const module = SidebarConfig as Record;
+ return module.loadRamMonitorWidgetConfig as LoadRamMonitorWidgetConfig;
+}
+
+type OpenCodePidSets = {
+ core: Set;
+ launcher: Set;
+ all: Set;
+};
+
+type ResolveActiveSessionPids = (
+ liveSets: OpenCodePidSets,
+ lockfileCandidates: number[],
+ currentPid?: number,
+) => number[];
+
+type ProcessNode = {
+ pid: number;
+ ppid: number;
+ rss: number;
+ command: string;
+ children: ProcessNode[];
+};
+
+type SelectTargetRoots = (processes: ProcessNode[], rootPids: Set) => ProcessNode[];
+
+function getResolveActiveSessionPids(): ResolveActiveSessionPids {
+ const module = MemoryModule as Record;
+ return module.resolveActiveSessionPids as ResolveActiveSessionPids;
+}
+
+function getSelectTargetRoots(): SelectTargetRoots {
+ const module = MemoryModule as Record;
+ return module.selectTargetRoots as SelectTargetRoots;
+}
+
describe("@capybearista/opencode-ram-monitor", () => {
const initialDebugValue = process.env.OPENCODE_RAM_MONITOR_DEBUG;
@@ -103,6 +152,183 @@ describe("@capybearista/opencode-ram-monitor", () => {
);
});
+ test("package metadata targets compiled TUI and debug artifacts", async () => {
+ const packageJson = JSON.parse(
+ await Bun.file(new URL("../package.json", import.meta.url)).text(),
+ ) as {
+ scripts: { build: string };
+ exports: { "./tui": { default: string } };
+ };
+
+ expect(packageJson.scripts.build).toContain(
+ "bun build src/debug.ts --outfile=dist/debug.js --target=bun",
+ );
+ expect(packageJson.scripts.build).toContain(
+ "bun build src/sidebar.tsx --outfile=dist/sidebar.js --target=bun",
+ );
+ expect(packageJson.exports["./tui"].default).toBe("./dist/sidebar.js");
+ });
+
+ test("build produces a loadable compiled TUI artifact", async () => {
+ const packageDir = new URL("..", import.meta.url).pathname;
+ await Bun.$`bun run build`.cwd(packageDir).quiet();
+ await Bun.$`bun --eval ${`import("./dist/sidebar.js").then((module) => {
+ if (module.default?.id !== "capybearista.opencode-ram-monitor") {
+ throw new Error("invalid sidebar module id")
+ }
+ if (typeof module.default?.tui !== "function") {
+ throw new Error("invalid sidebar module export")
+ }
+})`}`
+ .cwd(packageDir)
+ .quiet();
+ });
+
+ test("loads refresh interval from supported root config files with TUI precedence", async () => {
+ const loadRamMonitorWidgetConfig = getLoadRamMonitorWidgetConfig();
+ const dir = await mkdtemp(join(tmpdir(), "ram-monitor-config-"));
+
+ try {
+ await writeFile(
+ join(dir, "opencode.jsonc"),
+ `{
+ // general setting
+ "experimental": {
+ "ramMonitor": {
+ "refreshIntervalMs": 2000,
+ },
+ },
+}
+`,
+ );
+ await writeFile(
+ join(dir, "tui.json"),
+ JSON.stringify({
+ experimental: {
+ ramMonitor: {
+ refreshIntervalMs: 4000,
+ },
+ },
+ }),
+ );
+
+ await expect(loadRamMonitorWidgetConfig(dir)).resolves.toEqual({
+ intervalMs: 4000,
+ sourcePath: join(dir, "tui.json"),
+ warning: null,
+ warningPath: null,
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("loads refresh interval from .opencode JSONC config files", async () => {
+ const loadRamMonitorWidgetConfig = getLoadRamMonitorWidgetConfig();
+ const dir = await mkdtemp(join(tmpdir(), "ram-monitor-config-"));
+
+ try {
+ await mkdir(join(dir, ".opencode"), { recursive: true });
+ await writeFile(
+ join(dir, ".opencode", "tui.jsonc"),
+ `{
+ "experimental": {
+ "ramMonitor": {
+ "refreshIntervalMs": 3100,
+ },
+ },
+}
+`,
+ );
+
+ await expect(loadRamMonitorWidgetConfig(dir)).resolves.toEqual({
+ intervalMs: 3100,
+ sourcePath: join(dir, ".opencode", "tui.jsonc"),
+ warning: null,
+ warningPath: null,
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("clears stale config warnings when a later config file loads successfully", async () => {
+ const loadRamMonitorWidgetConfig = getLoadRamMonitorWidgetConfig();
+ const dir = await mkdtemp(join(tmpdir(), "ram-monitor-config-"));
+
+ try {
+ await writeFile(join(dir, "opencode.jsonc"), "{ invalid }");
+ await writeFile(
+ join(dir, "tui.jsonc"),
+ `{
+ "experimental": {
+ "ramMonitor": {
+ "refreshIntervalMs": 4200,
+ },
+ },
+}
+`,
+ );
+
+ await expect(loadRamMonitorWidgetConfig(dir)).resolves.toEqual({
+ intervalMs: 4200,
+ sourcePath: join(dir, "tui.jsonc"),
+ warning: null,
+ warningPath: null,
+ });
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("keeps live launcher and core sessions together when both are active", () => {
+ const resolveActiveSessionPids = getResolveActiveSessionPids();
+
+ expect(
+ resolveActiveSessionPids(
+ {
+ core: new Set([121]),
+ launcher: new Set([120]),
+ all: new Set([120, 121]),
+ },
+ [120, 121],
+ 900,
+ ),
+ ).toEqual([900, 120, 121]);
+ });
+
+ test("filters nested roots from the heavy process tree target set", () => {
+ const selectTargetRoots = getSelectTargetRoots();
+ const child: ProcessNode = { pid: 101, ppid: 100, rss: 1, command: "child", children: [] };
+ const parent: ProcessNode = { pid: 100, ppid: 1, rss: 1, command: "parent", children: [child] };
+
+ expect(selectTargetRoots([parent, child], new Set([100, 101]))).toEqual([parent]);
+ });
+
+ test("debug logging reports stderr fallback when file writes fail", async () => {
+ process.env.OPENCODE_RAM_MONITOR_DEBUG = "1";
+ const stderrWrite = mock(() => true);
+ const originalWrite = process.stderr.write.bind(process.stderr);
+
+ mock.module("node:fs/promises", () => ({
+ appendFile: async () => {
+ throw new Error("disk full");
+ },
+ }));
+
+ process.stderr.write = stderrWrite as typeof process.stderr.write;
+
+ try {
+ const module = await import(`./debug.js?stderr-fallback=${Date.now()}`);
+ await module.debugLog("test-event", { source: "unit-test" });
+ expect(stderrWrite).toHaveBeenCalledTimes(1);
+ const calls = (stderrWrite as unknown as { mock: { calls: unknown[][] } }).mock.calls;
+ expect(String(calls[0]?.[0])).toContain("disk full");
+ } finally {
+ process.stderr.write = originalWrite;
+ }
+ });
+
test("/ram command is handled only after prompt injection succeeds", async () => {
mock.module("./memory.js", () => ({
getHeavyProcessTree: async () => "tree",
@@ -129,7 +355,7 @@ describe("@capybearista/opencode-ram-monitor", () => {
expect(prompts.length).toBe(1);
});
- test("/ram command falls through when prompt injection fails", async () => {
+ test("/ram command raises a user-visible error when prompt injection fails", async () => {
mock.module("./memory.js", () => ({
getHeavyProcessTree: async () => "tree",
}));
@@ -150,6 +376,6 @@ describe("@capybearista/opencode-ram-monitor", () => {
expect(beforeExecute).toBeFunction();
await expect(
beforeExecute?.({ command: "ram", sessionID: "s-1" } as never, {} as never),
- ).resolves.toBeUndefined();
+ ).rejects.toThrow("Unable to display RAM usage output. Please try again.");
});
});
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
index e62efd4..809838b 100644
--- a/packages/opencode-ram-monitor/src/memory.ts
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -103,7 +103,7 @@ async function getLiveOpencodePidSets(): Promise {
if (osPlatform === "linux" || osPlatform === "darwin") {
try {
- const { stdout } = await execAsync("ps -eo pid=,args=", EXEC_OPTS);
+ const { stdout } = await execAsync("ps -A -o pid= -o command=", EXEC_OPTS);
for (const line of stdout.split("\n")) {
const trimmed = line.trim();
@@ -192,6 +192,18 @@ export function selectValidatedSessionPids(
return [...selected];
}
+export function resolveActiveSessionPids(
+ liveSets: OpenCodePidSets,
+ lockfileCandidates: number[],
+ currentPid: number = process.pid,
+): number[] {
+ return selectValidatedSessionPids(
+ [currentPid, ...lockfileCandidates, ...liveSets.all],
+ liveSets.all,
+ currentPid,
+ );
+}
+
async function readLockfileCandidates(): Promise {
const candidates: number[] = [];
const stateDirs = [
@@ -235,13 +247,11 @@ export async function getActiveSessions(): Promise {
readLockfileCandidates(),
]);
- const preferredLiveSet = liveSets.core.size > 0 ? liveSets.core : liveSets.launcher;
- const runtimeCandidates = [...preferredLiveSet];
- const allCandidates = [process.pid, ...lockfileCandidates, ...runtimeCandidates];
- const validated = selectValidatedSessionPids(allCandidates, preferredLiveSet, process.pid);
+ const runtimeCandidates = [...liveSets.all];
+ const validated = resolveActiveSessionPids(liveSets, lockfileCandidates, process.pid);
await debugLog("active-sessions-resolved", {
- candidates: allCandidates.length,
+ candidates: lockfileCandidates.length + runtimeCandidates.length + 1,
lockfileCandidates: lockfileCandidates.length,
runtimeCandidates: runtimeCandidates.length,
validated: validated.length,
@@ -364,6 +374,28 @@ export interface ProcessNode {
children: ProcessNode[];
}
+export function selectTargetRoots(processes: ProcessNode[], rootPids: Set): ProcessNode[] {
+ const procMap = new Map();
+ for (const processNode of processes) {
+ procMap.set(processNode.pid, processNode);
+ }
+
+ return processes.filter((processNode) => {
+ if (!rootPids.has(processNode.pid)) return false;
+
+ const visited = new Set([processNode.pid]);
+ let parentPid = processNode.ppid;
+
+ while (parentPid !== processNode.pid && procMap.has(parentPid) && !visited.has(parentPid)) {
+ if (rootPids.has(parentPid)) return false;
+ visited.add(parentPid);
+ parentPid = procMap.get(parentPid)?.ppid ?? parentPid;
+ }
+
+ return true;
+ });
+}
+
export async function getHeavyProcessTree(): Promise {
const pids = await getActiveSessions();
const osPlatform = platform();
@@ -372,7 +404,7 @@ export async function getHeavyProcessTree(): Promise {
if (osPlatform === "linux" || osPlatform === "darwin") {
try {
- const { stdout } = await execAsync(`ps -e -o pid=,ppid=,rss=,comm=`, EXEC_OPTS);
+ const { stdout } = await execAsync("ps -A -o pid= -o ppid= -o rss= -o comm=", EXEC_OPTS);
const lines = stdout.trim().split("\n");
processes = lines
.map((line) => {
@@ -439,7 +471,7 @@ export async function getHeavyProcessTree(): Promise {
}
const rootPids = new Set(pids);
- const targetRoots = processes.filter((p) => rootPids.has(p.pid));
+ const targetRoots = selectTargetRoots(processes, rootPids);
if (targetRoots.length === 0) {
await debugLog("heavy-tree-no-target-roots", {
diff --git a/packages/opencode-ram-monitor/src/server.ts b/packages/opencode-ram-monitor/src/server.ts
index ed031fe..b5b4c33 100644
--- a/packages/opencode-ram-monitor/src/server.ts
+++ b/packages/opencode-ram-monitor/src/server.ts
@@ -3,6 +3,7 @@ import { debugLog } from "./debug.js";
import { getHeavyProcessTree } from "./memory.js";
const COMMAND_HANDLED_SENTINEL = "__RAM_COMMAND_HANDLED__";
+const PROMPT_INJECTION_FAILURE_MESSAGE = "Unable to display RAM usage output. Please try again.";
function handled(): never {
throw new Error(COMMAND_HANDLED_SENTINEL);
@@ -51,7 +52,9 @@ const RamMonitorServer: Plugin = async ({ client }) => {
}
const injected = await injectRawOutput(input.sessionID, treeText);
- if (!injected) return;
+ if (!injected) {
+ throw new Error(PROMPT_INJECTION_FAILURE_MESSAGE);
+ }
handled();
},
};
diff --git a/packages/opencode-ram-monitor/src/sidebar-config.ts b/packages/opencode-ram-monitor/src/sidebar-config.ts
index ebcf90a..3bf112f 100644
--- a/packages/opencode-ram-monitor/src/sidebar-config.ts
+++ b/packages/opencode-ram-monitor/src/sidebar-config.ts
@@ -1,7 +1,28 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+
const DEFAULT_REFRESH_INTERVAL_MS = 5000;
const MIN_REFRESH_INTERVAL_MS = 1000;
const MAX_REFRESH_INTERVAL_MS = 60_000;
+const CONFIG_PATH_SEGMENTS = [
+ ["opencode.json"],
+ ["opencode.jsonc"],
+ [".opencode", "opencode.json"],
+ [".opencode", "opencode.jsonc"],
+ ["tui.json"],
+ ["tui.jsonc"],
+ [".opencode", "tui.json"],
+ [".opencode", "tui.jsonc"],
+] as const;
+
+export interface RamMonitorWidgetConfig {
+ intervalMs: number;
+ sourcePath: string | null;
+ warning: string | null;
+ warningPath: string | null;
+}
+
export function getDefaultRefreshIntervalMs(): number {
return DEFAULT_REFRESH_INTERVAL_MS;
}
@@ -17,3 +38,169 @@ export function getErrorMessage(error: unknown): string {
if (typeof error === "string" && error.trim().length > 0) return error;
return "RAM error";
}
+
+function stripJsonComments(input: string): string {
+ let output = "";
+ let inString = false;
+ let escaped = false;
+ let inLineComment = false;
+ let inBlockComment = false;
+
+ for (let index = 0; index < input.length; index++) {
+ const char = input[index];
+ const next = input[index + 1];
+
+ if (inLineComment) {
+ if (char === "\n" || char === "\r") {
+ inLineComment = false;
+ output += char;
+ continue;
+ }
+ output += " ";
+ continue;
+ }
+
+ if (inBlockComment) {
+ if (char === "*" && next === "/") {
+ inBlockComment = false;
+ output += " ";
+ index++;
+ continue;
+ }
+ output += char === "\n" || char === "\r" ? char : " ";
+ continue;
+ }
+
+ if (inString) {
+ output += char;
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char === "\\") {
+ escaped = true;
+ continue;
+ }
+ if (char === '"') {
+ inString = false;
+ }
+ continue;
+ }
+
+ if (char === '"') {
+ inString = true;
+ output += char;
+ continue;
+ }
+
+ if (char === "/" && next === "/") {
+ inLineComment = true;
+ output += " ";
+ index++;
+ continue;
+ }
+
+ if (char === "/" && next === "*") {
+ inBlockComment = true;
+ output += " ";
+ index++;
+ continue;
+ }
+
+ output += char;
+ }
+
+ return output;
+}
+
+function stripTrailingCommas(input: string): string {
+ let output = "";
+ let inString = false;
+ let escaped = false;
+
+ for (let index = 0; index < input.length; index++) {
+ const char = input[index];
+
+ if (inString) {
+ output += char;
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (char === "\\") {
+ escaped = true;
+ continue;
+ }
+ if (char === '"') {
+ inString = false;
+ }
+ continue;
+ }
+
+ if (char === '"') {
+ inString = true;
+ output += char;
+ continue;
+ }
+
+ if (char === ",") {
+ let nextIndex = index + 1;
+ while (nextIndex < input.length && /\s/.test(input[nextIndex])) {
+ nextIndex++;
+ }
+ if (input[nextIndex] === "}" || input[nextIndex] === "]") {
+ continue;
+ }
+ }
+
+ output += char;
+ }
+
+ return output;
+}
+
+function getConfigValue(config: unknown): unknown {
+ if (!config || typeof config !== "object") return undefined;
+ const experimental = (config as Record).experimental;
+ if (!experimental || typeof experimental !== "object") return undefined;
+ const ramMonitor = (experimental as Record).ramMonitor;
+ if (!ramMonitor || typeof ramMonitor !== "object") return undefined;
+ return (ramMonitor as Record).refreshIntervalMs;
+}
+
+function isMissingConfigError(error: unknown): boolean {
+ return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
+}
+
+export function getRamMonitorConfigPaths(worktree: string): string[] {
+ return CONFIG_PATH_SEGMENTS.map((segments) => join(worktree, ...segments));
+}
+
+export async function loadRamMonitorWidgetConfig(
+ worktree: string,
+): Promise {
+ let intervalMs = getDefaultRefreshIntervalMs();
+ let sourcePath: string | null = null;
+ let warning: string | null = null;
+ let warningPath: string | null = null;
+
+ for (const configPath of getRamMonitorConfigPaths(worktree)) {
+ try {
+ const parsed = JSON.parse(
+ stripTrailingCommas(stripJsonComments(await readFile(configPath, "utf8"))),
+ );
+ const refreshIntervalMs = getConfigValue(parsed);
+ if (refreshIntervalMs === undefined) continue;
+ intervalMs = normalizeRefreshIntervalMs(refreshIntervalMs);
+ sourcePath = configPath;
+ warning = null;
+ warningPath = null;
+ } catch (error) {
+ if (isMissingConfigError(error)) continue;
+ warning = `Failed to load ${configPath}: ${getErrorMessage(error)}`;
+ warningPath = configPath;
+ }
+ }
+
+ return { intervalMs, sourcePath, warning, warningPath };
+}
diff --git a/packages/opencode-ram-monitor/src/sidebar.tsx b/packages/opencode-ram-monitor/src/sidebar.tsx
index 4883d91..ff1a80f 100644
--- a/packages/opencode-ram-monitor/src/sidebar.tsx
+++ b/packages/opencode-ram-monitor/src/sidebar.tsx
@@ -1,51 +1,56 @@
-/** @jsxImportSource @opentui/solid */
-
-import * as fs from "node:fs/promises";
-import * as path from "node:path";
import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
+import type { JSX } from "@opentui/solid";
+import { createElement, insert, spread } from "@opentui/solid";
import { createSignal, onCleanup, onMount } from "solid-js";
import { debugLog } from "./debug.js";
import { formatBytes, getLightweightRam, type LightweightRamResult } from "./memory.js";
import {
getDefaultRefreshIntervalMs,
getErrorMessage,
- normalizeRefreshIntervalMs,
+ loadRamMonitorWidgetConfig,
} from "./sidebar-config.js";
-function RamWidget(props: { api: TuiPluginApi }) {
+function createTextNode(
+ props: Record,
+ content: string | null | (() => string | null),
+) {
+ const node = createElement("text");
+ spread(node, props, true);
+ insert(node, content);
+ return node;
+}
+
+function createBoxNode(props: Record, children: unknown[]) {
+ const node = createElement("box");
+ spread(node, props, true);
+ for (const child of children) {
+ insert(node, child);
+ }
+ return node;
+}
+
+function RamWidget(props: { api: TuiPluginApi }): JSX.Element {
const [ram, setRam] = createSignal({ current: 0, total: 0, count: 0 });
const [error, setError] = createSignal(null);
const [intervalMs, setIntervalMs] = createSignal(getDefaultRefreshIntervalMs());
const [tick, setTick] = createSignal(0);
+ const [warning, setWarning] = createSignal(null);
let disposed = false;
let timeout: ReturnType | undefined;
- // Fetch config once on mount
const loadConfig = async () => {
- try {
- const worktree = props.api.state.path?.worktree || process.cwd();
- const configPath = path.join(worktree, ".opencode", "opencode.json");
- const configContent = await fs.readFile(configPath, "utf8");
-
- // Basic JSON parsing. Real parser would strip comments, but since
- // comments break strict JSON anyway, we just try parse.
- const parsed = JSON.parse(configContent);
- const rawConfig = parsed?.experimental?.ramMonitor;
+ const worktree = props.api.state.path?.worktree || process.cwd();
+ const config = await loadRamMonitorWidgetConfig(worktree);
+ setIntervalMs(config.intervalMs);
+ setWarning(config.warning ? `Config warning: using ${config.intervalMs}ms fallback` : null);
- if (rawConfig && "refreshIntervalMs" in rawConfig) {
- const nextInterval = normalizeRefreshIntervalMs(rawConfig.refreshIntervalMs);
- setIntervalMs(nextInterval);
- }
- } catch (error) {
+ if (config.warning) {
await debugLog("sidebar-config-fallback", {
- configPath: path.join(
- props.api.state.path?.worktree || process.cwd(),
- ".opencode",
- "opencode.json",
- ),
- error: getErrorMessage(error),
- fallbackIntervalMs: intervalMs(),
+ appliedConfigPath: config.sourcePath || "unknown",
+ failedConfigPath: config.warningPath || "unknown",
+ error: config.warning,
+ fallbackIntervalMs: config.intervalMs,
});
}
};
@@ -59,6 +64,11 @@ function RamWidget(props: { api: TuiPluginApi }) {
setTick((t) => t + 1);
}
} catch (err: unknown) {
+ await debugLog("sidebar-poll-failed", {
+ worktree: props.api.state.path?.worktree || process.cwd(),
+ intervalMs: intervalMs(),
+ error: getErrorMessage(err),
+ });
if (!disposed) {
setError(getErrorMessage(err));
}
@@ -83,21 +93,22 @@ function RamWidget(props: { api: TuiPluginApi }) {
if (timeout) clearTimeout(timeout);
});
- return (
-
-
- RAM Usage {tick() % 2 === 0 ? "●" : "○"}
-
-
- {error() ? `Error: ${error()}` : `Current: ${formatBytes(ram().current)}`}
-
- {!error() && ram().count > 0 && (
-
- {`Total: ${formatBytes(ram().total)} (${ram().count} active)`}
-
- )}
-
- );
+ return createBoxNode({ gap: 0, padding: 1 }, [
+ createTextNode(
+ { fg: props.api.theme.current.text },
+ () => `RAM Usage ${tick() % 2 === 0 ? "●" : "○"}`,
+ ),
+ createTextNode(
+ { fg: () => (error() ? props.api.theme.current.error : props.api.theme.current.text) },
+ () => (error() ? `Error: ${error()}` : `Current: ${formatBytes(ram().current)}`),
+ ),
+ createTextNode({ fg: props.api.theme.current.secondary }, () =>
+ !error() && ram().count > 0
+ ? `Total: ${formatBytes(ram().total)} (${ram().count} active)`
+ : null,
+ ),
+ createTextNode({ fg: props.api.theme.current.error }, () => (error() ? null : warning())),
+ ]) as JSX.Element;
}
const SIDEBAR_ORDER = 150;
@@ -107,7 +118,7 @@ const tui: TuiPlugin = async (api) => {
order: SIDEBAR_ORDER,
slots: {
sidebar_content() {
- return ;
+ return RamWidget({ api });
},
},
});
From a4df9bc7793ecbad404099ae1ad5df9d45c3e305 Mon Sep 17 00:00:00 2001
From: capyBearista
Date: Sun, 10 May 2026 02:44:29 -0400
Subject: [PATCH 069/115] fix(ram-monitor): stabilize sidebar rendering and
harden RSS sampling fallbacks
Restore reliable sidebar mounting/rendering semantics and make darwin/win32 RAM collection resilient under malformed or partial snapshots.
- instantiate sidebar widget with createComponent and getter-backed render props
- harden ps/wmic parsing with strict integer validation
- add bulk snapshot + per-pid fallback helpers with coverage-aware merge
- avoid false partial telemetry and emit per-pid sample error callbacks
- optimize polling path by using per-pid-only sampling for small pid sets
- expand regression tests for sidebar renderability, parser edge cases, fallback, and membership coverage
---
.../opencode-ram-monitor/src/index.test.ts | 360 +++++++++++++++++-
packages/opencode-ram-monitor/src/memory.ts | 353 +++++++++++++++--
packages/opencode-ram-monitor/src/sidebar.tsx | 39 +-
3 files changed, 712 insertions(+), 40 deletions(-)
diff --git a/packages/opencode-ram-monitor/src/index.test.ts b/packages/opencode-ram-monitor/src/index.test.ts
index 24a7cff..721b18b 100644
--- a/packages/opencode-ram-monitor/src/index.test.ts
+++ b/packages/opencode-ram-monitor/src/index.test.ts
@@ -5,7 +5,17 @@ import "@opentui/solid/preload";
import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { getRamMonitorDebugLogPath, isRamMonitorDebugEnabled } from "./debug.js";
import * as MemoryModule from "./memory.js";
-import { classifyOpencodeProcess, selectValidatedSessionPids } from "./memory.js";
+import {
+ classifyOpencodeProcess,
+ parsePsRssSnapshot,
+ parseWmicWorkingSetSnapshot,
+ sampleDarwinRssPerPid,
+ sampleDarwinRssWithFallback,
+ sampleWindowsRssPerPid,
+ sampleWindowsRssWithFallback,
+ selectValidatedSessionPids,
+ shouldUseBulkSnapshot,
+} from "./memory.js";
import * as SidebarConfig from "./sidebar-config.js";
import { getErrorMessage, normalizeRefreshIntervalMs } from "./sidebar-config.js";
@@ -184,6 +194,354 @@ describe("@capybearista/opencode-ram-monitor", () => {
.quiet();
});
+ test("registers sidebar slot and returns a renderable", async () => {
+ mock.module("@opentui/solid", () => ({
+ createElement: () => ({ children: [] as unknown[] }),
+ insert: (node: { children?: unknown[] }, child: unknown) => {
+ node.children?.push(child);
+ },
+ spread: () => {},
+ }));
+
+ const module = await import(`./sidebar.js?slot-render=${Date.now()}`);
+ let sidebarContent: (() => unknown) | undefined;
+
+ await (module.default.tui as (api: unknown) => Promise)({
+ slots: {
+ register: (payload: { slots?: { sidebar_content?: () => unknown } }) => {
+ sidebarContent = payload.slots?.sidebar_content;
+ },
+ },
+ theme: {
+ current: {
+ text: "white",
+ secondary: "gray",
+ error: "red",
+ },
+ },
+ state: {
+ path: {
+ worktree: process.cwd(),
+ },
+ },
+ });
+
+ expect(sidebarContent).toBeFunction();
+ expect(() => sidebarContent?.()).not.toThrow();
+ expect(sidebarContent?.()).toBeTruthy();
+ });
+
+ test("parses bulk ps rss snapshots", () => {
+ const parsed = parsePsRssSnapshot("101 42\ninvalid line\n102 7\n103 NaN\n101x 8\n");
+ expect(parsed.get(101)).toBe(42 * 1024);
+ expect(parsed.get(102)).toBe(7 * 1024);
+ expect(parsed.has(103)).toBeFalse();
+ expect(parsed.size).toBe(2);
+ });
+
+ test("parses bulk wmic rss snapshots", () => {
+ const parsed = parseWmicWorkingSetSnapshot(
+ "ProcessId=101\r\nWorkingSetSize=42000\r\n\r\nProcessId=102\r\nWorkingSetSize=7000\r\n\r\nProcessId=103\r\nWorkingSetSize=bad\r\n",
+ );
+ expect(parsed.get(101)).toBe(42000);
+ expect(parsed.get(102)).toBe(7000);
+ expect(parsed.has(103)).toBeFalse();
+
+ const malformed = parseWmicWorkingSetSnapshot(
+ "ProcessId=10a\r\nWorkingSetSize=42000\r\n\r\nProcessId=105\r\nWorkingSetSize=77x\r\n",
+ );
+ expect(malformed.size).toBe(0);
+
+ const nonIdeal = parseWmicWorkingSetSnapshot(
+ "WorkingSetSize=9000\r\n\r\n\r\nProcessId=110\r\n\r\n\r\nProcessId=120\r\n\r\nWorkingSetSize=15000\r\n",
+ );
+ expect(nonIdeal.get(120)).toBe(15000);
+ expect(nonIdeal.has(110)).toBeFalse();
+ expect(nonIdeal.has(9000)).toBeFalse();
+ });
+
+ test("falls back to per-pid sampling when darwin bulk snapshot fails", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleDarwinRssWithFallback([201, 202], async (command) => {
+ calls.push(command);
+ if (command === "ps -A -o pid= -o rss=") {
+ throw new Error("bulk failed");
+ }
+ if (command === "ps -o rss= -p 201") return { stdout: "15\n" };
+ if (command === "ps -o rss= -p 202") return { stdout: "7\n" };
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain("ps -A -o pid= -o rss=");
+ expect(calls).toContain("ps -o rss= -p 201");
+ expect(calls).toContain("ps -o rss= -p 202");
+ expect(sampled.get(201)).toBe(15 * 1024);
+ expect(sampled.get(202)).toBe(7 * 1024);
+ });
+
+ test("falls back to per-pid sampling when windows bulk snapshot fails", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleWindowsRssWithFallback([301, 302], async (command) => {
+ calls.push(command);
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ throw new Error("bulk failed");
+ }
+ if (command === 'wmic process where "ProcessId=301" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n4096\n" };
+ }
+ if (command === 'wmic process where "ProcessId=302" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n2048\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain("wmic process get ProcessId,WorkingSetSize /format:value");
+ expect(calls).toContain('wmic process where "ProcessId=301" get WorkingSetSize');
+ expect(calls).toContain('wmic process where "ProcessId=302" get WorkingSetSize');
+ expect(sampled.get(301)).toBe(4096);
+ expect(sampled.get(302)).toBe(2048);
+ });
+
+ test("throws when darwin bulk and per-pid fallback sampling both fail", async () => {
+ await expect(
+ sampleDarwinRssWithFallback([401, 402], async (command) => {
+ if (command === "ps -A -o pid= -o rss=") throw new Error("bulk failed");
+ throw new Error("pid failed");
+ }),
+ ).rejects.toThrow("darwin rss sampling failed for all candidate PIDs");
+ });
+
+ test("throws when windows bulk and per-pid fallback sampling both fail", async () => {
+ await expect(
+ sampleWindowsRssWithFallback([501, 502], async (command) => {
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ throw new Error("bulk failed");
+ }
+ throw new Error("pid failed");
+ }),
+ ).rejects.toThrow("windows rss sampling failed for all candidate PIDs");
+ });
+
+ test("falls back to per-pid sampling when darwin bulk output is malformed", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleDarwinRssWithFallback([601], async (command) => {
+ calls.push(command);
+ if (command === "ps -A -o pid= -o rss=") {
+ return { stdout: "not-a-valid-row\n" };
+ }
+ return { stdout: "13\n" };
+ });
+
+ expect(calls).toContain("ps -A -o pid= -o rss=");
+ expect(calls).toContain("ps -o rss= -p 601");
+ expect(sampled.get(601)).toBe(13 * 1024);
+ });
+
+ test("merges partial darwin bulk snapshots with per-pid fallback", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleDarwinRssWithFallback([611, 612], async (command) => {
+ calls.push(command);
+ if (command === "ps -A -o pid= -o rss=") {
+ return { stdout: "611 20\n" };
+ }
+ if (command === "ps -o rss= -p 612") {
+ return { stdout: "7\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain("ps -A -o pid= -o rss=");
+ expect(calls).toContain("ps -o rss= -p 612");
+ expect(sampled.get(611)).toBe(20 * 1024);
+ expect(sampled.get(612)).toBe(7 * 1024);
+ });
+
+ test("does not treat unrelated darwin bulk rows as full coverage", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleDarwinRssWithFallback([621, 622], async (command) => {
+ calls.push(command);
+ if (command === "ps -A -o pid= -o rss=") {
+ return { stdout: "621 20\n999 99\n" };
+ }
+ if (command === "ps -o rss= -p 622") {
+ return { stdout: "8\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain("ps -o rss= -p 622");
+ expect(sampled.get(621)).toBe(20 * 1024);
+ expect(sampled.get(622)).toBe(8 * 1024);
+ });
+
+ test("falls back to per-pid sampling when windows bulk output is malformed", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleWindowsRssWithFallback([701], async (command) => {
+ calls.push(command);
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ return { stdout: "ProcessId=abc\nWorkingSetSize=def\n" };
+ }
+ return { stdout: "WorkingSetSize\n8192\n" };
+ });
+
+ expect(calls).toContain("wmic process get ProcessId,WorkingSetSize /format:value");
+ expect(calls).toContain('wmic process where "ProcessId=701" get WorkingSetSize');
+ expect(sampled.get(701)).toBe(8192);
+ });
+
+ test("merges partial windows bulk snapshots with per-pid fallback", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleWindowsRssWithFallback([711, 712], async (command) => {
+ calls.push(command);
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ return { stdout: "ProcessId=711\nWorkingSetSize=4096\n" };
+ }
+ if (command === 'wmic process where "ProcessId=712" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n2048\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain("wmic process get ProcessId,WorkingSetSize /format:value");
+ expect(calls).toContain('wmic process where "ProcessId=712" get WorkingSetSize');
+ expect(sampled.get(711)).toBe(4096);
+ expect(sampled.get(712)).toBe(2048);
+ });
+
+ test("does not treat unrelated windows bulk rows as full coverage", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleWindowsRssWithFallback([721, 722], async (command) => {
+ calls.push(command);
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ return {
+ stdout: "ProcessId=721\nWorkingSetSize=4096\nProcessId=999\nWorkingSetSize=1024\n",
+ };
+ }
+ if (command === 'wmic process where "ProcessId=722" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n2048\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toContain('wmic process where "ProcessId=722" get WorkingSetSize');
+ expect(sampled.get(721)).toBe(4096);
+ expect(sampled.get(722)).toBe(2048);
+ });
+
+ test("does not fire partial callback when all requested darwin pids are present", async () => {
+ const partialEvents: number[][] = [];
+ const sampled = await sampleDarwinRssWithFallback(
+ [731, 732],
+ async (command) => {
+ if (command === "ps -A -o pid= -o rss=") {
+ return { stdout: "731 20\n732 10\n999 1\n" };
+ }
+ return { stdout: "" };
+ },
+ undefined,
+ (missingPids) => {
+ partialEvents.push(missingPids);
+ },
+ );
+
+ expect(partialEvents.length).toBe(0);
+ expect(sampled.get(731)).toBe(20 * 1024);
+ expect(sampled.get(732)).toBe(10 * 1024);
+ });
+
+ test("reports darwin per-pid parse failures via onPidError", async () => {
+ const errors: Array<{ pid: number; source: string; error: string }> = [];
+
+ await expect(
+ sampleDarwinRssWithFallback(
+ [801],
+ async (command) => {
+ if (command === "ps -A -o pid= -o rss=") throw new Error("bulk failed");
+ return { stdout: "not-a-number\n" };
+ },
+ (pid, source, error) => {
+ errors.push({
+ pid,
+ source,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+ ),
+ ).rejects.toThrow("darwin rss sampling failed for all candidate PIDs");
+
+ expect(errors.length).toBe(1);
+ expect(errors[0]?.pid).toBe(801);
+ expect(errors[0]?.source).toBe("ps");
+ });
+
+ test("reports windows per-pid parse failures via onPidError", async () => {
+ const errors: Array<{ pid: number; source: string; error: string }> = [];
+
+ await expect(
+ sampleWindowsRssWithFallback(
+ [901],
+ async (command) => {
+ if (command === "wmic process get ProcessId,WorkingSetSize /format:value") {
+ throw new Error("bulk failed");
+ }
+ return { stdout: "WorkingSetSize\ninvalid\n" };
+ },
+ (pid, source, error) => {
+ errors.push({
+ pid,
+ source,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+ ),
+ ).rejects.toThrow("windows rss sampling failed for all candidate PIDs");
+
+ expect(errors.length).toBe(1);
+ expect(errors[0]?.pid).toBe(901);
+ expect(errors[0]?.source).toBe("wmic");
+ });
+
+ test("uses bulk sampling policy only for larger pid sets", () => {
+ expect(shouldUseBulkSnapshot(1)).toBeFalse();
+ expect(shouldUseBulkSnapshot(3)).toBeFalse();
+ expect(shouldUseBulkSnapshot(4)).toBeTrue();
+ });
+
+ test("samples darwin per-pid without bulk snapshot", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleDarwinRssPerPid([951, 952], async (command) => {
+ calls.push(command);
+ if (command === "ps -o rss= -p 951") return { stdout: "5\n" };
+ if (command === "ps -o rss= -p 952") return { stdout: "6\n" };
+ return { stdout: "" };
+ });
+
+ expect(calls).toEqual(["ps -o rss= -p 951", "ps -o rss= -p 952"]);
+ expect(sampled.get(951)).toBe(5 * 1024);
+ expect(sampled.get(952)).toBe(6 * 1024);
+ });
+
+ test("samples windows per-pid without bulk snapshot", async () => {
+ const calls: string[] = [];
+ const sampled = await sampleWindowsRssPerPid([961, 962], async (command) => {
+ calls.push(command);
+ if (command === 'wmic process where "ProcessId=961" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n1024\n" };
+ }
+ if (command === 'wmic process where "ProcessId=962" get WorkingSetSize') {
+ return { stdout: "WorkingSetSize\n2048\n" };
+ }
+ return { stdout: "" };
+ });
+
+ expect(calls).toEqual([
+ 'wmic process where "ProcessId=961" get WorkingSetSize',
+ 'wmic process where "ProcessId=962" get WorkingSetSize',
+ ]);
+ expect(sampled.get(961)).toBe(1024);
+ expect(sampled.get(962)).toBe(2048);
+ });
+
test("loads refresh interval from supported root config files with TUI precedence", async () => {
const loadRamMonitorWidgetConfig = getLoadRamMonitorWidgetConfig();
const dir = await mkdtemp(join(tmpdir(), "ram-monitor-config-"));
diff --git a/packages/opencode-ram-monitor/src/memory.ts b/packages/opencode-ram-monitor/src/memory.ts
index 809838b..224ce64 100644
--- a/packages/opencode-ram-monitor/src/memory.ts
+++ b/packages/opencode-ram-monitor/src/memory.ts
@@ -7,6 +7,11 @@ import { debugLog } from "./debug.js";
const EXEC_OPTS = { timeout: 5000, windowsHide: true };
const execAsync = promisify(exec);
+const BULK_SNAPSHOT_MIN_PID_COUNT = 4;
+
+export function shouldUseBulkSnapshot(pidCount: number): boolean {
+ return pidCount >= BULK_SNAPSHOT_MIN_PID_COUNT;
+}
function splitCommandTokens(commandLine: string): string[] {
const matches = commandLine.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g);
@@ -266,6 +271,253 @@ export interface LightweightRamResult {
count: number;
}
+function parseStrictPositiveInteger(value: string): number | null {
+ if (!/^\d+$/.test(value)) return null;
+ const parsed = Number(value);
+ if (!Number.isSafeInteger(parsed) || parsed < 0) return null;
+ return parsed;
+}
+
+export function parsePsRssSnapshot(stdout: string): Map {
+ const rssByPid = new Map();
+ for (const line of stdout.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+ const parts = trimmed.split(/\s+/);
+ if (parts.length < 2) continue;
+ const pid = parseStrictPositiveInteger(parts[0]);
+ const rssKb = parseStrictPositiveInteger(parts[1]);
+ if (pid !== null && rssKb !== null) {
+ rssByPid.set(pid, rssKb * 1024);
+ }
+ }
+ return rssByPid;
+}
+
+export function parseWmicWorkingSetSnapshot(stdout: string): Map {
+ const rssByPid = new Map();
+ const normalized = stdout.replace(/\r\n/g, "\n").trim();
+ if (!normalized) return rssByPid;
+
+ let pendingPid: number | null = null;
+ let pendingRss: number | null = null;
+
+ const flush = () => {
+ if (pendingPid !== null && pendingRss !== null) {
+ rssByPid.set(pendingPid, pendingRss);
+ }
+ pendingPid = null;
+ pendingRss = null;
+ };
+
+ for (const line of normalized.split("\n")) {
+ const trimmed = line.trim();
+ if (!trimmed) continue;
+
+ const eq = trimmed.indexOf("=");
+ if (eq === -1) continue;
+
+ const key = trimmed.slice(0, eq).trim();
+ const value = trimmed.slice(eq + 1).trim();
+
+ if (key === "ProcessId") {
+ if (pendingPid !== null || pendingRss !== null) flush();
+ pendingPid = parseStrictPositiveInteger(value);
+ continue;
+ }
+
+ if (key === "WorkingSetSize") {
+ pendingRss = parseStrictPositiveInteger(value);
+ if (pendingPid !== null && pendingRss !== null) flush();
+ }
+ }
+
+ flush();
+ return rssByPid;
+}
+
+export async function sampleDarwinRssWithFallback(
+ pids: number[],
+ execFn: (command: string) => Promise<{ stdout: string }>,
+ onPidError?: (pid: number, source: string, error: unknown) => Promise | void,
+ onPartialCoverage?: (missingPids: number[], source: string) => Promise | void,
+): Promise