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.
@@ -30,7 +30,7 @@ function readPackageVersion() {
30
30
  async function loadCore() {
31
31
  const distClassify = path.join(DIST_ROOT, "encoding", "classify.js");
32
32
  if (fs.existsSync(distClassify)) {
33
- const [configMod, classifyMod, convMod, eolMod, maintMod, grepMod, verMod] = await Promise.all([
33
+ const [configMod, classifyMod, convMod, eolMod, maintMod, grepMod, verMod, diagMod, setupMod] = await Promise.all([
34
34
  import(pathToFileURL(path.join(DIST_ROOT, "config.js")).href),
35
35
  import(pathToFileURL(distClassify).href),
36
36
  import(pathToFileURL(path.join(DIST_ROOT, "encoding", "converter.js")).href),
@@ -38,8 +38,10 @@ async function loadCore() {
38
38
  import(pathToFileURL(path.join(DIST_ROOT, "maintenance.js")).href),
39
39
  import(pathToFileURL(path.join(DIST_ROOT, "grep-core.js")).href),
40
40
  import(pathToFileURL(path.join(DIST_ROOT, "version.js")).href),
41
+ import(pathToFileURL(path.join(DIST_ROOT, "diagnostics", "incidents.js")).href),
42
+ import(pathToFileURL(path.join(DIST_ROOT, "setup", "adapters.js")).href),
41
43
  ]);
42
- return { runtimeMode: "dist", ...configMod, ...classifyMod, ...convMod, ...eolMod, ...maintMod, ...grepMod, ...verMod };
44
+ return { runtimeMode: "dist", ...configMod, ...classifyMod, ...convMod, ...eolMod, ...maintMod, ...grepMod, ...verMod, ...diagMod, ...setupMod };
43
45
  }
44
46
  if (!ROOT.split(path.sep).includes("node_modules") && fs.existsSync(path.join(SRC_ROOT, "config.ts"))) {
45
47
  const { registerHooks } = await import("node:module");
@@ -57,7 +59,7 @@ async function loadCore() {
57
59
  return nextResolve(specifier, context);
58
60
  },
59
61
  });
60
- const [configMod, classifyMod, convMod, eolMod, maintMod, grepMod, verMod] = await Promise.all([
62
+ const [configMod, classifyMod, convMod, eolMod, maintMod, grepMod, verMod, diagMod, setupMod] = await Promise.all([
61
63
  import(pathToFileURL(path.join(SRC_ROOT, "config.ts")).href),
62
64
  import(pathToFileURL(path.join(SRC_ROOT, "encoding", "classify.ts")).href),
63
65
  import(pathToFileURL(path.join(SRC_ROOT, "encoding", "converter.ts")).href),
@@ -65,8 +67,10 @@ async function loadCore() {
65
67
  import(pathToFileURL(path.join(SRC_ROOT, "maintenance.ts")).href),
66
68
  import(pathToFileURL(path.join(SRC_ROOT, "grep-core.ts")).href),
67
69
  import(pathToFileURL(path.join(SRC_ROOT, "version.ts")).href),
70
+ import(pathToFileURL(path.join(SRC_ROOT, "diagnostics", "incidents.ts")).href),
71
+ import(pathToFileURL(path.join(SRC_ROOT, "setup", "adapters.ts")).href),
68
72
  ]);
69
- return { runtimeMode: "src-dev", ...configMod, ...classifyMod, ...convMod, ...eolMod, ...maintMod, ...grepMod, ...verMod };
73
+ return { runtimeMode: "src-dev", ...configMod, ...classifyMod, ...convMod, ...eolMod, ...maintMod, ...grepMod, ...verMod, ...diagMod, ...setupMod };
70
74
  }
71
75
  console.error(`[pi-charset] Compiled runtime missing at ${distClassify}. Run "npm run build" or reinstall pi-charset.`);
72
76
  process.exit(1);
@@ -569,48 +573,248 @@ function runMcpConfig(args) {
569
573
  process.exit(0);
570
574
  }
571
575
 
576
+ async function runSetupCmd(args, core) {
577
+ let dryRun = false;
578
+ let uninstall = false;
579
+ let rollback = false;
580
+ let jsonOut = false;
581
+ let preferLegacy = false;
582
+ let hashlines = false;
583
+ let autoCommit = false;
584
+ let encoding;
585
+ let eol;
586
+ let clients;
587
+ const ALLOWED_CLIENTS = new Set(["pi", "codex", "agy", "antigravity", "claude", "cursor"]);
588
+
589
+ for (let i = 0; i < args.length; i++) {
590
+ const a = args[i];
591
+ if (a === "--help" || a === "-h") {
592
+ console.log(
593
+ [
594
+ "Usage: pi-charset setup [options]",
595
+ "Idempotently register permanent absolute node + pi-charset-mcp entrypoints across detected clients (Codex, Antigravity, Claude, Cursor).",
596
+ "Options:",
597
+ " --clients <list> Comma-separated clients (codex,agy,claude,cursor,pi)",
598
+ " --dry-run Preview planned changes without writing any files",
599
+ " --uninstall Remove ONLY pi-charset entries (preserves third-party MCPs & settings)",
600
+ " --rollback Restore prior pi-charset config snapshot from local backup",
601
+ " --encoding <enc> Optional default encoding flag for registered MCP servers",
602
+ " --eol <CRLF|LF> Optional default new-file EOL flag",
603
+ " --prefer-legacy Pass --prefer-legacy to registered MCP servers",
604
+ " --hashlines Pass --hashlines to registered MCP servers",
605
+ " --auto-commit Pass --auto-commit to registered MCP servers",
606
+ " --json Emit machine-readable JSON summary",
607
+ ].join("\n"),
608
+ );
609
+ process.exit(0);
610
+ } else if (a === "--dry-run") dryRun = true;
611
+ else if (a === "--uninstall") uninstall = true;
612
+ else if (a === "--rollback") rollback = true;
613
+ else if (a === "--json") jsonOut = true;
614
+ else if (a === "--prefer-legacy") preferLegacy = true;
615
+ else if (a === "--hashlines") hashlines = true;
616
+ else if (a === "--auto-commit") autoCommit = true;
617
+ else if (a === "--encoding") { encoding = requireVal(args, a, i); i++; }
618
+ else if (a === "--eol") {
619
+ const v = requireVal(args, a, i).toUpperCase();
620
+ i++;
621
+ if (v !== "CRLF" && v !== "LF") failArg(`Invalid --eol "${v}". Expected CRLF or LF.`);
622
+ eol = v;
623
+ } else if (a === "--clients") {
624
+ const raw = requireVal(args, a, i).split(",").map((s) => s.trim().toLowerCase()).filter(Boolean);
625
+ i++;
626
+ for (const c of raw) {
627
+ if (!ALLOWED_CLIENTS.has(c)) failArg(`Unknown client "${c}". Use pi, codex, agy, claude, or cursor.`);
628
+ }
629
+ clients = [...new Set(raw.map((c) => (c === "antigravity" ? "agy" : c)))];
630
+ } else {
631
+ failArg(`Unknown option for setup: ${a}`);
632
+ }
633
+ }
634
+
635
+ const mcpEntryPath = path.join(HERE, "pi-charset-mcp.mjs");
636
+ const out = core.runSetup({
637
+ clients,
638
+ dryRun,
639
+ uninstall,
640
+ rollback,
641
+ encoding,
642
+ eol,
643
+ preferLegacy,
644
+ hashlines,
645
+ autoCommit,
646
+ mcpEntryPath,
647
+ });
648
+
649
+ if (jsonOut) {
650
+ console.log(JSON.stringify(out, null, 2));
651
+ process.exit(out.ok ? 0 : 1);
652
+ }
653
+
654
+ console.log(`pi-charset setup (v${core.PLUGIN_VERSION}, Node ${out.node.current})`);
655
+ if (out.results.length === 0) {
656
+ console.log(" No supported MCP client config directories auto-detected.");
657
+ console.log(" Pass --clients codex,agy,claude,cursor to register explicitly.");
658
+ } else {
659
+ for (const r of out.results) {
660
+ console.log(` ${r.label.padEnd(18)} ${r.status.padEnd(19)} (${r.action}) — ${r.detail}`);
661
+ }
662
+ }
663
+ if (out.smoke) {
664
+ console.log(` ${"GBK self-test".padEnd(18)} ${out.smoke.ok ? "verified" : "FAILED"} — ${out.smoke.detail}`);
665
+ }
666
+ console.log(` ${"Protection".padEnd(18)} MCP guarded; native tool calls require host rules/hooks or pre-commit gate`);
667
+ console.log(` ${"Diagnostics".padEnd(18)} local only; no upload`);
668
+ process.exit(out.ok ? 0 : 1);
669
+ }
670
+
572
671
  async function runDoctor(args, core) {
573
- if (args.includes("--help") || args.includes("-h")) {
574
- console.log("Usage: pi-charset doctor [dir]");
575
- process.exit(0);
672
+ let jsonOut = false;
673
+ let fix = false;
674
+ let targetArg = ".";
675
+ for (let i = 0; i < args.length; i++) {
676
+ const a = args[i];
677
+ if (a === "--help" || a === "-h") {
678
+ console.log("Usage: pi-charset doctor [dir] [--json] [--fix]");
679
+ process.exit(0);
680
+ } else if (a === "--json") jsonOut = true;
681
+ else if (a === "--fix") fix = true;
682
+ else if (!a.startsWith("-")) targetArg = a;
683
+ else failArg(`Unknown option for doctor: ${a}`);
684
+ }
685
+
686
+ const targetDir = path.resolve(process.cwd(), targetArg);
687
+ const nodeReq = core.checkNodeRequirement();
688
+ const mcpEntryPath = path.join(HERE, "pi-charset-mcp.mjs");
689
+ let repaired = [];
690
+ if (fix) {
691
+ repaired = core.repairDegradedRegistrations({ mcpEntryPath });
576
692
  }
577
- const targetDir = path.resolve(process.cwd(), args.find((a) => !a.startsWith("-")) || ".");
578
693
  const found = await core.findNearestConfig(targetDir);
579
694
  const rg = await core.findRgAsync();
580
695
  const hints = core.detectProjectHints(found?.configDir ?? targetDir);
581
- let gitInfo = "not a git repository";
696
+ const clients = core.inspectClients();
697
+ const smoke = core.verifyMcpSmoke(process.execPath, mcpEntryPath);
698
+ const recorder = core.getIncidentRecorder("generic");
699
+ const incidents = await recorder.list();
700
+
701
+ let gitHook = { inGitRepo: false, hooksDir: null, customHooksPath: null, preCommitState: "not_applicable" };
582
702
  try {
583
703
  const { hooksDir, customHooksPath } = resolveEffectiveHooksDir(targetDir);
584
704
  const hookFile = path.join(hooksDir, "pre-commit");
585
- const hookState = fs.existsSync(hookFile)
586
- ? (fs.readFileSync(hookFile, "utf8").includes("# pi-charset-managed-hook") ? "installed (pi-charset managed)" : "present (custom hook)")
587
- : "not installed";
588
- gitInfo = `hooksDir=${hooksDir}${customHooksPath ? ` (core.hooksPath=${customHooksPath})` : ""} | pre-commit: ${hookState}`;
705
+ const preCommitState = fs.existsSync(hookFile)
706
+ ? (fs.readFileSync(hookFile, "utf8").includes("# pi-charset-managed-hook") ? "enforced_managed" : "custom_hook")
707
+ : "not_installed";
708
+ gitHook = { inGitRepo: true, hooksDir, customHooksPath, preCommitState };
589
709
  } catch { /* not a git repo */ }
590
710
 
711
+ const payload = {
712
+ version: core.PLUGIN_VERSION,
713
+ node: nodeReq.current,
714
+ nodeSupported: nodeReq.ok,
715
+ runtimeMode: core.runtimeMode,
716
+ workspace: targetDir,
717
+ config: found ? (found.configPath ?? path.join(found.configDir, CONFIG_NAME)) : null,
718
+ ripgrep: rg,
719
+ gitHook,
720
+ projectHints: hints,
721
+ mcpSmoke: smoke,
722
+ clients: clients.map((c) => ({
723
+ ...c,
724
+ status: c.status === "registered" && smoke.ok ? "handshake_verified" : c.status,
725
+ })),
726
+ repaired,
727
+ diagnostics: {
728
+ enabled: recorder.enabled,
729
+ stateRoot: recorder.root,
730
+ incidentCount: incidents.length,
731
+ networkUpload: false,
732
+ },
733
+ protectionSummary:
734
+ gitHook.preCommitState === "enforced_managed"
735
+ ? "MCP registered + Git pre-commit staged-blob gate active"
736
+ : "MCP only (native client tools require host rules/hooks or `pi-charset install-hook`)",
737
+ };
738
+
739
+ if (jsonOut) {
740
+ console.log(JSON.stringify(payload, null, 2));
741
+ process.exit(nodeReq.ok && smoke.ok ? 0 : 1);
742
+ }
743
+
591
744
  console.log(
592
745
  [
593
- `pi-charset v${core.PLUGIN_VERSION} (Node ${process.version}, runtime=${core.runtimeMode})`,
594
- `Workspace: ${targetDir}`,
595
- `Config: ${found ? (found.configPath ?? path.join(found.configDir, CONFIG_NAME)) : "zero-config adaptive mode"}`,
596
- `ripgrep (rg): ${rg ?? "NOT FOUND (grep will fail or fall back)"}`,
597
- `Git hook: ${gitInfo}`,
598
- `Project hints: ${hints.length ? hints.map((h) => `${h.source}(${h.detail})`).join("; ") : "none"}`,
746
+ `pi-charset v${payload.version} (Node ${payload.node} [${payload.nodeSupported ? "OK" : `requires ${nodeReq.required}`}], runtime=${payload.runtimeMode})`,
747
+ `Workspace: ${payload.workspace}`,
748
+ `Config: ${payload.config ?? "zero-config adaptive mode"}`,
749
+ `ripgrep: ${payload.ripgrep ?? "NOT FOUND (grep will fail or fall back)"}`,
750
+ `MCP smoke: ${smoke.ok ? `OK — ${smoke.detail}` : `FAILED — ${smoke.detail}`}`,
751
+ `Git hook: ${gitHook.inGitRepo ? `${gitHook.hooksDir}${gitHook.customHooksPath ? ` (core.hooksPath=${gitHook.customHooksPath})` : ""} [${gitHook.preCommitState}]` : "not a git repository"}`,
752
+ `Clients:`,
753
+ ...payload.clients.map((c) => ` - ${c.label.padEnd(16)} ${c.status.padEnd(19)} ${c.detail}`),
754
+ ...(repaired.length ? [`Repaired:`, ...repaired.map((r) => ` - ${r.label}: ${r.action} (${r.detail})`)] : []),
755
+ `Diagnostics: ${payload.diagnostics.enabled ? `local only (${payload.diagnostics.incidentCount} record(s) at ${payload.diagnostics.stateRoot})` : "disabled"}`,
756
+ `Protection: ${payload.protectionSummary}`,
757
+ `Hints: ${hints.length ? hints.map((h) => `${h.source}(${h.detail})`).join("; ") : "none"}`,
599
758
  ].join("\n"),
600
759
  );
601
- process.exit(0);
760
+ process.exit(nodeReq.ok && smoke.ok ? 0 : 1);
761
+ }
762
+
763
+ async function runFeedbackCmd(args, core) {
764
+ const [sub = "help", arg] = args;
765
+ const recorder = core.getIncidentRecorder("generic");
766
+ if (sub === "list") {
767
+ console.log(JSON.stringify(await recorder.list(), null, 2));
768
+ process.exit(0);
769
+ }
770
+ if (sub === "preview" || sub === "issue-url") {
771
+ if (!/^[a-f0-9]{32}$/.test(arg ?? "")) {
772
+ failArg(`Usage: pi-charset feedback ${sub} <32-hex-fingerprint>`);
773
+ }
774
+ const item = (await recorder.list()).find((x) => x.report.fingerprint === arg);
775
+ if (!item) {
776
+ console.error(`[pi-charset feedback] No matching local diagnostic for fingerprint ${arg}.`);
777
+ process.exit(1);
778
+ }
779
+ if (sub === "preview") {
780
+ const draft = core.issueDraft(item.report);
781
+ console.log(`# ${draft.title}\n\n${draft.body}`);
782
+ } else {
783
+ console.log(core.buildIssueUrl(item.report));
784
+ }
785
+ process.exit(0);
786
+ }
787
+ if (sub === "prune") {
788
+ await recorder.prune();
789
+ console.log("[pi-charset feedback] Expired diagnostic records pruned (local only).");
790
+ process.exit(0);
791
+ }
792
+ if (sub === "clear") {
793
+ const n = await recorder.clear();
794
+ console.log(`[pi-charset feedback] Cleared ${n} local diagnostic record(s).`);
795
+ process.exit(0);
796
+ }
797
+ console.log(
798
+ [
799
+ "Usage: pi-charset feedback <list | preview <fingerprint> | issue-url <fingerprint> | prune | clear>",
800
+ "Local only — never sends network requests, opens browsers, or includes source code/paths/secrets.",
801
+ ].join("\n"),
802
+ );
803
+ process.exit(sub === "help" || sub === "--help" || sub === "-h" ? 0 : 2);
602
804
  }
603
805
 
604
806
  const [cmd, ...rest] = process.argv.slice(2);
605
807
  if (!cmd || cmd === "--help" || cmd === "-h") {
606
808
  console.log([
607
- `pi-charset v${readPackageVersion()} — encoding governance, pre-commit hook, doctor & MCP setup`,
809
+ `pi-charset v${readPackageVersion()} — encoding governance, one-command setup, pre-commit hook, doctor & local diagnostics`,
608
810
  "Usage:",
811
+ " pi-charset setup [--clients codex,agy,claude,cursor] [--dry-run] [--uninstall] [--rollback] [--json]",
812
+ " pi-charset doctor [dir] [--json] [--fix]",
609
813
  " pi-charset check [--staged | --diff <ref> | <paths...>] [--encoding <enc>] [--eol CRLF|LF] [--prefer-legacy] [--strict-eol] [--json]",
610
814
  " pi-charset install-hook [--encoding <enc>] [--eol CRLF|LF] [--prefer-legacy] [--strict-eol] [--force]",
611
815
  " pi-charset mcp-config [--client codex|antigravity|cursor|windsurf|claude|generic] [--local] [--cwd <dir>] [...]",
816
+ " pi-charset feedback <list | preview <fp> | issue-url <fp> | prune | clear>",
612
817
  " pi-charset explain <file>",
613
- " pi-charset doctor [dir]",
614
818
  " pi-charset scan [dir] [--init [--force]] [--dry-run] [--damaged] [--list-unknown]",
615
819
  " pi-charset hints [dir]",
616
820
  " pi-charset --version",
@@ -630,12 +834,18 @@ else if (cmd === "scan") {
630
834
  } catch (e) {
631
835
  process.exit(e.status ?? 1);
632
836
  }
837
+ } else if (cmd === "setup") {
838
+ const core = await loadCore();
839
+ await runSetupCmd(rest, core);
633
840
  } else if (cmd === "check") {
634
841
  const core = await loadCore();
635
842
  await runCheck(rest, core);
636
843
  } else if (cmd === "doctor") {
637
844
  const core = await loadCore();
638
845
  await runDoctor(rest, core);
846
+ } else if (cmd === "feedback") {
847
+ const core = await loadCore();
848
+ await runFeedbackCmd(rest, core);
639
849
  } else if (cmd === "explain") {
640
850
  if (rest.includes("--help") || rest.includes("-h") || rest.length === 0) {
641
851
  console.log("Usage: pi-charset explain <file>");
@@ -25,6 +25,7 @@ function failArg(msg) {
25
25
 
26
26
  const argv = process.argv.slice(2);
27
27
  let cwd = process.cwd();
28
+ let clientName;
28
29
  const rawEnvEol = (process.env.PI_CHARSET_EOL ?? "").trim();
29
30
  if (rawEnvEol && !/^(CRLF|LF)$/i.test(rawEnvEol)) {
30
31
  failArg(`Invalid PI_CHARSET_EOL="${rawEnvEol}". Expected CRLF or LF.`);
@@ -77,6 +78,7 @@ for (let i = 0; i < argv.length; i++) {
77
78
  process.exit(0);
78
79
  }
79
80
  if (a === "--cwd") { cwd = path.resolve(requireValue(a, i)); i++; }
81
+ else if (a === "--client") { clientName = requireValue(a, i); i++; }
80
82
  else if (a === "--encoding") { defaults.sourceEncoding = requireValue(a, i); i++; }
81
83
  else if (a === "--write-encoding") { defaults.writeEncoding = requireValue(a, i); i++; }
82
84
  else if (a === "--eol") {
@@ -137,4 +139,4 @@ if (fs.existsSync(distServer) && fs.existsSync(distConfig)) {
137
139
  }
138
140
 
139
141
  setRuntimeDefaults(defaults);
140
- startMcpStdioServer(cwd);
142
+ startMcpStdioServer(cwd, clientName ? { client: clientName } : undefined);