@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/src/main.mjs
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// The command: reads the options, groups the log, asks Jev (unless --dry-run), and prints the report.
|
|
2
|
+
// run() returns the exit code and takes its streams, environment and fetch from `io`, so tests can run it
|
|
3
|
+
// in-process without a key or a network.
|
|
4
|
+
import { parseArgs } from "node:util";
|
|
5
|
+
import { DEFAULT_MODEL, JevError } from "./jev.mjs";
|
|
6
|
+
import { groupLog } from "./group.mjs";
|
|
7
|
+
import { planRequests } from "./questions.mjs";
|
|
8
|
+
import { VERSION, dryRunJson, dryRunText, reportJson, reportText } from "./report.mjs";
|
|
9
|
+
import { rank, triage } from "./triage.mjs";
|
|
10
|
+
|
|
11
|
+
export const USAGE = `Usage: wp-debuglog-triage <debug.log | -> [options]
|
|
12
|
+
|
|
13
|
+
Groups the entries of a WordPress debug.log, finds the core file, plugin or theme behind each group, and asks
|
|
14
|
+
Jev (TypeSafe) what kind of problem each group is and how soon it needs attention.
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
--json print JSON instead of the text report
|
|
18
|
+
--threshold <p> confidence from 0 to 1 below which a group goes to review (default 0.8)
|
|
19
|
+
--top <n> show only the n most urgent groups
|
|
20
|
+
--batch <n> send at most n groups per request (default: as many as fit the token budget)
|
|
21
|
+
--dry-run group the log and print the questions and a token estimate; nothing is sent
|
|
22
|
+
-h, --help show this help
|
|
23
|
+
-v, --version show the version
|
|
24
|
+
|
|
25
|
+
Environment:
|
|
26
|
+
TYPESAFE_API_KEY your TypeSafe key (not needed for --dry-run)
|
|
27
|
+
TYPESAFE_MODEL the model to ask (default ${DEFAULT_MODEL})
|
|
28
|
+
|
|
29
|
+
Use - as the file to read standard input. Exit codes: 0 done, 1 TypeSafe error, 2 bad options or input.
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
const MISSING_KEY =
|
|
33
|
+
"TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first, or use --dry-run to see what would be sent.\n";
|
|
34
|
+
|
|
35
|
+
const OPTIONS = {
|
|
36
|
+
json: { type: "boolean", default: false },
|
|
37
|
+
"dry-run": { type: "boolean", default: false },
|
|
38
|
+
threshold: { type: "string" },
|
|
39
|
+
top: { type: "string" },
|
|
40
|
+
batch: { type: "string" },
|
|
41
|
+
help: { type: "boolean", short: "h", default: false },
|
|
42
|
+
version: { type: "boolean", short: "v", default: false },
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function wholeNumber(value, name) {
|
|
46
|
+
if (value === undefined) return null;
|
|
47
|
+
const n = Number(value);
|
|
48
|
+
if (!Number.isInteger(n) || n < 1) throw new Error(`--${name} must be a whole number above 0.`);
|
|
49
|
+
return n;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Parsed options, or an Error whose message says what is wrong. */
|
|
53
|
+
export function readOptions(argv) {
|
|
54
|
+
const { values, positionals } = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
55
|
+
if (values.help || values.version) return { help: values.help, version: values.version };
|
|
56
|
+
if (positionals.length !== 1) {
|
|
57
|
+
throw new Error(positionals.length ? "Give one log file." : "Give the path to a debug.log, or - to read standard input.");
|
|
58
|
+
}
|
|
59
|
+
const threshold = values.threshold === undefined ? 0.8 : Number(values.threshold);
|
|
60
|
+
if (values.threshold !== undefined && (values.threshold.trim() === "" || !(threshold >= 0 && threshold <= 1))) {
|
|
61
|
+
throw new Error("--threshold must be a number from 0 to 1.");
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
file: positionals[0],
|
|
65
|
+
json: values.json,
|
|
66
|
+
dryRun: values["dry-run"],
|
|
67
|
+
threshold,
|
|
68
|
+
top: wholeNumber(values.top, "top"),
|
|
69
|
+
batch: wholeNumber(values.batch, "batch"),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function readProblem(error) {
|
|
74
|
+
if (error?.code === "ENOENT") return "no such file";
|
|
75
|
+
if (error?.code === "EISDIR") return "it is a folder, not a file";
|
|
76
|
+
if (error?.code === "EACCES" || error?.code === "EPERM") return "permission denied";
|
|
77
|
+
return error?.message ?? String(error);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function run(argv, io = {}) {
|
|
81
|
+
const stdout = io.stdout ?? process.stdout;
|
|
82
|
+
const stderr = io.stderr ?? process.stderr;
|
|
83
|
+
const env = io.env ?? process.env;
|
|
84
|
+
|
|
85
|
+
let options;
|
|
86
|
+
try {
|
|
87
|
+
options = readOptions(argv);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
stderr.write(`${error.message}\n\n${USAGE}`);
|
|
90
|
+
return 2;
|
|
91
|
+
}
|
|
92
|
+
if (options.help) {
|
|
93
|
+
stdout.write(USAGE);
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
if (options.version) {
|
|
97
|
+
stdout.write(`${VERSION}\n`);
|
|
98
|
+
return 0;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim();
|
|
102
|
+
if (!options.dryRun && !apiKey) {
|
|
103
|
+
stderr.write(MISSING_KEY);
|
|
104
|
+
return 2;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
let log;
|
|
108
|
+
try {
|
|
109
|
+
log = await groupLog(options.file === "-" ? (io.stdin ?? process.stdin) : options.file);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
stderr.write(`Cannot read ${options.file}: ${readProblem(error)}\n`);
|
|
112
|
+
return 2;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const model = env.TYPESAFE_MODEL?.trim() || DEFAULT_MODEL;
|
|
116
|
+
const requests = planRequests(log.groups, log.stats.last, { maxGroups: options.batch ?? Infinity });
|
|
117
|
+
const meta = { file: options.file, model, threshold: options.threshold, top: options.top };
|
|
118
|
+
if (options.dryRun) {
|
|
119
|
+
stdout.write(options.json ? dryRunJson(log, requests, meta) : dryRunText(log, requests, meta));
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
let outcome = { model, usage: { input_tokens: 0, output_tokens: 0 }, requests: 0 };
|
|
124
|
+
if (requests.length) {
|
|
125
|
+
try {
|
|
126
|
+
outcome = await triage(log.groups, requests, {
|
|
127
|
+
threshold: options.threshold,
|
|
128
|
+
apiKey,
|
|
129
|
+
model,
|
|
130
|
+
fetchImpl: io.fetchImpl ?? globalThis.fetch,
|
|
131
|
+
...io.jev,
|
|
132
|
+
});
|
|
133
|
+
} catch (error) {
|
|
134
|
+
if (error instanceof JevError) {
|
|
135
|
+
stderr.write(`${error.message}\n`);
|
|
136
|
+
return 1;
|
|
137
|
+
}
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const ranked = rank(log.groups);
|
|
142
|
+
stdout.write(options.json ? reportJson(log, outcome, ranked, meta) : reportText(log, outcome, ranked, meta));
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
package/src/parse.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Reads a WordPress debug.log one line at a time and turns it into entries: one per logged message, with its
|
|
2
|
+
// timestamp, PHP level, message and any stack trace that followed it. Nothing is held in memory but the entry
|
|
3
|
+
// being read, so a log of any size streams through.
|
|
4
|
+
import { createReadStream } from "node:fs";
|
|
5
|
+
import { stat } from "node:fs/promises";
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
|
|
8
|
+
const BOM = String.fromCharCode(0xfeff); // a byte-order mark some editors put at the start of a file
|
|
9
|
+
const MONTHS = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 };
|
|
10
|
+
|
|
11
|
+
// PHP's error_log() starts every entry with "[26-Sep-2026 10:15:32 UTC] ". WordPress sets UTC; code that runs
|
|
12
|
+
// before WordPress loads (wp-config.php) can log in the server's own zone.
|
|
13
|
+
const STAMP = /^\[(\d{1,2})-([A-Z][a-z]{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2})(?: ([^\]]+))?\] ?(.*)$/;
|
|
14
|
+
|
|
15
|
+
// The labels PHP writes before a message ("PHP Warning: ..."), mapped to one level per kind of report.
|
|
16
|
+
const PHP_LEVELS = new Map([
|
|
17
|
+
["Fatal error", "fatal"],
|
|
18
|
+
["Recoverable fatal error", "fatal"],
|
|
19
|
+
["Catchable fatal error", "fatal"],
|
|
20
|
+
["Parse error", "parse"],
|
|
21
|
+
["Warning", "warning"],
|
|
22
|
+
["Notice", "notice"],
|
|
23
|
+
["Strict Standards", "notice"],
|
|
24
|
+
["Deprecated", "deprecated"],
|
|
25
|
+
["Unknown error", "unknown"],
|
|
26
|
+
]);
|
|
27
|
+
const PHP_MESSAGE = new RegExp(`^PHP (${[...PHP_LEVELS.keys()].join("|")}):\\s+(.*)$`);
|
|
28
|
+
const DB_MESSAGE = /^WordPress database error (.*)$/;
|
|
29
|
+
// Xdebug writes its own stack trace as separate timestamped lines ("PHP Stack trace:", "PHP 1. {main}() ...").
|
|
30
|
+
const XDEBUG_STACK = /^PHP Stack trace:\s*$/;
|
|
31
|
+
const XDEBUG_FRAME = /^PHP\s+(\d+)\.\s+(.*?)(?:\s+((?:[A-Za-z]:)?[\\/][^\s]*?):(\d+))?\s*$/;
|
|
32
|
+
// PHP's own stack trace lines after an uncaught exception.
|
|
33
|
+
const FRAME = /^#(\d+) (.*)$/;
|
|
34
|
+
const THROWN = /^\s*thrown in (.+?) on line (\d+)\s*$/;
|
|
35
|
+
|
|
36
|
+
const MAX_MESSAGE = 4000; // characters kept of one message
|
|
37
|
+
const MAX_FRAMES = 50; // stack frames kept per entry
|
|
38
|
+
const MAX_EXTRA = 20; // other continuation lines kept per entry
|
|
39
|
+
|
|
40
|
+
const zoneFormats = new Map();
|
|
41
|
+
|
|
42
|
+
/** Minutes east of UTC for `zone` at the instant `ms`, or null when the zone name is unknown. */
|
|
43
|
+
export function zoneOffset(zone, ms) {
|
|
44
|
+
if (!zone || /^(?:UTC|GMT|UCT|Z|Etc\/UTC|Etc\/GMT|Universal|Zulu)$/i.test(zone)) return 0;
|
|
45
|
+
const numeric = /^(?:UTC|GMT)?([+-])(\d{2}):?(\d{2})$/.exec(zone);
|
|
46
|
+
if (numeric) return (numeric[1] === "-" ? -1 : 1) * (Number(numeric[2]) * 60 + Number(numeric[3]));
|
|
47
|
+
let format = zoneFormats.get(zone);
|
|
48
|
+
if (format === undefined) {
|
|
49
|
+
try {
|
|
50
|
+
format = new Intl.DateTimeFormat("en-US", { timeZone: zone, timeZoneName: "longOffset" });
|
|
51
|
+
} catch {
|
|
52
|
+
format = null;
|
|
53
|
+
}
|
|
54
|
+
if (zoneFormats.size >= 100) zoneFormats.clear();
|
|
55
|
+
zoneFormats.set(zone, format);
|
|
56
|
+
}
|
|
57
|
+
if (!format) return null;
|
|
58
|
+
const name = format.formatToParts(new Date(ms)).find((part) => part.type === "timeZoneName")?.value ?? "";
|
|
59
|
+
const offset = /GMT([+-])(\d{2}):(\d{2})/.exec(name);
|
|
60
|
+
return offset ? (offset[1] === "-" ? -1 : 1) * (Number(offset[2]) * 60 + Number(offset[3])) : 0;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Milliseconds since the epoch (UTC) for the parts of a log timestamp, and whether the zone had to be assumed. */
|
|
64
|
+
export function toUtc(day, month, year, hour, minute, second, zone) {
|
|
65
|
+
const wall = Date.UTC(Number(year), MONTHS[month], Number(day), Number(hour), Number(minute), Number(second));
|
|
66
|
+
if (!Number.isFinite(wall) || MONTHS[month] === undefined) return null;
|
|
67
|
+
const first = zoneOffset(zone, wall);
|
|
68
|
+
if (first === null) return { ms: wall, zoneAssumed: true };
|
|
69
|
+
const offset = zoneOffset(zone, wall - first * 60_000); // second pass settles the daylight-saving edge
|
|
70
|
+
return { ms: wall - offset * 60_000, zoneAssumed: false };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Splits the text after the timestamp into a level, the label PHP or WordPress used, and the message. */
|
|
74
|
+
export function classify(text) {
|
|
75
|
+
const php = PHP_MESSAGE.exec(text);
|
|
76
|
+
if (php) return { level: PHP_LEVELS.get(php[1]), label: `PHP ${php[1]}`, message: php[2] };
|
|
77
|
+
const db = DB_MESSAGE.exec(text);
|
|
78
|
+
if (db) return { level: "database", label: "WordPress database error", message: db[1] };
|
|
79
|
+
return { level: "log", label: "Log line without a PHP level", message: text };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One PHP stack frame: "#3 /path/file.php(324): call(args)", "#1 [internal function]: call()", "#4 {main}". */
|
|
83
|
+
export function parseFrame(index, text) {
|
|
84
|
+
const frame = { index: Number(index), file: null, line: null, call: null, text };
|
|
85
|
+
if (text === "{main}") return { ...frame, call: "{main}" };
|
|
86
|
+
const internal = /^\[internal function\]: (.*)$/.exec(text);
|
|
87
|
+
if (internal) return { ...frame, call: internal[1] };
|
|
88
|
+
const located =
|
|
89
|
+
/^(.+?\.php(?:\(\d+\) : eval\(\)'d code)?)\((\d+)\): (.*)$/.exec(text) ?? /^(.*)\((\d+)\): (.*)$/.exec(text);
|
|
90
|
+
if (located) return { ...frame, file: located[1], line: Number(located[2]), call: located[3] };
|
|
91
|
+
return frame;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function newEntry(lineNo, stamp, text) {
|
|
95
|
+
const { level, label, message } = classify(text);
|
|
96
|
+
const time = stamp ? toUtc(stamp[1], stamp[2], stamp[3], stamp[4], stamp[5], stamp[6], stamp[7]) : null;
|
|
97
|
+
return {
|
|
98
|
+
line: lineNo,
|
|
99
|
+
time: time ? time.ms : null,
|
|
100
|
+
zoneAssumed: time ? time.zoneAssumed : false,
|
|
101
|
+
level,
|
|
102
|
+
label,
|
|
103
|
+
message: message.slice(0, MAX_MESSAGE),
|
|
104
|
+
frames: [],
|
|
105
|
+
frameCount: 0,
|
|
106
|
+
thrown: null,
|
|
107
|
+
extra: [],
|
|
108
|
+
extraCount: 0,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function addFrame(entry, frame) {
|
|
113
|
+
entry.frameCount++;
|
|
114
|
+
if (entry.frames.length < MAX_FRAMES) entry.frames.push(frame);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function xdebugFrame(match) {
|
|
118
|
+
const [, index, call, file, line] = match;
|
|
119
|
+
const text = file ? `${file}(${line}): ${call}` : call;
|
|
120
|
+
// Xdebug numbers frames from the outermost call; PHP's own traces start at the innermost.
|
|
121
|
+
return { index: Number(index), file: file ?? null, line: line ? Number(line) : null, call, text, xdebug: true };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Feeds lines in with push(); it returns the previous entry each time a new one starts, and end() returns the
|
|
126
|
+
* last one. Lines before the first entry that are not PHP messages are counted as skipped.
|
|
127
|
+
*/
|
|
128
|
+
export class EntryParser {
|
|
129
|
+
constructor() {
|
|
130
|
+
this.current = null;
|
|
131
|
+
this.lineNo = 0;
|
|
132
|
+
this.skipped = 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
push(raw) {
|
|
136
|
+
this.lineNo++;
|
|
137
|
+
let line = this.lineNo === 1 && raw.startsWith(BOM) ? raw.slice(1) : raw;
|
|
138
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
139
|
+
const stamp = STAMP.exec(line);
|
|
140
|
+
if (stamp) {
|
|
141
|
+
const text = stamp[8];
|
|
142
|
+
if (this.current && XDEBUG_STACK.test(text)) return null;
|
|
143
|
+
const xdebug = this.current && XDEBUG_FRAME.exec(text);
|
|
144
|
+
if (xdebug) {
|
|
145
|
+
addFrame(this.current, xdebugFrame(xdebug));
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
const done = this.current;
|
|
149
|
+
this.current = newEntry(this.lineNo, stamp, text);
|
|
150
|
+
return done;
|
|
151
|
+
}
|
|
152
|
+
// A PHP or database message without a timestamp still starts an entry of its own.
|
|
153
|
+
if (PHP_MESSAGE.test(line) || DB_MESSAGE.test(line)) {
|
|
154
|
+
const done = this.current;
|
|
155
|
+
this.current = newEntry(this.lineNo, null, line);
|
|
156
|
+
return done;
|
|
157
|
+
}
|
|
158
|
+
if (!this.current) {
|
|
159
|
+
this.skipped++;
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
this.continueEntry(line);
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
continueEntry(line) {
|
|
167
|
+
const entry = this.current;
|
|
168
|
+
if (/^(?:PHP )?Stack trace:\s*$/.test(line) || line.trim() === "") return;
|
|
169
|
+
const frame = FRAME.exec(line);
|
|
170
|
+
if (frame) return addFrame(entry, parseFrame(frame[1], frame[2]));
|
|
171
|
+
const xdebug = XDEBUG_FRAME.exec(line);
|
|
172
|
+
if (xdebug) return addFrame(entry, xdebugFrame(xdebug));
|
|
173
|
+
const thrown = THROWN.exec(line);
|
|
174
|
+
if (thrown) {
|
|
175
|
+
entry.thrown = { file: thrown[1], line: Number(thrown[2]) };
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
entry.extraCount++;
|
|
179
|
+
if (entry.extra.length < MAX_EXTRA) entry.extra.push(line.slice(0, 500));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
end() {
|
|
183
|
+
const done = this.current;
|
|
184
|
+
this.current = null;
|
|
185
|
+
return done;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Lines of a file path, or of a readable stream such as standard input, one at a time. */
|
|
190
|
+
export async function* readLines(input) {
|
|
191
|
+
if (typeof input === "string") {
|
|
192
|
+
const info = await stat(input);
|
|
193
|
+
if (info.isDirectory()) throw Object.assign(new Error("it is a folder, not a file"), { code: "EISDIR" });
|
|
194
|
+
}
|
|
195
|
+
const stream = typeof input === "string" ? createReadStream(input, { encoding: "utf8" }) : input;
|
|
196
|
+
const reader = createInterface({ input: stream, crlfDelay: Infinity });
|
|
197
|
+
let failure = null;
|
|
198
|
+
stream.on("error", (error) => {
|
|
199
|
+
failure = error;
|
|
200
|
+
reader.close();
|
|
201
|
+
});
|
|
202
|
+
for await (const line of reader) yield line;
|
|
203
|
+
if (failure) throw failure;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Every entry in `input` (a path or a stream), in file order. */
|
|
207
|
+
export async function* readEntries(input, parser = new EntryParser()) {
|
|
208
|
+
for await (const line of readLines(input)) {
|
|
209
|
+
const done = parser.push(line);
|
|
210
|
+
if (done) yield done;
|
|
211
|
+
}
|
|
212
|
+
const last = parser.end();
|
|
213
|
+
if (last) yield last;
|
|
214
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// The two questions asked about every group, the state each group contributes, and how groups are packed into
|
|
2
|
+
// requests. Jev reads the state once per request and answers every question against it, so a request carries as
|
|
3
|
+
// many groups as fit the token budget, each under its own key ("groups.g07"), with two questions per group.
|
|
4
|
+
import { choice, score } from "./jev.mjs";
|
|
5
|
+
import { describeSource } from "./source.mjs";
|
|
6
|
+
|
|
7
|
+
export const KINDS = {
|
|
8
|
+
noise:
|
|
9
|
+
"Expected or harmless output with no effect on visitors, data or security, such as debug or progress lines a plugin writes on purpose.",
|
|
10
|
+
deprecation:
|
|
11
|
+
"Code uses a PHP or WordPress function, argument, hook or behaviour that is marked deprecated. It still works today but will break in a later version.",
|
|
12
|
+
warning:
|
|
13
|
+
"PHP or WordPress hit a problem and carried on: a missing array key, variable or property, a null or wrong-type value, or a failed file, database or remote request.",
|
|
14
|
+
fatal:
|
|
15
|
+
"The request stopped on a code error: an uncaught error or exception, a parse error, or a call to an undefined function, class or method. Running out of memory or time is performance, not fatal.",
|
|
16
|
+
"security-relevant":
|
|
17
|
+
"A sign of an attack, a compromise or an exposure: PHP running from the uploads folder, eval'd or obfuscated code, SQL errors from injected input, failed nonce or login checks, or file access outside the site.",
|
|
18
|
+
performance:
|
|
19
|
+
"The request ran into a resource limit or was slow: memory exhausted, maximum execution time exceeded, slow or repeated database queries, or remote requests that time out.",
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export const URGENCY = [
|
|
23
|
+
"No action needed: harmless output, or a notice with no visible effect on visitors, data or security.",
|
|
24
|
+
"Routine maintenance: works today but should be fixed before the next PHP, WordPress or plugin update, or in the next cleanup.",
|
|
25
|
+
"Fix this week: a feature fails or is degraded for some requests, or pages are slow.",
|
|
26
|
+
"Fix now: the site or an important page is down, data may be lost or damaged, or the site may be under attack or exposed.",
|
|
27
|
+
];
|
|
28
|
+
export const URGENCY_LABELS = ["can wait", "routine", "this week", "now"];
|
|
29
|
+
|
|
30
|
+
const ABOUT =
|
|
31
|
+
"Groups of entries from one WordPress debug.log. Each group is one message that was logged one or more times. Paths are relative to the WordPress folder.";
|
|
32
|
+
|
|
33
|
+
const MESSAGE_CHARS = 500; // characters of a group's message that are sent
|
|
34
|
+
const STACK_FRAMES = 6; // stack frames sent per group
|
|
35
|
+
const FRAME_CHARS = 200; // characters sent per frame
|
|
36
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
// The model's limits (TypeSafe's models page, 2026-09-26): 32k tokens for the state plus the longest question,
|
|
39
|
+
// 64k for the state plus all questions. Token counts here are estimates, so requests are packed to 90% of each.
|
|
40
|
+
export const BUDGET = { state: 28_800, request: 57_600 };
|
|
41
|
+
|
|
42
|
+
/** A rough token count: one token per three characters of JSON, which overestimates English text. */
|
|
43
|
+
export function estimateTokens(value) {
|
|
44
|
+
return Math.ceil(JSON.stringify(value).length / 3);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function questionsFor(id) {
|
|
48
|
+
return {
|
|
49
|
+
[`${id}_kind`]: choice(`Which kind best describes the log message in \`groups.${id}\`?`, KINDS),
|
|
50
|
+
[`${id}_urgency`]: score(`How soon should someone act on the log message in \`groups.${id}\`?`, URGENCY),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** How often a group occurred, as words: Jev reads words more reliably than counts. */
|
|
55
|
+
export function occurrences(count) {
|
|
56
|
+
if (count <= 1) return "once";
|
|
57
|
+
if (count < 10) return "a few times";
|
|
58
|
+
if (count < 100) return "dozens of times";
|
|
59
|
+
if (count < 1000) return "hundreds of times";
|
|
60
|
+
return "thousands of times or more";
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const clip = (text, max) => (text.length > max ? `${text.slice(0, max - 3)}...` : text);
|
|
64
|
+
|
|
65
|
+
/** What is sent about one group. `logEnd` is the time of the log's last entry, when the log has timestamps. */
|
|
66
|
+
export function stateFor(group, logEnd) {
|
|
67
|
+
const state = { level: group.label, message: clip(group.message, MESSAGE_CHARS) };
|
|
68
|
+
const frames = group.stack.filter((frame) => frame.text !== "{main}");
|
|
69
|
+
if (frames.length) state.stack_trace = frames.slice(0, STACK_FRAMES).map((frame) => clip(frame.text, FRAME_CHARS));
|
|
70
|
+
state.source = describeSource(group.source);
|
|
71
|
+
state.occurrences = occurrences(group.count);
|
|
72
|
+
if (logEnd != null && group.last != null) state.seen_in_last_24_hours_of_log = group.last >= logEnd - DAY_MS ? "yes" : "no";
|
|
73
|
+
return state;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Packs groups into requests, in order, so that each stays under the budget: the state plus the longest
|
|
78
|
+
* question under `budget.state`, and the state plus all questions under `budget.request`. `maxGroups` caps the
|
|
79
|
+
* groups per request when a smaller state is wanted.
|
|
80
|
+
*/
|
|
81
|
+
export function planRequests(groups, logEnd, { budget = BUDGET, maxGroups = Infinity } = {}) {
|
|
82
|
+
const requests = [];
|
|
83
|
+
const empty = () => ({ ids: [], state: { about: ABOUT, groups: {} }, questions: {}, stateTokens: estimateTokens({ about: ABOUT, groups: {} }), questionTokens: 0 });
|
|
84
|
+
let current = null;
|
|
85
|
+
for (const group of groups) {
|
|
86
|
+
const entry = stateFor(group, logEnd);
|
|
87
|
+
const questions = questionsFor(group.id);
|
|
88
|
+
const stateTokens = estimateTokens({ [group.id]: entry });
|
|
89
|
+
const questionTokens = estimateTokens(questions);
|
|
90
|
+
const longest = Math.max(...Object.values(questions).map(estimateTokens));
|
|
91
|
+
if (
|
|
92
|
+
current &&
|
|
93
|
+
(current.ids.length >= maxGroups ||
|
|
94
|
+
current.stateTokens + stateTokens + longest > budget.state ||
|
|
95
|
+
current.stateTokens + stateTokens + current.questionTokens + questionTokens > budget.request)
|
|
96
|
+
) {
|
|
97
|
+
requests.push(current);
|
|
98
|
+
current = null;
|
|
99
|
+
}
|
|
100
|
+
current ??= empty();
|
|
101
|
+
current.ids.push(group.id);
|
|
102
|
+
current.state.groups[group.id] = entry;
|
|
103
|
+
Object.assign(current.questions, questions);
|
|
104
|
+
current.stateTokens += stateTokens;
|
|
105
|
+
current.questionTokens += questionTokens;
|
|
106
|
+
}
|
|
107
|
+
if (current) requests.push(current);
|
|
108
|
+
return requests.map(({ ids, state, questions }) => ({
|
|
109
|
+
ids,
|
|
110
|
+
state,
|
|
111
|
+
questions,
|
|
112
|
+
estimatedTokens: estimateTokens(state) + estimateTokens(questions),
|
|
113
|
+
}));
|
|
114
|
+
}
|
package/src/report.mjs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
// Turns grouped and triaged results into the text report, the JSON report, and the dry-run output. Every word in
|
|
2
|
+
// the output comes from the log itself or from the fixed templates here; Jev only returns probabilities.
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { JEV_ENDPOINT } from "./jev.mjs";
|
|
5
|
+
import { KINDS, URGENCY, URGENCY_LABELS, questionsFor, stateFor } from "./questions.mjs";
|
|
6
|
+
import { describeSource } from "./source.mjs";
|
|
7
|
+
|
|
8
|
+
export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
9
|
+
|
|
10
|
+
const int = (n) => Math.round(n).toLocaleString("en-US");
|
|
11
|
+
const plural = (n, one, many = `${one}s`) => `${int(n)} ${n === 1 ? one : many}`;
|
|
12
|
+
const times = (n) => (n === 1 ? "once" : `${int(n)} times`);
|
|
13
|
+
const clock = (ms) => new Date(ms).toISOString().replace("T", " ").slice(0, 19);
|
|
14
|
+
const iso = (ms) => (ms == null ? null : new Date(ms).toISOString().replace(".000Z", "Z"));
|
|
15
|
+
|
|
16
|
+
function topProbabilities(probabilities, name = (key) => key) {
|
|
17
|
+
return Object.entries(probabilities ?? {})
|
|
18
|
+
.filter(([, p]) => Number.isFinite(p) && p >= 0.005)
|
|
19
|
+
.sort((a, b) => b[1] - a[1])
|
|
20
|
+
.slice(0, 3)
|
|
21
|
+
.map(([key, p]) => `${name(key)} ${p.toFixed(2)}`)
|
|
22
|
+
.join(", ");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function headerLines(log, file) {
|
|
26
|
+
const { stats, groups } = log;
|
|
27
|
+
const lines = [`File: ${file}`];
|
|
28
|
+
const outside = stats.skipped ? `, ${int(stats.skipped)} outside any entry` : "";
|
|
29
|
+
lines.push(`Entries: ${int(stats.entries)} in ${plural(groups.length, "group")} (${plural(stats.lines, "line")}${outside})`);
|
|
30
|
+
if (stats.first !== null) lines.push(`Time span: ${clock(stats.first)} to ${clock(stats.last)} UTC`);
|
|
31
|
+
if (stats.zoneAssumed) lines.push(`Note: ${plural(stats.zoneAssumed, "entry", "entries")} named an unknown time zone and were read as UTC.`);
|
|
32
|
+
if (stats.overflow) {
|
|
33
|
+
lines.push(`Note: the log has more than ${int(groups.length)} distinct messages; ${plural(stats.overflow, "later entry", "later entries")} with new messages were counted but not grouped.`);
|
|
34
|
+
}
|
|
35
|
+
return lines;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function seenLine(group) {
|
|
39
|
+
const where = group.sourceLines.length ? `; source ${group.sourceLines.length === 1 ? "line" : "lines"} ${group.sourceLines.join(", ")}` : "";
|
|
40
|
+
if (group.first === null) return `No timestamps${where}`;
|
|
41
|
+
if (group.count === 1 || group.first === group.last) return `Seen ${clock(group.first)} UTC${where}`;
|
|
42
|
+
return `Seen ${clock(group.first)} to ${clock(group.last)} UTC${where}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function groupBlock(group, threshold) {
|
|
46
|
+
const pad = " ".repeat(group.id.length + 2);
|
|
47
|
+
const urgency = group.urgency ? group.urgency.label : "no answer";
|
|
48
|
+
const kind = group.kind ? group.kind.choice : "no answer";
|
|
49
|
+
const lines = [`${group.id} ${urgency} ${kind} ${describeSource(group.source)} ${times(group.count)}`];
|
|
50
|
+
lines.push(`${pad}${group.label}: ${group.message}`);
|
|
51
|
+
lines.push(`${pad}${seenLine(group)}`);
|
|
52
|
+
const parts = [];
|
|
53
|
+
if (group.urgency) {
|
|
54
|
+
const levels = topProbabilities(group.urgency.probabilities, (level) => URGENCY_LABELS[Number(level)] ?? level);
|
|
55
|
+
parts.push(`Urgency ${group.urgency.score.toFixed(2)} of 3: ${levels}.`);
|
|
56
|
+
}
|
|
57
|
+
if (group.kind) parts.push(`Kind: ${topProbabilities(group.kind.probabilities)}.`);
|
|
58
|
+
if (parts.length) lines.push(`${pad}${parts.join(" ")}`);
|
|
59
|
+
if (group.decision === "review") lines.push(`${pad}Review: ${group.reviewReasons.join(", ")} (threshold ${threshold.toFixed(2)}).`);
|
|
60
|
+
return lines.join("\n");
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The human-readable report: triaged groups most urgent first, then the groups for review. */
|
|
64
|
+
export function reportText(log, outcome, ranked, meta) {
|
|
65
|
+
const shown = meta.top ? ranked.slice(0, meta.top) : ranked;
|
|
66
|
+
const triaged = ranked.filter((g) => g.decision === "triaged").length;
|
|
67
|
+
const lines = [`wp-debuglog-triage ${VERSION}`, ...headerLines(log, meta.file)];
|
|
68
|
+
if (!ranked.length) {
|
|
69
|
+
lines.push("", "No log entries found.");
|
|
70
|
+
return `${lines.join("\n")}\n`;
|
|
71
|
+
}
|
|
72
|
+
lines.push(`Jev: model ${outcome.model ?? meta.model}, ${plural(outcome.requests, "request")}, ${int(outcome.usage.input_tokens)} input tokens`);
|
|
73
|
+
lines.push(`Threshold ${meta.threshold.toFixed(2)}: ${int(triaged)} triaged, ${int(ranked.length - triaged)} for review`);
|
|
74
|
+
if (shown.length < ranked.length) lines.push(`Showing the ${int(shown.length)} most urgent of ${plural(ranked.length, "group")}.`);
|
|
75
|
+
const sections = [
|
|
76
|
+
["Triaged, most urgent first", shown.filter((g) => g.decision === "triaged")],
|
|
77
|
+
[`For review, most urgent first (confidence below ${meta.threshold.toFixed(2)} or no answer)`, shown.filter((g) => g.decision !== "triaged")],
|
|
78
|
+
];
|
|
79
|
+
for (const [title, groups] of sections) {
|
|
80
|
+
if (!groups.length) continue;
|
|
81
|
+
lines.push("", title);
|
|
82
|
+
for (const group of groups) lines.push("", groupBlock(group, meta.threshold));
|
|
83
|
+
}
|
|
84
|
+
return `${lines.join("\n")}\n`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function groupJson(group) {
|
|
88
|
+
return {
|
|
89
|
+
id: group.id,
|
|
90
|
+
decision: group.decision ?? null,
|
|
91
|
+
review_reasons: group.reviewReasons ?? [],
|
|
92
|
+
urgency: group.urgency ?? null,
|
|
93
|
+
kind: group.kind ?? null,
|
|
94
|
+
label: group.label,
|
|
95
|
+
log_level: group.level,
|
|
96
|
+
count: group.count,
|
|
97
|
+
first_seen: iso(group.first),
|
|
98
|
+
last_seen: iso(group.last),
|
|
99
|
+
source: {
|
|
100
|
+
type: group.source.type,
|
|
101
|
+
slug: group.source.slug ?? null,
|
|
102
|
+
file: group.source.file ?? null,
|
|
103
|
+
via: group.source.via ?? null,
|
|
104
|
+
text_domain: group.source.textDomain ?? null,
|
|
105
|
+
description: describeSource(group.source),
|
|
106
|
+
},
|
|
107
|
+
source_lines: group.sourceLines,
|
|
108
|
+
message: group.message,
|
|
109
|
+
stack_trace: group.stack.map((frame) => frame.text),
|
|
110
|
+
stack_depth: group.stackDepth,
|
|
111
|
+
first_log_line: group.firstLogLine,
|
|
112
|
+
template: group.template,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function summaryJson(log, meta) {
|
|
117
|
+
return {
|
|
118
|
+
tool: "wp-debuglog-triage",
|
|
119
|
+
version: VERSION,
|
|
120
|
+
file: meta.file,
|
|
121
|
+
entries: log.stats.entries,
|
|
122
|
+
lines: log.stats.lines,
|
|
123
|
+
skipped_lines: log.stats.skipped,
|
|
124
|
+
ungrouped_entries: log.stats.overflow,
|
|
125
|
+
first_seen: iso(log.stats.first),
|
|
126
|
+
last_seen: iso(log.stats.last),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** The JSON report: the same groups and order as the text report, with every probability. */
|
|
131
|
+
export function reportJson(log, outcome, ranked, meta) {
|
|
132
|
+
const shown = meta.top ? ranked.slice(0, meta.top) : ranked;
|
|
133
|
+
const triaged = ranked.filter((g) => g.decision === "triaged").length;
|
|
134
|
+
const report = {
|
|
135
|
+
...summaryJson(log, meta),
|
|
136
|
+
model: outcome.model ?? meta.model,
|
|
137
|
+
requests: outcome.requests,
|
|
138
|
+
usage: outcome.usage,
|
|
139
|
+
threshold: meta.threshold,
|
|
140
|
+
groups_total: ranked.length,
|
|
141
|
+
triaged,
|
|
142
|
+
review: ranked.length - triaged,
|
|
143
|
+
groups: shown.map(groupJson),
|
|
144
|
+
};
|
|
145
|
+
return `${JSON.stringify(report, null, 2)}\n`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const byCount = (groups) => [...groups].sort((a, b) => b.count - a.count || a.firstLogLine - b.firstLogLine);
|
|
149
|
+
|
|
150
|
+
/** What a run would send, without sending it: the requests, the two questions, and each group's state. */
|
|
151
|
+
export function dryRunText(log, requests, meta) {
|
|
152
|
+
const lines = [`wp-debuglog-triage ${VERSION} (dry run: nothing was sent)`, ...headerLines(log, meta.file)];
|
|
153
|
+
if (!requests.length) {
|
|
154
|
+
lines.push("", "Nothing to send.");
|
|
155
|
+
return `${lines.join("\n")}\n`;
|
|
156
|
+
}
|
|
157
|
+
const total = requests.reduce((sum, r) => sum + r.estimatedTokens, 0);
|
|
158
|
+
lines.push("", `Would send ${plural(requests.length, "request")} to ${JEV_ENDPOINT} with model ${meta.model}:`);
|
|
159
|
+
requests.forEach((request, i) => {
|
|
160
|
+
lines.push(` request ${i + 1}: ${plural(request.ids.length, "group")}, about ${int(request.estimatedTokens)} input tokens`);
|
|
161
|
+
});
|
|
162
|
+
lines.push(`Estimated total: about ${int(total)} input tokens`);
|
|
163
|
+
|
|
164
|
+
const example = log.groups[0].id;
|
|
165
|
+
lines.push("", `Questions for each group (shown for ${example}; every group gets the same two under its own key):`);
|
|
166
|
+
for (const [key, question] of Object.entries(questionsFor(example))) {
|
|
167
|
+
lines.push("", `${key} (${question.type}): ${question.instructions}`);
|
|
168
|
+
if (question.type === "choice") for (const option of Object.keys(KINDS)) lines.push(` ${option}: ${KINDS[option]}`);
|
|
169
|
+
else URGENCY.forEach((level, i) => lines.push(` ${i} ${URGENCY_LABELS[i]}: ${level}`));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const listed = byCount(log.groups);
|
|
173
|
+
const shown = meta.top ? listed.slice(0, meta.top) : listed;
|
|
174
|
+
lines.push("", "Groups, most frequent first, with the state sent for each (--dry-run --json prints the exact request bodies):");
|
|
175
|
+
for (const group of shown) {
|
|
176
|
+
const state = stateFor(group, log.stats.last);
|
|
177
|
+
const pad = " ".repeat(group.id.length + 2);
|
|
178
|
+
lines.push("", `${group.id} ${state.level} ${state.occurrences} ${state.source}`);
|
|
179
|
+
lines.push(`${pad}${state.message}`);
|
|
180
|
+
for (const frame of state.stack_trace ?? []) lines.push(`${pad} ${frame}`);
|
|
181
|
+
if (state.seen_in_last_24_hours_of_log) lines.push(`${pad}seen in the last 24 hours of the log: ${state.seen_in_last_24_hours_of_log}`);
|
|
182
|
+
}
|
|
183
|
+
if (shown.length < listed.length) lines.push("", `${int(listed.length - shown.length)} more groups not shown.`);
|
|
184
|
+
return `${lines.join("\n")}\n`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The dry run as JSON, including the exact body of every request that would be sent. */
|
|
188
|
+
export function dryRunJson(log, requests, meta) {
|
|
189
|
+
const total = requests.reduce((sum, r) => sum + r.estimatedTokens, 0);
|
|
190
|
+
const listed = byCount(log.groups);
|
|
191
|
+
const report = {
|
|
192
|
+
...summaryJson(log, meta),
|
|
193
|
+
dry_run: true,
|
|
194
|
+
endpoint: JEV_ENDPOINT,
|
|
195
|
+
model: meta.model,
|
|
196
|
+
groups_total: log.groups.length,
|
|
197
|
+
estimated_input_tokens: total,
|
|
198
|
+
requests: requests.map((request) => ({
|
|
199
|
+
groups: request.ids,
|
|
200
|
+
estimated_input_tokens: request.estimatedTokens,
|
|
201
|
+
body: { model: meta.model, state: request.state, questions: request.questions },
|
|
202
|
+
})),
|
|
203
|
+
groups: (meta.top ? listed.slice(0, meta.top) : listed).map(groupJson),
|
|
204
|
+
};
|
|
205
|
+
return `${JSON.stringify(report, null, 2)}\n`;
|
|
206
|
+
}
|