@hamzaahmadaslam/wp-debuglog-triage 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.md +205 -2
- package/SECURITY.md +20 -0
- package/package.json +43 -4
- package/src/clean.mjs +133 -0
- package/src/cli.mjs +17 -0
- package/src/group.mjs +98 -0
- package/src/jev.mjs +92 -0
- package/src/main.mjs +144 -0
- package/src/parse.mjs +214 -0
- package/src/questions.mjs +114 -0
- package/src/report.mjs +206 -0
- package/src/source.mjs +166 -0
- package/src/triage.mjs +66 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hamza Ahmad Aslam
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,206 @@
|
|
|
1
|
-
#
|
|
1
|
+
# wp-debuglog-triage
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A command-line tool for WordPress developers and maintainers that turns a `debug.log` into a short list of
|
|
4
|
+
problems, each tied to the plugin, theme or core file behind it and ranked by how soon it needs attention.
|
|
5
|
+
|
|
6
|
+
On a busy site the log grows by thousands of lines a day. Most of them are the same few deprecation notices, and
|
|
7
|
+
the one fatal error that matters sits somewhere in the middle. Grouping repeats and reading file paths is exact
|
|
8
|
+
work, so the tool does it in code. Deciding whether a group is harmless noise, a deprecation, a warning, a fatal
|
|
9
|
+
error, a security sign or a performance problem, and how urgent it is, takes judgment. Jev answers those two
|
|
10
|
+
questions with probabilities, and a group it is unsure about goes to a review list instead of being ranked as if
|
|
11
|
+
the answer were certain.
|
|
12
|
+
|
|
13
|
+
## How it uses Jev
|
|
14
|
+
|
|
15
|
+
The log is read line by line, so a large file never has to fit in memory. Every entry is parsed in code: the timestamp, the PHP
|
|
16
|
+
level (Notice, Warning, Deprecated, Fatal error, Parse error), WordPress database errors, lines a plugin wrote
|
|
17
|
+
itself, and stack traces. Entries that differ only in line numbers, numbers, hashes or long quoted values form
|
|
18
|
+
one group, and each group is attributed to WordPress core, a plugin, a must-use plugin, a theme, a drop-in,
|
|
19
|
+
`wp-config.php` or a PHP file in the uploads folder.
|
|
20
|
+
|
|
21
|
+
Then Jev gets two questions per group:
|
|
22
|
+
|
|
23
|
+
- a choice of kind: `noise`, `deprecation`, `warning`, `fatal`, `security-relevant` or `performance`, each with
|
|
24
|
+
a one-line description (running out of memory or time counts as performance, not fatal);
|
|
25
|
+
- a score of urgency on four levels: can wait, routine maintenance, fix this week, fix now.
|
|
26
|
+
|
|
27
|
+
The groups go into as few requests as TypeSafe's limits allow (32k tokens for the state plus the longest question,
|
|
28
|
+
64k for the whole request). Each group sits under its own key in the state, such as `groups.g07`, and its two
|
|
29
|
+
questions point at that key. The 18 groups of the example fit in one request.
|
|
30
|
+
|
|
31
|
+
A group whose kind or urgency confidence is below the threshold (0.8 unless you set `--threshold`) goes to the
|
|
32
|
+
review section. Every group is printed with its probabilities. Jev is TypeSafe AI's System One model: it answers
|
|
33
|
+
typed questions with probabilities and writes no text, so every word in the report comes from your log or from
|
|
34
|
+
fixed text in this tool.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```sh
|
|
39
|
+
npm install -g @hamzaahmadaslam/wp-debuglog-triage
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
It needs Node 20 or later and installs no other packages.
|
|
43
|
+
|
|
44
|
+
## Usage
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
export TYPESAFE_API_KEY="..."
|
|
48
|
+
wp-debuglog-triage wp-content/debug.log
|
|
49
|
+
wp-debuglog-triage wp-content/debug.log --top 10
|
|
50
|
+
wp-debuglog-triage wp-content/debug.log --json > triage.json
|
|
51
|
+
wp-debuglog-triage wp-content/debug.log --dry-run
|
|
52
|
+
ssh example-host cat /srv/site/wp-content/debug.log | wp-debuglog-triage -
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
| Option | What it does |
|
|
56
|
+
| ----------------- | ---------------------------------------------------------------------------------- |
|
|
57
|
+
| `--json` | Print JSON instead of the text report |
|
|
58
|
+
| `--threshold <p>` | Confidence from 0 to 1 below which a group goes to review (default 0.8) |
|
|
59
|
+
| `--top <n>` | Show only the n most urgent groups |
|
|
60
|
+
| `--batch <n>` | Send at most n groups per request (default: as many as fit the token budget) |
|
|
61
|
+
| `--dry-run` | Group the log, then print the questions and a token estimate; nothing is sent |
|
|
62
|
+
| `-h`, `--help` | Show the help |
|
|
63
|
+
| `-v`, `--version` | Show the version |
|
|
64
|
+
|
|
65
|
+
`TYPESAFE_API_KEY` holds your key and is not needed for `--dry-run`. `TYPESAFE_MODEL` picks the model
|
|
66
|
+
(`jev-latest` by default). Use `-` as the file to read standard input. The exit code is 0 when the report is
|
|
67
|
+
printed, 1 for a TypeSafe error (refused key, invalid request, rate limit, overload, timeout) and 2 for a missing
|
|
68
|
+
key, bad options or a file that cannot be read.
|
|
69
|
+
|
|
70
|
+
### How groups are formed
|
|
71
|
+
|
|
72
|
+
Two entries share a group when their level and message match after line numbers, numbers, hex values, hashes and
|
|
73
|
+
quoted values that are not identifiers are set aside. So `Undefined array key "example_ref" ... on line 212` and
|
|
74
|
+
the same warning on line 215 after a theme update are one group, and so are memory errors with different byte
|
|
75
|
+
counts. Short quoted identifiers stay: `Undefined array key "a"` and `Undefined array key "b"` are two groups.
|
|
76
|
+
Database errors are compared without the values in their query and without WordPress's list of callers.
|
|
77
|
+
|
|
78
|
+
### How a group is attributed
|
|
79
|
+
|
|
80
|
+
- `wp-includes/`, `wp-admin/` and the files in the WordPress folder are core; `wp-content/plugins/<slug>/` is a
|
|
81
|
+
plugin, `mu-plugins/` a must-use plugin, `themes/<slug>/` a theme, a PHP file directly in `wp-content` (such as
|
|
82
|
+
`object-cache.php`) a drop-in, and anything under `wp-content/uploads/` is flagged, because PHP should never run
|
|
83
|
+
from there. Bedrock's `app/plugins` layout and Windows paths work too.
|
|
84
|
+
- "Headers already sent" points at the file where the output started.
|
|
85
|
+
- A fatal error raised inside core points at the first plugin or theme frame in its stack trace.
|
|
86
|
+
- Notices that WordPress raises through `_doing_it_wrong()` and its deprecation helpers stay with core, because
|
|
87
|
+
the calling code is not in the log. The report says so and names the text domain when the message includes it.
|
|
88
|
+
- A database error points at the plugin or theme in WordPress's list of callers. Failing that, and for lines a
|
|
89
|
+
plugin writes itself, a function name or line prefix that matches a plugin or theme seen elsewhere in the same
|
|
90
|
+
log is used, and the report marks it as a guess.
|
|
91
|
+
|
|
92
|
+
## Example
|
|
93
|
+
|
|
94
|
+
The example log is synthetic: [`examples/debug.log`](examples/debug.log) has 422 entries invented for this README,
|
|
95
|
+
and every path, plugin, theme and value in it is made up. The output below came from `npm run example`, which runs
|
|
96
|
+
the tool with hand-written fixture answers ([`examples/answers.json`](examples/answers.json)) in place of Jev, so
|
|
97
|
+
the probabilities are illustrations and the model shows as `fixture`. A live run gives its own numbers.
|
|
98
|
+
|
|
99
|
+
```sh
|
|
100
|
+
wp-debuglog-triage examples/debug.log
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
```text
|
|
104
|
+
wp-debuglog-triage 1.0.0
|
|
105
|
+
File: examples/debug.log
|
|
106
|
+
Entries: 422 in 18 groups (479 lines, 1 outside any entry)
|
|
107
|
+
Time span: 2026-09-18 03:09:04 to 2026-09-25 23:38:01 UTC
|
|
108
|
+
Jev: model fixture, 1 request, 12,954 input tokens
|
|
109
|
+
Threshold 0.80: 13 triaged, 5 for review
|
|
110
|
+
|
|
111
|
+
Triaged, most urgent first
|
|
112
|
+
|
|
113
|
+
g18 now fatal plugin example-gallery 3 times
|
|
114
|
+
PHP Fatal error: Uncaught Error: Call to undefined function example_gallery_legacy_thumb() in wp-content/plugins/example-gallery/includes/render.php:88
|
|
115
|
+
Seen 2026-09-24 10:02:11 to 2026-09-25 22:40:05 UTC; source line 88
|
|
116
|
+
Urgency 2.97 of 3: now 0.97, this week 0.03. Kind: fatal 0.99, warning 0.01.
|
|
117
|
+
|
|
118
|
+
g17 now security-relevant PHP file in the uploads folder (wp-content/uploads/2026/09/cache-3f9a.php) 6 times
|
|
119
|
+
PHP Warning: Undefined variable $o in wp-content/uploads/2026/09/cache-3f9a.php(2) : eval()'d code on line 1
|
|
120
|
+
Seen 2026-09-24 05:42:53 to 2026-09-25 20:09:45 UTC; source line 2
|
|
121
|
+
Urgency 2.95 of 3: now 0.95, this week 0.05. Kind: security-relevant 0.94, warning 0.06.
|
|
122
|
+
|
|
123
|
+
g12 now fatal plugin example-importer (from the stack trace) 2 times
|
|
124
|
+
PHP Fatal error: Uncaught Error: Object of class WP_Error could not be converted to string in wp-includes/formatting.php:1098
|
|
125
|
+
Seen 2026-09-21 01:32:40 to 2026-09-23 01:33:09 UTC; source line 61
|
|
126
|
+
Urgency 2.88 of 3: now 0.88, this week 0.12. Kind: fatal 0.98, warning 0.02.
|
|
127
|
+
|
|
128
|
+
[...]
|
|
129
|
+
|
|
130
|
+
g04 routine deprecation plugin example-forms 100 times
|
|
131
|
+
PHP Deprecated: Creation of dynamic property Example_Forms_Field::$label is deprecated in wp-content/plugins/example-forms/includes/class-field.php on line 41
|
|
132
|
+
Seen 2026-09-18 05:29:06 to 2026-09-25 23:33:17 UTC; source line 41
|
|
133
|
+
Urgency 0.96 of 3: routine 0.92, can wait 0.06, this week 0.02. Kind: deprecation 0.97, warning 0.02, noise 0.01.
|
|
134
|
+
|
|
135
|
+
[...]
|
|
136
|
+
|
|
137
|
+
For review, most urgent first (confidence below 0.80 or no answer)
|
|
138
|
+
|
|
139
|
+
g15 now fatal theme example-theme once
|
|
140
|
+
PHP Parse error: syntax error, unexpected token "}" in wp-content/themes/example-theme/inc/template-tags.php on line 58
|
|
141
|
+
Seen 2026-09-22 14:03:10 UTC; source line 58
|
|
142
|
+
Urgency 2.62 of 3: now 0.62, this week 0.38. Kind: fatal 0.99, warning 0.01.
|
|
143
|
+
Review: urgency confidence 0.49 (threshold 0.80).
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The full outputs are in [`examples/report.txt`](examples/report.txt), [`examples/report.json`](examples/report.json)
|
|
147
|
+
and [`examples/dry-run.txt`](examples/dry-run.txt).
|
|
148
|
+
|
|
149
|
+
## What leaves your machine
|
|
150
|
+
|
|
151
|
+
Nothing, unless you run the tool with a key and without `--dry-run`. Then it sends POST requests to
|
|
152
|
+
`https://api.typesafe.ai/v1/systemone`, and nowhere else. Each request carries:
|
|
153
|
+
|
|
154
|
+
- your key, in the `Authorization` header;
|
|
155
|
+
- the model name, one fixed sentence saying the state holds grouped entries from a WordPress debug.log, and the
|
|
156
|
+
two questions per group shown by `--dry-run`;
|
|
157
|
+
- for each group: its level (such as `PHP Warning`), the group's first message (cleaned, at most 500
|
|
158
|
+
characters), up to six stack trace frames (cleaned, at most 200 characters each), a phrase naming the source
|
|
159
|
+
(such as `plugin example-gallery`), how often the group occurred in words (`once`, `a few times`,
|
|
160
|
+
`dozens of times` and so on), and whether it was seen in the last 24 hours of the log.
|
|
161
|
+
|
|
162
|
+
Cleaning happens on your machine before anything is shown or sent. Server paths are cut back to the WordPress
|
|
163
|
+
folder (`wp-content/...`, `wp-includes/...`) and other paths to the file name. Email addresses become `<email>`,
|
|
164
|
+
public IP addresses become `<ip>` (loopback and private addresses stay), URL query strings become `?<query>` and
|
|
165
|
+
user names or passwords in URLs are dropped. Values in SQL queries and string arguments in stack frames become
|
|
166
|
+
`'<str>'`. WordPress's `<strong>`, `<code>` and link markup is removed, and so are control characters and
|
|
167
|
+
text-direction marks, which could otherwise change your terminal when the report prints.
|
|
168
|
+
|
|
169
|
+
Timestamps, exact counts, the rest of the log and anything else on your machine are not sent. The tool makes no
|
|
170
|
+
other network requests, such as telemetry or update checks. `--dry-run --json` prints the exact body of every
|
|
171
|
+
request it would send.
|
|
172
|
+
|
|
173
|
+
## Limits
|
|
174
|
+
|
|
175
|
+
- It sees the log and nothing else. It cannot tell whether a plugin is still active, whether an error has been
|
|
176
|
+
fixed since, or which PHP version ran.
|
|
177
|
+
- Attribution comes from file paths. Core notices about a caller, database errors without a plugin in the caller
|
|
178
|
+
list, and custom lines without a known prefix stay with core or "unknown".
|
|
179
|
+
- Grouping can merge two different bugs that print the same message from the same file.
|
|
180
|
+
- Jev judges each group from its text and does not read your code. Log lines can hold text an attacker wrote (a
|
|
181
|
+
URL, a form value); Jev reads the state as data, but such text can still move an answer. Check every
|
|
182
|
+
security-relevant group yourself.
|
|
183
|
+
- PHP writes the time zone name with each entry and WordPress logs in UTC. An unknown zone name is read as UTC and
|
|
184
|
+
the report says how many entries that affected.
|
|
185
|
+
- Up to 20,000 distinct messages are grouped. After that, entries with new messages are counted but not grouped.
|
|
186
|
+
- The token counts from `--dry-run` are estimates (one token per three characters). After a run the report shows
|
|
187
|
+
the count TypeSafe returned.
|
|
188
|
+
- TypeSafe's notes on jev-1.13 say accuracy falls as the state fills with detail unrelated to a question, and a
|
|
189
|
+
request here can hold up to about 80 groups. If answers look off, send fewer groups per request with `--batch`.
|
|
190
|
+
- English messages work best.
|
|
191
|
+
|
|
192
|
+
## Token use
|
|
193
|
+
|
|
194
|
+
The tool estimates about 720 input tokens per group, most of it the text of the two questions. The example's 18
|
|
195
|
+
groups are one request of about 12,950 tokens. A log with 500 distinct groups would be about 360,000 tokens in 7
|
|
196
|
+
requests. Run `--dry-run` first to see the estimate for your own log.
|
|
197
|
+
|
|
198
|
+
## Development
|
|
199
|
+
|
|
200
|
+
`npm test` runs 26 tests with Node's test runner. They need no key: a fixture stands in for Jev, and any attempt to
|
|
201
|
+
reach the network fails the test. `npm run example` rebuilds the files in `examples/`, and a test checks that they
|
|
202
|
+
match the code.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
MIT. Made by [Hamza Ahmad Aslam](https://hamzaahmadaslam.com), WordPress and web performance engineer.
|
package/SECURITY.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
## Reporting a vulnerability
|
|
4
|
+
|
|
5
|
+
Please report security problems privately through GitHub: open the repository's **Security** tab and choose
|
|
6
|
+
**Report a vulnerability**. Do not open a public issue for a security problem.
|
|
7
|
+
|
|
8
|
+
You will get a reply within seven days. Fixes are released as a new version with a note in the changelog.
|
|
9
|
+
|
|
10
|
+
## What this project does with your data
|
|
11
|
+
|
|
12
|
+
- It reads your TypeSafe API key from the `TYPESAFE_API_KEY` environment variable and sends it only to
|
|
13
|
+
`https://api.typesafe.ai` in the `Authorization` header. It never logs, prints or stores the key.
|
|
14
|
+
- It sends only the text described in the README's "What leaves your machine" section, and only when you run it
|
|
15
|
+
with a key.
|
|
16
|
+
- It makes no other network requests: no telemetry, no update checks.
|
|
17
|
+
|
|
18
|
+
## Supported versions
|
|
19
|
+
|
|
20
|
+
Only the latest release receives fixes.
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hamzaahmadaslam/wp-debuglog-triage",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Group a WordPress debug.log by message, attribute each group to core, a plugin or a theme, and rank the groups by kind and urgency with Jev.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"wp-debuglog-triage": "src/cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"src",
|
|
11
|
+
"README.md",
|
|
12
|
+
"LICENSE",
|
|
13
|
+
"SECURITY.md"
|
|
14
|
+
],
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"test": "node --test test/*.test.mjs",
|
|
20
|
+
"example": "node examples/build.mjs"
|
|
21
|
+
},
|
|
22
|
+
"keywords": [
|
|
23
|
+
"wordpress",
|
|
24
|
+
"debug.log",
|
|
25
|
+
"php",
|
|
26
|
+
"error-log",
|
|
27
|
+
"triage",
|
|
28
|
+
"cli",
|
|
29
|
+
"typesafe",
|
|
30
|
+
"jev"
|
|
31
|
+
],
|
|
32
|
+
"author": "Hamza Ahmad Aslam (https://hamzaahmadaslam.com)",
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/hamzaahmadaslam/wp-debuglog-triage.git"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://hamzaahmadaslam.com/open-source/wp-debuglog-triage",
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/hamzaahmadaslam/wp-debuglog-triage/issues"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/src/clean.mjs
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
// Cleans log text before it is grouped, shown or sent, and turns a cleaned message into the template that
|
|
2
|
+
// identifies its group.
|
|
3
|
+
//
|
|
4
|
+
// cleanMessage(): server paths become relative to the WordPress folder ("wp-content/plugins/...") and other
|
|
5
|
+
// paths keep only the file name; email addresses, public IP addresses, URL query strings and credentials, and
|
|
6
|
+
// values inside SQL queries are replaced with placeholders; WordPress's <strong>/<code>/<a> formatting is removed.
|
|
7
|
+
// templateOf(): line numbers, numbers, hashes and long quoted values become placeholders, so repeats of one
|
|
8
|
+
// message with different data share a template.
|
|
9
|
+
import { isIPv4, isIPv6 } from "node:net";
|
|
10
|
+
|
|
11
|
+
// Where a WordPress path starts to mean something. Bedrock keeps plugins and themes under app/.
|
|
12
|
+
const MARKER = String.raw`(?:wp-content|wp-includes|wp-admin|app\/(?:plugins|mu-plugins|themes|uploads))\/`;
|
|
13
|
+
const ROOT_FILE = String.raw`(?:wp-[a-z-]+|index|xmlrpc)\.php\b`;
|
|
14
|
+
// A path starts at the beginning of the text or after a space, bracket, quote, "=" or ",".
|
|
15
|
+
const START = String.raw`(?<=^|[\s(\[{'"=,])`;
|
|
16
|
+
// Paths that contain spaces (such as "Local Sites") are only recognised after " in ", " at ", an opening
|
|
17
|
+
// bracket or a quote; they cannot run past a bracket, quote or colon.
|
|
18
|
+
const OPENER = String.raw`(?<=\b(?:in|at) |[('"])`;
|
|
19
|
+
const DRIVE = String.raw`(?:[A-Za-z]:)?`;
|
|
20
|
+
const SPACED = String.raw`[^'"()<>:\n]*?`;
|
|
21
|
+
const PLAIN = String.raw`[^\s'"()<>:]`;
|
|
22
|
+
const BASENAME = String.raw`([^\s'"()<>:/]+\.php)\b`;
|
|
23
|
+
|
|
24
|
+
const PATH_RULES = [
|
|
25
|
+
[new RegExp(`${OPENER}${DRIVE}\\/${SPACED}\\/(?=${MARKER})`, "g"), ""],
|
|
26
|
+
[new RegExp(`${OPENER}${DRIVE}\\/${SPACED}\\/(?=${ROOT_FILE})`, "g"), ""],
|
|
27
|
+
[new RegExp(`${START}${DRIVE}\\/(?:${PLAIN}*?\\/)?(?=${MARKER})`, "g"), ""],
|
|
28
|
+
[new RegExp(`${START}${DRIVE}\\/(?:${PLAIN}*\\/)?(?=${ROOT_FILE})`, "g"), ""],
|
|
29
|
+
[new RegExp(`${OPENER}${DRIVE}\\/${SPACED}\\/${BASENAME}`, "g"), ".../$1"],
|
|
30
|
+
[new RegExp(`${START}${DRIVE}\\/(?:${PLAIN}*\\/)?${BASENAME}`, "g"), ".../$1"],
|
|
31
|
+
];
|
|
32
|
+
const WINDOWS_PATH = /[A-Za-z]:\\[^'"()<>\n]*?\.php\b|\\(?:wp-content|wp-includes|wp-admin)\\[^\s'"()<>]*/g;
|
|
33
|
+
const URL = /\b(https?|ftps?):\/\/(?:[^\s'"<>()/?#@]+@)?([^\s'"<>()/?#]+)([^\s'"<>()?#]*)(\?[^\s'"<>()#]*)?(#[^\s'"<>()]*)?/gi;
|
|
34
|
+
const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
|
|
35
|
+
const IPV4 = /(?<![\d.])\d{1,3}(?:\.\d{1,3}){3}(?![\d.])/g;
|
|
36
|
+
const IPV6 = /(?<![\w:])(?:[0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}(?![\w:])/g;
|
|
37
|
+
const WP_TAGS = /<\/?(?:strong|code|em|b|i|kbd)>|<br\s*\/?>|<a\s[^>]*>|<\/a>/gi;
|
|
38
|
+
const SQL_STRING = /'(?:[^'\\]|\\.|'')*'|"(?:[^"\\]|\\.)*"/g;
|
|
39
|
+
// Log lines can carry text from visitors. Control characters (terminal escape sequences) and text-direction
|
|
40
|
+
// overrides could rewrite the terminal or disguise text when printed, so they are removed first.
|
|
41
|
+
const char = (code) => String.fromCharCode(code);
|
|
42
|
+
const INVISIBLE = new RegExp(`[\\x00-\\x08\\x0b-\\x1f\\x7f-\\x9f${char(0x202a)}-${char(0x202e)}${char(0x2066)}-${char(0x2069)}]`, "g");
|
|
43
|
+
|
|
44
|
+
/** True for addresses that point at a person or a public server (not loopback, private or link-local). */
|
|
45
|
+
export function isPublicIp(address) {
|
|
46
|
+
if (isIPv4(address)) {
|
|
47
|
+
const [a, b] = address.split(".").map(Number);
|
|
48
|
+
if (a === 10 || a === 127 || a === 0 || a >= 224) return false;
|
|
49
|
+
if (a === 169 && b === 254) return false;
|
|
50
|
+
if (a === 172 && b >= 16 && b <= 31) return false;
|
|
51
|
+
if (a === 192 && b === 168) return false;
|
|
52
|
+
if (a === 100 && b >= 64 && b <= 127) return false;
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
if (isIPv6(address)) {
|
|
56
|
+
const lower = address.toLowerCase();
|
|
57
|
+
if (lower === "::1" || lower === "::") return false;
|
|
58
|
+
if (/^fe[89ab]/.test(lower) || /^f[cd]/.test(lower)) return false;
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// WordPress's caller lists ("made by ...") shorten includes by removing the content folder:
|
|
65
|
+
// include('/themes/example/page.php'). Putting "wp-content" back lets them be read like any other path.
|
|
66
|
+
const SHORT_INCLUDE = /\b((?:include|require)(?:_once)?\(')\/(plugins|mu-plugins|themes)\//g;
|
|
67
|
+
|
|
68
|
+
/** Relative WordPress paths and placeholders in place of personal or secret-looking values. */
|
|
69
|
+
export function cleanText(text) {
|
|
70
|
+
let out = text
|
|
71
|
+
.replace(INVISIBLE, "")
|
|
72
|
+
.replace(WINDOWS_PATH, (path) => path.replace(/\\/g, "/"))
|
|
73
|
+
.replace(SHORT_INCLUDE, "$1wp-content/$2/");
|
|
74
|
+
for (const [pattern, replacement] of PATH_RULES) out = out.replace(pattern, replacement);
|
|
75
|
+
out = out
|
|
76
|
+
.replace(WP_TAGS, "")
|
|
77
|
+
.replace(URL, (_, scheme, host, path, query) => `${scheme}://${host}${path}${query ? "?<query>" : ""}`)
|
|
78
|
+
.replace(EMAIL, "<email>")
|
|
79
|
+
.replace(IPV4, (ip) => (isPublicIp(ip) ? "<ip>" : ip))
|
|
80
|
+
.replace(IPV6, (ip) => (isPublicIp(ip) ? "<ip>" : ip));
|
|
81
|
+
return out.replace(/\s+/g, " ").trim();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** cleanText(), plus the values in a database error's query and in "Duplicate entry '...'". */
|
|
85
|
+
export function cleanMessage(message, level) {
|
|
86
|
+
let out = cleanText(message);
|
|
87
|
+
if (level === "database") {
|
|
88
|
+
out = out.replace(/Duplicate entry '(?:[^'\\]|\\.)*'/g, "Duplicate entry '<str>'");
|
|
89
|
+
const at = out.indexOf(" for query ");
|
|
90
|
+
if (at !== -1) {
|
|
91
|
+
const madeBy = out.indexOf(" made by ", at);
|
|
92
|
+
const end = madeBy === -1 ? out.length : madeBy;
|
|
93
|
+
const query = out.slice(at, end).replace(SQL_STRING, (value) => `${value[0]}<str>${value[0]}`);
|
|
94
|
+
out = out.slice(0, at) + query + out.slice(end);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A stack frame's file and call, cleaned; string arguments are replaced because they can hold any data. */
|
|
101
|
+
export function cleanFrame(frame) {
|
|
102
|
+
const hideStrings = (text) => text.replace(SQL_STRING, (value) => `${value[0]}<str>${value[0]}`);
|
|
103
|
+
const file = frame.file ? cleanText(frame.file) : null;
|
|
104
|
+
const call = frame.call ? cleanText(hideStrings(frame.call)) : null;
|
|
105
|
+
const text = file ? `${file}(${frame.line}): ${call ?? ""}` : cleanText(hideStrings(frame.text));
|
|
106
|
+
return { file, line: frame.line, call, text };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// An opening quote never follows a letter, digit or ")", which keeps "doesn't" and "eval()'d" out of it.
|
|
110
|
+
const QUOTED = /(?<![\w)])(["'])((?:(?!\1)[^\\]|\\.)*)\1/g;
|
|
111
|
+
const IDENTIFIER = /^[\w$\\.:\-/[\]>]{1,60}$/;
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* The part of a cleaned message that stays the same between repeats. Line numbers, numbers, hex values,
|
|
115
|
+
* hashes, UUIDs and quoted values that are not identifiers become placeholders; for database errors the
|
|
116
|
+
* caller list ("made by ...") is dropped because one failing query can be reached from many places.
|
|
117
|
+
*/
|
|
118
|
+
export function templateOf(message, level) {
|
|
119
|
+
let out = message;
|
|
120
|
+
if (level === "database") out = out.replace(/ made by .*$/, "");
|
|
121
|
+
out = out
|
|
122
|
+
.replace(/ on line \d+/g, " on line <n>")
|
|
123
|
+
.replace(/(\.php):\d+\b/g, "$1:<n>")
|
|
124
|
+
.replace(/(\.php)\(\d+\)/g, "$1(<n>)")
|
|
125
|
+
.replace(/\b0x[0-9a-f]+\b/gi, "<hex>")
|
|
126
|
+
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<uuid>")
|
|
127
|
+
.replace(/\b(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{16,}\b/gi, "<hash>")
|
|
128
|
+
.replace(QUOTED, (quoted, mark, body) => (IDENTIFIER.test(body) || body === "<str>" ? quoted : `${mark}<str>${mark}`))
|
|
129
|
+
.replace(/(?<![\w$\\<])\d+(?:\.\d+)*(?![\w>])/g, "<n>")
|
|
130
|
+
// A list of values ("IN (1, 2, 3)", "VALUES ('a', 'b')") becomes its first placeholder, whatever its length.
|
|
131
|
+
.replace(/(<n>|'<str>'|"<str>")(?:\s*,\s*(?:<n>|'<str>'|"<str>"))+/g, "$1");
|
|
132
|
+
return out.replace(/\s+/g, " ").trim();
|
|
133
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Entry point for the wp-debuglog-triage command. Errors are printed as one line, never as a stack trace.
|
|
3
|
+
import { run } from "./main.mjs";
|
|
4
|
+
|
|
5
|
+
process.stdout.on("error", (error) => {
|
|
6
|
+
if (error.code === "EPIPE") process.exit(0); // the reader (for example `head`) closed the pipe
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
run(process.argv.slice(2)).then(
|
|
10
|
+
(code) => {
|
|
11
|
+
process.exitCode = code;
|
|
12
|
+
},
|
|
13
|
+
(error) => {
|
|
14
|
+
process.stderr.write(`wp-debuglog-triage: ${error?.message ?? error}\n`);
|
|
15
|
+
process.exitCode = 1;
|
|
16
|
+
},
|
|
17
|
+
);
|
package/src/group.mjs
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Groups a log's entries: one group per repeated message, with how often and when it was seen and which part of
|
|
2
|
+
// the site it comes from. Entries arrive one at a time, so memory grows with the number of groups, not the log.
|
|
3
|
+
import { cleanFrame, cleanMessage, templateOf } from "./clean.mjs";
|
|
4
|
+
import { EntryParser, readEntries } from "./parse.mjs";
|
|
5
|
+
import { guessOwners, primaryPath, sourceOf } from "./source.mjs";
|
|
6
|
+
|
|
7
|
+
export const MAX_GROUPS = 20_000; // distinct messages kept; later new ones are only counted
|
|
8
|
+
const MAX_STACK = 8; // stack frames kept per group
|
|
9
|
+
const MAX_MESSAGE = 1000; // characters kept of a group's message
|
|
10
|
+
const MAX_SOURCE_LINES = 12; // source line numbers listed per group
|
|
11
|
+
const CACHE_SIZE = 5000; // raw messages whose cleaned form is remembered
|
|
12
|
+
|
|
13
|
+
export function createGrouper() {
|
|
14
|
+
const groups = new Map();
|
|
15
|
+
const cache = new Map();
|
|
16
|
+
const stats = { entries: 0, first: null, last: null, zoneAssumed: 0, overflow: 0, lines: 0, skipped: 0 };
|
|
17
|
+
|
|
18
|
+
function cleaned(entry) {
|
|
19
|
+
const cacheKey = `${entry.level}\n${entry.message}`;
|
|
20
|
+
let hit = cache.get(cacheKey);
|
|
21
|
+
if (!hit) {
|
|
22
|
+
const message = cleanMessage(entry.message, entry.level).slice(0, MAX_MESSAGE);
|
|
23
|
+
hit = { message, template: templateOf(message, entry.level), at: primaryPath(message) };
|
|
24
|
+
if (cache.size >= CACHE_SIZE) cache.clear();
|
|
25
|
+
cache.set(cacheKey, hit);
|
|
26
|
+
}
|
|
27
|
+
return hit;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function add(entry) {
|
|
31
|
+
stats.entries++;
|
|
32
|
+
if (entry.zoneAssumed) stats.zoneAssumed++;
|
|
33
|
+
if (entry.time !== null) {
|
|
34
|
+
if (stats.first === null || entry.time < stats.first) stats.first = entry.time;
|
|
35
|
+
if (stats.last === null || entry.time > stats.last) stats.last = entry.time;
|
|
36
|
+
}
|
|
37
|
+
const { message, template, at } = cleaned(entry);
|
|
38
|
+
const key = `${entry.level}\n${template}`;
|
|
39
|
+
let group = groups.get(key);
|
|
40
|
+
if (!group) {
|
|
41
|
+
if (groups.size >= MAX_GROUPS) {
|
|
42
|
+
stats.overflow++;
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const frames = entry.frames.some((f) => f.xdebug) ? [...entry.frames].reverse() : entry.frames;
|
|
46
|
+
const stack = frames.map(cleanFrame);
|
|
47
|
+
group = {
|
|
48
|
+
id: null,
|
|
49
|
+
key,
|
|
50
|
+
level: entry.level,
|
|
51
|
+
label: entry.label,
|
|
52
|
+
template,
|
|
53
|
+
message,
|
|
54
|
+
stack: stack.slice(0, MAX_STACK),
|
|
55
|
+
stackDepth: entry.frameCount,
|
|
56
|
+
source: sourceOf(message, stack, entry.level),
|
|
57
|
+
count: 0,
|
|
58
|
+
first: null,
|
|
59
|
+
last: null,
|
|
60
|
+
sourceLines: new Set(),
|
|
61
|
+
firstLogLine: entry.line,
|
|
62
|
+
};
|
|
63
|
+
groups.set(key, group);
|
|
64
|
+
}
|
|
65
|
+
group.count++;
|
|
66
|
+
if (entry.time !== null) {
|
|
67
|
+
if (group.first === null || entry.time < group.first) group.first = entry.time;
|
|
68
|
+
if (group.last === null || entry.time > group.last) group.last = entry.time;
|
|
69
|
+
}
|
|
70
|
+
if (at?.line != null && at.path === group.source.file && group.sourceLines.size < MAX_SOURCE_LINES) {
|
|
71
|
+
group.sourceLines.add(at.line);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function finish() {
|
|
76
|
+
const list = [...groups.values()];
|
|
77
|
+
const width = Math.max(2, String(list.length).length);
|
|
78
|
+
list.forEach((group, i) => {
|
|
79
|
+
group.id = `g${String(i + 1).padStart(width, "0")}`;
|
|
80
|
+
group.sourceLines = [...group.sourceLines].sort((a, b) => a - b);
|
|
81
|
+
if (!group.sourceLines.length && group.source.line != null) group.sourceLines = [group.source.line];
|
|
82
|
+
});
|
|
83
|
+
guessOwners(list);
|
|
84
|
+
return { groups: list, stats };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return { add, finish, stats };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Reads a log (a path, or a stream such as standard input) and returns its groups in order of first appearance. */
|
|
91
|
+
export async function groupLog(input) {
|
|
92
|
+
const parser = new EntryParser();
|
|
93
|
+
const grouper = createGrouper();
|
|
94
|
+
for await (const entry of readEntries(input, parser)) grouper.add(entry);
|
|
95
|
+
grouper.stats.lines = parser.lineNo;
|
|
96
|
+
grouper.stats.skipped = parser.skipped;
|
|
97
|
+
return grouper.finish();
|
|
98
|
+
}
|
package/src/jev.mjs
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// A small client for TypeSafe's System One API (Jev). Copy this file into a tool as src/jev.mjs.
|
|
2
|
+
// API: POST https://api.typesafe.ai/v1/systemone { model, state, questions } -> { model, answers, usage }
|
|
3
|
+
// The key comes from TYPESAFE_API_KEY and is only ever sent in the Authorization header.
|
|
4
|
+
|
|
5
|
+
export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
|
|
6
|
+
export const DEFAULT_MODEL = "jev-latest";
|
|
7
|
+
|
|
8
|
+
export class JevError extends Error {
|
|
9
|
+
constructor(message, status) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = "JevError";
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Asks Jev the `questions` about `state`. Retries 429 and 529 up to `retries` times with exponential backoff
|
|
20
|
+
* (honouring retry-after), times out each attempt after `timeoutMs`, and throws a JevError with a plain message
|
|
21
|
+
* otherwise. `fetchImpl` is injectable so tests never touch the network.
|
|
22
|
+
*/
|
|
23
|
+
export async function askJev(state, questions, options = {}) {
|
|
24
|
+
const {
|
|
25
|
+
apiKey = process.env.TYPESAFE_API_KEY,
|
|
26
|
+
model = process.env.TYPESAFE_MODEL || DEFAULT_MODEL,
|
|
27
|
+
timeoutMs = 10_000,
|
|
28
|
+
retries = 3,
|
|
29
|
+
fetchImpl = globalThis.fetch,
|
|
30
|
+
} = options;
|
|
31
|
+
if (!apiKey || !apiKey.trim()) {
|
|
32
|
+
throw new JevError("TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first.", 0);
|
|
33
|
+
}
|
|
34
|
+
const body = JSON.stringify({ model, state, questions });
|
|
35
|
+
for (let attempt = 0; ; attempt++) {
|
|
36
|
+
let res;
|
|
37
|
+
try {
|
|
38
|
+
res = await fetchImpl(JEV_ENDPOINT, {
|
|
39
|
+
method: "POST",
|
|
40
|
+
headers: { authorization: `Bearer ${apiKey.trim()}`, "content-type": "application/json" },
|
|
41
|
+
body,
|
|
42
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
43
|
+
});
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (attempt < retries) {
|
|
46
|
+
await sleep(500 * 2 ** attempt);
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
throw new JevError(`Could not reach TypeSafe: ${error?.name === "TimeoutError" ? "timed out" : error?.message}`, 0);
|
|
50
|
+
}
|
|
51
|
+
if (res.ok) {
|
|
52
|
+
const data = await res.json();
|
|
53
|
+
if (!data || typeof data.answers !== "object") throw new JevError("TypeSafe answered without answers.", res.status);
|
|
54
|
+
return data;
|
|
55
|
+
}
|
|
56
|
+
if ((res.status === 429 || res.status === 529) && attempt < retries) {
|
|
57
|
+
const after = Number(res.headers.get("retry-after"));
|
|
58
|
+
await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : 500 * 2 ** attempt);
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const detail = await res.text().catch(() => "");
|
|
62
|
+
const reason =
|
|
63
|
+
res.status === 401
|
|
64
|
+
? "the API key was refused"
|
|
65
|
+
: res.status === 422
|
|
66
|
+
? `the request was invalid: ${detail.slice(0, 300)}`
|
|
67
|
+
: res.status === 429
|
|
68
|
+
? "rate limited; try again later"
|
|
69
|
+
: res.status === 529
|
|
70
|
+
? "TypeSafe is overloaded; try again later"
|
|
71
|
+
: `HTTP ${res.status}`;
|
|
72
|
+
throw new JevError(`TypeSafe error: ${reason}`, res.status);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Question helpers (the shapes in reference/typesafe/api.md). */
|
|
77
|
+
export const noul = (instructions, criteria) => ({ type: "noul", instructions, ...(criteria ? { criteria } : {}) });
|
|
78
|
+
export const choice = (instructions, options) => ({ type: "choice", instructions, criteria: options });
|
|
79
|
+
export const score = (instructions, levels) => ({ type: "score", instructions, criteria: levels });
|
|
80
|
+
|
|
81
|
+
/** A fetch stand-in for tests: answers each request with `respond(body)` (a plain object) or an error status. */
|
|
82
|
+
export function fixtureFetch(respond) {
|
|
83
|
+
const calls = [];
|
|
84
|
+
const fetchImpl = async (url, init) => {
|
|
85
|
+
const body = JSON.parse(init.body);
|
|
86
|
+
calls.push({ url, body, headers: init.headers });
|
|
87
|
+
const out = await respond(body, calls.length);
|
|
88
|
+
if (typeof out === "number") return new Response(JSON.stringify({ error: "fixture" }), { status: out });
|
|
89
|
+
return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json" } });
|
|
90
|
+
};
|
|
91
|
+
return { fetchImpl, calls };
|
|
92
|
+
}
|