tewip-ai 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,528 +1,544 @@
1
- # Tewip
2
-
3
- **Tewip** (Uyghur *téwip*, تېۋىپ: healer, doctor) finds why each failing test failed: a real bug, a flaky test, the environment, test data, or a changed selector. Every answer comes with its confidence, its evidence and one next step, and names its source: a deterministic rule, the AI model, or a person's correction.
4
-
5
- It works for every stack: Node.js (node:test, Jest, Vitest, Mocha), Python (pytest, unittest), Java and Kotlin (JUnit, TestNG), Go, .NET, Ruby, PHP and Rust, each checked against its real runner's report ([the full list](QUICKSTART.md#not-using-playwright-every-stack-works)), plus Playwright in depth with traces, selector drift and verified fixes. It also reads the failure wording of the browser and component-test tools on top of those runners (Selenium, WebdriverIO, Cypress, Testing Library for React, Vue and Angular, Vue Test Utils, jest-dom and Jasmine), checked against more than 500 real messages from public projects.
6
-
7
- | Where | How |
8
- |---|---|
9
- | **Terminal** | `npm install -g tewip-ai`, then `tewip explain report.xml`, `tewip ci owner/repo --pr 12`, `tewip mcp` |
10
- | **VS Code, Cursor, Windsurf, VSCodium** | the Tewip extension: registers Tewip with the editor's AI assistant and adds *Explain a test report* and *Why did CI fail on this branch?* |
11
- | **JetBrains, Claude, other AI assistants** | add the MCP server `tewip mcp` (see [editor setup](#use-it-from-your-editor-any-ide-that-speaks-mcp)) |
12
- | **Any model** | OpenAI, Claude, Gemini, Azure, or a model on your own machine with Ollama (no account, nothing leaves the computer): `TEWIP_PROVIDER` |
13
- | **GitHub CI** | the Tewip Action: a comment on every pull request, an optional merge gate, verified fix PRs ([QUICKSTART](QUICKSTART.md)) |
14
-
15
- Formerly *triage-agent*: the repository moved to `hmamut39/tewip`, and GitHub redirects the old address. See [ROADMAP.md](ROADMAP.md) for the plan.
16
-
17
- **Status: phases 1 to 4 are built, Phase 5 (auto-fix) is in progress, and phases 6 and 7 (test plans and verified test writing) are built.** Those phases are collection, rule-based diagnosis, LLM diagnosis with a real-data eval, multi-role views, and planning and writing tests in the project's own framework. It runs live in GitHub CI and answers questions from AI assistants through MCP. On fresh real Gutenberg CI failures, with the pipeline frozen before labelling, accuracy is 93.4%; the caveats are in [eval/README.md](eval/README.md).
18
-
19
- ## Use it in your project
20
-
21
- **Giving it to your team (or another company): [TEAM-GUIDE.md](TEAM-GUIDE.md)** — what to install, what each role uses it for, and what it never does.
22
-
23
- **Putting it on a real repository: [QUICKSTART.md](QUICKSTART.md)** — ten minutes, copy-paste, and what to check on the first failing run.
24
-
25
- ### 1. In GitHub CI (developers, SDETs, DevOps)
26
-
27
- Tell Playwright to write a blob report in CI. It's a built-in reporter, so there's no triage-agent code in your config:
28
-
29
- ```ts
30
- // playwright.config.ts
31
- reporter: process.env.CI ? [['list'], ['blob']] : 'list',
32
- use: { trace: 'retain-on-failure' },
33
- ```
34
-
35
- Then add one step after your tests:
36
-
37
- ```yaml
38
- permissions:
39
- contents: write # only needed for autofix
40
- pull-requests: write
41
- issues: write
42
- actions: read # lets it read the failed job's log when no test report was written
43
-
44
- steps:
45
- # ... checkout, install, npx playwright test ...
46
- - name: triage-agent
47
- if: always()
48
- uses: hmamut39/tewip@main
49
- with:
50
- openai-api-key: ${{ secrets.OPENAI_API_KEY }} # optional: without it only the rules run
51
- autofix: 'true' # optional: verified locator-fix PRs
52
- ```
53
-
54
- On every run, the action:
55
- - **Developers:** posts one diagnosis comment on the pull request and keeps it updated. For each failure it says whether the change likely caused it, why, and what to do next.
56
- - **SDETs:** writes the triage board into the job summary.
57
- - **DevOps:** collects environment failures (server errors, connection resets, outages) in **one** GitHub issue, and each new run adds a single grouped comment to it.
58
- - **Fixes (`autofix: true`):** for drifted locators that the deterministic rule matched to a renamed element, it rewrites the locator, re-runs that test, and opens a separate pull request with the changes that passed. It never merges and never edits application code.
59
- - **Every role:** uploads all role views as the `tewip-report` artifact.
60
- - **When the job dies before any test runs** (an image that would not pull, a runner out of disk, a service container that never came up): it reads the failed job's log and names the cause, instead of leaving a red X with no explanation.
61
- - **History:** keeps the run history in the Actions cache, never in git.
62
- - **Corrections:** reply to the agent's comment with `/triage CATEGORY #n reason` (e.g. `/triage TIMING #2 flaky on CI`). It stores that with the history and, next time that test fails the same way, gives the person's answer instead of its own, naming them and their reason. A corrected failure also costs nothing: it never goes to the model again.
63
-
64
- For **senior engineers, architects and leads**, add a scheduled workflow with `mode: report`, for example weekly. It builds the engineering-quality, architecture and risk-digest views from the stored CI history, reusing earlier diagnoses so it makes no repeat AI calls. The views are kept in one GitHub issue that each report updates:
65
-
66
- ```yaml
67
- on:
68
- schedule: [{ cron: '0 6 * * 1' }]
69
- workflow_dispatch:
70
- permissions: { contents: read, issues: write }
71
- jobs:
72
- report:
73
- runs-on: ubuntu-latest
74
- steps:
75
- - uses: hmamut39/tewip@main
76
- with: { mode: report }
77
- ```
78
-
79
- The report reads the history cache of the branch it runs on, usually the default branch.
80
-
81
- The repository needs "Allow GitHub Actions to create and approve pull requests" enabled for fix PRs. Pull requests opened by the workflow token don't trigger CI themselves; the agent verified each change by re-running the test before opening the PR. See [triage-agent-sandbox](https://github.com/hmamut39/triage-agent-sandbox) for a working example. If this repository is private, other repositories can only use the action when Settings → Actions → Access allows it.
82
-
83
- ### 2. From any AI assistant, through MCP (the whole IT team)
84
-
85
- `mcp/server.ts` is a read-only [Model Context Protocol](https://modelcontextprotocol.io) server. Anyone on the team can ask their own assistant about test failures, in the editor or chat they already use:
86
-
87
- | Ask your assistant | Tool it uses |
88
- |---|---|
89
- | "Why did CI fail on PR 12 in our-org/web?" | `github_ci_report`: the latest CI report for that PR, plus any verified fix PR |
90
- | "Explain the failing checkout test" | `explain_failure`: root cause, confidence, evidence, history on this commit vs others, next action |
91
- | "What should I fix first from the last run?" | `triage_board` (SDET) · `pr_impact` (developer) |
92
- | "Is the test environment broken?" | `environment_report` (DevOps / SRE) |
93
- | "Can we release?" | `release_readiness` (business / UAT) |
94
- | "Where is our test suite fragile?" | `quality_report` (senior / principal) · `architecture_report` (architect) · `risk_digest` (lead) |
95
- | "Write a test plan for the checkout feature in C:\work\shop" | `test_plan`: risks and scenarios grounded in that project's tests, code and pages; saved in its `.tewip` folder |
96
-
97
- Setup, after `npm install`:
98
-
99
- - **Claude Code** in this repo: [.mcp.json](.mcp.json) is already here, so approve `tewip` when asked. From anywhere else, run `claude mcp add tewip -- tewip mcp` (installed), or `claude mcp add tewip -- node /path/to/tewip/mcp/server.ts` (from a checkout).
100
- - **Claude Desktop, Cursor, VS Code, and other MCP clients:** add a stdio server with command `tewip` and args `["mcp"]`, or command `node` with args `["/path/to/tewip/mcp/server.ts"]` from a checkout.
101
-
102
- `github_ci_report` uses the `gh` CLI login on your machine. The other tools read the datasets under `data/`, and the AI layer uses `OPENAI_API_KEY` from `.env`.
103
-
104
- ## Use it from your editor (any IDE that speaks MCP)
105
-
106
- **VS Code, Cursor, Windsurf and VSCodium:** install the Tewip extension (`extensions/vscode`, packaged as `tewip-<version>.vsix`: *Extensions → … → Install from VSIX*). It registers Tewip as an MCP server by itself, so the assistant can use it with no configuration, and adds two commands: *Tewip: Explain a test report…* and *Tewip: Why did CI fail on this branch?*
107
-
108
- **Every other MCP client** (JetBrains IDEs 2025.2+, Claude Code, Claude Desktop, or an editor without the extension) takes one entry. With Tewip installed from its release file (`npm install -g tewip-<version>.tgz`), the command is simply `tewip mcp`; from a checkout, point at `cli/tewip.ts`:
109
-
110
- Point the entry at this checkout with an absolute path (the server resolves its own data, so the editor's working directory does not matter). **VS Code** uses its own shape, with a `servers` key and a `type`; put it in the workspace's `.vscode/mcp.json`, or in your user-level configuration (command *MCP: Open User Configuration*) to have it in every window:
111
-
112
- ```json
113
- {
114
- "servers": {
115
- "tewip": { "type": "stdio", "command": "tewip", "args": ["mcp"] }
116
- }
117
- }
118
- ```
119
-
120
- **Cursor, Claude Desktop, Windsurf and most other clients** use the `mcpServers` shape (Cursor: Settings → MCP):
121
-
122
- ```json
123
- {
124
- "mcpServers": {
125
- "tewip": { "command": "tewip", "args": ["mcp"] }
126
- }
127
- }
128
- ```
129
-
130
- - **JetBrains** (IntelliJ, WebStorm, PyCharm 2025.2+): Settings → Tools → MCP Server.
131
- - **Inside this repository** nothing is needed for Claude Code: `.mcp.json` is already set up.
132
-
133
- Then ask, in plain language: *"why did CI fail on my PR?"*, *"which tests are flaky in checkout?"*, *"is the main branch safe to release?"*. You can also ask it to *"write a test plan for the checkout feature in C:\work\shop"*: the `test_plan` tool plans from that project's real tests, code and pages, and saves the plan in its `.tewip` folder. Every other tool is read-only, and `github_ci_report` reads the report the Action uploaded, so you can ask about a repository's CI **without cloning it or opening the Actions page** (it uses your `gh` login).
134
-
135
- ## Plan and write tests (Phases 6 and 7, new)
136
-
137
- Run these inside your project. Both need `OPENAI_API_KEY`, and both print what they cost.
138
-
139
- ```bash
140
- tewip plan "Checkout: a signed-in shopper pays by card and gets a receipt" --url http://localhost:3000/checkout
141
- tewip write # tests for the plan's "to automate next" scenarios
142
- tewip write --only CO-002,CO-004 --framework pytest
143
- ```
144
-
145
- - **`tewip plan`** reads what is really there: the tests you already have (in any language), the change (`--diff main...HEAD`), the live pages (what a user sees on each page, via Playwright), and the failures Tewip has diagnosed in this project before. The plan lists risks and scenarios by priority. A claim that a scenario is "already covered" is checked against your real test names, and dropped if no such test exists. Saved to `.tewip/plans/` as Markdown to review and JSON for `write`.
146
- - **`tewip write`** writes each scenario as a test in **your** framework and style: Playwright, Cypress, WebdriverIO, Angular, Jest, Vitest, pytest (with Selenium or Playwright), JUnit on Maven or Gradle (Selenium, Spring Boot), .NET or Go. It copies the style of an existing test and uses only elements seen on the real page. Front-end apps get component tests the way their own tests are written: React, Vue or Svelte with Testing Library under Jest or Vitest, and Angular through `ng test` (Karma and Jasmine, or Vitest). A project with both e2e and unit tests gets browser tests when the plan read pages, and unit or component tests when it did not. Then it runs the test. A draft is **kept only if** it passes every run (3 by default) **and** fails once its main check is broken on purpose, because a test that cannot fail is worse than no test. A failing draft is repaired from the real error, twice at most. If the test looks right and the app does something else, Tewip reports a **possible bug** instead of weakening the test until it passes. Kept tests are new files beside yours, for you to review and commit; nothing is committed, and no application code is touched.
147
-
148
- ## Check the page against the design (Phase 11, new)
149
-
150
- ```bash
151
- tewip design "https://www.figma.com/design/KEY/Checkout?node-id=12-34" --url http://localhost:3000/checkout
152
- tewip design frame.json --frame "Sign in" # a saved frame, no Figma token needed
153
- ```
154
-
155
- Tewip reads the frame (Figma's REST API, read only, `TEWIP_FIGMA_TOKEN`) and the running page
156
- (its accessibility snapshot, which is what a screen reader and a test both see), and says where they
157
- disagree: `the design says button "Sign in", the page says button "Log in"`. It checks the words the
158
- design specifies, the controls its layer names imply, and the regions its sections imply - never
159
- pixels, colours or spacing, because a design tool and a browser do not measure those the same way.
160
- No model is called, so it costs nothing and answers the same way every time.
161
-
162
- Measured on four real design/page pairs (a public repository's Figma exports and the pages built
163
- from them): 38 checks, **0 differences reported on pages that match their design**, **11 of 11 real
164
- drifts caught** (a renamed control, a dropped sentence, a word swapped inside a sentence, a region
165
- that lost its markup) and **5 of 5 harmless changes ignored** (capitals, extra spaces, a button
166
- implemented as a link, reordered sections). No designer has judged the output yet, so the roadmap's
167
- own metric is still open.
168
-
169
- ## More runners: Robot Framework, JMeter, k6 (new)
170
-
171
- Tewip now reads **Robot Framework's output.xml**, **JMeter's .jtl** and a **k6 summary** as well as
172
- JUnit XML, TRX, NUnit and Playwright's own reports. A load test does not fail test by test, so a
173
- JMeter report becomes one line per request ("4 of 5 requests failed, an assertion failed") and a k6
174
- run becomes one record per crossed threshold, with the number that crossed it.
175
-
176
- Appium and Selenium need no importer: those suites report through Mocha, pytest or JUnit, which
177
- Tewip already reads, and their own error messages ("Could not find a connected device", "stale
178
- element reference") are already understood.
179
-
180
- Each reader was checked against real reports published in public repositories, which is how three
181
- defects were found before release - a Robot timestamp that is not a date, k6's numbers living under
182
- `values`, and a JMeter line that read "mostly 200" when an assertion had failed.
183
-
184
- ## Tell it when it is wrong (new)
185
-
186
- ```bash
187
- tewip correct diagnosis "checkout charges twice" TEST_DATA "the fixture has stale prices"
188
- tewip correct flaky "adds an item" fix-now "it is a real race, not flakiness"
189
- tewip correct security "src/config.ts:12" noise "that is a sample key in a fixture"
190
- tewip correct --list
191
- ```
192
-
193
- Tewip answers with **your** decision from then on, and says it was yours: *"TEST_DATA, confidence
194
- 1.00, source: corrected by a person"*. Corrections live in your project, so they belong to the team;
195
- the newest one wins, so changing your mind is just saying so again.
196
-
197
- **A correction changes what Tewip says, never what it does on its own** — it will not change code,
198
- quarantine a test or file a ticket because you corrected it.
199
-
200
- ## Build a feature, test first (new)
201
-
202
- ```bash
203
- tewip build "naturalsize should take a sep argument that goes between the number and the unit"
204
- tewip build --issue PROJ-123 # build from the ticket's own description and acceptance criteria
205
- tewip build "..." --pr # commit the proved work on its own branch, open a draft PR
206
- tewip build "..." --dry-run # prove it, show the patch, leave nothing on disk
207
- ```
208
-
209
- Tewip writes the **test first** and runs it. **If that test passes, it stops and keeps nothing** —
210
- a test that passes before the feature exists is testing nothing. Then it writes the smallest code
211
- that makes the test pass, and keeps the work only if the new test passes *and* nothing that was
212
- passing has started to fail. Otherwise every file goes back byte for byte, including the test it
213
- wrote. Nothing is ever committed.
214
-
215
- Tried on two real public projects: it added a trailing-slash rule to **unjs/ufo** (4 lines,
216
- TypeScript, $0.18) and a `sep` argument to **python-humanize** (2 lines, Python, $0.10), each with
217
- its own failing-then-passing test and the project's whole suite still green. Asked for something
218
- that already worked, it stopped after one model call and kept nothing.
219
-
220
- It also refuses a feature that does not belong here at all. Handed a real Apache ticket about a
221
- Flink HTTP sink, a URL library got an "HTTP sink" built into it - test passing, suite green, every
222
- proof rule held, because when Tewip writes *both* the test and the code it can always make a
223
- self-consistent pair pass. So before writing anything it now asks whether the words of the feature
224
- mean anything in this repository, and refuses for free when they do not.
225
-
226
- The old promise was *"it can't touch your code"*. The new one is *"it can't change your code without
227
- showing you it works"*.
228
-
229
- ## Before anyone reads the diff (new)
230
-
231
- ```bash
232
- tewip review --diff main...HEAD
233
- ```
234
-
235
- Which tests cover this change and **how** (they import the file, they import the package that
236
- exports it, or their words merely match); which of them have flaked before, so a red run is not
237
- blamed on your change; what has gone wrong in these areas before; what nothing tests at all; and the
238
- command to run the telling tests first. From your project's own history, so it costs nothing.
239
-
240
- Measured on **16 real commits** from two public projects, where the developers changed source *and*
241
- its test: given only the source files, Tewip **named the right test in 16 of 16, ranked it first in
242
- 12**.
243
-
244
- ## Which flaky tests to quarantine, and what they cost (new)
245
-
246
- ```bash
247
- tewip flaky --days 30 # the dossier: quarantine, fix, or watch - with the evidence
248
- tewip flaky --apply # writes the quarantine line into the test file
249
- ```
250
-
251
- Other tools count retries. Tewip already decided *why* each failure happened, so it can say: this
252
- test failed in 161 of 647 runs **across 109 different branches** - that is the test, not your
253
- change - and quarantining it gives the team back 148 CI minutes a week. It refuses to hide a test
254
- that mostly fails (that one is broken, not flaky) and **never** quarantines a test whose failures
255
- looked like a real bug.
256
-
257
- Measured on three real projects' CI history (Gutenberg twice, Supabase): 76 tests proposed for
258
- quarantine, **zero of them containing a single real-bug failure**, giving back roughly 34, 148 and
259
- 1,178 CI minutes a week. It also tells you when a quarantined test has stopped failing and should
260
- come back - the half nobody ever does.
261
-
262
- ## Bugs filed back, and test cases where your team keeps them (Phase 10, completed)
263
-
264
- ```bash
265
- tewip bugs report.xml --project SHOP # shows what it would file; nothing is created
266
- tewip bugs report.xml --project SHOP --create # files them
267
- tewip jira plan.json --export xray --out cases.csv # or --export zephyr
268
- ```
269
-
270
- `tewip bugs` files a ticket only for failures **it** diagnosed as a real bug, with the error, the
271
- evidence and the run link. A flaky test or a broken environment is deliberately not filed - that is
272
- the point of diagnosing first. The same failure is never filed twice: the second sighting is a short
273
- note on the ticket Tewip itself opened. A dry run needs no Jira account at all.
274
-
275
- `--export xray|zephyr` writes the plan's scenarios as the CSV those tools import, one row per step.
276
- No account, no network; importing stays your step.
277
-
278
- ## Security: which findings actually matter (Phase 9, new)
279
-
280
- ```bash
281
- tewip secure # secrets + npm audit / pip-audit / osv-scanner, triaged
282
- tewip secure --url http://localhost:3000 # also check the running app
283
- tewip secure --zap-report zap.json # and triage an OWASP ZAP baseline report
284
- tewip secure --gate # fails a build only on what needs a person now
285
- ```
286
-
287
- Scanners are good at finding things and bad at saying which of them matter. Tewip runs the ones your
288
- project already has and sorts every finding into **act on this now**, **real but not reachable**
289
- (a dev dependency, a package nothing imports, a file git does not track), **noise** (a placeholder
290
- from a README), or **accepted** (a person already judged it, in a file only people write). Each
291
- verdict carries the evidence. No model is called, so it costs nothing, and **a credential is
292
- located, never printed**.
293
-
294
- With `--url` it also checks the running app the way a browser would: security headers, cookie
295
- flags, and the files that must never be served (.env, .git). No payloads, no fuzzing, no login
296
- bypass - and **an address that is not your machine is refused** unless you say `--i-am-authorised`.
297
- For the deep scan it prints the OWASP ZAP command and triages ZAP's report rather than pretending
298
- to be a scanner.
299
-
300
- Measured on the gitleaks project's own labelled samples, for the credential kinds Tewip covers:
301
- **50 of 54 real credentials found**. The web check found **8 of 8 planted weaknesses** in two local
302
- apps and reported **nothing** about the carefully served one; on four real public homepages its
303
- report matched the headers those sites actually send, every time. Four defects that corpus exposed are fixed; the four still
304
- missed are things that are not credentials (an unsigned token, a Stripe *test* key). It never claims
305
- a project is secure - it prints what it checked and what it did not.
306
-
307
- ## Epics, stories and acceptance criteria (Phase 14, new)
308
-
309
- ```bash
310
- tewip spec "Readers can search the library and open a result"
311
- tewip spec "..." --project PROJ # shows what it would file in Jira
312
- tewip spec "..." --project PROJ --create # files the epic and its stories
313
- ```
314
-
315
- An epic, user stories and Given / When / Then acceptance criteria, written from your code, your
316
- tests and your failure history. Anything it says the system **already** does carries a quote from a
317
- file it read, and Tewip checks that quote word by word; what it cannot quote becomes an open
318
- question instead of a confident sentence. It writes no estimates, dates or business cases, because
319
- it cannot check them.
320
-
321
- Measured on three real projects: 15 stories, 49 acceptance criteria, and of 46 claims about existing
322
- behaviour, **22 were kept with a checkable quote and 24 were turned into open questions**.
323
-
324
- ## Any CI, your chat, and your own machine (Phase 13, new)
325
-
326
- ```bash
327
- tewip report report.xml --gate # GitLab CI, Jenkins, CircleCI, Azure, Bitbucket, Travis, Drone
328
- tewip watch --cmd "npm test" # beside your editor: explains each failure as it happens
329
- tewip note --days 7 # the weekly quality note for a lead - free, no model calls
330
- ```
331
-
332
- `tewip report` reads which CI it is in from that platform's own variables, prints the triage board,
333
- writes it to a file, appends it to the job summary, and with `--gate` fails the build **only** on
334
- failures that are not known flaky or environment noise. On GitLab it posts the diagnosis as one
335
- merge-request note and edits that same note next run instead of piling up. With
336
- `TEWIP_SLACK_WEBHOOK` or `TEWIP_TEAMS_WEBHOOK` it tells the team's chat - and says nothing at all
337
- when no failure needs a person, so nobody mutes it.
338
-
339
- ## Fix the code, but only when the tests prove it (Phase 12, new, opt-in)
340
-
341
- ```bash
342
- tewip fix --code report.xml # shows the patch; your files are left as they were
343
- tewip fix --code report.xml --apply # leaves the proved change in your working tree
344
- ```
345
-
346
- Tewip has refused to touch application code since day one. This is the one exception, and it only
347
- runs when you type `--code`. It takes a failure **it** diagnosed as a real bug (0.85 confidence or
348
- more), finds the file the failure points at, asks for the smallest change, and then proves it: the
349
- failing test must pass **and** the whole suite must still pass. It will not edit tests,
350
- configuration, CI files, lockfiles, migrations or anything with secrets in it, because a test going
351
- green after changing those proves nothing. If it cannot prove a change, it explains the bug instead
352
- and puts your file back byte for byte. It never commits and never merges.
353
-
354
- Measured by replaying **16 real bug fixes** from two public repositories, in two languages: the
355
- commit before each fix, with only that fix's tests, so the real bug really reproduces.
356
-
357
- | Project | Language | Bugs | Proved by the tests | Right file |
358
- |---|---|---|---|---|
359
- | unjs/ufo | TypeScript, Vitest | 8 | **8** | 8 of 8 |
360
- | python-humanize/humanize | Python, pytest | 8 | **8** | 8 of 8 |
361
-
362
- Every change is small (1 to 16 lines, median 4) and most are what the developers themselves wrote.
363
- **No wrong fix was offered**: anything that could not be proved was thrown away and the file put
364
- back byte for byte.
365
-
366
- ## Where it has been tried
367
-
368
- | Project | How | Result |
369
- |---|---|---|
370
- | [triage-agent-sandbox](https://github.com/hmamut39/triage-agent-sandbox) (private practice repo) | Live GitHub Action on a release PR with 11 planted failures | Diagnosis comment, one environment issue, and a fix PR whose 5 locator changes pass when checked out. Traps left alone. Synthetic. |
371
- | WordPress Gutenberg (public) | Offline, from 5 windows of real CI blob reports, two of them harvested after the pipeline was frozen | 84–98% accuracy on 1,441 labelled real failures; the only project with enough drift cases to measure that category (see [eval/README.md](eval/README.md) for caveats) |
372
- | JupyterLab (public) | Offline, from its Galata UI suite | 90.2% on 41 labelled failures; the deterministic rules alone were right on 34 of 34 they decided |
373
- | LXD UI (public) | Offline, from its pull-request suite | 91.3% on 69 labelled failures; rules right on 63 of 63. All 6 misses are cross-branch flakes read as real bugs |
374
- | Supabase Studio (public) | Shadow run: real CI blob reports, nothing posted to the project | REAL_BUG 6/6, TEST_DATA 6/6; the TIMING majority shares its signal with the labels |
375
- | Penpot (public) | Shadow run over 21 runs that were still downloadable | Works on a third project; only 5 labelled cases, too few to score |
376
- | Nextcloud server (public) | Attempted | Harvests fine (45 failures) but only 1 case had the evidence to label in the window: too sparse to score |
377
- | Ghost (public) | Attempted | **Not usable from outside**: Ghost uploads blob reports only for failed runs and keeps them about a day, so 3 of 255 runs survived |
378
-
379
- Shadow runs are how the agent is tried on public projects without touching them: `npm run harvest -- <source>`, then `node scripts/shadow.ts <source> [--publish your/private-repo]`.
380
-
381
- ## How it compares (September 2026)
382
-
383
- Other tools cover parts of this job. This table is what each is known for from its own public material, and where triage-agent differs; it is not a benchmark of them.
384
-
385
- | Tool | What it does | Where triage-agent differs |
386
- |---|---|---|
387
- | [Playwright Test Agents](https://playwright.dev) — the Healer | Rewrites a broken selector and re-runs the test; its makers report about 75% success on selector failures | triage-agent first decides **whether** it is a changed selector at all (real bug, race, environment and test data are ruled out first), then fixes only what a deterministic rule matched and a re-run proved: 14 real fixes with none wrong. A healer that repairs every selector failure will also "repair" a removed feature |
388
- | [Trunk](https://docs.trunk.io/flaky-tests/detection), [BuildPulse](https://buildpulse.io/products/flaky-tests), [Datadog Test Optimization](https://www.getpanto.ai/blog/best-flaky-test-tools) | Detect flaky tests from pass/fail history and quarantine them so they stop blocking merges | Same core signal (a test that failed and passed on the same code), plus a cause for **every** failure, not only flaky ones, and a per-failure merge gate. Measured on 2,296 real failures (below) |
389
- | [ReportPortal](https://reportportal.io/docs/analysis/AutoAnalysisOfLaunches/) | Classifies failures as product bug, automation bug or system issue by matching earlier human classifications | Same idea of learning from people (`/triage` corrections), plus deterministic rules that need no training data, so it is useful from the first run |
390
- | [Develocity](https://develocity.ai/product/failure-analytics/) | Groups build and test failures by root cause across history (Gradle and Maven) | Any language through JUnit XML or TRX, and it acts on each failure: comment, grouped environment issue, verified fix, gate |
391
-
392
- What it does not have, and they do: dashboards and hosted history (it keeps history in the Actions cache), and years of production use.
393
-
394
- ## Smart merge gate
395
-
396
- With `gate: real-failures`, the triage step fails the build only when a failing test needs someone: a real bug, a changed selector, a test-data problem, or anything undecided. Failures that a deterministic rule or a person classified as flaky or environment do not block. AI-only verdicts still block, because the model is the less reliable half.
397
-
398
- ```yaml
399
- - name: Tests
400
- continue-on-error: true # let the gate decide the outcome
401
- run: npx playwright test # or pytest, jest, mvn test, go test ...
402
- - name: triage-agent
403
- if: always()
404
- uses: hmamut39/tewip@main
405
- with:
406
- gate: real-failures
407
- ```
408
-
409
- Measured on 2,296 labelled real failures from five projects, the gate lets **1,823** failures through and **none of them is a real bug**, a changed selector or a test-data problem; **84%** of all flaky and environment failures (1,823 of 2,160) stop blocking merges. Read the zero with care: the first measurement let one real bug through (a new test on a feature branch hit a server error from new backend code), and the server-error rule was then changed to step back when a test has never passed. The zero is measured on the same data that exposed the gap, so it is optimistic; the weekly job keeps checking it on new data. The counts are also step outputs (`blocking`, `flaky`, `environment`) for later steps to use.
410
-
411
- ## How it works
412
-
413
- - `reporters/triage-reporter.ts` is a custom Playwright reporter. It runs alongside `list`. For every attempt with status `failed` or `timedOut`, it captures the error, stack, duration, retry, trace, screenshot and `error-context.md` paths, run id and git SHA. It runs the rule engine on each failure and **appends** the records, each with its `diagnosis`, to `data/triage.jsonl`. It also appends one summary line per run to `data/runs.jsonl`, which records how many times each test ran.
414
- - `engine/` is the phase-2 rule engine. It is deterministic: the same failure and history always give the same answer. It classifies a failure into one of the five root causes (`REAL_BUG`, `LOCATOR_DRIFT`, `TIMING`, `ENV`, `TEST_DATA`) with a confidence and evidence. If no rule can decide, it returns `UNKNOWN` with confidence 0, along with what each rule saw, for phase 3.
415
- - `engine/llm/` + `engine/trace/` make up the phase-3 LLM layer. It only sees failures the rules left `UNKNOWN`. It reads `trace.zip` (the final DOM, failed requests, console errors, test steps) and `error-context.md` (the page snapshot and the failing code line, with comments stripped). It builds a short structured summary, not raw logs, and asks the model for a strict JSON answer that must be one of the five categories. The answer is checked again locally. If the call fails or the answer is invalid, the failure stays `UNKNOWN`. `engine/pipeline.ts` runs rules and then the LLM, and the reporter, CLI and eval all use it.
416
- - `eval/` holds the ground-truth labels and `evaluate.ts`, which prints the phase-3 accuracy metric. `eval/harvest/` imports real CI runs from public repos. See [eval/README.md](eval/README.md).
417
- - `engine/decide.ts` is the agent's DECIDE step. It turns each diagnosis into a next action following the autonomy table in ROADMAP.md: fix a locator or a fixed wait, re-run and notify, fix the test setup, file a bug, or escalate to a human. Low confidence (below 0.5) always escalates. Code fixes are only agent-eligible above 0.85. Nothing is executed yet: acting comes with Phase 5.
418
- - `outlets/` holds the Phase 4 views. Every view renders the same `TriageItem`: diagnosis, next action, confidence, data source and evidence. `npm run triage` writes them as markdown under `data/reports/<dataset>/` (gitignored).
419
-
420
- | Role | View | Scope |
421
- |---|---|---|
422
- | Developer | `pr-comment.md`: which failures are likely caused by this change, and why | each failed run |
423
- | SDET | `sdet-board.md`: every failure grouped by next action | each failed run |
424
- | DevOps / SRE | `infra.md`: environment failures grouped by what broke, retry recovery, one grouped alert | each failed run |
425
- | Business / UAT | `release.md`: READY / WAIT / NOT READY in plain words | each failed run |
426
- | Senior / principal engineers | `quality.md`: flakiness hotspots, recurring patterns, test-design debt ranked by CI time lost | whole window |
427
- | Architects | `architecture.md`: fragility by area, single commits that broke many suites, failing dependencies | whole window |
428
- | Leads / managers | `digest.md`: areas whose failure rate grew between the first and second half of the window | whole window |
429
- - `scripts/history.ts` groups the records by test and prints failure rates. A test is flagged `SUSPECTED_FLAKY` when its failure rate is between 20% and 80% and its error messages vary.
430
- - `scripts/diagnose.ts` runs the engine over every collected failure and prints the phase-2 metric (coverage), labelled with the dataset it came from.
431
- - `tests/` contains 5 tests that fail on purpose, served offline from `fixtures/`. **They only exist to exercise the pipeline. Numbers computed on them are not product metrics.**
432
-
433
- `data/` is gitignored because the collected data stays local. Each run writes its artifacts to `test-results/<runId>/`, so attachment paths from older runs keep working.
434
-
435
- ## Rules (engine/rules.ts)
436
-
437
- The first matching rule, in this order, decides the category. If a lower-priority rule disagrees, the confidence drops by 0.1.
438
-
439
- | Rule | Category | Fires when |
440
- |---|---|---|
441
- | `env-mass-failure` | ENV | at least 3 tests, making up at least 30% of the run, fail with the **same** error shape. Many failures with different errors don't count. |
442
- | `env-network` | ENV | the error shows a connection error (`net::ERR_*`, `ECONNREFUSED`, ...), an HTTP 5xx, or an auth failure |
443
- | `test-data-collision` | TEST_DATA | the error shows the test's data collided with existing data (duplicate key, unique constraint, "already exists") |
444
- | `env-server-error` | ENV | the app's backend answered a 5xx during the test; declines for tests that provoke errors on purpose, and for errors seen only on this commit |
445
- | `locator-drift-strict` | LOCATOR_DRIFT | an action's locator now matches several elements, and exactly one of them carries the locator's name as a whole word (`name: 'Edit'` → "Editor canvas", "Edit link"). The fix is the locator Playwright printed for that element. |
446
- | `timing-intercepted` | TIMING | the element was ready, but the error says another element (a snackbar, menu or overlay) intercepts pointer events, so the click could not land. Also Selenium's `Other element would receive the click` and Cypress's `is being covered by another element` (0.65 until measured on labelled data) |
447
- | `timing-stale-element` | TIMING | Selenium's `StaleElementReferenceException` or Cypress's `the page updated while this command was executing`: the page replaced the element between finding and using it (0.65 until measured) |
448
- | `timing-retry-pass` | TIMING | another attempt of the same code in the same run passed |
449
- | `timing-known-flaky` | TIMING | a known flaky test: in an earlier run it failed with this same error and then passed on a retry. Steps back when a request failed during the test |
450
- | `locator-drift` | LOCATOR_DRIFT | the element was never found (Playwright, Selenium `NoSuchElementException`, WebdriverIO, Cypress `Expected to find element`), but the page snapshot has an element with a similar name (similarity ≥ 0.6). Declines when the test has no recorded passing run: nothing then shows the element ever matched. |
451
- | `timing-flaky` | TIMING | the failure rate is 20%-80% over at least 3 runs, and the error message varies |
452
- | `real-bug-assertion` | REAL_BUG | a value mismatch on a test whose history is stable: it was clean before and has failed the same way since |
453
-
454
- History is **point-in-time**: each failure is judged only with runs up to and including its own run, never later ones. A test's first-ever failure therefore has no history, and history-based rules decline it.
455
-
456
- ## Usage
457
-
458
- Requires Node >= 22.18. Node runs the `.ts` scripts directly.
459
-
460
- ```bash
461
- npm install
462
- npx playwright install chromium
463
-
464
- npm test # one run (records are diagnosed as they are saved)
465
- npm run test:loop # 5 runs in a row, to build up history
466
- npm run history # failure-rate table
467
- npm run diagnose # rule-engine classification + coverage metric (add -- --evidence for details)
468
- npm run eval:synthetic # rules + LLM vs the synthetic labels (pipeline check, not a product metric)
469
- npm run eval # rules + LLM vs your real labels in eval/ground-truth.jsonl
470
- npm run lab # drift lab: the full collect -> diagnose -> decide -> auto-fix -> verify loop, locally
471
- npm run triage # every role's view for data/ + the phase-4 metric
472
- npm run triage -- --data data/real/gutenberg-holdout # the same on real CI data
473
- npm run test:engine # unit tests for rules, LLM layer, decide step and views (no network)
474
- ```
475
-
476
- ## Auto-fix and the drift lab (Phase 5, in progress)
477
-
478
- `engine/autofix/` is the ACT + VERIFY loop for LOCATOR_DRIFT. It finds the failing locator in the spec, then tries up to 3 role-based replacements taken from the failure-time page. It re-runs that one test after each attempt, keeps a change only if the test passes, and otherwise restores the file. These safety rules are built into the code:
479
-
480
- - It only edits files inside a sandbox directory, never application code.
481
- - It refuses tests with no `expect()` after the broken call, because a pass there would prove nothing.
482
- - It acts only on drift diagnosed by a deterministic drift rule (`locator-drift` or `locator-drift-strict`) above 0.85. On real CI data the AI alone called real bugs "drift" at 0.88–0.96, so AI-only drift goes to a person.
483
- - Every decision is logged with its reason, and it never pushes or merges.
484
-
485
- `npm run lab` runs the whole loop against `lab/app`. Version v1 is what the tests were written for. Version v2 is a release with 6 renamed or re-shaped elements and 5 traps: removed features with look-alike elements, a wrong price, a disabled button, a server outage, and a test without assertions. The ground truth is in `lab/cases.json`. The current result is **6/7 drifted locators fixed and verified, 0/6 false fixes**. This is synthetic data and not a product metric. On real labelled Gutenberg failures the rules now reach **15 auto-fix-eligible drift cases with 0 wrong**, each suggesting exactly the locator the developers themselves wrote.
486
-
487
- ## Learning from people (LEARN)
488
-
489
- The agent's PR comment ends with one line telling people how to correct it. A reply like `/triage TEST_DATA #1 the fixture user has no saved card` is read on the next run, stored with the run history, and applied to every later failure of that test that fails the same way. The view then shows the category as **corrected by a person**, with their name and reason as the evidence, and keeps what the agent had said next to it, so a disagreement stays visible rather than being quietly overwritten.
490
-
491
- Two limits are deliberate:
492
- - A correction settles the **category**, never a code change. Someone writing `LOCATOR_DRIFT` has not given the agent a replacement locator that a re-run has proved, so an SDET still writes that fix.
493
- - It applies to the same test failing **the same way**. A different failure of that test is a different question, and the agent answers it itself.
494
-
495
- ## What a run costs
496
-
497
- Every triage run, the CLI, the eval and the CI job summary end with one line: how many model calls were made, how long they took, how many came free from the cache, the tokens used, and the cost in dollars. Each call is priced by its own model from OpenAI's published prices (cached input at the cached rate); a team with its own price sets `TRIAGE_LLM_PRICE_IN/OUT`, and a model with no known price is reported as such, never guessed. A run is cheap because the deterministic rules answer most failures and only what they cannot settle reaches the model. Measured example (JupyterLab, 41 real failures): the rules decided 34 of them, 6 went to the model, and those 6 calls took 30 seconds and about 31,000 tokens in total.
498
-
499
- ## Security
500
-
501
- The agent reads text that a pull request's author controls (test names, error messages, traces) and it can change what blocks a merge, so it is built for untrusted input:
502
-
503
- - **Corrections come only from people with write access** (owner, member or collaborator). On a public repository a stranger's `/triage` comment is ignored, so nobody outside the team can wave a real failure past the merge gate.
504
- - **Only the agent's own comment defines what `#1` means.** A numbering map posted by anyone else is ignored, and the map's fields are encoded so no test name can break out of it.
505
- - **Text from a test run is made inert in comments:** `@mentions` do not notify anyone, links and images show as plain text, and HTML is escaped.
506
- - **The AI never has the last word on anything risky.** A crafted error message could try to talk the model into an answer, but AI-only verdicts never let a failure through the gate and never authorise a code change; fixes need a deterministic rule's match and a passing re-run.
507
- - **It never merges, never edits application code**, and keeps collected data in the Actions cache, not in the repository. The OpenAI key is optional and only ever read from a secret.
508
-
509
- ## Known issues (found on real data)
510
-
511
- - **Drift and real bugs are hard to tell apart (improving).** Rules-5 reads Playwright's strict-mode errors: when a locator like `name: 'Edit'` starts matching several elements, the error already lists them, and the one named with the whole word is the element the test means. On the fresh set (Sep 1–3) drift is **16/20 = 80%** (**16/23 = 70%** on the labels before a labelling flaw was corrected, see [eval/README.md](eval/README.md)), real bugs called drift **1 of 29**, and **15 drift cases would now be auto-fixed, each suggestion identical to the developers' own fix**. On an unseen week (Aug 20–26, 473 labels) drift is **3/3** and the agent would still have made **0 automatic changes**. The remaining misses have no usable page data: the error names no locator at all.
512
- - **Playwright does not always write a page snapshot.** For some failures (timeouts inside frames) `error-context.md` holds only the error and the test source, so the similarity rule is blind. Rebuilding the page from the trace DOM does not help: on real data, real bugs score as similar as drift (0.80–0.96), so it gives the AI noise rather than signal (it lowered held-out accuracy from 86.1% to 81.3% when tried).
513
- - **Expected server errors (partly fixed).** Tests that deliberately provoke server errors used to be read as ENV. The model is now told when a test's name says it exercises error handling (prompt llm-4).
514
- - **Views can't tell pull-request branches from the main branch yet.** Records don't store the branch, so regressions inside unmerged PRs count as product bugs in the architecture view and the digest.
515
- - **Some recurring flakes are misread.** Flaky tests that also fail on other branches are misclassified (0/22 on the held-out set), and TEST_DATA and LOCATOR_DRIFT are not yet measured on real data.
516
-
517
- Environment variables (you can put them in `.env`, which is gitignored):
518
-
519
- - `OPENAI_API_KEY`: turns the LLM layer on. Without it, only the rules run.
520
- - `TRIAGE_LLM=off`: turns the LLM layer off even when a key is set.
521
- - `TRIAGE_LLM_MODEL` (default `gpt-5.4-mini`) and `TRIAGE_LLM_REASONING` (default `low`): choose the model and its reasoning effort.
522
- - `TRIAGE_LLM_CACHE=off`: skips the response cache in `data/llm-cache.jsonl`. With the cache on, an unchanged request is answered from the cache for free.
523
- - `TRIAGE_LLM_MAX_CALLS`: at most this many model calls per run. Further failures keep the rules' answer and say so, instead of running up an unbounded bill on a huge failed run.
524
- - `TRIAGE_LLM_PRICE_IN` / `TRIAGE_LLM_PRICE_OUT`: your own price per million input / output tokens, overriding the published prices built in for OpenAI's models. For a model without a built-in price, set them to see a cost; otherwise the run says the price is unknown.
525
- - `CI_RUN_ID`: used as the run id. If it is not set, the run id is based on a timestamp.
526
- - `GIT_SHA` or `GITHUB_SHA`: stored as the record's `gitSha`. If neither is set, `gitSha` is left empty.
527
-
528
- **Data leaving the machine:** with the LLM layer on, the summary of each UNKNOWN failure is sent to OpenAI. That summary includes the error text, the page snapshot, failed request URLs (without query strings) and console errors. Nothing is committed to git.
1
+ # Tewip
2
+
3
+ **Tewip** (Uyghur *téwip*, تېۋىپ: healer, doctor) finds why each failing test failed: a real bug, a flaky test, the environment, test data, or a changed selector. Every answer comes with its confidence, its evidence and one next step, and names its source: a deterministic rule, the AI model, or a person's correction.
4
+
5
+ It works for every stack: Node.js (node:test, Jest, Vitest, Mocha), Python (pytest, unittest), Java and Kotlin (JUnit, TestNG), Go, .NET, Ruby, PHP and Rust, each checked against its real runner's report ([the full list](QUICKSTART.md#not-using-playwright-every-stack-works)), plus Playwright in depth with traces, selector drift and verified fixes. It also reads the failure wording of the browser and component-test tools on top of those runners (Selenium, WebdriverIO, Cypress, Testing Library for React, Vue and Angular, Vue Test Utils, jest-dom and Jasmine), checked against more than 500 real messages from public projects.
6
+
7
+ | Where | How |
8
+ |---|---|
9
+ | **Terminal** | `npm install -g tewip-ai`, then `tewip explain report.xml`, `tewip ci owner/repo --pr 12`, `tewip mcp` |
10
+ | **VS Code, Cursor, Windsurf, VSCodium** | the Tewip extension: registers Tewip with the editor's AI assistant and adds *Explain a test report* and *Why did CI fail on this branch?* |
11
+ | **JetBrains, Claude, other AI assistants** | add the MCP server `tewip mcp` (see [editor setup](#use-it-from-your-editor-any-ide-that-speaks-mcp)) |
12
+ | **Any model** | OpenAI, Claude, Gemini, Azure, or a model on your own machine with Ollama (no account, nothing leaves the computer): `TEWIP_PROVIDER` |
13
+ | **GitHub CI** | the Tewip Action: a comment on every pull request, an optional merge gate, verified fix PRs ([QUICKSTART](QUICKSTART.md)) |
14
+
15
+ Formerly *triage-agent*: the repository moved to `hmamut39/tewip`, and GitHub redirects the old address. See [ROADMAP.md](ROADMAP.md) for the plan.
16
+
17
+ **Status: phases 1 to 4 are built, Phase 5 (auto-fix) is in progress, and phases 6 and 7 (test plans and verified test writing) are built.** Those phases are collection, rule-based diagnosis, LLM diagnosis with a real-data eval, multi-role views, and planning and writing tests in the project's own framework. It runs live in GitHub CI and answers questions from AI assistants through MCP. On fresh real Gutenberg CI failures, with the pipeline frozen before labelling, accuracy is 93.4%; the caveats are in [eval/README.md](eval/README.md).
18
+
19
+ ## Use it in your project
20
+
21
+ **Giving it to your team (or another company): [TEAM-GUIDE.md](TEAM-GUIDE.md)** — what to install, what each role uses it for, and what it never does.
22
+
23
+ **Putting it on a real repository: [QUICKSTART.md](QUICKSTART.md)** — ten minutes, copy-paste, and what to check on the first failing run.
24
+
25
+ ### 1. In GitHub CI (developers, SDETs, DevOps)
26
+
27
+ Tell Playwright to write a blob report in CI. It's a built-in reporter, so there's no triage-agent code in your config:
28
+
29
+ ```ts
30
+ // playwright.config.ts
31
+ reporter: process.env.CI ? [['list'], ['blob']] : 'list',
32
+ use: { trace: 'retain-on-failure' },
33
+ ```
34
+
35
+ Then add one step after your tests:
36
+
37
+ ```yaml
38
+ permissions:
39
+ contents: write # only needed for autofix
40
+ pull-requests: write
41
+ issues: write
42
+ actions: read # lets it read the failed job's log when no test report was written
43
+
44
+ steps:
45
+ # ... checkout, install, npx playwright test ...
46
+ - name: triage-agent
47
+ if: always()
48
+ uses: hmamut39/tewip@main
49
+ with:
50
+ openai-api-key: ${{ secrets.OPENAI_API_KEY }} # optional: without it only the rules run
51
+ autofix: 'true' # optional: verified locator-fix PRs
52
+ ```
53
+
54
+ On every run, the action:
55
+ - **Developers:** posts one diagnosis comment on the pull request and keeps it updated. For each failure it says whether the change likely caused it, why, and what to do next.
56
+ - **SDETs:** writes the triage board into the job summary.
57
+ - **DevOps:** collects environment failures (server errors, connection resets, outages) in **one** GitHub issue, and each new run adds a single grouped comment to it.
58
+ - **Fixes (`autofix: true`):** for drifted locators that the deterministic rule matched to a renamed element, it rewrites the locator, re-runs that test, and opens a separate pull request with the changes that passed. It never merges and never edits application code.
59
+ - **Every role:** uploads all role views as the `tewip-report` artifact.
60
+ - **When the job dies before any test runs** (an image that would not pull, a runner out of disk, a service container that never came up): it reads the failed job's log and names the cause, instead of leaving a red X with no explanation.
61
+ - **History:** keeps the run history in the Actions cache, never in git.
62
+ - **Corrections:** reply to the agent's comment with `/triage CATEGORY #n reason` (e.g. `/triage TIMING #2 flaky on CI`). It stores that with the history and, next time that test fails the same way, gives the person's answer instead of its own, naming them and their reason. A corrected failure also costs nothing: it never goes to the model again.
63
+
64
+ For **senior engineers, architects and leads**, add a scheduled workflow with `mode: report`, for example weekly. It builds the engineering-quality, architecture and risk-digest views from the stored CI history, reusing earlier diagnoses so it makes no repeat AI calls. The views are kept in one GitHub issue that each report updates:
65
+
66
+ ```yaml
67
+ on:
68
+ schedule: [{ cron: '0 6 * * 1' }]
69
+ workflow_dispatch:
70
+ permissions: { contents: read, issues: write }
71
+ jobs:
72
+ report:
73
+ runs-on: ubuntu-latest
74
+ steps:
75
+ - uses: hmamut39/tewip@main
76
+ with: { mode: report }
77
+ ```
78
+
79
+ The report reads the history cache of the branch it runs on, usually the default branch.
80
+
81
+ The repository needs "Allow GitHub Actions to create and approve pull requests" enabled for fix PRs. Pull requests opened by the workflow token don't trigger CI themselves; the agent verified each change by re-running the test before opening the PR. See [triage-agent-sandbox](https://github.com/hmamut39/triage-agent-sandbox) for a working example. If this repository is private, other repositories can only use the action when Settings → Actions → Access allows it.
82
+
83
+ ### 2. From any AI assistant, through MCP (the whole IT team)
84
+
85
+ `mcp/server.ts` is a read-only [Model Context Protocol](https://modelcontextprotocol.io) server. Anyone on the team can ask their own assistant about test failures, in the editor or chat they already use:
86
+
87
+ | Ask your assistant | Tool it uses |
88
+ |---|---|
89
+ | "Why did CI fail on PR 12 in our-org/web?" | `github_ci_report`: the latest CI report for that PR, plus any verified fix PR |
90
+ | "Explain the failing checkout test" | `explain_failure`: root cause, confidence, evidence, history on this commit vs others, next action |
91
+ | "What should I fix first from the last run?" | `triage_board` (SDET) · `pr_impact` (developer) |
92
+ | "Is the test environment broken?" | `environment_report` (DevOps / SRE) |
93
+ | "Can we release?" | `release_readiness` (business / UAT) |
94
+ | "Where is our test suite fragile?" | `quality_report` (senior / principal) · `architecture_report` (architect) · `risk_digest` (lead) |
95
+ | "Write a test plan for the checkout feature in C:\work\shop" | `test_plan`: risks and scenarios grounded in that project's tests, code and pages; saved in its `.tewip` folder |
96
+
97
+ Setup, after `npm install`:
98
+
99
+ - **Claude Code** in this repo: [.mcp.json](.mcp.json) is already here, so approve `tewip` when asked. From anywhere else, run `claude mcp add tewip -- tewip mcp` (installed), or `claude mcp add tewip -- node /path/to/tewip/mcp/server.ts` (from a checkout).
100
+ - **Claude Desktop, Cursor, VS Code, and other MCP clients:** add a stdio server with command `tewip` and args `["mcp"]`, or command `node` with args `["/path/to/tewip/mcp/server.ts"]` from a checkout.
101
+
102
+ `github_ci_report` uses the `gh` CLI login on your machine. The other tools read the datasets under `data/`, and the AI layer uses `OPENAI_API_KEY` from `.env`.
103
+
104
+ ## Use it from your editor (any IDE that speaks MCP)
105
+
106
+ **VS Code, Cursor, Windsurf and VSCodium:** install the Tewip extension (`extensions/vscode`, packaged as `tewip-<version>.vsix`: *Extensions → … → Install from VSIX*). It registers Tewip as an MCP server by itself, so the assistant can use it with no configuration, and adds two commands: *Tewip: Explain a test report…* and *Tewip: Why did CI fail on this branch?*
107
+
108
+ **Every other MCP client** (JetBrains IDEs 2025.2+, Claude Code, Claude Desktop, or an editor without the extension) takes one entry. With Tewip installed from its release file (`npm install -g tewip-<version>.tgz`), the command is simply `tewip mcp`; from a checkout, point at `cli/tewip.ts`:
109
+
110
+ Point the entry at this checkout with an absolute path (the server resolves its own data, so the editor's working directory does not matter). **VS Code** uses its own shape, with a `servers` key and a `type`; put it in the workspace's `.vscode/mcp.json`, or in your user-level configuration (command *MCP: Open User Configuration*) to have it in every window:
111
+
112
+ ```json
113
+ {
114
+ "servers": {
115
+ "tewip": { "type": "stdio", "command": "tewip", "args": ["mcp"] }
116
+ }
117
+ }
118
+ ```
119
+
120
+ **Cursor, Claude Desktop, Windsurf and most other clients** use the `mcpServers` shape (Cursor: Settings → MCP):
121
+
122
+ ```json
123
+ {
124
+ "mcpServers": {
125
+ "tewip": { "command": "tewip", "args": ["mcp"] }
126
+ }
127
+ }
128
+ ```
129
+
130
+ - **JetBrains** (IntelliJ, WebStorm, PyCharm 2025.2+): Settings → Tools → MCP Server.
131
+ - **Inside this repository** nothing is needed for Claude Code: `.mcp.json` is already set up.
132
+
133
+ Then ask, in plain language: *"why did CI fail on my PR?"*, *"which tests are flaky in checkout?"*, *"is the main branch safe to release?"*. You can also ask it to *"write a test plan for the checkout feature in C:\work\shop"*: the `test_plan` tool plans from that project's real tests, code and pages, and saves the plan in its `.tewip` folder. Every other tool is read-only, and `github_ci_report` reads the report the Action uploaded, so you can ask about a repository's CI **without cloning it or opening the Actions page** (it uses your `gh` login).
134
+
135
+ ## Plan and write tests (Phases 6 and 7, new)
136
+
137
+ Run these inside your project. Both need `OPENAI_API_KEY`, and both print what they cost.
138
+
139
+ ```bash
140
+ tewip plan "Checkout: a signed-in shopper pays by card and gets a receipt" --url http://localhost:3000/checkout
141
+ tewip write # tests for the plan's "to automate next" scenarios
142
+ tewip write --only CO-002,CO-004 --framework pytest
143
+ ```
144
+
145
+ - **`tewip plan`** reads what is really there: the tests you already have (in any language), the change (`--diff main...HEAD`), the live pages (what a user sees on each page, via Playwright), and the failures Tewip has diagnosed in this project before. The plan lists risks and scenarios by priority. A claim that a scenario is "already covered" is checked against your real test names, and dropped if no such test exists. Saved to `.tewip/plans/` as Markdown to review and JSON for `write`.
146
+ - **`tewip write`** writes each scenario as a test in **your** framework and style: Playwright, Cypress, WebdriverIO, Angular, Jest, Vitest, pytest (with Selenium or Playwright), JUnit on Maven or Gradle (Selenium, Spring Boot), .NET or Go. It copies the style of an existing test and uses only elements seen on the real page. Front-end apps get component tests the way their own tests are written: React, Vue or Svelte with Testing Library under Jest or Vitest, and Angular through `ng test` (Karma and Jasmine, or Vitest). A project with both e2e and unit tests gets browser tests when the plan read pages, and unit or component tests when it did not. Then it runs the test. A draft is **kept only if** it passes every run (3 by default) **and** fails once its main check is broken on purpose, because a test that cannot fail is worse than no test. A failing draft is repaired from the real error, twice at most. If the test looks right and the app does something else, Tewip reports a **possible bug** instead of weakening the test until it passes. Kept tests are new files beside yours, for you to review and commit; nothing is committed, and no application code is touched.
147
+
148
+ ## Check the page against the design (Phase 11, new)
149
+
150
+ ```bash
151
+ tewip design "https://www.figma.com/design/KEY/Checkout?node-id=12-34" --url http://localhost:3000/checkout
152
+ tewip design frame.json --frame "Sign in" # a saved frame, no Figma token needed
153
+ ```
154
+
155
+ Tewip reads the frame (Figma's REST API, read only, `TEWIP_FIGMA_TOKEN`) and the running page
156
+ (its accessibility snapshot, which is what a screen reader and a test both see), and says where they
157
+ disagree: `the design says button "Sign in", the page says button "Log in"`. It checks the words the
158
+ design specifies, the controls its layer names imply, and the regions its sections imply - never
159
+ pixels, colours or spacing, because a design tool and a browser do not measure those the same way.
160
+ No model is called, so it costs nothing and answers the same way every time.
161
+
162
+ Measured on four real design/page pairs (a public repository's Figma exports and the pages built
163
+ from them): 38 checks, **0 differences reported on pages that match their design**, **11 of 11 real
164
+ drifts caught** (a renamed control, a dropped sentence, a word swapped inside a sentence, a region
165
+ that lost its markup) and **5 of 5 harmless changes ignored** (capitals, extra spaces, a button
166
+ implemented as a link, reordered sections). No designer has judged the output yet, so the roadmap's
167
+ own metric is still open.
168
+
169
+ ## More runners: Robot Framework, JMeter, k6 (new)
170
+
171
+ Tewip now reads **Robot Framework's output.xml**, **JMeter's .jtl** and a **k6 summary** as well as
172
+ JUnit XML, TRX, NUnit and Playwright's own reports. A load test does not fail test by test, so a
173
+ JMeter report becomes one line per request ("4 of 5 requests failed, an assertion failed") and a k6
174
+ run becomes one record per crossed threshold, with the number that crossed it.
175
+
176
+ Appium and Selenium need no importer: those suites report through Mocha, pytest or JUnit, which
177
+ Tewip already reads, and their own error messages ("Could not find a connected device", "stale
178
+ element reference") are already understood.
179
+
180
+ Each reader was checked against real reports published in public repositories, which is how three
181
+ defects were found before release - a Robot timestamp that is not a date, k6's numbers living under
182
+ `values`, and a JMeter line that read "mostly 200" when an assertion had failed.
183
+
184
+ ## Tell it when it is wrong (new)
185
+
186
+ ```bash
187
+ tewip correct diagnosis "checkout charges twice" TEST_DATA "the fixture has stale prices"
188
+ tewip correct flaky "adds an item" fix-now "it is a real race, not flakiness"
189
+ tewip correct security "src/config.ts:12" noise "that is a sample key in a fixture"
190
+ tewip correct --list
191
+ ```
192
+
193
+ Tewip answers with **your** decision from then on, and says it was yours: *"TEST_DATA, confidence
194
+ 1.00, source: corrected by a person"*. Corrections live in your project, so they belong to the team;
195
+ the newest one wins, so changing your mind is just saying so again.
196
+
197
+ **A correction changes what Tewip says, never what it does on its own** — it will not change code,
198
+ quarantine a test or file a ticket because you corrected it.
199
+
200
+ ## What your corrections add up to (new)
201
+
202
+ ```bash
203
+ tewip learn # where Tewip is systematically wrong, from what you corrected
204
+ tewip learn --labels labels.jsonl # your corrections as labelled examples, to measure a change against
205
+ ```
206
+
207
+ One correction fixes one failure. Twenty of them say which rule to change. `tewip learn` groups
208
+ them - "45x said REAL_BUG, you said TIMING; rule `locator-drift` decided 27 of them; from 11
209
+ different tests" - and points at the rule to read, with three of the real failures underneath.
210
+
211
+ It will not pretend. Fewer than three corrections of the same shape is "not yet a pattern", not a
212
+ finding; when no single rule is behind a group it says a rule is *missing* rather than blaming one;
213
+ and it tells you how many different tests a pattern came from, because one flaky test corrected six
214
+ times is one piece of evidence, not six.
215
+
216
+ ## Build a feature, test first (new)
217
+
218
+ ```bash
219
+ tewip build "naturalsize should take a sep argument that goes between the number and the unit"
220
+ tewip build --issue PROJ-123 # build from the ticket's own description and acceptance criteria
221
+ tewip build "..." --pr # commit the proved work on its own branch, open a draft PR
222
+ tewip build "..." --dry-run # prove it, show the patch, leave nothing on disk
223
+ ```
224
+
225
+ Tewip writes the **test first** and runs it. **If that test passes, it stops and keeps nothing** —
226
+ a test that passes before the feature exists is testing nothing. Then it writes the smallest code
227
+ that makes the test pass, and keeps the work only if the new test passes *and* nothing that was
228
+ passing has started to fail. Otherwise every file goes back byte for byte, including the test it
229
+ wrote. Nothing is ever committed.
230
+
231
+ Tried on two real public projects: it added a trailing-slash rule to **unjs/ufo** (4 lines,
232
+ TypeScript, $0.18) and a `sep` argument to **python-humanize** (2 lines, Python, $0.10), each with
233
+ its own failing-then-passing test and the project's whole suite still green. Asked for something
234
+ that already worked, it stopped after one model call and kept nothing.
235
+
236
+ It also refuses a feature that does not belong here at all. Handed a real Apache ticket about a
237
+ Flink HTTP sink, a URL library got an "HTTP sink" built into it - test passing, suite green, every
238
+ proof rule held, because when Tewip writes *both* the test and the code it can always make a
239
+ self-consistent pair pass. So before writing anything it now asks whether the words of the feature
240
+ mean anything in this repository, and refuses for free when they do not.
241
+
242
+ The old promise was *"it can't touch your code"*. The new one is *"it can't change your code without
243
+ showing you it works"*.
244
+
245
+ ## Before anyone reads the diff (new)
246
+
247
+ ```bash
248
+ tewip review --diff main...HEAD
249
+ ```
250
+
251
+ Which tests cover this change and **how** (they import the file, they import the package that
252
+ exports it, or their words merely match); which of them have flaked before, so a red run is not
253
+ blamed on your change; what has gone wrong in these areas before; what nothing tests at all; and the
254
+ command to run the telling tests first. From your project's own history, so it costs nothing.
255
+
256
+ Measured on **16 real commits** from two public projects, where the developers changed source *and*
257
+ its test: given only the source files, Tewip **named the right test in 16 of 16, ranked it first in
258
+ 12**.
259
+
260
+ ## Which flaky tests to quarantine, and what they cost (new)
261
+
262
+ ```bash
263
+ tewip flaky --days 30 # the dossier: quarantine, fix, or watch - with the evidence
264
+ tewip flaky --apply # writes the quarantine line into the test file
265
+ ```
266
+
267
+ Other tools count retries. Tewip already decided *why* each failure happened, so it can say: this
268
+ test failed in 161 of 647 runs **across 109 different branches** - that is the test, not your
269
+ change - and quarantining it gives the team back 148 CI minutes a week. It refuses to hide a test
270
+ that mostly fails (that one is broken, not flaky) and **never** quarantines a test whose failures
271
+ looked like a real bug.
272
+
273
+ Measured on three real projects' CI history (Gutenberg twice, Supabase): 76 tests proposed for
274
+ quarantine, **zero of them containing a single real-bug failure**, giving back roughly 34, 148 and
275
+ 1,178 CI minutes a week. It also tells you when a quarantined test has stopped failing and should
276
+ come back - the half nobody ever does.
277
+
278
+ ## Bugs filed back, and test cases where your team keeps them (Phase 10, completed)
279
+
280
+ ```bash
281
+ tewip bugs report.xml --project SHOP # shows what it would file; nothing is created
282
+ tewip bugs report.xml --project SHOP --create # files them
283
+ tewip jira plan.json --export xray --out cases.csv # or --export zephyr
284
+ ```
285
+
286
+ `tewip bugs` files a ticket only for failures **it** diagnosed as a real bug, with the error, the
287
+ evidence and the run link. A flaky test or a broken environment is deliberately not filed - that is
288
+ the point of diagnosing first. The same failure is never filed twice: the second sighting is a short
289
+ note on the ticket Tewip itself opened. A dry run needs no Jira account at all.
290
+
291
+ `--export xray|zephyr` writes the plan's scenarios as the CSV those tools import, one row per step.
292
+ No account, no network; importing stays your step.
293
+
294
+ ## Security: which findings actually matter (Phase 9, new)
295
+
296
+ ```bash
297
+ tewip secure # secrets + npm audit / pip-audit / osv-scanner, triaged
298
+ tewip secure --url http://localhost:3000 # also check the running app
299
+ tewip secure --zap-report zap.json # and triage an OWASP ZAP baseline report
300
+ tewip secure --gate # fails a build only on what needs a person now
301
+ ```
302
+
303
+ Scanners are good at finding things and bad at saying which of them matter. Tewip runs the ones your
304
+ project already has and sorts every finding into **act on this now**, **real but not reachable**
305
+ (a dev dependency, a package nothing imports, a file git does not track), **noise** (a placeholder
306
+ from a README), or **accepted** (a person already judged it, in a file only people write). Each
307
+ verdict carries the evidence. No model is called, so it costs nothing, and **a credential is
308
+ located, never printed**.
309
+
310
+ With `--url` it also checks the running app the way a browser would: security headers, cookie
311
+ flags, and the files that must never be served (.env, .git). No payloads, no fuzzing, no login
312
+ bypass - and **an address that is not your machine is refused** unless you say `--i-am-authorised`.
313
+ For the deep scan it prints the OWASP ZAP command and triages ZAP's report rather than pretending
314
+ to be a scanner.
315
+
316
+ Measured on the gitleaks project's own labelled samples, for the credential kinds Tewip covers:
317
+ **50 of 54 real credentials found**. The web check found **8 of 8 planted weaknesses** in two local
318
+ apps and reported **nothing** about the carefully served one; on four real public homepages its
319
+ report matched the headers those sites actually send, every time. Four defects that corpus exposed are fixed; the four still
320
+ missed are things that are not credentials (an unsigned token, a Stripe *test* key). It never claims
321
+ a project is secure - it prints what it checked and what it did not.
322
+
323
+ ## Epics, stories and acceptance criteria (Phase 14, new)
324
+
325
+ ```bash
326
+ tewip spec "Readers can search the library and open a result"
327
+ tewip spec "..." --project PROJ # shows what it would file in Jira
328
+ tewip spec "..." --project PROJ --create # files the epic and its stories
329
+ ```
330
+
331
+ An epic, user stories and Given / When / Then acceptance criteria, written from your code, your
332
+ tests and your failure history. Anything it says the system **already** does carries a quote from a
333
+ file it read, and Tewip checks that quote word by word; what it cannot quote becomes an open
334
+ question instead of a confident sentence. It writes no estimates, dates or business cases, because
335
+ it cannot check them.
336
+
337
+ Measured on three real projects: 15 stories, 49 acceptance criteria, and of 46 claims about existing
338
+ behaviour, **22 were kept with a checkable quote and 24 were turned into open questions**.
339
+
340
+ ## Any CI, your chat, and your own machine (Phase 13, new)
341
+
342
+ ```bash
343
+ tewip report report.xml --gate # GitLab CI, Jenkins, CircleCI, Azure, Bitbucket, Travis, Drone
344
+ tewip watch --cmd "npm test" # beside your editor: explains each failure as it happens
345
+ tewip note --days 7 # the weekly quality note for a lead - free, no model calls
346
+ ```
347
+
348
+ `tewip report` reads which CI it is in from that platform's own variables, prints the triage board,
349
+ writes it to a file, appends it to the job summary, and with `--gate` fails the build **only** on
350
+ failures that are not known flaky or environment noise. On GitLab it posts the diagnosis as one
351
+ merge-request note and edits that same note next run instead of piling up. With
352
+ `TEWIP_SLACK_WEBHOOK` or `TEWIP_TEAMS_WEBHOOK` it tells the team's chat - and says nothing at all
353
+ when no failure needs a person, so nobody mutes it.
354
+
355
+ ## Fix the code, but only when the tests prove it (Phase 12, new, opt-in)
356
+
357
+ ```bash
358
+ tewip fix --code report.xml # shows the patch; your files are left as they were
359
+ tewip fix --code report.xml --apply # leaves the proved change in your working tree
360
+ ```
361
+
362
+ Tewip has refused to touch application code since day one. This is the one exception, and it only
363
+ runs when you type `--code`. It takes a failure **it** diagnosed as a real bug (0.85 confidence or
364
+ more), finds the file the failure points at, asks for the smallest change, and then proves it: the
365
+ failing test must pass **and** the whole suite must still pass. It will not edit tests,
366
+ configuration, CI files, lockfiles, migrations or anything with secrets in it, because a test going
367
+ green after changing those proves nothing. If it cannot prove a change, it explains the bug instead
368
+ and puts your file back byte for byte. It never commits and never merges.
369
+
370
+ Measured by replaying **16 real bug fixes** from two public repositories, in two languages: the
371
+ commit before each fix, with only that fix's tests, so the real bug really reproduces.
372
+
373
+ | Project | Language | Bugs | Proved by the tests | Right file |
374
+ |---|---|---|---|---|
375
+ | unjs/ufo | TypeScript, Vitest | 8 | **8** | 8 of 8 |
376
+ | python-humanize/humanize | Python, pytest | 8 | **8** | 8 of 8 |
377
+
378
+ Every change is small (1 to 16 lines, median 4) and most are what the developers themselves wrote.
379
+ **No wrong fix was offered**: anything that could not be proved was thrown away and the file put
380
+ back byte for byte.
381
+
382
+ ## Where it has been tried
383
+
384
+ | Project | How | Result |
385
+ |---|---|---|
386
+ | [triage-agent-sandbox](https://github.com/hmamut39/triage-agent-sandbox) (private practice repo) | Live GitHub Action on a release PR with 11 planted failures | Diagnosis comment, one environment issue, and a fix PR whose 5 locator changes pass when checked out. Traps left alone. Synthetic. |
387
+ | WordPress Gutenberg (public) | Offline, from 5 windows of real CI blob reports, two of them harvested after the pipeline was frozen | 84–98% accuracy on 1,441 labelled real failures; the only project with enough drift cases to measure that category (see [eval/README.md](eval/README.md) for caveats) |
388
+ | JupyterLab (public) | Offline, from its Galata UI suite | 90.2% on 41 labelled failures; the deterministic rules alone were right on 34 of 34 they decided |
389
+ | LXD UI (public) | Offline, from its pull-request suite | 91.3% on 69 labelled failures; rules right on 63 of 63. All 6 misses are cross-branch flakes read as real bugs |
390
+ | Supabase Studio (public) | Shadow run: real CI blob reports, nothing posted to the project | REAL_BUG 6/6, TEST_DATA 6/6; the TIMING majority shares its signal with the labels |
391
+ | Penpot (public) | Shadow run over 21 runs that were still downloadable | Works on a third project; only 5 labelled cases, too few to score |
392
+ | Nextcloud server (public) | Attempted | Harvests fine (45 failures) but only 1 case had the evidence to label in the window: too sparse to score |
393
+ | Ghost (public) | Attempted | **Not usable from outside**: Ghost uploads blob reports only for failed runs and keeps them about a day, so 3 of 255 runs survived |
394
+
395
+ Shadow runs are how the agent is tried on public projects without touching them: `npm run harvest -- <source>`, then `node scripts/shadow.ts <source> [--publish your/private-repo]`.
396
+
397
+ ## How it compares (September 2026)
398
+
399
+ Other tools cover parts of this job. This table is what each is known for from its own public material, and where triage-agent differs; it is not a benchmark of them.
400
+
401
+ | Tool | What it does | Where triage-agent differs |
402
+ |---|---|---|
403
+ | [Playwright Test Agents](https://playwright.dev) — the Healer | Rewrites a broken selector and re-runs the test; its makers report about 75% success on selector failures | triage-agent first decides **whether** it is a changed selector at all (real bug, race, environment and test data are ruled out first), then fixes only what a deterministic rule matched and a re-run proved: 14 real fixes with none wrong. A healer that repairs every selector failure will also "repair" a removed feature |
404
+ | [Trunk](https://docs.trunk.io/flaky-tests/detection), [BuildPulse](https://buildpulse.io/products/flaky-tests), [Datadog Test Optimization](https://www.getpanto.ai/blog/best-flaky-test-tools) | Detect flaky tests from pass/fail history and quarantine them so they stop blocking merges | Same core signal (a test that failed and passed on the same code), plus a cause for **every** failure, not only flaky ones, and a per-failure merge gate. Measured on 2,296 real failures (below) |
405
+ | [ReportPortal](https://reportportal.io/docs/analysis/AutoAnalysisOfLaunches/) | Classifies failures as product bug, automation bug or system issue by matching earlier human classifications | Same idea of learning from people (`/triage` corrections), plus deterministic rules that need no training data, so it is useful from the first run |
406
+ | [Develocity](https://develocity.ai/product/failure-analytics/) | Groups build and test failures by root cause across history (Gradle and Maven) | Any language through JUnit XML or TRX, and it acts on each failure: comment, grouped environment issue, verified fix, gate |
407
+
408
+ What it does not have, and they do: dashboards and hosted history (it keeps history in the Actions cache), and years of production use.
409
+
410
+ ## Smart merge gate
411
+
412
+ With `gate: real-failures`, the triage step fails the build only when a failing test needs someone: a real bug, a changed selector, a test-data problem, or anything undecided. Failures that a deterministic rule or a person classified as flaky or environment do not block. AI-only verdicts still block, because the model is the less reliable half.
413
+
414
+ ```yaml
415
+ - name: Tests
416
+ continue-on-error: true # let the gate decide the outcome
417
+ run: npx playwright test # or pytest, jest, mvn test, go test ...
418
+ - name: triage-agent
419
+ if: always()
420
+ uses: hmamut39/tewip@main
421
+ with:
422
+ gate: real-failures
423
+ ```
424
+
425
+ Measured on 2,296 labelled real failures from five projects, the gate lets **1,823** failures through and **none of them is a real bug**, a changed selector or a test-data problem; **84%** of all flaky and environment failures (1,823 of 2,160) stop blocking merges. Read the zero with care: the first measurement let one real bug through (a new test on a feature branch hit a server error from new backend code), and the server-error rule was then changed to step back when a test has never passed. The zero is measured on the same data that exposed the gap, so it is optimistic; the weekly job keeps checking it on new data. The counts are also step outputs (`blocking`, `flaky`, `environment`) for later steps to use.
426
+
427
+ ## How it works
428
+
429
+ - `reporters/triage-reporter.ts` is a custom Playwright reporter. It runs alongside `list`. For every attempt with status `failed` or `timedOut`, it captures the error, stack, duration, retry, trace, screenshot and `error-context.md` paths, run id and git SHA. It runs the rule engine on each failure and **appends** the records, each with its `diagnosis`, to `data/triage.jsonl`. It also appends one summary line per run to `data/runs.jsonl`, which records how many times each test ran.
430
+ - `engine/` is the phase-2 rule engine. It is deterministic: the same failure and history always give the same answer. It classifies a failure into one of the five root causes (`REAL_BUG`, `LOCATOR_DRIFT`, `TIMING`, `ENV`, `TEST_DATA`) with a confidence and evidence. If no rule can decide, it returns `UNKNOWN` with confidence 0, along with what each rule saw, for phase 3.
431
+ - `engine/llm/` + `engine/trace/` make up the phase-3 LLM layer. It only sees failures the rules left `UNKNOWN`. It reads `trace.zip` (the final DOM, failed requests, console errors, test steps) and `error-context.md` (the page snapshot and the failing code line, with comments stripped). It builds a short structured summary, not raw logs, and asks the model for a strict JSON answer that must be one of the five categories. The answer is checked again locally. If the call fails or the answer is invalid, the failure stays `UNKNOWN`. `engine/pipeline.ts` runs rules and then the LLM, and the reporter, CLI and eval all use it.
432
+ - `eval/` holds the ground-truth labels and `evaluate.ts`, which prints the phase-3 accuracy metric. `eval/harvest/` imports real CI runs from public repos. See [eval/README.md](eval/README.md).
433
+ - `engine/decide.ts` is the agent's DECIDE step. It turns each diagnosis into a next action following the autonomy table in ROADMAP.md: fix a locator or a fixed wait, re-run and notify, fix the test setup, file a bug, or escalate to a human. Low confidence (below 0.5) always escalates. Code fixes are only agent-eligible above 0.85. Nothing is executed yet: acting comes with Phase 5.
434
+ - `outlets/` holds the Phase 4 views. Every view renders the same `TriageItem`: diagnosis, next action, confidence, data source and evidence. `npm run triage` writes them as markdown under `data/reports/<dataset>/` (gitignored).
435
+
436
+ | Role | View | Scope |
437
+ |---|---|---|
438
+ | Developer | `pr-comment.md`: which failures are likely caused by this change, and why | each failed run |
439
+ | SDET | `sdet-board.md`: every failure grouped by next action | each failed run |
440
+ | DevOps / SRE | `infra.md`: environment failures grouped by what broke, retry recovery, one grouped alert | each failed run |
441
+ | Business / UAT | `release.md`: READY / WAIT / NOT READY in plain words | each failed run |
442
+ | Senior / principal engineers | `quality.md`: flakiness hotspots, recurring patterns, test-design debt ranked by CI time lost | whole window |
443
+ | Architects | `architecture.md`: fragility by area, single commits that broke many suites, failing dependencies | whole window |
444
+ | Leads / managers | `digest.md`: areas whose failure rate grew between the first and second half of the window | whole window |
445
+ - `scripts/history.ts` groups the records by test and prints failure rates. A test is flagged `SUSPECTED_FLAKY` when its failure rate is between 20% and 80% and its error messages vary.
446
+ - `scripts/diagnose.ts` runs the engine over every collected failure and prints the phase-2 metric (coverage), labelled with the dataset it came from.
447
+ - `tests/` contains 5 tests that fail on purpose, served offline from `fixtures/`. **They only exist to exercise the pipeline. Numbers computed on them are not product metrics.**
448
+
449
+ `data/` is gitignored because the collected data stays local. Each run writes its artifacts to `test-results/<runId>/`, so attachment paths from older runs keep working.
450
+
451
+ ## Rules (engine/rules.ts)
452
+
453
+ The first matching rule, in this order, decides the category. If a lower-priority rule disagrees, the confidence drops by 0.1.
454
+
455
+ | Rule | Category | Fires when |
456
+ |---|---|---|
457
+ | `env-mass-failure` | ENV | at least 3 tests, making up at least 30% of the run, fail with the **same** error shape. Many failures with different errors don't count. |
458
+ | `env-network` | ENV | the error shows a connection error (`net::ERR_*`, `ECONNREFUSED`, ...), an HTTP 5xx, or an auth failure |
459
+ | `test-data-collision` | TEST_DATA | the error shows the test's data collided with existing data (duplicate key, unique constraint, "already exists") |
460
+ | `env-server-error` | ENV | the app's backend answered a 5xx during the test; declines for tests that provoke errors on purpose, and for errors seen only on this commit |
461
+ | `locator-drift-strict` | LOCATOR_DRIFT | an action's locator now matches several elements, and exactly one of them carries the locator's name as a whole word (`name: 'Edit'` → "Editor canvas", "Edit link"). The fix is the locator Playwright printed for that element. |
462
+ | `timing-intercepted` | TIMING | the element was ready, but the error says another element (a snackbar, menu or overlay) intercepts pointer events, so the click could not land. Also Selenium's `Other element would receive the click` and Cypress's `is being covered by another element` (0.65 until measured on labelled data) |
463
+ | `timing-stale-element` | TIMING | Selenium's `StaleElementReferenceException` or Cypress's `the page updated while this command was executing`: the page replaced the element between finding and using it (0.65 until measured) |
464
+ | `timing-retry-pass` | TIMING | another attempt of the same code in the same run passed |
465
+ | `timing-known-flaky` | TIMING | a known flaky test: in an earlier run it failed with this same error and then passed on a retry. Steps back when a request failed during the test |
466
+ | `locator-drift` | LOCATOR_DRIFT | the element was never found (Playwright, Selenium `NoSuchElementException`, WebdriverIO, Cypress `Expected to find element`), but the page snapshot has an element with a similar name (similarity ≥ 0.6). Declines when the test has no recorded passing run: nothing then shows the element ever matched. |
467
+ | `timing-flaky` | TIMING | the failure rate is 20%-80% over at least 3 runs, and the error message varies |
468
+ | `real-bug-assertion` | REAL_BUG | a value mismatch on a test whose history is stable: it was clean before and has failed the same way since |
469
+
470
+ History is **point-in-time**: each failure is judged only with runs up to and including its own run, never later ones. A test's first-ever failure therefore has no history, and history-based rules decline it.
471
+
472
+ ## Usage
473
+
474
+ Requires Node >= 22.18. Node runs the `.ts` scripts directly.
475
+
476
+ ```bash
477
+ npm install
478
+ npx playwright install chromium
479
+
480
+ npm test # one run (records are diagnosed as they are saved)
481
+ npm run test:loop # 5 runs in a row, to build up history
482
+ npm run history # failure-rate table
483
+ npm run diagnose # rule-engine classification + coverage metric (add -- --evidence for details)
484
+ npm run eval:synthetic # rules + LLM vs the synthetic labels (pipeline check, not a product metric)
485
+ npm run eval # rules + LLM vs your real labels in eval/ground-truth.jsonl
486
+ npm run lab # drift lab: the full collect -> diagnose -> decide -> auto-fix -> verify loop, locally
487
+ npm run triage # every role's view for data/ + the phase-4 metric
488
+ npm run triage -- --data data/real/gutenberg-holdout # the same on real CI data
489
+ npm run test:engine # unit tests for rules, LLM layer, decide step and views (no network)
490
+ ```
491
+
492
+ ## Auto-fix and the drift lab (Phase 5, in progress)
493
+
494
+ `engine/autofix/` is the ACT + VERIFY loop for LOCATOR_DRIFT. It finds the failing locator in the spec, then tries up to 3 role-based replacements taken from the failure-time page. It re-runs that one test after each attempt, keeps a change only if the test passes, and otherwise restores the file. These safety rules are built into the code:
495
+
496
+ - It only edits files inside a sandbox directory, never application code.
497
+ - It refuses tests with no `expect()` after the broken call, because a pass there would prove nothing.
498
+ - It acts only on drift diagnosed by a deterministic drift rule (`locator-drift` or `locator-drift-strict`) above 0.85. On real CI data the AI alone called real bugs "drift" at 0.88–0.96, so AI-only drift goes to a person.
499
+ - Every decision is logged with its reason, and it never pushes or merges.
500
+
501
+ `npm run lab` runs the whole loop against `lab/app`. Version v1 is what the tests were written for. Version v2 is a release with 6 renamed or re-shaped elements and 5 traps: removed features with look-alike elements, a wrong price, a disabled button, a server outage, and a test without assertions. The ground truth is in `lab/cases.json`. The current result is **6/7 drifted locators fixed and verified, 0/6 false fixes**. This is synthetic data and not a product metric. On real labelled Gutenberg failures the rules now reach **15 auto-fix-eligible drift cases with 0 wrong**, each suggesting exactly the locator the developers themselves wrote.
502
+
503
+ ## Learning from people (LEARN)
504
+
505
+ The agent's PR comment ends with one line telling people how to correct it. A reply like `/triage TEST_DATA #1 the fixture user has no saved card` is read on the next run, stored with the run history, and applied to every later failure of that test that fails the same way. The view then shows the category as **corrected by a person**, with their name and reason as the evidence, and keeps what the agent had said next to it, so a disagreement stays visible rather than being quietly overwritten.
506
+
507
+ Two limits are deliberate:
508
+ - A correction settles the **category**, never a code change. Someone writing `LOCATOR_DRIFT` has not given the agent a replacement locator that a re-run has proved, so an SDET still writes that fix.
509
+ - It applies to the same test failing **the same way**. A different failure of that test is a different question, and the agent answers it itself.
510
+
511
+ ## What a run costs
512
+
513
+ Every triage run, the CLI, the eval and the CI job summary end with one line: how many model calls were made, how long they took, how many came free from the cache, the tokens used, and the cost in dollars. Each call is priced by its own model from OpenAI's published prices (cached input at the cached rate); a team with its own price sets `TRIAGE_LLM_PRICE_IN/OUT`, and a model with no known price is reported as such, never guessed. A run is cheap because the deterministic rules answer most failures and only what they cannot settle reaches the model. Measured example (JupyterLab, 41 real failures): the rules decided 34 of them, 6 went to the model, and those 6 calls took 30 seconds and about 31,000 tokens in total.
514
+
515
+ ## Security
516
+
517
+ The agent reads text that a pull request's author controls (test names, error messages, traces) and it can change what blocks a merge, so it is built for untrusted input:
518
+
519
+ - **Corrections come only from people with write access** (owner, member or collaborator). On a public repository a stranger's `/triage` comment is ignored, so nobody outside the team can wave a real failure past the merge gate.
520
+ - **Only the agent's own comment defines what `#1` means.** A numbering map posted by anyone else is ignored, and the map's fields are encoded so no test name can break out of it.
521
+ - **Text from a test run is made inert in comments:** `@mentions` do not notify anyone, links and images show as plain text, and HTML is escaped.
522
+ - **The AI never has the last word on anything risky.** A crafted error message could try to talk the model into an answer, but AI-only verdicts never let a failure through the gate and never authorise a code change; fixes need a deterministic rule's match and a passing re-run.
523
+ - **It never merges, never edits application code**, and keeps collected data in the Actions cache, not in the repository. The OpenAI key is optional and only ever read from a secret.
524
+
525
+ ## Known issues (found on real data)
526
+
527
+ - **Drift and real bugs are hard to tell apart (improving).** Rules-5 reads Playwright's strict-mode errors: when a locator like `name: 'Edit'` starts matching several elements, the error already lists them, and the one named with the whole word is the element the test means. On the fresh set (Sep 1–3) drift is **16/20 = 80%** (**16/23 = 70%** on the labels before a labelling flaw was corrected, see [eval/README.md](eval/README.md)), real bugs called drift **1 of 29**, and **15 drift cases would now be auto-fixed, each suggestion identical to the developers' own fix**. On an unseen week (Aug 20–26, 473 labels) drift is **3/3** and the agent would still have made **0 automatic changes**. The remaining misses have no usable page data: the error names no locator at all.
528
+ - **Playwright does not always write a page snapshot.** For some failures (timeouts inside frames) `error-context.md` holds only the error and the test source, so the similarity rule is blind. Rebuilding the page from the trace DOM does not help: on real data, real bugs score as similar as drift (0.80–0.96), so it gives the AI noise rather than signal (it lowered held-out accuracy from 86.1% to 81.3% when tried).
529
+ - **Expected server errors (partly fixed).** Tests that deliberately provoke server errors used to be read as ENV. The model is now told when a test's name says it exercises error handling (prompt llm-4).
530
+ - **Views can't tell pull-request branches from the main branch yet.** Records don't store the branch, so regressions inside unmerged PRs count as product bugs in the architecture view and the digest.
531
+ - **Some recurring flakes are misread.** Flaky tests that also fail on other branches are misclassified (0/22 on the held-out set), and TEST_DATA and LOCATOR_DRIFT are not yet measured on real data.
532
+
533
+ Environment variables (you can put them in `.env`, which is gitignored):
534
+
535
+ - `OPENAI_API_KEY`: turns the LLM layer on. Without it, only the rules run.
536
+ - `TRIAGE_LLM=off`: turns the LLM layer off even when a key is set.
537
+ - `TRIAGE_LLM_MODEL` (default `gpt-5.4-mini`) and `TRIAGE_LLM_REASONING` (default `low`): choose the model and its reasoning effort.
538
+ - `TRIAGE_LLM_CACHE=off`: skips the response cache in `data/llm-cache.jsonl`. With the cache on, an unchanged request is answered from the cache for free.
539
+ - `TRIAGE_LLM_MAX_CALLS`: at most this many model calls per run. Further failures keep the rules' answer and say so, instead of running up an unbounded bill on a huge failed run.
540
+ - `TRIAGE_LLM_PRICE_IN` / `TRIAGE_LLM_PRICE_OUT`: your own price per million input / output tokens, overriding the published prices built in for OpenAI's models. For a model without a built-in price, set them to see a cost; otherwise the run says the price is unknown.
541
+ - `CI_RUN_ID`: used as the run id. If it is not set, the run id is based on a timestamp.
542
+ - `GIT_SHA` or `GITHUB_SHA`: stored as the record's `gitSha`. If neither is set, `gitSha` is left empty.
543
+
544
+ **Data leaving the machine:** with the LLM layer on, the summary of each UNKNOWN failure is sent to OpenAI. That summary includes the error text, the page snapshot, failed request URLs (without query strings) and console errors. Nothing is committed to git.