Repository navigation
Expand file tree
/
Copy pathnexon_code.cpp
More file actions
4265 lines (4114 loc) · 207 KB
/
Copy pathnexon_code.cpp
File metadata and controls
4265 lines (4114 loc) · 207 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// nexon_code.cpp - TOKEN-EFFICIENT, ROBUST version
// Fixes: raw-mode tty, ANSI UI, per-tool timeouts, edit offset tracking,
// clear error locations, no spurious post-result output, binary detect,
// large-paste safety, multi-patch line drift fully correct.
//
// Build: g++ -O2 -std=c++17 nexon_code.cpp -o nexon_code
// Use: ./nexon_code /path/to/project # interactive
// ./nexon_code /path/to/project < req.json # piped (recommended for LLMs)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <filesystem>
#include <regex>
#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <cctype>
#include <cstring>
#include <cerrno>
#include <csignal>
#include <algorithm>
#include <chrono>
#include <array>
#include <stdexcept>
#include <map>
#include <set>
#include <termios.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <fcntl.h>
namespace fs = std::filesystem;
// ===========================================================================
// ANSI color helpers (auto-disabled when output is not a tty)
// ===========================================================================
static bool g_colorOut = false;
static bool g_colorIn = false;
static bool g_plainMode = false; // --plain / TOOLS_PLAIN / NO_COLOR: no ANSI, no box-drawing decoration
static size_t g_maxOutputChars = 0; // --max-output=N / TOOLS_MAX_OUTPUT: 0 = unlimited
#include <sys/ioctl.h>
#include <unistd.h>
#include <cstdlib>
static size_t g_maxInputBytes = 64 * 1024 * 1024; // --max-input=N / TOOLS_MAX_INPUT: cap on one pasted/piped JSON payload
// --- Multi-workspace registry ------------------------------------------------
// Up to a handful of registered project roots. Empty means classic
// single-root mode: every consumer below falls back to the baseDir it was
// handed, so single-root behavior is identical to before this existed.
// Populated at startup (1-3 dirs) and by the add_dir tool mid-session.
static std::vector<fs::path> g_roots;
// Which registered root owns this user-supplied path? Absolute path: the
// root that contains it. Relative path: the first root where <root>/<rel>
// actually exists. Fallback is the passed-in baseDir so single-root callers
// always get a usable root back.
static fs::path rootFor(const fs::path& baseDir, const std::string& relPath) {
std::vector<fs::path> roots;
if (g_roots.empty()) roots.push_back(baseDir);
else roots = g_roots;
fs::path rp(relPath);
std::error_code ec;
if (rp.is_absolute()) {
fs::path nc = fs::weakly_canonical(rp, ec);
if (ec) nc = rp.lexically_normal();
for (auto& r : roots) {
fs::path nb = fs::weakly_canonical(r, ec);
if (ec) nb = r.lexically_normal();
auto bi = nb.begin(), be = nb.end();
auto ci = nc.begin(), ce = nc.end();
bool under = true;
for (; bi != be; ++bi, ++ci) if (ci == ce || *ci != *bi) { under = false; break; }
if (under) return r;
}
return baseDir;
}
for (auto& r : roots) if (fs::exists(r / rp, ec)) return r;
return baseDir;
}
// True if canon (already canonicalized) is baseDir itself or one of the
// registered extra roots — validates the optional 'dir' argument that
// sh/git/diagnostics accept to pick their working directory.
static bool isRegisteredRoot(const fs::path& baseDir, const fs::path& canon) {
std::error_code ec;
fs::path nb = fs::weakly_canonical(baseDir, ec);
if (ec) nb = baseDir.lexically_normal();
if (nb == canon) return true;
for (auto& r : g_roots) {
fs::path nr = fs::weakly_canonical(r, ec);
if (ec) nr = r.lexically_normal();
if (nr == canon) return true;
}
return false;
}
struct C { const char* s; };
static const C RST {"\033[0m"};
static const C BOLD {"\033[1m"};
static const C RED {"\033[31m"};
static const C GRN {"\033[32m"};
static const C YEL {"\033[33m"};
static const C MAG {"\033[35m"};
static const C CYN {"\033[36m"};
static const C BG_CYAN {"\033[46;30m"};
static const C BG_GRN {"\033[42;30m"};
static const C BG_RED {"\033[41;37m"};
static const C DIM {"\033[2m"};
static std::ostream& operator<<(std::ostream& os, const C& c) {
if ((&os == &std::cout && g_colorOut) || (&os == &std::cerr && g_colorOut))
os << c.s;
return os;
}
static fs::path g_primary; // primary workspace, for the TUI status line
static long g_statCalls = 0; // session tool-call counter
static std::string g_lastTool; // last tool name, for the status line
static long g_lastMs = 0;
// ---- TUI helpers ------------------------------------------------------
static int termWidth() {
struct winsize ws;
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0) return (int)ws.ws_col;
return 80;
}
static std::string tuiHLine(size_t n) {
std::string s;
s.reserve(n * 3);
for (size_t i = 0; i < n; ++i) s += "─";
return s;
}
static std::string tuiCenter(const std::string& text, int width) {
if ((int)text.size() >= width) return text;
return std::string((size_t)((width - (int)text.size()) / 2), ' ') + text;
}
static void tuiSep() {
std::cout << std::string((size_t)termWidth(), '-') << "\n";
}
static void tuiPrompt() {
std::string label = g_primary.empty() ? std::string("?") : g_primary.filename().string();
std::cout << DIM << label << " · calls: " << g_statCalls;
if (g_statCalls > 0) std::cout << " · last: " << g_lastTool << " (" << g_lastMs << "ms)";
std::cout << RST << "\n";
std::cout << BOLD << CYN << "❯ " << RST;
std::cout.flush();
}
static void tuiHeaderBox() {
int w = termWidth();
if (w > 60) w = 60;
if (w < 40) w = 40;
const size_t iw = (size_t)w - 2;
std::cout << CYN << "┌" << tuiHLine(iw) << "┐" << RST << "\n";
const char* rows[3] = {
"nexon_code - local multi-tool bridge for LLMs",
"no API keys - no subscriptions",
"paste is all you need",
};
for (const char* r : rows) {
std::string t = " " + std::string(r);
if (t.size() > iw) t = t.substr(0, iw);
t += std::string(iw - t.size(), ' ');
std::cout << CYN << "│" << RST << t << CYN << "│" << RST << "\n";
}
std::cout << CYN << "└" << tuiHLine(iw) << "┘" << RST << "\n";
}
static void printTuiBanner() {
if (g_colorOut) std::cout << "\033[2J\033[H";
tuiHeaderBox();
int w = termWidth();
std::cout << "\n" << BOLD << tuiCenter("What can I do for you?", w) << RST << "\n";
std::cout << tuiCenter("paste JSON - runs when braces balance", w) << "\n";
std::cout << tuiCenter("'help' for tools - 'exit' to quit", w) << "\n";
}
// ===========================================================================
// Minimal JSON value type
// ===========================================================================
struct Json {
enum class Type { Null, Bool, Number, String, Array, Object };
Type type = Type::Null;
bool b = false;
double num = 0;
std::string str;
std::vector<Json> arr;
std::vector<std::pair<std::string, Json>> obj;
static Json Null_() { return Json(); }
static Json Bool(bool v) { Json j; j.type = Type::Bool; j.b = v; return j; }
static Json Num(double v) { Json j; j.type = Type::Number; j.num = v; return j; }
static Json Str(std::string v) { Json j; j.type = Type::String; j.str = std::move(v); return j; }
static Json Arr() { Json j; j.type = Type::Array; return j; }
static Json Obj() { Json j; j.type = Type::Object; return j; }
void set(const std::string& k, Json v) {
for (auto& p : obj) if (p.first == k) { p.second = std::move(v); return; }
obj.emplace_back(k, std::move(v));
}
const Json* get(const std::string& k) const {
for (auto& p : obj) if (p.first == k) return &p.second;
return nullptr;
}
std::string getStr2(const std::string& a, const std::string& b, const std::string& def = "") const {
auto p = get(a); if (!p) p = get(b);
return (p && p->type == Type::String) ? p->str : def;
}
long getInt2(const std::string& a, const std::string& b, long def = 0) const {
auto p = get(a); if (!p) p = get(b);
return (p && p->type == Type::Number) ? (long)p->num : def;
}
bool getBool2(const std::string& a, const std::string& b, bool def = false) const {
auto p = get(a); if (!p) p = get(b);
return (p && p->type == Type::Bool) ? p->b : def;
}
const std::vector<Json>* getArr2(const std::string& a, const std::string& b) const {
auto p = get(a); if (!p) p = get(b);
return (p && p->type == Type::Array) ? &p->arr : nullptr;
}
static Json parse(const std::string& text, std::string* err = nullptr);
std::string dump() const;
};
struct JsonParser {
const std::string& s;
size_t i = 0;
explicit JsonParser(const std::string& s_) : s(s_) {}
void skipWs() { while (i < s.size() && isspace((unsigned char)s[i])) i++; }
char peek() { return i < s.size() ? s[i] : '\0'; }
void expect(char c) {
if (peek() != c) throw std::runtime_error(std::string("expected '") + c + "' at pos " + std::to_string(i));
i++;
}
Json parseValue() {
skipWs();
char c = peek();
if (c == '{') return parseObject();
if (c == '[') return parseArray();
if (c == '"') return Json::Str(parseString());
if (c == 't' || c == 'f') return parseBool();
if (c == 'n') return parseNull();
return parseNumber();
}
Json parseObject() {
Json j = Json::Obj();
expect('{'); skipWs();
if (peek() == '}') { i++; return j; }
while (true) {
skipWs();
std::string key = parseString();
skipWs(); expect(':');
Json val = parseValue();
j.obj.emplace_back(std::move(key), std::move(val));
skipWs();
if (peek() == ',') { i++; continue; }
if (peek() == '}') { i++; break; }
throw std::runtime_error("expected ',' or '}' at pos " + std::to_string(i));
}
return j;
}
Json parseArray() {
Json j = Json::Arr();
expect('['); skipWs();
if (peek() == ']') { i++; return j; }
while (true) {
Json val = parseValue();
j.arr.push_back(std::move(val));
skipWs();
if (peek() == ',') { i++; continue; }
if (peek() == ']') { i++; break; }
throw std::runtime_error("expected ',' or ']' at pos " + std::to_string(i));
}
return j;
}
std::string parseString() {
skipWs(); expect('"');
std::string out; out.reserve(1024);
while (true) {
if (i >= s.size()) throw std::runtime_error("unterminated string at pos " + std::to_string(i));
char c = s[i++];
if (c == '"') break;
if (c == '\\') {
if (i >= s.size()) throw std::runtime_error("bad escape at pos " + std::to_string(i));
char e = s[i++];
switch (e) {
case '"': out += '"'; break;
case '\\': out += '\\'; break;
case '/': out += '/'; break;
case 'n': out += '\n'; break;
case 't': out += '\t'; break;
case 'r': out += '\r'; break;
case 'b': out += '\b'; break;
case 'f': out += '\f'; break;
case 'u': {
if (i + 4 > s.size()) throw std::runtime_error("bad unicode escape");
std::string hex = s.substr(i, 4); i += 4;
unsigned int cp = (unsigned int)std::stoul(hex, nullptr, 16);
if (cp < 0x80) out += (char)cp;
else if (cp < 0x800) {
out += (char)(0xC0 | (cp >> 6));
out += (char)(0x80 | (cp & 0x3F));
} else {
out += (char)(0xE0 | (cp >> 12));
out += (char)(0x80 | ((cp >> 6) & 0x3F));
out += (char)(0x80 | (cp & 0x3F));
}
break;
}
default:
// Not a standard JSON escape (JSON only defines the ones above).
// Regex patterns routinely contain \w \s \d \. \( \) etc, and an
// LLM emitting {"q":["\\w+"]} means "the two chars \ and w in the
// pattern", not "drop the backslash". Keep both chars so those
// escapes reach std::regex intact instead of silently corrupting
// into a literal 'w'/'s'/'d'.
out += '\\';
out += e;
break;
}
} else out += c;
}
return out;
}
Json parseBool() {
if (s.compare(i, 4, "true") == 0) { i += 4; return Json::Bool(true); }
if (s.compare(i, 5, "false") == 0) { i += 5; return Json::Bool(false); }
throw std::runtime_error("invalid literal at pos " + std::to_string(i));
}
Json parseNull() {
if (s.compare(i, 4, "null") == 0) { i += 4; return Json::Null_(); }
throw std::runtime_error("invalid literal at pos " + std::to_string(i));
}
Json parseNumber() {
size_t start = i;
if (peek() == '-') i++;
while (isdigit((unsigned char)peek())) i++;
if (peek() == '.') { i++; while (isdigit((unsigned char)peek())) i++; }
if (peek() == 'e' || peek() == 'E') {
i++;
if (peek() == '+' || peek() == '-') i++;
while (isdigit((unsigned char)peek())) i++;
}
if (i == start) throw std::runtime_error("invalid number at pos " + std::to_string(i));
return Json::Num(std::stod(s.substr(start, i - start)));
}
};
Json Json::parse(const std::string& text, std::string* err) {
try {
JsonParser p(text);
Json v = p.parseValue();
p.skipWs();
if (p.i != text.size()) {
throw std::runtime_error("unexpected trailing data at pos " + std::to_string(p.i));
}
return v;
} catch (std::exception& e) {
if (err) *err = e.what();
return Json::Null_();
}
}
static void jsonEscape(const std::string& s, std::string& out) {
out.reserve(s.size() + 32);
for (char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if ((unsigned char)c < 0x20) {
char buf[8]; snprintf(buf, sizeof(buf), "\\u%04x", (unsigned char)c);
out += buf;
} else out += c;
}
}
}
std::string Json::dump() const {
std::ostringstream out;
switch (type) {
case Type::Null: out << "null"; break;
case Type::Bool: out << (b ? "true" : "false"); break;
case Type::Number:
if (num == (double)(long long)num) out << (long long)num;
else out << num;
break;
case Type::String: {
std::string esc; jsonEscape(str, esc);
out << '"' << esc << '"'; break;
}
case Type::Array: {
out << "[";
for (size_t k = 0; k < arr.size(); ++k) {
if (k) out << ",";
out << arr[k].dump();
}
out << "]"; break;
}
case Type::Object: {
out << "{";
for (size_t k = 0; k < obj.size(); ++k) {
if (k) out << ",";
std::string esc; jsonEscape(obj[k].first, esc);
out << "\"" << esc << "\":" << obj[k].second.dump();
}
out << "}"; break;
}
}
return out.str();
}
// ===========================================================================
// Generic utilities
// ===========================================================================
std::string trim(const std::string& s) {
size_t a = 0, b = s.size();
while (a < b && isspace((unsigned char)s[a])) a++;
while (b > a && isspace((unsigned char)s[b - 1])) b--;
return s.substr(a, b - a);
}
std::string toLower(const std::string& s) {
std::string r = s;
for (auto& c : r) c = (char)tolower((unsigned char)c);
return r;
}
std::string truncateOutput(const std::string& s, size_t maxLen = 6000) {
if (s.size() <= maxLen) return s;
size_t headLen = 800;
size_t tailLen = maxLen - headLen - 80;
std::string head = s.substr(0, headLen);
std::string tail = s.substr(s.size() - tailLen);
return head + "\n...[" + std::to_string(s.size() - headLen - tailLen) + " chars omitted]...\n" + tail;
}
std::string shellQuote(const std::string& s) {
std::string out = "'";
for (char c : s) { if (c == '\'') out += "'\\''"; else out += c; }
out += "'";
return out;
}
std::vector<std::string> splitLines(const std::string& content) {
std::vector<std::string> out;
std::string cur;
for (char c : content) {
if (c == '\n') { out.push_back(cur); cur.clear(); }
else if (c == '\r') continue;
else cur += c;
}
out.push_back(cur);
if (!out.empty() && out.back().empty() && !content.empty() && content.back() == '\n') out.pop_back();
return out;
}
// Same line-count semantics as splitLines(normalizeLineEndings(x)).size(), but
// O(1) extra memory instead of allocating a std::string per line + a full
// normalized copy of content. For a large create_file payload, the old path
// was the actual dominant source of peak RSS (millions of small heap allocs).
size_t countLines(const std::string& content) {
if (content.empty()) return 1; // matches splitLines("") == 1
size_t breaks = 0;
bool endsWithBreak = false;
for (size_t i = 0; i < content.size(); ++i) {
char c = content[i];
if (c == '\r') {
breaks++; endsWithBreak = true;
if (i + 1 < content.size() && content[i + 1] == '\n') i++;
} else if (c == '\n') {
breaks++; endsWithBreak = true;
} else {
endsWithBreak = false;
}
}
return endsWithBreak ? breaks : breaks + 1;
}
std::string joinLines(const std::vector<std::string>& lines) {
std::string out;
for (auto& l : lines) { out += l; out += '\n'; }
return out;
}
std::string readFileAll(const std::string& path) {
std::ifstream in(path, std::ios::binary);
if (!in) return "";
std::ostringstream ss; ss << in.rdbuf();
return ss.str();
}
std::vector<std::string> readFileLines(const std::string& path) {
std::ifstream in(path, std::ios::binary);
std::vector<std::string> lines;
if (!in) return lines;
std::string line;
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
lines.push_back(line);
}
return lines;
}
bool writeFileAll(const std::string& path, const std::string& content) {
// Atomic replace on POSIX: write a sibling temporary file, fsync it, then rename.
// Do not fall back to truncating the target: that defeats the crash-safety guarantee.
fs::path target(path);
fs::path tmp = target;
tmp += ".tmp." + std::to_string((long long) ::getpid()) + "." +
std::to_string((long long)std::chrono::steady_clock::now().time_since_epoch().count());
{
std::ofstream out(tmp, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(content.data(), (std::streamsize)content.size());
if (!out) return false;
out.flush();
if (!out) return false;
}
int fd = ::open(tmp.c_str(), O_RDONLY);
if (fd < 0) {
std::error_code ec; fs::remove(tmp, ec);
return false;
}
bool ok = (::fsync(fd) == 0);
::close(fd);
if (!ok) {
std::error_code ec; fs::remove(tmp, ec);
return false;
}
std::error_code ec;
fs::rename(tmp, target, ec);
if (ec) {
fs::remove(tmp, ec);
return false;
}
// Best effort directory durability. The rename itself is already atomic.
fs::path parent = target.parent_path().empty() ? fs::path(".") : target.parent_path();
int dfd = ::open(parent.c_str(), O_RDONLY | O_DIRECTORY);
if (dfd >= 0) { ::fsync(dfd); ::close(dfd); }
return true;
}
long lineNumberAt(const std::string& content, size_t pos) {
long n = 1;
for (size_t k = 0; k < pos && k < content.size(); ++k) if (content[k] == '\n') n++;
return n;
}
// Forward-declared here (defined below) so backupSafeName can hash the full
// relative path to avoid backup-filename collisions.
std::string fnv1a64Hex(const std::string& s);
// Turns a relative path into a name safe for the flat .mpt_backups directory.
// Prefixed with a hash of the FULL path so distinct paths that flatten to the
// same string after '/'->'_' substitution (e.g. "src/foo.cpp" vs "src_foo.cpp")
// never collide and mix undo histories.
std::string backupSafeName(const std::string& relFile) {
std::string flat = relFile;
for (auto& c : flat) if (c == '/' || c == '\\') c = '_';
return fnv1a64Hex(relFile).substr(0, 8) + "_" + flat;
}
void backupFile(const fs::path& baseDir, const std::string& relFile, const std::string& originalContent) {
try {
// Backups live in the OWNING root's .mpt_backups, not whichever root
// the calling tool was handed — cross-root edits keep their history
// beside the file they belong to.
fs::path bdir = rootFor(baseDir, relFile) / ".mpt_backups";
std::error_code ec;
fs::create_directories(bdir, ec);
std::string safeName = backupSafeName(relFile);
auto now = std::chrono::system_clock::now().time_since_epoch().count();
fs::path bfile = bdir / (safeName + "." + std::to_string(now) + ".bak");
std::ofstream out(bfile, std::ios::binary);
if (out) out << originalContent;
} catch (...) {}
}
// Lenient base64 decoder: skips whitespace/newlines/invalid chars, stops at '='.
// Lets callers send old/new/content text as base64 to sidestep JSON-escaping
// pain entirely (no backslash-doubling for regex-y source text).
std::string base64Decode(const std::string& in) {
static int T[256];
static bool init = false;
if (!init) {
for (int i = 0; i < 256; ++i) T[i] = -1;
const char* chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (int i = 0; i < 64; ++i) T[(unsigned char)chars[i]] = i;
init = true;
}
std::string out; out.reserve(in.size() * 3 / 4 + 3);
int val = 0, bits = -8;
for (unsigned char c : in) {
if (c == '=') break;
int d = T[c];
if (d == -1) continue; // skip whitespace/newlines/anything not base64
val = (val << 6) + d;
bits += 6;
if (bits >= 0) {
out.push_back((char)((val >> bits) & 0xFF));
bits -= 8;
}
}
return out;
}
// Reads a text field that may be supplied either as a plain JSON string
// (shortKey/longKey) or as base64 (b64Key). base64 wins if both are present
// and non-empty, since it's the unambiguous form.
std::string getTextOrB64(const Json& j, const std::string& shortKey,
const std::string& longKey, const std::string& b64Key) {
const Json* b64p = j.get(b64Key);
if (b64p && b64p->type == Json::Type::String && !b64p->str.empty()) {
return base64Decode(b64p->str);
}
return j.getStr2(shortKey, longKey);
}
// Cheap, fast, non-cryptographic content checksum (FNV-1a 64-bit) so callers
// can confirm a write landed as expected without a follow-up read.
std::string fnv1a64Hex(const std::string& s) {
uint64_t h = 1469598103934665603ULL;
for (unsigned char c : s) { h ^= c; h *= 1099511628211ULL; }
char buf[17];
snprintf(buf, sizeof(buf), "%016llx", (unsigned long long)h);
return std::string(buf);
}
std::string normalizeLineEndings(const std::string& s) {
std::string out; out.reserve(s.size());
for (size_t i=0;i<s.size();++i) {
if (s[i]=='\r') {
if (i+1 < s.size() && s[i+1]=='\n') { out.push_back('\n'); ++i; }
else out.push_back('\n');
} else out.push_back(s[i]);
}
return out;
}
// Optional content-drift guard for line-number-addressed edits (patch's
// replace_lines/delete_lines, edit's delete/insert_after/insert_before). The
// caller may pass "exp" (exact text expected to currently occupy the target
// line[s]) and/or "expH" (fnv1a64Hex of that text). If either is supplied and
// doesn't match what's actually there, the mutation is refused instead of
// silently rewriting whatever currently sits at that line number -- closing
// the gap between the system prompt's "read fresh before patching" advice and
// what the tool itself verifies.
bool verifyExpectedContent(const Json& p, const std::vector<std::string>& lines,
size_t adjStart, size_t adjEnd, std::string& failReason) {
std::string expect = p.getStr2("exp", "expect");
std::string expectHash = p.getStr2("expH", "expect_hash");
if (expect.empty() && expectHash.empty()) return true; // no assertion requested
std::ostringstream actual;
for (size_t i = adjStart; i <= adjEnd && i < lines.size(); ++i) {
actual << lines[i];
if (i != adjEnd) actual << "\n";
}
std::string actualText = actual.str();
if (!expect.empty() && normalizeLineEndings(expect) != normalizeLineEndings(actualText)) {
failReason = "'exp' doesn't match what's currently at those line(s); file likely changed "
"since it was last read. Re-read the file and retry.";
return false;
}
if (!expectHash.empty() && fnv1a64Hex(actualText) != expectHash) {
failReason = "'expH' doesn't match the hash of what's currently at those line(s); file "
"likely changed since it was last read. Re-read the file and retry.";
return false;
}
return true;
}
// Returns every start index at which oldLines matches fileLines (optionally
// whitespace-trimmed), instead of just the first, so fuzzy (whitespace-
// insensitive) matches can be checked for ambiguity the same way exact and
// normalized-newline matches already are.
std::vector<size_t> findAllLinesSequences(const std::vector<std::string>& fileLines,
const std::vector<std::string>& oldLines,
bool trimWhitespace) {
std::vector<size_t> out;
if (oldLines.empty() || oldLines.size() > fileLines.size()) return out;
for (size_t i=0;i+oldLines.size()<=fileLines.size();++i) {
bool ok=true;
for (size_t j=0;j<oldLines.size();++j) {
std::string a = fileLines[i+j];
std::string b = oldLines[j];
if (trimWhitespace) { a = trim(a); b = trim(b); }
if (a != b) { ok=false; break; }
}
if (ok) { out.push_back(i); if (out.size() > 10000) break; }
}
return out;
}
// Resolves relPath against baseDir and refuses to leave the sandbox.
// Two escape routes this closes:
// 1. fs::path's operator/ silently DISCARDS baseDir when relPath is
// absolute (baseDir / "/etc/passwd" == "/etc/passwd", not an error).
// 2. "../../whatever" can walk a relative path above baseDir even though
// each individual segment looks harmless.
// Returns false (and leaves out untouched) if relPath would resolve outside
// baseDir. Uses weakly_canonical so this works for paths that don't exist
// yet (e.g. a file about to be created).
static bool safeResolveIn(const fs::path& root, const std::string& relPath, fs::path& out) {
fs::path rp(relPath);
std::error_code ec;
fs::path normBase = fs::weakly_canonical(root, ec);
if (ec) normBase = root.lexically_normal();
fs::path combined = rp.is_absolute() ? rp : (root / rp); // absolute rp replaces root
fs::path normCombined = fs::weakly_canonical(combined, ec);
if (ec) normCombined = combined.lexically_normal();
auto bi = normBase.begin(), be = normBase.end();
auto ci = normCombined.begin(), ce = normCombined.end();
for (; bi != be; ++bi, ++ci) {
if (ci == ce || *ci != *bi) return false; // combined isn't under root
}
out = combined;
return true;
}
bool safeResolve(const fs::path& baseDir, const std::string& relPath, fs::path& out) {
if (relPath.empty()) return false;
// Multi-root resolution (sandbox = union of registered roots):
// 1. A relative path that does not exist under baseDir but does exist
// under a sibling root resolves to the sibling — the real file wins
// over a same-named primary path that isn't there.
// 2. Otherwise baseDir gets first claim: single-root behavior is
// unchanged, and brand-new relative paths are created in the
// primary workspace.
// 3. Finally, absolute paths and ../ relatives are accepted if they
// land inside any other registered root.
std::error_code ec;
fs::path rp(relPath);
if (!rp.is_absolute()) {
bool underBase = fs::exists(baseDir / rp, ec);
if (!underBase) {
for (auto& r : g_roots) {
if (r == baseDir) continue;
if (fs::exists(r / rp, ec) && safeResolveIn(r, relPath, out)) return true;
}
}
}
if (safeResolveIn(baseDir, relPath, out)) return true;
for (auto& r : g_roots) {
if (r == baseDir) continue;
if (safeResolveIn(r, relPath, out)) return true;
}
return false;
}
// Returns true if `full` (already safeResolve'd) IS baseDir itself, or is/lives
// inside baseDir/.mpt_backups. Destructive ops (delete, and move/rename onto
// this path) must refuse these: deleting baseDir wipes the whole project in one
// call, and deleting/overwriting .mpt_backups silently disables undo.
bool isProtectedPath(const fs::path& baseDir, const fs::path& full) {
std::error_code ec;
fs::path normBase = fs::weakly_canonical(baseDir, ec);
if (ec) normBase = baseDir.lexically_normal();
fs::path normFull = fs::weakly_canonical(full, ec);
if (ec) normFull = full.lexically_normal();
if (normFull == normBase) return true;
fs::path normBackups = fs::weakly_canonical(baseDir / ".mpt_backups", ec);
if (ec) normBackups = (baseDir / ".mpt_backups").lexically_normal();
auto bi = normBackups.begin(), be = normBackups.end();
auto fi = normFull.begin(), fe = normFull.end();
for (; bi != be; ++bi, ++fi) {
if (fi == fe || *fi != *bi) return false;
}
return true; // normFull == normBackups or nested inside it
}
bool isBinaryContent(const std::string& content) {
size_t checkLen = std::min<size_t>(8192, content.size());
if (checkLen == 0) return false;
size_t nonText = 0;
size_t i = 0;
while (i < checkLen) {
unsigned char c = (unsigned char)content[i];
if (c == 0) return true; // NUL byte: near-universal binary signal, short-circuit
if (c == '\n' || c == '\r' || c == '\t') { i++; continue; }
if (c < 0x20 || c == 0x7F) { nonText++; i++; continue; } // control chars
if (c < 0x80) { i++; continue; } // printable ASCII
// c >= 0x80: only count as binary if it's NOT a valid UTF-8 multi-byte
// sequence, so accented text / CJK / box-drawing / emoji aren't flagged.
int seqLen = 0;
if ((c & 0xE0) == 0xC0) seqLen = 2;
else if ((c & 0xF0) == 0xE0) seqLen = 3;
else if ((c & 0xF8) == 0xF0) seqLen = 4;
else { nonText++; i++; continue; } // invalid lead byte / stray continuation byte
if (i + (size_t)seqLen > checkLen) { nonText++; i++; continue; } // truncated sequence
bool valid = true;
for (int k = 1; k < seqLen; ++k) {
if (((unsigned char)content[i + k] & 0xC0) != 0x80) { valid = false; break; }
}
if (!valid) { nonText++; i++; continue; }
i += (size_t)seqLen; // valid multi-byte UTF-8 char: counts as text
}
return nonText > checkLen / 8;
}
// Content-based binary check for one file: reads only the first 8192 bytes.
// Extension checks can never catch extensionless artifacts (compiled
// binaries, suffix-less images) — this is the ground truth the walk filter
// and the bin tags trust.
bool looksBinaryFile(const fs::path& p) {
std::ifstream in(p, std::ios::binary);
if (!in) return false;
std::string head(8192, '\0');
in.read(&head[0], (std::streamsize)head.size());
head.resize((size_t)in.gcount());
return isBinaryContent(head);
}
// ===========================================================================
// Timeout-aware shell execution (fork + execvp + select with deadline)
// ===========================================================================
std::pair<int, std::string> runShellTimed(const std::string& cmd, const fs::path& cwd, long timeoutSec) {
int pipefd[2];
if (pipe(pipefd) != 0) return {-1001, "pipe() failed"};
pid_t pid = fork();
if (pid < 0) {
close(pipefd[0]); close(pipefd[1]);
return {-1001, "fork() failed"};
}
if (pid == 0) {
// Put the shell and all descendants in a dedicated process group so timeout
// and output-cap termination cannot leave npm/python/etc. children running.
setpgid(0, 0);
close(pipefd[0]);
if (dup2(pipefd[1], STDOUT_FILENO) < 0 || dup2(pipefd[1], STDERR_FILENO) < 0) _exit(126);
close(pipefd[1]);
if (!cwd.empty() && chdir(cwd.c_str()) != 0) _exit(127);
signal(SIGINT, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
std::string full = "cd " + shellQuote(cwd.string()) + " && (" + cmd + ") 2>&1";
execl("/bin/sh", "sh", "-c", full.c_str(), (char*)nullptr);
_exit(127);
}
// Race-safe on normal POSIX systems: child also calls setpgid, so whichever wins
// first establishes the same process-group ID.
setpgid(pid, pid);
close(pipefd[1]);
std::string output;
constexpr size_t OUTPUT_CAP = 8 * 1024 * 1024;
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeoutSec);
bool timedOut = false;
bool outputLimited = false;
std::array<char, 8192> buf{};
int flags = fcntl(pipefd[0], F_GETFL, 0);
if (flags >= 0) fcntl(pipefd[0], F_SETFL, flags | O_NONBLOCK);
while (true) {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(pipefd[0], &rfds);
auto now = std::chrono::steady_clock::now();
auto remaining = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - now);
if (remaining.count() <= 0) { timedOut = true; break; }
timeval tv{};
tv.tv_sec = remaining.count() / 1000;
tv.tv_usec = (remaining.count() % 1000) * 1000;
int sel = select(pipefd[0] + 1, &rfds, nullptr, nullptr, &tv);
if (sel < 0) {
if (errno == EINTR) continue;
break;
}
if (sel == 0) { timedOut = true; break; }
while (true) {
ssize_t n = read(pipefd[0], buf.data(), buf.size());
if (n > 0) {
if (output.size() + (size_t)n > OUTPUT_CAP) {
size_t keep = OUTPUT_CAP - output.size();
output.append(buf.data(), keep);
outputLimited = true;
break;
}
output.append(buf.data(), (size_t)n);
continue;
}
if (n == 0) { close(pipefd[0]); int status; waitpid(pid, &status, 0);
int code = WIFEXITED(status) ? WEXITSTATUS(status) : (WIFSIGNALED(status) ? 128 + WTERMSIG(status) : -1);
return {code, output}; }
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
close(pipefd[0]); int status; waitpid(pid, &status, 0);
return {-1001, output + "\n[nexon] read() failed: " + std::strerror(errno)};
}
if (outputLimited) break;
}
close(pipefd[0]);
if (timedOut || outputLimited) {
// Kill the entire process group, not just the shell.
kill(-pid, SIGTERM);
auto killDeadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(750);
int status = 0;
while (std::chrono::steady_clock::now() < killDeadline) {
pid_t w = waitpid(pid, &status, WNOHANG);
if (w == pid) break;
if (w < 0 && errno != EINTR) break;
usleep(20000);
}
if (waitpid(pid, &status, WNOHANG) == 0) {
kill(-pid, SIGKILL);
waitpid(pid, &status, 0);
}
if (timedOut) return {-1000, output + "\n[nexon] TIMEOUT after " + std::to_string(timeoutSec) + "s"};
return {-1002, output + "\n[nexon] OUTPUT_LIMIT: command exceeded 8MB"};
}
int status = 0;
waitpid(pid, &status, 0);
int code = WIFEXITED(status) ? WEXITSTATUS(status) : (WIFSIGNALED(status) ? 128 + WTERMSIG(status) : -1);
return {code, output};
}
// ===========================================================================
// Unified diff parser
// ===========================================================================
struct DiffHunk {
long oldStart, oldCount, newStart, newCount;
std::vector<std::string> lines;
};
std::vector<DiffHunk> parseUnifiedDiff(const std::string& diffText) {
std::vector<DiffHunk> hunks;
auto lines = splitLines(diffText);
size_t i = 0;
while (i < lines.size()) {
if (lines[i].substr(0, 2) == "@@") break;
i++;
}
while (i < lines.size()) {
if (lines[i].substr(0, 2) != "@@") { i++; continue; }
std::string header = lines[i];
long os=0, oc=1, ns=0, nc=1;
size_t minusPos = header.find('-');
size_t plusPos = header.find('+');
if (minusPos == std::string::npos || plusPos == std::string::npos) { i++; continue; }
{
std::string oldRange = trim(header.substr(minusPos + 1, plusPos - minusPos - 1));
size_t comma = oldRange.find(',');
if (comma == std::string::npos) { os = std::stol(oldRange); oc = 1; }
else { os = std::stol(oldRange.substr(0, comma)); oc = std::stol(oldRange.substr(comma + 1)); }
}
{
std::string rest = header.substr(plusPos + 1);
size_t endPos = rest.find_first_of(" @");
std::string newRange = trim((endPos == std::string::npos) ? rest : rest.substr(0, endPos));
size_t comma = newRange.find(',');
if (comma == std::string::npos) { ns = std::stol(newRange); nc = 1; }
else { ns = std::stol(newRange.substr(0, comma)); nc = std::stol(newRange.substr(comma + 1)); }
}
DiffHunk h{os, oc, ns, nc, {}};
i++;
while (i < lines.size() && lines[i].substr(0, 2) != "@@") {
if (lines[i].substr(0, 3) == "---" || lines[i].substr(0, 3) == "+++") break;
h.lines.push_back(lines[i]);
i++;
}
hunks.push_back(h);
}
return hunks;
}
// Map an original (pre-batch) line number to its current line index. origins[i] is
// the original line number still represented by current line i; inserted/generated
// lines carry 0. This prevents the classic "global line offset" bug where an edit at
// line 1 shifts an unrelated edit intended for line 50.
static bool currentIndexForOriginalLine(const std::vector<long>& origins, long originalLine, size_t& outIndex) {
if (originalLine < 1) return false;
for (size_t i = 0; i < origins.size(); ++i) {
if (origins[i] == originalLine) { outIndex = i; return true; }
}
return false;
}
static long currentLineNumberForOriginalLine(const std::vector<long>& origins, long originalLine) {
size_t idx = 0;
return currentIndexForOriginalLine(origins, originalLine, idx) ? (long)idx + 1 : 0;
}
static void initOriginalOrigins(const std::vector<std::string>& lines, std::vector<long>& origins) {
origins.resize(lines.size());
for (size_t i = 0; i < lines.size(); ++i) origins[i] = (long)i + 1;
}
static void replaceLineRange(std::vector<std::string>& lines, std::vector<long>& origins,
size_t start, size_t oldCount, const std::vector<std::string>& newLines) {
std::vector<long> replacementOrigins;
replacementOrigins.reserve(newLines.size());
for (size_t i = 0; i < newLines.size(); ++i) {
// Preserve original identity for as many replacement slots as possible.
// Extra generated lines have no original-line identity (0).
replacementOrigins.push_back(i < oldCount && start + i < origins.size() ? origins[start + i] : 0);
}
lines.erase(lines.begin() + (long)start, lines.begin() + (long)(start + oldCount));
origins.erase(origins.begin() + (long)start, origins.begin() + (long)(start + oldCount));
lines.insert(lines.begin() + (long)start, newLines.begin(), newLines.end());
origins.insert(origins.begin() + (long)start, replacementOrigins.begin(), replacementOrigins.end());
}
struct MappedDiffResult { bool ok; std::string error; std::vector<std::string> lines; std::vector<long> origins; long delta = 0; };
static bool tryApplyMappedHunk(const std::vector<std::string>& working,
const DiffHunk& h, long startPos,
std::vector<std::string>& newContent,
std::vector<long>* consumedOrigins) {
std::vector<std::string> verifiedOld;