pi-charset 0.1.6 → 0.1.8
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/CHANGELOG.md +28 -0
- package/CHANGELOG.zh-CN.md +28 -0
- package/dist/config.js +943 -0
- package/dist/diagnostics/incidents.js +436 -0
- package/dist/edit/apply-patch-core.js +274 -0
- package/dist/edit/diagnostics.js +73 -0
- package/dist/edit/hashline.js +400 -0
- package/dist/edit/patch.js +634 -0
- package/dist/edit/paths.js +48 -0
- package/dist/edit/plan.js +90 -0
- package/dist/encoding/classify.js +430 -0
- package/dist/encoding/common-scripts.js +58 -0
- package/dist/encoding/converter.js +311 -0
- package/dist/encoding/fast-codec.js +476 -0
- package/dist/encoding/file-stamp.js +32 -0
- package/dist/encoding/line-endings.js +118 -0
- package/dist/encoding/mime.js +88 -0
- package/dist/encoding/stream-transcode.js +287 -0
- package/dist/faults.js +67 -0
- package/dist/grep-core.js +730 -0
- package/dist/journal.js +494 -0
- package/dist/maintenance.js +333 -0
- package/dist/mcp/server.js +959 -0
- package/dist/notify.js +60 -0
- package/dist/operations.js +1155 -0
- package/dist/path-key.js +10 -0
- package/dist/read-view.js +927 -0
- package/dist/resolve.js +325 -0
- package/dist/setup/adapters.js +524 -0
- package/dist/version.js +2 -0
- package/docs/MCP-AND-MULTI-AGENT.md +43 -20
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +43 -20
- package/package.json +14 -2
- package/src/diagnostics/incidents.ts +474 -0
- package/src/edit/apply-patch-core.ts +32 -3
- package/src/edit/diagnostics.ts +31 -0
- package/src/faults.ts +165 -0
- package/src/grep-core.ts +50 -8
- package/src/grep.ts +9 -1
- package/src/index.ts +8 -5
- package/src/journal.ts +167 -42
- package/src/mcp/server.ts +597 -179
- package/src/operations.ts +370 -100
- package/src/read-view.ts +111 -8
- package/src/setup/adapters.ts +613 -0
- package/src/shell-guard.ts +38 -1
- package/src/version.ts +1 -1
- package/tools/pi-charset-cli.mjs +664 -168
- package/tools/pi-charset-mcp.mjs +81 -42
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
// Privacy-first local incident recorder integrated into pi-charset's shared core.
|
|
2
|
+
// Zero network calls, zero raw exception text, zero source code, zero paths, zero credentials.
|
|
3
|
+
// Uses Node built-ins only; only call with structured, trusted internal metadata from typed faults.
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { promises as fs } from "node:fs";
|
|
6
|
+
import * as os from "node:os";
|
|
7
|
+
import * as path from "node:path";
|
|
8
|
+
import { PLUGIN_VERSION } from "../version.js";
|
|
9
|
+
const SCHEMA = 1;
|
|
10
|
+
const CODES = Object.freeze({
|
|
11
|
+
WRITE_VERIFY_FAILED: ["engine", "Verify rollback and reproduce using a synthetic encoded fixture."],
|
|
12
|
+
ROLLBACK_FAILED: ["critical", "Stop further writes; inspect local recovery journal."],
|
|
13
|
+
BYTE_INVARIANT_FAILED: ["critical", "Stop further writes; compare synthetic byte-preservation fixture."],
|
|
14
|
+
MCP_PROTOCOL_ERROR: ["compatibility", "Reproduce initialize, tools/list and tools/call with a synthetic client."],
|
|
15
|
+
CLIENT_STARTUP_FAILED: ["compatibility", "Check installed package entrypoint, runtime and stdio handshake."],
|
|
16
|
+
TOOL_BYPASS_DETECTED: ["compatibility", "Check client rules and hooks; inspect local Git diff."],
|
|
17
|
+
LOCK_INVARIANT_FAILED: ["engine", "Reproduce with separate processes and concurrent writes."],
|
|
18
|
+
GIT_INDEX_INVARIANT_FAILED: ["critical", "Reproduce in a temporary repository with staged changes."],
|
|
19
|
+
SEARCH_ENGINE_FAILED: ["compatibility", "Reproduce with synthetic legacy-encoded files and ripgrep."],
|
|
20
|
+
INTERNAL: ["engine", "Reproduce the failed operation with a minimal synthetic fixture."],
|
|
21
|
+
});
|
|
22
|
+
const EXPECTED_REJECTIONS = new Set([
|
|
23
|
+
"INVALID_INPUT",
|
|
24
|
+
"UNMAPPABLE",
|
|
25
|
+
"UNKNOWN_ENCODING",
|
|
26
|
+
"AMBIGUOUS_ENCODING",
|
|
27
|
+
"MIXED_EOL",
|
|
28
|
+
"STALE_VERSION",
|
|
29
|
+
"STALE_READ",
|
|
30
|
+
"CONFLICT",
|
|
31
|
+
"CANCELLED",
|
|
32
|
+
"PERMISSION_DENIED",
|
|
33
|
+
"NOT_FOUND",
|
|
34
|
+
"BINARY_FILE",
|
|
35
|
+
"UNSUPPORTED_FILE",
|
|
36
|
+
"LOCK_BUSY",
|
|
37
|
+
]);
|
|
38
|
+
const OPS = [
|
|
39
|
+
"read", "write", "edit", "apply_patch", "grep", "check", "fix", "undo",
|
|
40
|
+
"setup", "initialize", "tools_list", "hook", "unknown",
|
|
41
|
+
];
|
|
42
|
+
const CLIENTS = [
|
|
43
|
+
"pi", "codex", "agy", "antigravity-ide", "antigravity-app",
|
|
44
|
+
"claude", "cursor", "windsurf", "generic", "unknown",
|
|
45
|
+
];
|
|
46
|
+
const ENCODINGS = [
|
|
47
|
+
"ASCII", "UTF-8", "UTF-16LE", "UTF-16BE", "GBK", "GB18030",
|
|
48
|
+
"BIG5", "SHIFT_JIS", "EUC-KR", "EUC-JP", "ISO-8859-1", "UNKNOWN", "unknown",
|
|
49
|
+
];
|
|
50
|
+
const PHASES = [
|
|
51
|
+
"startup", "detect", "decode", "validate", "encode", "commit",
|
|
52
|
+
"verify", "rollback", "transport", "search", "policy", "unknown",
|
|
53
|
+
];
|
|
54
|
+
const OUTCOMES = ["not_applied", "rolled_back", "applied_verified", "uncertain", "unknown"];
|
|
55
|
+
const PLATFORMS = ["win32", "linux", "darwin", "unknown"];
|
|
56
|
+
const ARCHS = ["x64", "arm64", "ia32", "unknown"];
|
|
57
|
+
const EOLS = ["LF", "CRLF", "CR", "MIXED", "NONE", "unknown"];
|
|
58
|
+
const SIZE_BUCKETS = ["lt4KiB", "4-64KiB", "64KiB-1MiB", "1-10MiB", "gte10MiB", "unknown"];
|
|
59
|
+
function enumValue(v, allowed) {
|
|
60
|
+
return typeof v === "string" && allowed.includes(v) ? v : "unknown";
|
|
61
|
+
}
|
|
62
|
+
function sanitizeVersion(v) {
|
|
63
|
+
return typeof v === "string" && /^\d{1,4}\.\d{1,4}\.\d{1,4}(?:-[0-9A-Za-z.-]{1,24})?$/.test(v) ? v : "unknown";
|
|
64
|
+
}
|
|
65
|
+
function dayString(date) {
|
|
66
|
+
return date.toISOString().slice(0, 10);
|
|
67
|
+
}
|
|
68
|
+
function bucketSize(v) {
|
|
69
|
+
if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0)
|
|
70
|
+
return "unknown";
|
|
71
|
+
if (v < 4096)
|
|
72
|
+
return "lt4KiB";
|
|
73
|
+
if (v < 65536)
|
|
74
|
+
return "4-64KiB";
|
|
75
|
+
if (v < 1048576)
|
|
76
|
+
return "64KiB-1MiB";
|
|
77
|
+
if (v < 10485760)
|
|
78
|
+
return "1-10MiB";
|
|
79
|
+
return "gte10MiB";
|
|
80
|
+
}
|
|
81
|
+
function fingerprintFields(fields) {
|
|
82
|
+
return createHash("sha256").update(JSON.stringify(fields)).digest("hex").slice(0, 32);
|
|
83
|
+
}
|
|
84
|
+
export function normalizeIncident(input = {}, runtime = {}) {
|
|
85
|
+
if (!input || typeof input !== "object")
|
|
86
|
+
return null;
|
|
87
|
+
const code = input.code;
|
|
88
|
+
if (typeof code !== "string" || EXPECTED_REJECTIONS.has(code) || !Object.hasOwn(CODES, code))
|
|
89
|
+
return null;
|
|
90
|
+
const typedCode = code;
|
|
91
|
+
const fields = {
|
|
92
|
+
schema: SCHEMA,
|
|
93
|
+
code: typedCode,
|
|
94
|
+
category: CODES[typedCode][0],
|
|
95
|
+
operation: enumValue(input.operation, OPS),
|
|
96
|
+
phase: enumValue(input.phase, PHASES),
|
|
97
|
+
outcome: enumValue(input.outcome, OUTCOMES),
|
|
98
|
+
client: enumValue(runtime.client, CLIENTS),
|
|
99
|
+
packageVersion: sanitizeVersion(runtime.packageVersion ?? PLUGIN_VERSION),
|
|
100
|
+
platform: enumValue(runtime.platform ?? process.platform, PLATFORMS),
|
|
101
|
+
arch: enumValue(runtime.arch ?? process.arch, ARCHS),
|
|
102
|
+
nodeMajor: Math.min(99, Math.max(0, Number(process.versions.node.split(".")[0]) || 0)),
|
|
103
|
+
encoding: enumValue(typeof input.encoding === "string" ? input.encoding.toUpperCase() : "unknown", ENCODINGS),
|
|
104
|
+
eol: enumValue(input.eol, EOLS),
|
|
105
|
+
sizeBucket: bucketSize(input.fileBytes),
|
|
106
|
+
};
|
|
107
|
+
return Object.freeze({ ...fields, fingerprint: fingerprintFields(fields) });
|
|
108
|
+
}
|
|
109
|
+
export function diagnosticsStateRoot() {
|
|
110
|
+
if (process.env.PI_CHARSET_DIAGNOSTICS_DIR?.trim()) {
|
|
111
|
+
return path.resolve(process.env.PI_CHARSET_DIAGNOSTICS_DIR.trim());
|
|
112
|
+
}
|
|
113
|
+
if (process.platform === "win32") {
|
|
114
|
+
return path.join(process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local"), "pi-charset", "diagnostics-v1");
|
|
115
|
+
}
|
|
116
|
+
if (process.platform === "darwin") {
|
|
117
|
+
return path.join(os.homedir(), "Library", "Application Support", "pi-charset", "diagnostics-v1");
|
|
118
|
+
}
|
|
119
|
+
return path.join(process.env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state"), "pi-charset", "diagnostics-v1");
|
|
120
|
+
}
|
|
121
|
+
/** Respect user-level opt-out (env var only; never overridden by project .pi-charset.json or model prompts). */
|
|
122
|
+
export function isDiagnosticsEnabledByEnv() {
|
|
123
|
+
const v = (process.env.PI_CHARSET_DIAGNOSTICS ?? "").trim().toLowerCase();
|
|
124
|
+
if (v === "0" || v === "false" || v === "off" || v === "no")
|
|
125
|
+
return false;
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
const isDayDir = (v) => /^\d{4}-\d{2}-\d{2}$/.test(v);
|
|
129
|
+
const isSlotFile = (v) => /^slot-\d{3}\.json$/.test(v);
|
|
130
|
+
const isTempFile = (v) => /^\.tmp-[0-9a-f]{24}$/.test(v);
|
|
131
|
+
async function safeDir(dir) {
|
|
132
|
+
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
133
|
+
const s = await fs.lstat(dir);
|
|
134
|
+
if (!s.isDirectory() || s.isSymbolicLink())
|
|
135
|
+
throw new Error("unsafe diagnostic directory");
|
|
136
|
+
}
|
|
137
|
+
function validatePersisted(v) {
|
|
138
|
+
if (!v || typeof v !== "object")
|
|
139
|
+
return null;
|
|
140
|
+
const obj = v;
|
|
141
|
+
if (obj.schema !== SCHEMA || typeof obj.code !== "string" || !Object.hasOwn(CODES, obj.code))
|
|
142
|
+
return null;
|
|
143
|
+
const typedCode = obj.code;
|
|
144
|
+
const fields = {
|
|
145
|
+
schema: SCHEMA,
|
|
146
|
+
code: typedCode,
|
|
147
|
+
category: CODES[typedCode][0],
|
|
148
|
+
operation: enumValue(obj.operation, OPS),
|
|
149
|
+
phase: enumValue(obj.phase, PHASES),
|
|
150
|
+
outcome: enumValue(obj.outcome, OUTCOMES),
|
|
151
|
+
client: enumValue(obj.client, CLIENTS),
|
|
152
|
+
packageVersion: sanitizeVersion(obj.packageVersion),
|
|
153
|
+
platform: enumValue(obj.platform, PLATFORMS),
|
|
154
|
+
arch: enumValue(obj.arch, ARCHS),
|
|
155
|
+
nodeMajor: typeof obj.nodeMajor === "number" && Number.isInteger(obj.nodeMajor) && obj.nodeMajor >= 0 && obj.nodeMajor <= 99 ? obj.nodeMajor : 0,
|
|
156
|
+
encoding: enumValue(obj.encoding, ENCODINGS),
|
|
157
|
+
eol: enumValue(obj.eol, EOLS),
|
|
158
|
+
sizeBucket: enumValue(obj.sizeBucket, SIZE_BUCKETS),
|
|
159
|
+
};
|
|
160
|
+
const fingerprint = fingerprintFields(fields);
|
|
161
|
+
if (obj.fingerprint !== fingerprint)
|
|
162
|
+
return null;
|
|
163
|
+
return { ...fields, fingerprint };
|
|
164
|
+
}
|
|
165
|
+
async function readRecord(file) {
|
|
166
|
+
try {
|
|
167
|
+
const st = await fs.lstat(file);
|
|
168
|
+
if (!st.isFile() || st.isSymbolicLink() || st.size > 4096)
|
|
169
|
+
return null;
|
|
170
|
+
return validatePersisted(JSON.parse(await fs.readFile(file, "utf8")));
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
export function issueDraft(report) {
|
|
177
|
+
const r = validatePersisted(report);
|
|
178
|
+
if (!r)
|
|
179
|
+
throw new Error("Invalid incident report");
|
|
180
|
+
return {
|
|
181
|
+
title: `[${r.code}] ${r.operation} / ${r.client} / ${r.platform}`,
|
|
182
|
+
body: `## Sanitized diagnostic\n\n` +
|
|
183
|
+
`Fingerprint: \`${r.fingerprint}\`\n\n` +
|
|
184
|
+
`\`\`\`json\n${JSON.stringify(r, null, 2)}\n\`\`\`\n\n` +
|
|
185
|
+
`## Suggested reproduction\n\n` +
|
|
186
|
+
`${CODES[r.code][1]}\n\n` +
|
|
187
|
+
`No project files, file paths, raw error messages, environment variables, credentials, or prompts are included. This is a diagnostic signal, not proof of root cause.\n`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
export function buildIssueUrl(report, repo = "ethan-blue/pi-charset") {
|
|
191
|
+
const draft = issueDraft(report);
|
|
192
|
+
const url = new URL(`https://github.com/${repo}/issues/new`);
|
|
193
|
+
url.searchParams.set("title", draft.title);
|
|
194
|
+
url.searchParams.set("body", draft.body);
|
|
195
|
+
return url.href;
|
|
196
|
+
}
|
|
197
|
+
export class IncidentRecorder {
|
|
198
|
+
root;
|
|
199
|
+
enabled;
|
|
200
|
+
runtime;
|
|
201
|
+
slots;
|
|
202
|
+
retention;
|
|
203
|
+
maxPending;
|
|
204
|
+
clock;
|
|
205
|
+
#pending = [];
|
|
206
|
+
#drain = null;
|
|
207
|
+
#seen = new Set();
|
|
208
|
+
#lastPrune = "";
|
|
209
|
+
constructor(opts = {}) {
|
|
210
|
+
this.root = path.resolve(opts.root ?? diagnosticsStateRoot());
|
|
211
|
+
this.enabled = opts.enabled !== undefined ? opts.enabled === true : isDiagnosticsEnabledByEnv();
|
|
212
|
+
this.runtime = { packageVersion: PLUGIN_VERSION, ...opts.runtime };
|
|
213
|
+
this.slots = Math.max(1, Math.min(256, Math.floor(opts.slotsPerDay ?? 64) || 64));
|
|
214
|
+
this.retention = Math.max(1, Math.min(30, Math.floor(opts.retentionDays ?? 14) || 14));
|
|
215
|
+
this.maxPending = Math.max(1, Math.min(128, Math.floor(opts.maxPending ?? 32) || 32));
|
|
216
|
+
this.clock = opts.clock ?? (() => new Date());
|
|
217
|
+
}
|
|
218
|
+
/** Fire-and-forget on reportable failure only; bounded memory, zero stdout logging, never throws. */
|
|
219
|
+
record(input) {
|
|
220
|
+
try {
|
|
221
|
+
if (!this.enabled)
|
|
222
|
+
return { status: "disabled" };
|
|
223
|
+
const event = normalizeIncident(input, this.runtime);
|
|
224
|
+
if (!event)
|
|
225
|
+
return { status: "ignored" };
|
|
226
|
+
const date = dayString(this.clock());
|
|
227
|
+
const key = `${date}:${event.fingerprint}`;
|
|
228
|
+
if (this.#seen.has(key))
|
|
229
|
+
return { status: "duplicate", fingerprint: event.fingerprint };
|
|
230
|
+
if (this.#pending.length >= this.maxPending)
|
|
231
|
+
return { status: "queue_full" };
|
|
232
|
+
this.#seen.add(key);
|
|
233
|
+
if (this.#seen.size > 512) {
|
|
234
|
+
this.#seen.clear();
|
|
235
|
+
this.#seen.add(key);
|
|
236
|
+
}
|
|
237
|
+
this.#pending.push({ date, event, key });
|
|
238
|
+
this.#startDrain();
|
|
239
|
+
return { status: "queued", fingerprint: event.fingerprint };
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
return { status: "unavailable" };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
#startDrain() {
|
|
246
|
+
if (this.#drain)
|
|
247
|
+
return;
|
|
248
|
+
this.#drain = this.#run().finally(() => {
|
|
249
|
+
this.#drain = null;
|
|
250
|
+
if (this.#pending.length)
|
|
251
|
+
this.#startDrain();
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async #publishSlot(temp, dest, payload) {
|
|
255
|
+
try {
|
|
256
|
+
await fs.link(temp, dest);
|
|
257
|
+
return "published";
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
const code = error?.code;
|
|
261
|
+
if (code === "EEXIST")
|
|
262
|
+
return "exists";
|
|
263
|
+
// Safe fallback for filesystems without hard-link support (e.g. FAT32/exFAT/network mounts).
|
|
264
|
+
if (code === "EPERM" || code === "ENOTSUP" || code === "EXDEV" || code === "EACCES" || code === "ENOSYS") {
|
|
265
|
+
try {
|
|
266
|
+
await fs.writeFile(dest, payload, { flag: "wx", mode: 0o600 });
|
|
267
|
+
return "published";
|
|
268
|
+
}
|
|
269
|
+
catch (wxErr) {
|
|
270
|
+
if (wxErr?.code === "EEXIST")
|
|
271
|
+
return "exists";
|
|
272
|
+
throw wxErr;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
throw error;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
async #run() {
|
|
279
|
+
while (this.#pending.length) {
|
|
280
|
+
const item = this.#pending.shift();
|
|
281
|
+
const { date, event, key } = item;
|
|
282
|
+
try {
|
|
283
|
+
await safeDir(this.root);
|
|
284
|
+
if (this.#lastPrune !== date) {
|
|
285
|
+
await this.prune();
|
|
286
|
+
this.#lastPrune = date;
|
|
287
|
+
}
|
|
288
|
+
const dir = path.join(this.root, date);
|
|
289
|
+
await safeDir(dir);
|
|
290
|
+
const payload = JSON.stringify(event) + "\n";
|
|
291
|
+
const temp = path.join(dir, `.tmp-${randomBytes(12).toString("hex")}`);
|
|
292
|
+
try {
|
|
293
|
+
await fs.writeFile(temp, payload, { flag: "wx", mode: 0o600 });
|
|
294
|
+
const start = parseInt(event.fingerprint.slice(0, 8), 16) % this.slots;
|
|
295
|
+
for (let i = 0; i < this.slots; i++) {
|
|
296
|
+
const dest = path.join(dir, `slot-${String((start + i) % this.slots).padStart(3, "0")}.json`);
|
|
297
|
+
const pub = await this.#publishSlot(temp, dest, payload);
|
|
298
|
+
if (pub === "published")
|
|
299
|
+
break;
|
|
300
|
+
const existing = await readRecord(dest);
|
|
301
|
+
if (existing?.fingerprint === event.fingerprint)
|
|
302
|
+
break;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
finally {
|
|
306
|
+
await fs.unlink(temp).catch(() => undefined);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
this.#seen.delete(key);
|
|
311
|
+
// Diagnostic I/O must never alter or block tool results.
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
async flush(timeoutMs = 1500) {
|
|
316
|
+
const waitAll = async () => {
|
|
317
|
+
while (this.#drain)
|
|
318
|
+
await this.#drain;
|
|
319
|
+
};
|
|
320
|
+
if (timeoutMs <= 0) {
|
|
321
|
+
await waitAll();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
await Promise.race([
|
|
325
|
+
waitAll(),
|
|
326
|
+
new Promise((resolve) => {
|
|
327
|
+
const t = setTimeout(resolve, timeoutMs);
|
|
328
|
+
t.unref?.();
|
|
329
|
+
}),
|
|
330
|
+
]);
|
|
331
|
+
}
|
|
332
|
+
async prune() {
|
|
333
|
+
const cutoff = new Date(this.clock().getTime() - (this.retention - 1) * 86400000).toISOString().slice(0, 10);
|
|
334
|
+
let dirs;
|
|
335
|
+
try {
|
|
336
|
+
dirs = await fs.readdir(this.root, { withFileTypes: true });
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
for (const d of dirs) {
|
|
342
|
+
if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
|
|
343
|
+
continue;
|
|
344
|
+
const expired = d.name < cutoff;
|
|
345
|
+
const dir = path.join(this.root, d.name);
|
|
346
|
+
try {
|
|
347
|
+
for (const f of await fs.readdir(dir, { withFileTypes: true })) {
|
|
348
|
+
if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name)))
|
|
349
|
+
continue;
|
|
350
|
+
const full = path.join(dir, f.name);
|
|
351
|
+
if ((expired && isSlotFile(f.name)) ||
|
|
352
|
+
(isTempFile(f.name) && this.clock().getTime() - (await fs.stat(full)).mtimeMs > 86400000)) {
|
|
353
|
+
await fs.unlink(full).catch(() => undefined);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (expired)
|
|
357
|
+
await fs.rmdir(dir).catch(() => undefined);
|
|
358
|
+
}
|
|
359
|
+
catch { /* Concurrent process may prune first. */ }
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
async clear() {
|
|
363
|
+
await this.flush();
|
|
364
|
+
this.#seen.clear();
|
|
365
|
+
let removed = 0;
|
|
366
|
+
let dirs;
|
|
367
|
+
try {
|
|
368
|
+
dirs = await fs.readdir(this.root, { withFileTypes: true });
|
|
369
|
+
}
|
|
370
|
+
catch {
|
|
371
|
+
return 0;
|
|
372
|
+
}
|
|
373
|
+
for (const d of dirs) {
|
|
374
|
+
if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
|
|
375
|
+
continue;
|
|
376
|
+
const dir = path.join(this.root, d.name);
|
|
377
|
+
try {
|
|
378
|
+
for (const f of await fs.readdir(dir, { withFileTypes: true })) {
|
|
379
|
+
if (!f.isFile() || f.isSymbolicLink() || !(isSlotFile(f.name) || isTempFile(f.name)))
|
|
380
|
+
continue;
|
|
381
|
+
await fs.unlink(path.join(dir, f.name)).catch(() => undefined);
|
|
382
|
+
if (isSlotFile(f.name))
|
|
383
|
+
removed++;
|
|
384
|
+
}
|
|
385
|
+
await fs.rmdir(dir).catch(() => undefined);
|
|
386
|
+
}
|
|
387
|
+
catch { /* ignore */ }
|
|
388
|
+
}
|
|
389
|
+
return removed;
|
|
390
|
+
}
|
|
391
|
+
async list() {
|
|
392
|
+
await this.flush();
|
|
393
|
+
const out = [];
|
|
394
|
+
let dirs;
|
|
395
|
+
try {
|
|
396
|
+
dirs = await fs.readdir(this.root, { withFileTypes: true });
|
|
397
|
+
}
|
|
398
|
+
catch {
|
|
399
|
+
return out;
|
|
400
|
+
}
|
|
401
|
+
for (const d of dirs) {
|
|
402
|
+
if (!d.isDirectory() || d.isSymbolicLink() || !isDayDir(d.name))
|
|
403
|
+
continue;
|
|
404
|
+
const dir = path.join(this.root, d.name);
|
|
405
|
+
let files;
|
|
406
|
+
try {
|
|
407
|
+
files = await fs.readdir(dir, { withFileTypes: true });
|
|
408
|
+
}
|
|
409
|
+
catch {
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
for (const f of files) {
|
|
413
|
+
if (!f.isFile() || !isSlotFile(f.name))
|
|
414
|
+
continue;
|
|
415
|
+
const report = await readRecord(path.join(dir, f.name));
|
|
416
|
+
if (report)
|
|
417
|
+
out.push({ date: d.name, report });
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return out.sort((a, b) => b.date.localeCompare(a.date) || a.report.fingerprint.localeCompare(b.report.fingerprint));
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
let singletonRecorder = null;
|
|
424
|
+
let singletonClient = "generic";
|
|
425
|
+
/** Lazy process-level diagnostic recorder singleton; instantiated only on reportable failures or explicit CLI queries. */
|
|
426
|
+
export function getIncidentRecorder(client = singletonClient) {
|
|
427
|
+
if (!singletonRecorder || (client !== "generic" && client !== singletonClient)) {
|
|
428
|
+
singletonClient = client;
|
|
429
|
+
singletonRecorder = new IncidentRecorder({ runtime: { client, packageVersion: PLUGIN_VERSION } });
|
|
430
|
+
}
|
|
431
|
+
return singletonRecorder;
|
|
432
|
+
}
|
|
433
|
+
export function resetIncidentRecorderForTests() {
|
|
434
|
+
singletonRecorder = null;
|
|
435
|
+
singletonClient = "generic";
|
|
436
|
+
}
|