pi-charset 0.1.7 → 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 +10 -0
- package/CHANGELOG.zh-CN.md +10 -0
- package/dist/diagnostics/incidents.js +436 -0
- package/dist/edit/diagnostics.js +27 -0
- package/dist/faults.js +67 -0
- package/dist/mcp/server.js +138 -45
- package/dist/operations.js +169 -35
- package/dist/setup/adapters.js +524 -0
- package/dist/version.js +1 -1
- package/docs/MCP-AND-MULTI-AGENT.md +17 -2
- package/docs/zh-CN/MCP-AND-MULTI-AGENT.md +17 -2
- package/package.json +1 -1
- package/src/diagnostics/incidents.ts +474 -0
- package/src/edit/diagnostics.ts +31 -0
- package/src/faults.ts +165 -0
- package/src/mcp/server.ts +191 -45
- package/src/operations.ts +178 -37
- package/src/setup/adapters.ts +613 -0
- package/src/version.ts +1 -1
- package/tools/pi-charset-cli.mjs +232 -22
- package/tools/pi-charset-mcp.mjs +3 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.1.8] - 2026-12-06
|
|
13
|
+
|
|
14
|
+
### Added
|
|
15
|
+
|
|
16
|
+
- **Unified Typed Fault Contract (`src/faults.ts`)**: Replaced ad-hoc string errors across core I/O (`src/operations.ts`), edit/patch diagnostics (`src/edit/diagnostics.ts`), and MCP (`src/mcp/server.ts`) with typed `CharsetFault` / `FaultMetadata` (`code`, `category`, `phase`, `outcome`, `retryable`, `actionHint`) and a consistent machine-readable MCP error envelope (`status: "failed"`, `error`, `applied`, `verified`, `committed`, `outcome`, `actionHint`) on every failure branch.
|
|
17
|
+
- **Privacy-First Local Incident Recorder (`src/diagnostics/incidents.ts`) & `pi-charset feedback`**: Integrated a zero-network, bounded, allowlist-only local diagnostic recorder (never records source code, paths, raw exception strings, prompts, or secrets; ignores expected operational rejections; deduplicates across independent OS processes with daily slot caps, 14-day retention pruning, fingerprint tamper verification, and safe fallback on filesystems without hard-link support; disable via `PI_CHARSET_DIAGNOSTICS=0`). Added `pi-charset feedback list | preview <fp> | issue-url <fp> | prune | clear`.
|
|
18
|
+
- **Host Adapter Registry & One-Command `pi-charset setup` (`src/setup/adapters.ts`)**: Added idempotent, atomic, non-destructive setup, `--dry-run`, `--uninstall`, and `--rollback` for Codex (`~/.codex/config.toml`), Antigravity (`~/.gemini/config/mcp_config.json`), Claude Code, and Cursor using permanent absolute `node` + `pi-charset-mcp.mjs` entrypoints (preserving all third-party MCP servers and refusing to overwrite invalid JSON), paired with an isolated temp-dir synthetic GBK+CRLF `read`/`edit`/`undo` smoke test.
|
|
19
|
+
- **Upgraded `pi-charset doctor --json` / `--fix` & Selective AGY `_meta`**: `doctor --json` now reports Node compatibility, live MCP smoke verification, honest per-client status (`not_installed` / `unregistered` / `registered` / `handshake_verified` / `degraded`), Git hook enforcement, and local diagnostics state; `doctor --fix` repairs only broken `pi-charset`-owned MCP entries. Added selective `_meta: { "antigravity/alwaysLoad": true }` to the 3 high-frequency core MCP tools (`charset_read`, `charset_edit`, `charset_grep`).
|
|
20
|
+
- **Cross-Process & Windows Path Hardening Tests**: Added independent multi-OS-process `pi-charset-mcp` concurrency tests (`expectedVersion` across separate processes), complex Chinese/space/parenthesis/bracket path tests, full privacy/dedup/retention tests, and isolated `HOME` adapter setup/rollback tests (`test/diagnostics-incidents.test.ts`, `test/setup-adapters.test.ts`, `test/cross-process-and-faults.test.ts`).
|
|
21
|
+
|
|
12
22
|
## [0.1.7] - 2026-12-06
|
|
13
23
|
|
|
14
24
|
### Fixed
|
package/CHANGELOG.zh-CN.md
CHANGED
|
@@ -8,6 +8,16 @@
|
|
|
8
8
|
|
|
9
9
|
## [Unreleased]
|
|
10
10
|
|
|
11
|
+
## [0.1.8] - 2026-12-06
|
|
12
|
+
|
|
13
|
+
### 新增
|
|
14
|
+
|
|
15
|
+
- **统一类型化故障契约(`src/faults.ts`)**:在核心 I/O(`src/operations.ts`)、编辑诊断(`src/edit/diagnostics.ts`)与 MCP 服务(`src/mcp/server.ts`)全链路落地 `CharsetFault` / `FaultMetadata`(`code`、`category`、`phase`、`outcome`、`retryable`、`actionHint`),确保所有失败分支均返回稳定结构化错误信封(`status: "failed"`、`error`、`applied`、`verified`、`committed`、`outcome`、`actionHint`),彻底消除从人类文本反推错误码。
|
|
16
|
+
- **隐私优先本地诊断记录器(`src/diagnostics/incidents.ts`)与 `pi-charset feedback`**:集成零联网、有界内存与磁盘配额的纯白名单本地故障记录器(严禁记录源码、路径、原始异常文本、提示词或凭据;自动忽略正常安全拒绝;支持独立 OS 进程跨进程去重、每日槽位上限、14 天留存清理、篡改指纹校验及无 hardlink 文件系统安全回退;设 `PI_CHARSET_DIAGNOSTICS=0` 可彻底关闭),并在 CLI 新增 `pi-charset feedback list | preview <指纹> | issue-url <指纹> | prune | clear`。
|
|
17
|
+
- **Host Adapter Registry 与真正的一键 `pi-charset setup`(`src/setup/adapters.ts`)**:为 Codex(`~/.codex/config.toml`)、Antigravity(`~/.gemini/config/mcp_config.json`)、Claude Code 与 Cursor 提供幂等、原子、无损的 `setup` / `--dry-run` / `--uninstall` / `--rollback`,写入永久绝对路径的 `node` + `pi-charset-mcp.mjs` 入口(完整保留第三方 MCP 配置,遇非法 JSON 拒绝覆盖),并在隔离临时目录执行合成 GBK+CRLF `read`/`edit`/`undo` 端到端自检。
|
|
18
|
+
- **升级 `pi-charset doctor --json` / `--fix` 与 AGY 选择性 `_meta`**:`doctor --json` 输出稳定的机器可读诊断状态(严格区分 `not_installed` / `unregistered` / `registered` / `handshake_verified` / `degraded` 与真实防护边界);`doctor --fix` 仅安全修复 `pi-charset` 自有失效条目,绝不触碰用户源码或自定义钩子;在 3 个高频核心 MCP 工具(`charset_read`、`charset_edit`、`charset_grep`)上选择性标记 `_meta: { "antigravity/alwaysLoad": true }`。
|
|
19
|
+
- **独立多进程并发与全套硬化回归测试**:新增双独立 OS 进程 `pi-charset-mcp` 并发 `expectedVersion` 验证、中文/空格/括号/方括号复杂路径测试、隐私与跨进程去重测试以及隔离 `HOME` 安装/回滚/卸载测试(`test/diagnostics-incidents.test.ts`、`test/setup-adapters.test.ts`、`test/cross-process-and-faults.test.ts`)。
|
|
20
|
+
|
|
11
21
|
## [0.1.7] - 2026-12-06
|
|
12
22
|
|
|
13
23
|
### 修复
|
|
@@ -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
|
+
}
|
package/dist/edit/diagnostics.js
CHANGED
|
@@ -1,3 +1,19 @@
|
|
|
1
|
+
const EDIT_ERROR_MAP = {
|
|
2
|
+
INVALID_INPUT: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Fix the edit input parameters and retry." },
|
|
3
|
+
NOT_FOUND: { code: "NOT_FOUND", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read the file with charset_read to confirm target text or path." },
|
|
4
|
+
AMBIGUOUS_MATCH: { code: "CONFLICT", category: "conflict", phase: "validate", retryable: true, actionHint: "Provide more context or use hashlines anchors for an exact match." },
|
|
5
|
+
OVERLAPPING_EDITS: { code: "INVALID_INPUT", category: "input", phase: "validate", retryable: false, actionHint: "Make edit ranges disjoint and retry." },
|
|
6
|
+
HASH_MISMATCH: { code: "STALE_VERSION", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read the file with hashlines=true and use the updated anchors." },
|
|
7
|
+
UNSUPPORTED_FILE: { code: "UNSUPPORTED_FILE", category: "policy", phase: "detect", retryable: false, actionHint: "Inspect the file with charset_check; symlinks, hardlinks, read-only, and binary files are refused." },
|
|
8
|
+
UNENCODABLE: { code: "UNMAPPABLE", category: "policy", phase: "encode", retryable: false, actionHint: "Replace unmappable characters or convert the file encoding explicitly via charset_fix." },
|
|
9
|
+
AMBIGUOUS_ENCODING: { code: "AMBIGUOUS_ENCODING", category: "policy", phase: "detect", retryable: false, actionHint: "Inspect with charset_check and declare the intended encoding before non-ASCII writes." },
|
|
10
|
+
STALE_READ: { code: "STALE_VERSION", category: "conflict", phase: "validate", retryable: true, actionHint: "Re-read using charset_read, then rebuild the edit with the latest version." },
|
|
11
|
+
STALE_PLAN: { code: "CONFLICT", category: "conflict", phase: "commit", retryable: true, actionHint: "Re-read using charset_read and retry the edit against the current file state." },
|
|
12
|
+
CANCELLED: { code: "CANCELLED", category: "io", phase: "commit", retryable: true, actionHint: "Retry if the cancellation was unintentional." },
|
|
13
|
+
TEMP_WRITE_FAILED: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: true, actionHint: "Check directory permissions and free disk space, then retry." },
|
|
14
|
+
VERIFY_FAILED: { code: "WRITE_VERIFY_FAILED", category: "engine", phase: "verify", retryable: false, actionHint: "Re-read the file to inspect on-disk state before retrying; use charset_fix(action='undo') if needed." },
|
|
15
|
+
COMMIT_UNKNOWN: { code: "WRITE_FAILED", category: "io", phase: "commit", retryable: false, actionHint: "Re-read the file to confirm on-disk state before retrying." },
|
|
16
|
+
};
|
|
1
17
|
export class EditError extends Error {
|
|
2
18
|
code;
|
|
3
19
|
commitState;
|
|
@@ -7,6 +23,17 @@ export class EditError extends Error {
|
|
|
7
23
|
this.commitState = commitState;
|
|
8
24
|
this.name = "EditError";
|
|
9
25
|
}
|
|
26
|
+
toFaultMetadata() {
|
|
27
|
+
const base = EDIT_ERROR_MAP[this.code];
|
|
28
|
+
const outcome = this.commitState === "not_applied" ? "not_applied" : "uncertain";
|
|
29
|
+
return {
|
|
30
|
+
...base,
|
|
31
|
+
outcome,
|
|
32
|
+
applied: false,
|
|
33
|
+
verified: false,
|
|
34
|
+
committed: false,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
10
37
|
}
|
|
11
38
|
export function lineAt(text, offset) {
|
|
12
39
|
let count = 1;
|
package/dist/faults.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Canonical typed fault contract shared across core I/O, edit/patch engines, grep, CLI, and MCP.
|
|
2
|
+
// Error classification always originates from typed codes at the source — never parsed from human-readable text.
|
|
3
|
+
export const REPORTABLE_FAULT_CODES = new Set([
|
|
4
|
+
"WRITE_VERIFY_FAILED",
|
|
5
|
+
"ROLLBACK_FAILED",
|
|
6
|
+
"BYTE_INVARIANT_FAILED",
|
|
7
|
+
"MCP_PROTOCOL_ERROR",
|
|
8
|
+
"CLIENT_STARTUP_FAILED",
|
|
9
|
+
"TOOL_BYPASS_DETECTED",
|
|
10
|
+
"LOCK_INVARIANT_FAILED",
|
|
11
|
+
"GIT_INDEX_INVARIANT_FAILED",
|
|
12
|
+
"SEARCH_ENGINE_FAILED",
|
|
13
|
+
"INTERNAL",
|
|
14
|
+
]);
|
|
15
|
+
export class CharsetFault extends Error {
|
|
16
|
+
fault;
|
|
17
|
+
constructor(message, fault) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = "CharsetFault";
|
|
20
|
+
this.fault = Object.freeze({ ...fault });
|
|
21
|
+
}
|
|
22
|
+
get code() {
|
|
23
|
+
return this.fault.code;
|
|
24
|
+
}
|
|
25
|
+
get outcome() {
|
|
26
|
+
return this.fault.outcome;
|
|
27
|
+
}
|
|
28
|
+
get reportable() {
|
|
29
|
+
return REPORTABLE_FAULT_CODES.has(this.fault.code);
|
|
30
|
+
}
|
|
31
|
+
toMcpEnvelope() {
|
|
32
|
+
const f = this.fault;
|
|
33
|
+
return {
|
|
34
|
+
status: "failed",
|
|
35
|
+
error: {
|
|
36
|
+
code: f.code,
|
|
37
|
+
category: f.category,
|
|
38
|
+
phase: f.phase,
|
|
39
|
+
retryable: f.retryable,
|
|
40
|
+
},
|
|
41
|
+
applied: f.applied ?? false,
|
|
42
|
+
verified: f.verified ?? false,
|
|
43
|
+
committed: f.committed ?? false,
|
|
44
|
+
outcome: f.outcome,
|
|
45
|
+
actionHint: f.actionHint,
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function isCharsetFault(err) {
|
|
50
|
+
return err instanceof CharsetFault;
|
|
51
|
+
}
|
|
52
|
+
export function toMcpErrorEnvelope(fault) {
|
|
53
|
+
return {
|
|
54
|
+
status: "failed",
|
|
55
|
+
error: {
|
|
56
|
+
code: fault.code,
|
|
57
|
+
category: fault.category,
|
|
58
|
+
phase: fault.phase,
|
|
59
|
+
retryable: fault.retryable,
|
|
60
|
+
},
|
|
61
|
+
applied: fault.applied ?? false,
|
|
62
|
+
verified: fault.verified ?? false,
|
|
63
|
+
committed: fault.committed ?? false,
|
|
64
|
+
outcome: fault.outcome,
|
|
65
|
+
actionHint: fault.actionHint,
|
|
66
|
+
};
|
|
67
|
+
}
|