@iroaxel/arcena 4.3.157

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.
@@ -0,0 +1,941 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ DEFAULT_INGEST_URL,
4
+ source_default
5
+ } from "./chunk-YKKUCYNE.js";
6
+ import {
7
+ init_esm_shims
8
+ } from "./chunk-YNWFCUMR.js";
9
+
10
+ // ../ggcoder/dist/core/pixel-fix.js
11
+ init_esm_shims();
12
+ import { spawn } from "child_process";
13
+ import { readFileSync as readFileSync2, existsSync as existsSync2 } from "fs";
14
+ import { homedir } from "os";
15
+ import { join as join2 } from "path";
16
+
17
+ // ../ggcoder/dist/core/pixel-fix-agent.js
18
+ init_esm_shims();
19
+ var PIXEL_FIX_SYSTEM_PROMPT = `You are the gg-pixel fix agent \u2014 a non-interactive coding agent invoked by the gg-pixel fix-queue runner.
20
+
21
+ Your single job for this session is to fix the one specific error described in the user message. You do not chat. You do not ask questions. You investigate, fix, commit, stop.
22
+
23
+ # Identity
24
+ - You are NOT the regular arcicoder interactive assistant.
25
+ - You are a one-shot fix worker. Your work will be reviewed by a human after you stop.
26
+ - Be terse. Don't narrate your reasoning unless it materially affects the fix.
27
+
28
+ # Required workflow
29
+ 1. Read the error in the user message (type, message, file:line, code window, stack).
30
+ 2. Use your tools (read, grep, find, edit, bash) to investigate. Prefer reading the exact file:line referenced in the error first.
31
+ 3. Make the smallest fix that resolves the actual error. Do not refactor surrounding code, do not improve unrelated things, do not add tests unless the error is in a test.
32
+ 4. Create the git branch named in the user message. Do NOT switch back to main afterward.
33
+ 5. Commit your changes on that branch with a clear message.
34
+ 6. If the project has quality checks (\`pnpm check\`, \`pnpm test\`, \`pytest\`, \`cargo check\`, etc.), run them. Only commit if they pass \u2014 if checks fail, fix and retry, do not commit broken code.
35
+ 7. Stop. The runner will inspect git state and mark the result.
36
+
37
+ # Hard rules
38
+ - Do NOT merge. Do NOT push. Do NOT open a PR.
39
+ - Do NOT switch back to main/master after committing on the fix branch.
40
+ - Do NOT mark the error status yourself \u2014 the runner observes git state and updates status.
41
+ - If you cannot fix the error (genuinely stuck, missing context, ambiguous), commit nothing and stop. The runner will mark it as failed; a human will look.
42
+
43
+ # Recurrence signal
44
+ If the user message says "Recurrence: Nth time", the previous fix did not hold. Investigate why before patching again \u2014 a quick re-patch is likely to regress.`;
45
+
46
+ // ../ggcoder/dist/core/source-maps.js
47
+ init_esm_shims();
48
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
49
+ import { dirname, join, posix } from "path";
50
+
51
+ // ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
52
+ init_esm_shims();
53
+
54
+ // ../../node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
55
+ init_esm_shims();
56
+ var comma = ",".charCodeAt(0);
57
+ var semicolon = ";".charCodeAt(0);
58
+ var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
59
+ var intToChar = new Uint8Array(64);
60
+ var charToInt = new Uint8Array(128);
61
+ for (let i = 0; i < chars.length; i++) {
62
+ const c = chars.charCodeAt(i);
63
+ intToChar[i] = c;
64
+ charToInt[c] = i;
65
+ }
66
+ function decodeInteger(reader, relative) {
67
+ let value = 0;
68
+ let shift = 0;
69
+ let integer = 0;
70
+ do {
71
+ const c = reader.next();
72
+ integer = charToInt[c];
73
+ value |= (integer & 31) << shift;
74
+ shift += 5;
75
+ } while (integer & 32);
76
+ const shouldNegate = value & 1;
77
+ value >>>= 1;
78
+ if (shouldNegate) {
79
+ value = -2147483648 | -value;
80
+ }
81
+ return relative + value;
82
+ }
83
+ function hasMoreVlq(reader, max) {
84
+ if (reader.pos >= max) return false;
85
+ return reader.peek() !== comma;
86
+ }
87
+ var bufLength = 1024 * 16;
88
+ var StringReader = class {
89
+ constructor(buffer) {
90
+ this.pos = 0;
91
+ this.buffer = buffer;
92
+ }
93
+ next() {
94
+ return this.buffer.charCodeAt(this.pos++);
95
+ }
96
+ peek() {
97
+ return this.buffer.charCodeAt(this.pos);
98
+ }
99
+ indexOf(char) {
100
+ const { buffer, pos } = this;
101
+ const idx = buffer.indexOf(char, pos);
102
+ return idx === -1 ? buffer.length : idx;
103
+ }
104
+ };
105
+ function decode(mappings) {
106
+ const { length } = mappings;
107
+ const reader = new StringReader(mappings);
108
+ const decoded = [];
109
+ let genColumn = 0;
110
+ let sourcesIndex = 0;
111
+ let sourceLine = 0;
112
+ let sourceColumn = 0;
113
+ let namesIndex = 0;
114
+ do {
115
+ const semi = reader.indexOf(";");
116
+ const line = [];
117
+ let sorted = true;
118
+ let lastCol = 0;
119
+ genColumn = 0;
120
+ while (reader.pos < semi) {
121
+ let seg;
122
+ genColumn = decodeInteger(reader, genColumn);
123
+ if (genColumn < lastCol) sorted = false;
124
+ lastCol = genColumn;
125
+ if (hasMoreVlq(reader, semi)) {
126
+ sourcesIndex = decodeInteger(reader, sourcesIndex);
127
+ sourceLine = decodeInteger(reader, sourceLine);
128
+ sourceColumn = decodeInteger(reader, sourceColumn);
129
+ if (hasMoreVlq(reader, semi)) {
130
+ namesIndex = decodeInteger(reader, namesIndex);
131
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
132
+ } else {
133
+ seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
134
+ }
135
+ } else {
136
+ seg = [genColumn];
137
+ }
138
+ line.push(seg);
139
+ reader.pos++;
140
+ }
141
+ if (!sorted) sort(line);
142
+ decoded.push(line);
143
+ reader.pos = semi + 1;
144
+ } while (reader.pos <= length);
145
+ return decoded;
146
+ }
147
+ function sort(line) {
148
+ line.sort(sortComparator);
149
+ }
150
+ function sortComparator(a, b) {
151
+ return a[0] - b[0];
152
+ }
153
+
154
+ // ../../node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
155
+ init_esm_shims();
156
+ var schemeRegex = /^[\w+.-]+:\/\//;
157
+ var urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
158
+ var fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
159
+ function isAbsoluteUrl(input) {
160
+ return schemeRegex.test(input);
161
+ }
162
+ function isSchemeRelativeUrl(input) {
163
+ return input.startsWith("//");
164
+ }
165
+ function isAbsolutePath(input) {
166
+ return input.startsWith("/");
167
+ }
168
+ function isFileUrl(input) {
169
+ return input.startsWith("file:");
170
+ }
171
+ function isRelative(input) {
172
+ return /^[.?#]/.test(input);
173
+ }
174
+ function parseAbsoluteUrl(input) {
175
+ const match = urlRegex.exec(input);
176
+ return makeUrl(match[1], match[2] || "", match[3], match[4] || "", match[5] || "/", match[6] || "", match[7] || "");
177
+ }
178
+ function parseFileUrl(input) {
179
+ const match = fileRegex.exec(input);
180
+ const path = match[2];
181
+ return makeUrl("file:", "", match[1] || "", "", isAbsolutePath(path) ? path : "/" + path, match[3] || "", match[4] || "");
182
+ }
183
+ function makeUrl(scheme, user, host, port, path, query, hash) {
184
+ return {
185
+ scheme,
186
+ user,
187
+ host,
188
+ port,
189
+ path,
190
+ query,
191
+ hash,
192
+ type: 7
193
+ };
194
+ }
195
+ function parseUrl(input) {
196
+ if (isSchemeRelativeUrl(input)) {
197
+ const url2 = parseAbsoluteUrl("http:" + input);
198
+ url2.scheme = "";
199
+ url2.type = 6;
200
+ return url2;
201
+ }
202
+ if (isAbsolutePath(input)) {
203
+ const url2 = parseAbsoluteUrl("http://foo.com" + input);
204
+ url2.scheme = "";
205
+ url2.host = "";
206
+ url2.type = 5;
207
+ return url2;
208
+ }
209
+ if (isFileUrl(input))
210
+ return parseFileUrl(input);
211
+ if (isAbsoluteUrl(input))
212
+ return parseAbsoluteUrl(input);
213
+ const url = parseAbsoluteUrl("http://foo.com/" + input);
214
+ url.scheme = "";
215
+ url.host = "";
216
+ url.type = input ? input.startsWith("?") ? 3 : input.startsWith("#") ? 2 : 4 : 1;
217
+ return url;
218
+ }
219
+ function stripPathFilename(path) {
220
+ if (path.endsWith("/.."))
221
+ return path;
222
+ const index = path.lastIndexOf("/");
223
+ return path.slice(0, index + 1);
224
+ }
225
+ function mergePaths(url, base) {
226
+ normalizePath(base, base.type);
227
+ if (url.path === "/") {
228
+ url.path = base.path;
229
+ } else {
230
+ url.path = stripPathFilename(base.path) + url.path;
231
+ }
232
+ }
233
+ function normalizePath(url, type) {
234
+ const rel = type <= 4;
235
+ const pieces = url.path.split("/");
236
+ let pointer = 1;
237
+ let positive = 0;
238
+ let addTrailingSlash = false;
239
+ for (let i = 1; i < pieces.length; i++) {
240
+ const piece = pieces[i];
241
+ if (!piece) {
242
+ addTrailingSlash = true;
243
+ continue;
244
+ }
245
+ addTrailingSlash = false;
246
+ if (piece === ".")
247
+ continue;
248
+ if (piece === "..") {
249
+ if (positive) {
250
+ addTrailingSlash = true;
251
+ positive--;
252
+ pointer--;
253
+ } else if (rel) {
254
+ pieces[pointer++] = piece;
255
+ }
256
+ continue;
257
+ }
258
+ pieces[pointer++] = piece;
259
+ positive++;
260
+ }
261
+ let path = "";
262
+ for (let i = 1; i < pointer; i++) {
263
+ path += "/" + pieces[i];
264
+ }
265
+ if (!path || addTrailingSlash && !path.endsWith("/..")) {
266
+ path += "/";
267
+ }
268
+ url.path = path;
269
+ }
270
+ function resolve(input, base) {
271
+ if (!input && !base)
272
+ return "";
273
+ const url = parseUrl(input);
274
+ let inputType = url.type;
275
+ if (base && inputType !== 7) {
276
+ const baseUrl = parseUrl(base);
277
+ const baseType = baseUrl.type;
278
+ switch (inputType) {
279
+ case 1:
280
+ url.hash = baseUrl.hash;
281
+ // fall through
282
+ case 2:
283
+ url.query = baseUrl.query;
284
+ // fall through
285
+ case 3:
286
+ case 4:
287
+ mergePaths(url, baseUrl);
288
+ // fall through
289
+ case 5:
290
+ url.user = baseUrl.user;
291
+ url.host = baseUrl.host;
292
+ url.port = baseUrl.port;
293
+ // fall through
294
+ case 6:
295
+ url.scheme = baseUrl.scheme;
296
+ }
297
+ if (baseType > inputType)
298
+ inputType = baseType;
299
+ }
300
+ normalizePath(url, inputType);
301
+ const queryHash = url.query + url.hash;
302
+ switch (inputType) {
303
+ // This is impossible, because of the empty checks at the start of the function.
304
+ // case UrlType.Empty:
305
+ case 2:
306
+ case 3:
307
+ return queryHash;
308
+ case 4: {
309
+ const path = url.path.slice(1);
310
+ if (!path)
311
+ return queryHash || ".";
312
+ if (isRelative(base || input) && !isRelative(path)) {
313
+ return "./" + path + queryHash;
314
+ }
315
+ return path + queryHash;
316
+ }
317
+ case 5:
318
+ return url.path + queryHash;
319
+ default:
320
+ return url.scheme + "//" + url.user + url.host + url.port + url.path + queryHash;
321
+ }
322
+ }
323
+
324
+ // ../../node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs
325
+ function stripFilename(path) {
326
+ if (!path) return "";
327
+ const index = path.lastIndexOf("/");
328
+ return path.slice(0, index + 1);
329
+ }
330
+ function resolver(mapUrl, sourceRoot) {
331
+ const from = stripFilename(mapUrl);
332
+ const prefix = sourceRoot ? sourceRoot + "/" : "";
333
+ return (source) => resolve(prefix + (source || ""), from);
334
+ }
335
+ var COLUMN = 0;
336
+ var SOURCES_INDEX = 1;
337
+ var SOURCE_LINE = 2;
338
+ var SOURCE_COLUMN = 3;
339
+ var NAMES_INDEX = 4;
340
+ function maybeSort(mappings, owned) {
341
+ const unsortedIndex = nextUnsortedSegmentLine(mappings, 0);
342
+ if (unsortedIndex === mappings.length) return mappings;
343
+ if (!owned) mappings = mappings.slice();
344
+ for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) {
345
+ mappings[i] = sortSegments(mappings[i], owned);
346
+ }
347
+ return mappings;
348
+ }
349
+ function nextUnsortedSegmentLine(mappings, start) {
350
+ for (let i = start; i < mappings.length; i++) {
351
+ if (!isSorted(mappings[i])) return i;
352
+ }
353
+ return mappings.length;
354
+ }
355
+ function isSorted(line) {
356
+ for (let j = 1; j < line.length; j++) {
357
+ if (line[j][COLUMN] < line[j - 1][COLUMN]) {
358
+ return false;
359
+ }
360
+ }
361
+ return true;
362
+ }
363
+ function sortSegments(line, owned) {
364
+ if (!owned) line = line.slice();
365
+ return line.sort(sortComparator2);
366
+ }
367
+ function sortComparator2(a, b) {
368
+ return a[COLUMN] - b[COLUMN];
369
+ }
370
+ var found = false;
371
+ function binarySearch(haystack, needle, low, high) {
372
+ while (low <= high) {
373
+ const mid = low + (high - low >> 1);
374
+ const cmp = haystack[mid][COLUMN] - needle;
375
+ if (cmp === 0) {
376
+ found = true;
377
+ return mid;
378
+ }
379
+ if (cmp < 0) {
380
+ low = mid + 1;
381
+ } else {
382
+ high = mid - 1;
383
+ }
384
+ }
385
+ found = false;
386
+ return low - 1;
387
+ }
388
+ function upperBound(haystack, needle, index) {
389
+ for (let i = index + 1; i < haystack.length; index = i++) {
390
+ if (haystack[i][COLUMN] !== needle) break;
391
+ }
392
+ return index;
393
+ }
394
+ function lowerBound(haystack, needle, index) {
395
+ for (let i = index - 1; i >= 0; index = i--) {
396
+ if (haystack[i][COLUMN] !== needle) break;
397
+ }
398
+ return index;
399
+ }
400
+ function memoizedState() {
401
+ return {
402
+ lastKey: -1,
403
+ lastNeedle: -1,
404
+ lastIndex: -1
405
+ };
406
+ }
407
+ function memoizedBinarySearch(haystack, needle, state, key) {
408
+ const { lastKey, lastNeedle, lastIndex } = state;
409
+ let low = 0;
410
+ let high = haystack.length - 1;
411
+ if (key === lastKey) {
412
+ if (needle === lastNeedle) {
413
+ found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle;
414
+ return lastIndex;
415
+ }
416
+ if (needle >= lastNeedle) {
417
+ low = lastIndex === -1 ? 0 : lastIndex;
418
+ } else {
419
+ high = lastIndex;
420
+ }
421
+ }
422
+ state.lastKey = key;
423
+ state.lastNeedle = needle;
424
+ return state.lastIndex = binarySearch(haystack, needle, low, high);
425
+ }
426
+ function parse(map) {
427
+ return typeof map === "string" ? JSON.parse(map) : map;
428
+ }
429
+ var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)";
430
+ var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)";
431
+ var LEAST_UPPER_BOUND = -1;
432
+ var GREATEST_LOWER_BOUND = 1;
433
+ var TraceMap = class {
434
+ constructor(map, mapUrl) {
435
+ const isString = typeof map === "string";
436
+ if (!isString && map._decodedMemo) return map;
437
+ const parsed = parse(map);
438
+ const { version, file, names, sourceRoot, sources, sourcesContent } = parsed;
439
+ this.version = version;
440
+ this.file = file;
441
+ this.names = names || [];
442
+ this.sourceRoot = sourceRoot;
443
+ this.sources = sources;
444
+ this.sourcesContent = sourcesContent;
445
+ this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0;
446
+ const resolve2 = resolver(mapUrl, sourceRoot);
447
+ this.resolvedSources = sources.map(resolve2);
448
+ const { mappings } = parsed;
449
+ if (typeof mappings === "string") {
450
+ this._encoded = mappings;
451
+ this._decoded = void 0;
452
+ } else if (Array.isArray(mappings)) {
453
+ this._encoded = void 0;
454
+ this._decoded = maybeSort(mappings, isString);
455
+ } else if (parsed.sections) {
456
+ throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`);
457
+ } else {
458
+ throw new Error(`invalid source map: ${JSON.stringify(parsed)}`);
459
+ }
460
+ this._decodedMemo = memoizedState();
461
+ this._bySources = void 0;
462
+ this._bySourceMemos = void 0;
463
+ }
464
+ };
465
+ function cast(map) {
466
+ return map;
467
+ }
468
+ function decodedMappings(map) {
469
+ var _a;
470
+ return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded));
471
+ }
472
+ function originalPositionFor(map, needle) {
473
+ let { line, column, bias } = needle;
474
+ line--;
475
+ if (line < 0) throw new Error(LINE_GTR_ZERO);
476
+ if (column < 0) throw new Error(COL_GTR_EQ_ZERO);
477
+ const decoded = decodedMappings(map);
478
+ if (line >= decoded.length) return OMapping(null, null, null, null);
479
+ const segments = decoded[line];
480
+ const index = traceSegmentInternal(
481
+ segments,
482
+ cast(map)._decodedMemo,
483
+ line,
484
+ column,
485
+ bias || GREATEST_LOWER_BOUND
486
+ );
487
+ if (index === -1) return OMapping(null, null, null, null);
488
+ const segment = segments[index];
489
+ if (segment.length === 1) return OMapping(null, null, null, null);
490
+ const { names, resolvedSources } = map;
491
+ return OMapping(
492
+ resolvedSources[segment[SOURCES_INDEX]],
493
+ segment[SOURCE_LINE] + 1,
494
+ segment[SOURCE_COLUMN],
495
+ segment.length === 5 ? names[segment[NAMES_INDEX]] : null
496
+ );
497
+ }
498
+ function OMapping(source, line, column, name) {
499
+ return { source, line, column, name };
500
+ }
501
+ function traceSegmentInternal(segments, memo, line, column, bias) {
502
+ let index = memoizedBinarySearch(segments, column, memo, line);
503
+ if (found) {
504
+ index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index);
505
+ } else if (bias === LEAST_UPPER_BOUND) index++;
506
+ if (index === -1 || index === segments.length) return -1;
507
+ return index;
508
+ }
509
+
510
+ // ../ggcoder/dist/core/source-maps.js
511
+ var COMMON_BUILD_DIRS = ["dist", "build", ".next", "out", "public", ".vite"];
512
+ var MAX_DEPTH = 4;
513
+ var SourceMapResolver = class {
514
+ projectDir;
515
+ cache = /* @__PURE__ */ new Map();
516
+ constructor(projectDir) {
517
+ this.projectDir = projectDir;
518
+ }
519
+ /**
520
+ * Resolve a minified stack into the original source. Frames that can't
521
+ * be resolved are returned unchanged so the caller still sees something.
522
+ */
523
+ resolveStack(stack) {
524
+ return stack.map((f) => this.resolveFrame(f));
525
+ }
526
+ resolveFrame(frame) {
527
+ const minifiedName = filenameFromUrl(frame.file);
528
+ if (!minifiedName)
529
+ return frame;
530
+ const entry = this.findMap(minifiedName);
531
+ if (!entry)
532
+ return frame;
533
+ let resolved;
534
+ try {
535
+ resolved = originalPositionFor(entry.trace, { line: frame.line, column: frame.col });
536
+ } catch {
537
+ return frame;
538
+ }
539
+ if (!resolved.source)
540
+ return frame;
541
+ const sourceAbs = posix.normalize(posix.join(entry.mapDir, resolved.source));
542
+ return {
543
+ file: sourceAbs,
544
+ line: resolved.line ?? frame.line,
545
+ col: resolved.column ?? frame.col,
546
+ fn: resolved.name || frame.fn,
547
+ in_app: !sourceAbs.includes("/node_modules/") && !sourceAbs.startsWith("webpack:///")
548
+ };
549
+ }
550
+ findMap(minifiedName) {
551
+ const cached = this.cache.get(minifiedName);
552
+ if (cached !== void 0)
553
+ return cached;
554
+ const result = this.searchForMap(minifiedName);
555
+ this.cache.set(minifiedName, result);
556
+ return result;
557
+ }
558
+ searchForMap(minifiedName) {
559
+ for (const dir of COMMON_BUILD_DIRS) {
560
+ const root = join(this.projectDir, dir);
561
+ if (!existsSync(root))
562
+ continue;
563
+ const found2 = walkForMap(root, minifiedName, MAX_DEPTH);
564
+ if (found2)
565
+ return loadMap(found2);
566
+ }
567
+ const rootCandidate = join(this.projectDir, minifiedName + ".map");
568
+ if (existsSync(rootCandidate))
569
+ return loadMap(rootCandidate);
570
+ return null;
571
+ }
572
+ };
573
+ function filenameFromUrl(file) {
574
+ if (!file)
575
+ return null;
576
+ const cleaned = file.split("?")[0].split("#")[0];
577
+ const last = cleaned.split("/").pop();
578
+ return last || null;
579
+ }
580
+ function walkForMap(root, minifiedName, depth) {
581
+ const target = minifiedName + ".map";
582
+ const direct = join(root, target);
583
+ if (existsSync(direct))
584
+ return direct;
585
+ if (depth <= 0)
586
+ return null;
587
+ let entries;
588
+ try {
589
+ entries = readdirSync(root);
590
+ } catch {
591
+ return null;
592
+ }
593
+ for (const entry of entries) {
594
+ if (entry.startsWith("."))
595
+ continue;
596
+ const child = join(root, entry);
597
+ if (!isDirectorySafe(child))
598
+ continue;
599
+ const found2 = walkForMap(child, minifiedName, depth - 1);
600
+ if (found2)
601
+ return found2;
602
+ }
603
+ return null;
604
+ }
605
+ function isDirectorySafe(path) {
606
+ try {
607
+ return statSync(path).isDirectory();
608
+ } catch {
609
+ return false;
610
+ }
611
+ }
612
+ function loadMap(mapPath) {
613
+ try {
614
+ const raw = readFileSync(mapPath, "utf8");
615
+ const parsed = JSON.parse(raw);
616
+ return { trace: new TraceMap(parsed), mapDir: dirname(mapPath) };
617
+ } catch {
618
+ return null;
619
+ }
620
+ }
621
+ function tryResolveStack(stack, projectDir) {
622
+ try {
623
+ const resolver2 = new SourceMapResolver(projectDir);
624
+ return resolver2.resolveStack(stack);
625
+ } catch {
626
+ return stack;
627
+ }
628
+ }
629
+
630
+ // ../ggcoder/dist/core/pixel-fix.js
631
+ async function fixError(errorId, opts = {}) {
632
+ const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\/+$/, "");
633
+ const fetchFn = opts.fetchFn ?? fetch;
634
+ const home = opts.homeDir ?? homedir();
635
+ const owner = await resolveErrorOwner(fetchFn, ingestUrl, errorId, home);
636
+ const { error, project, secret } = owner;
637
+ const branch = `fix/pixel-${error.id}`;
638
+ await patchError(fetchFn, ingestUrl, error.id, { status: "in_progress", branch }, secret);
639
+ const exitCode = await runAgent({
640
+ cwd: project.path,
641
+ prompt: buildAgentPrompt(error, branch, project.path),
642
+ systemPrompt: PIXEL_FIX_SYSTEM_PROMPT,
643
+ spawnFn: opts.spawnFn ?? spawn,
644
+ ggcoderBin: opts.ggcoderBin ?? "arcicoder",
645
+ inheritStdio: opts.inheritStdio ?? true,
646
+ maxTurns: opts.maxTurns ?? 60
647
+ });
648
+ const observed = await observeOutcome(project.path, branch, opts.spawnFn ?? spawn);
649
+ let outcome;
650
+ let reason;
651
+ if (exitCode !== 0) {
652
+ outcome = "failed";
653
+ reason = `Agent exited with code ${exitCode}`;
654
+ } else if (!observed.branchExists) {
655
+ outcome = "failed";
656
+ reason = `Branch ${branch} was not created`;
657
+ } else if (!observed.hasCommits) {
658
+ outcome = "failed";
659
+ reason = `Branch ${branch} has no new commits`;
660
+ } else {
661
+ outcome = "awaiting_review";
662
+ reason = `Branch ${branch} created with ${observed.commitCount} commit(s) \u2014 ready for review`;
663
+ }
664
+ await patchError(fetchFn, ingestUrl, error.id, { status: outcome, branch }, secret);
665
+ return { errorId: error.id, projectName: project.name, branch, outcome, reason };
666
+ }
667
+ async function runQueue(opts = {}) {
668
+ const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\/+$/, "");
669
+ const fetchFn = opts.fetchFn ?? fetch;
670
+ const home = opts.homeDir ?? homedir();
671
+ const log = opts.onProgress ?? ((msg) => console.log(msg));
672
+ const projectsPath = join2(home, ".gg", "projects.json");
673
+ if (!existsSync2(projectsPath)) {
674
+ log(source_default.dim("No projects registered. Run `arcicoder pixel install` first."));
675
+ return { fixed: 0, failed: 0, total: 0 };
676
+ }
677
+ const projects = JSON.parse(readFileSync2(projectsPath, "utf8"));
678
+ const queue = [];
679
+ for (const [projectId, project] of Object.entries(projects)) {
680
+ if (!project.secret)
681
+ continue;
682
+ try {
683
+ const res = await fetchFn(`${ingestUrl}/api/projects/${projectId}/errors?status=open`, {
684
+ headers: { authorization: `Bearer ${project.secret}` }
685
+ });
686
+ if (!res.ok)
687
+ continue;
688
+ const body = await res.json();
689
+ for (const e of body.errors) {
690
+ queue.push({ projectName: project.name, errorId: e.id });
691
+ }
692
+ } catch {
693
+ }
694
+ }
695
+ if (queue.length === 0) {
696
+ log(source_default.hex("#4ade80")("No open errors. Queue is clean."));
697
+ return { fixed: 0, failed: 0, total: 0 };
698
+ }
699
+ log(source_default.bold(`Fixing ${queue.length} ${queue.length === 1 ? "error" : "errors"}...`));
700
+ log("");
701
+ let fixed = 0;
702
+ let failed = 0;
703
+ for (const item of queue) {
704
+ log(source_default.hex("#a78bfa").bold(`\u25B8 ${item.projectName}`) + source_default.dim(` ${item.errorId}`));
705
+ try {
706
+ const result = await fixError(item.errorId, opts);
707
+ if (result.outcome === "awaiting_review") {
708
+ log(source_default.hex("#4ade80")(` \u2713 ${result.reason}`));
709
+ fixed++;
710
+ } else {
711
+ log(source_default.hex("#ef4444")(` \u2717 ${result.reason}`));
712
+ failed++;
713
+ }
714
+ } catch (err) {
715
+ log(source_default.hex("#ef4444")(` \u2717 ${err instanceof Error ? err.message : String(err)}`));
716
+ failed++;
717
+ }
718
+ log("");
719
+ }
720
+ return { fixed, failed, total: queue.length };
721
+ }
722
+ async function preparePixelFix(errorId, opts = {}) {
723
+ const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\/+$/, "");
724
+ const fetchFn = opts.fetchFn ?? fetch;
725
+ const home = opts.homeDir ?? homedir();
726
+ const owner = await resolveErrorOwner(fetchFn, ingestUrl, errorId, home);
727
+ const { error, project, secret } = owner;
728
+ const branch = `fix/pixel-${error.id}`;
729
+ await patchError(fetchFn, ingestUrl, error.id, { status: "in_progress", branch }, secret);
730
+ return {
731
+ errorId: error.id,
732
+ projectId: error.project_id,
733
+ projectName: project.name,
734
+ projectPath: project.path,
735
+ branch,
736
+ prompt: buildAgentPrompt(error, branch, project.path)
737
+ };
738
+ }
739
+ async function finalizePixelFix(prep, opts = {}) {
740
+ const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\/+$/, "");
741
+ const fetchFn = opts.fetchFn ?? fetch;
742
+ const home = opts.homeDir ?? homedir();
743
+ const observed = await observeOutcome(prep.projectPath, prep.branch, opts.spawnFn ?? spawn);
744
+ let outcome;
745
+ let reason;
746
+ if (opts.agentExitedCleanly === false) {
747
+ outcome = "failed";
748
+ reason = "Agent did not finish cleanly";
749
+ } else if (!observed.branchExists) {
750
+ outcome = "failed";
751
+ reason = `Branch ${prep.branch} was not created`;
752
+ } else if (!observed.hasCommits) {
753
+ outcome = "failed";
754
+ reason = `Branch ${prep.branch} has no new commits`;
755
+ } else {
756
+ outcome = "awaiting_review";
757
+ reason = `Branch ${prep.branch} created with ${observed.commitCount} commit(s) \u2014 ready for review`;
758
+ }
759
+ const secret = lookupProjectSecret(home, prep.projectId);
760
+ await patchError(fetchFn, ingestUrl, prep.errorId, { status: outcome, branch: prep.branch }, secret);
761
+ return { outcome, reason };
762
+ }
763
+ function buildAgentPrompt(error, branch, projectDir) {
764
+ let stack = parseStackJson(error.stack);
765
+ if (projectDir && stack.length > 0 && looksLikeMinifiedBrowserStack(stack)) {
766
+ stack = tryResolveStack(stack, projectDir);
767
+ }
768
+ const ctx = parseCodeContext(error.code_context);
769
+ const lines = [];
770
+ lines.push("An error has been identified in this project. Investigate and fix it.");
771
+ lines.push("");
772
+ lines.push(`Error: ${error.type ?? "Error"} \u2014 ${error.message ?? "(no message)"}`);
773
+ const topInApp = stack.find((f) => f.in_app) ?? stack[0];
774
+ if (topInApp)
775
+ lines.push(`Location: ${topInApp.file}:${topInApp.line}`);
776
+ if (ctx && ctx.lines.length > 0) {
777
+ lines.push("");
778
+ lines.push("Code at site:");
779
+ const startLine = ctx.error_line - Math.floor((ctx.lines.length - 1) / 2);
780
+ ctx.lines.forEach((line, i) => {
781
+ const lineNum = startLine + i;
782
+ const marker = lineNum === ctx.error_line ? ">" : " ";
783
+ lines.push(` ${marker}${String(lineNum).padStart(4)} | ${line}`);
784
+ });
785
+ }
786
+ if (stack.length > 0) {
787
+ lines.push("");
788
+ lines.push("Stack:");
789
+ for (const f of stack.slice(0, 10)) {
790
+ const lib = f.in_app ? "" : " (lib)";
791
+ lines.push(` ${f.fn || "<anon>"} ${f.file}:${f.line}${lib}`);
792
+ }
793
+ }
794
+ if (error.runtime)
795
+ lines.push(`
796
+ Runtime: ${error.runtime}`);
797
+ lines.push(`Occurrences: ${error.occurrences}`);
798
+ if (error.recurrence_count > 0) {
799
+ lines.push("");
800
+ lines.push(`Recurrence: this is the ${ordinal(error.recurrence_count)} time this fingerprint has appeared after a previous fix was merged. The earlier fix did not hold \u2014 investigate why.`);
801
+ }
802
+ lines.push("");
803
+ lines.push("When done:");
804
+ lines.push(` 1. Create branch: ${branch}`);
805
+ lines.push(" 2. Commit the fix on that branch");
806
+ lines.push(" 3. Run the project's quality checks (only commit if they pass)");
807
+ lines.push("");
808
+ lines.push("Do not merge. Do not push. Do not switch back to main.");
809
+ return lines.join("\n");
810
+ }
811
+ async function resolveErrorOwner(fetchFn, ingestUrl, errorId, home) {
812
+ const projectsPath = join2(home, ".gg", "projects.json");
813
+ if (!existsSync2(projectsPath)) {
814
+ throw new Error(`No projects mapping at ${projectsPath} \u2014 run \`arcicoder pixel install\` in the project first.`);
815
+ }
816
+ const projects = JSON.parse(readFileSync2(projectsPath, "utf8"));
817
+ const ownersWithSecret = Object.entries(projects).filter(([, p]) => Boolean(p.secret));
818
+ if (ownersWithSecret.length === 0) {
819
+ throw new Error("No managed projects on this machine \u2014 run `arcicoder pixel install` in the project to refresh management access.");
820
+ }
821
+ for (const [, project] of ownersWithSecret) {
822
+ const res = await fetchFn(`${ingestUrl}/api/errors/${errorId}`, {
823
+ headers: { authorization: `Bearer ${project.secret}` }
824
+ });
825
+ if (res.ok) {
826
+ const error = await res.json();
827
+ return { error, project, secret: project.secret };
828
+ }
829
+ }
830
+ throw new Error(`Error ${errorId} was not found in any registered project. Ensure the project is installed (\`arcicoder pixel install\`).`);
831
+ }
832
+ function lookupProjectSecret(home, projectId) {
833
+ const projectsPath = join2(home, ".gg", "projects.json");
834
+ if (!existsSync2(projectsPath)) {
835
+ throw new Error(`No projects mapping at ${projectsPath} \u2014 run \`arcicoder pixel install\` in the project first.`);
836
+ }
837
+ const projects = JSON.parse(readFileSync2(projectsPath, "utf8"));
838
+ const project = projects[projectId];
839
+ if (!project) {
840
+ throw new Error(`No local mapping for project ${projectId} in ${projectsPath}. Run \`arcicoder pixel install\` in the project's directory.`);
841
+ }
842
+ if (!project.secret) {
843
+ throw new Error(`Project ${projectId} is missing its bearer secret in ${projectsPath} \u2014 re-run \`arcicoder pixel install\` to refresh.`);
844
+ }
845
+ return project.secret;
846
+ }
847
+ async function patchError(fetchFn, ingestUrl, errorId, body, secret) {
848
+ const res = await fetchFn(`${ingestUrl}/api/errors/${errorId}`, {
849
+ method: "PATCH",
850
+ headers: {
851
+ "content-type": "application/json",
852
+ authorization: `Bearer ${secret}`
853
+ },
854
+ body: JSON.stringify(body)
855
+ });
856
+ if (!res.ok)
857
+ throw new Error(`PATCH /api/errors/${errorId} failed: ${res.status}`);
858
+ }
859
+ async function runAgent(opts) {
860
+ return new Promise((resolve2, reject) => {
861
+ const args = [
862
+ "--json",
863
+ "--max-turns",
864
+ String(opts.maxTurns),
865
+ "--system-prompt",
866
+ opts.systemPrompt,
867
+ opts.prompt
868
+ ];
869
+ const child = opts.spawnFn(opts.ggcoderBin, args, {
870
+ cwd: opts.cwd,
871
+ stdio: opts.inheritStdio ? "inherit" : ["ignore", "pipe", "pipe"]
872
+ });
873
+ child.on("error", reject);
874
+ child.on("exit", (code) => resolve2(code ?? 1));
875
+ });
876
+ }
877
+ async function observeOutcome(cwd, branch, spawnFn) {
878
+ const exists = await runGit(cwd, ["show-ref", "--verify", `refs/heads/${branch}`], spawnFn);
879
+ if (exists.code !== 0)
880
+ return { branchExists: false, hasCommits: false, commitCount: 0 };
881
+ let baseBranch = null;
882
+ for (const candidate of ["main", "master"]) {
883
+ const r = await runGit(cwd, ["show-ref", "--verify", `refs/heads/${candidate}`], spawnFn);
884
+ if (r.code === 0) {
885
+ baseBranch = candidate;
886
+ break;
887
+ }
888
+ }
889
+ if (!baseBranch)
890
+ return { branchExists: true, hasCommits: false, commitCount: 0 };
891
+ const ahead = await runGit(cwd, ["rev-list", "--count", `${baseBranch}..${branch}`], spawnFn);
892
+ const count = ahead.code === 0 ? parseInt(ahead.stdout.trim(), 10) || 0 : 0;
893
+ return { branchExists: true, hasCommits: count > 0, commitCount: count };
894
+ }
895
+ function runGit(cwd, args, spawnFn) {
896
+ return new Promise((resolve2) => {
897
+ const child = spawnFn("git", args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
898
+ let stdout = "";
899
+ let stderr = "";
900
+ child.stdout?.on("data", (b) => stdout += b.toString());
901
+ child.stderr?.on("data", (b) => stderr += b.toString());
902
+ child.on("error", () => resolve2({ code: 1, stdout, stderr }));
903
+ child.on("exit", (code) => resolve2({ code: code ?? 1, stdout, stderr }));
904
+ });
905
+ }
906
+ function looksLikeMinifiedBrowserStack(stack) {
907
+ return stack.some((f) => /^https?:\/\//.test(f.file));
908
+ }
909
+ function parseStackJson(raw) {
910
+ if (!raw)
911
+ return [];
912
+ try {
913
+ const parsed = JSON.parse(raw);
914
+ if (Array.isArray(parsed))
915
+ return parsed;
916
+ } catch {
917
+ }
918
+ return [];
919
+ }
920
+ function parseCodeContext(raw) {
921
+ if (!raw)
922
+ return null;
923
+ try {
924
+ return JSON.parse(raw);
925
+ } catch {
926
+ return null;
927
+ }
928
+ }
929
+ function ordinal(n) {
930
+ const s = ["th", "st", "nd", "rd"];
931
+ const v = n % 100;
932
+ return `${n}${s[(v - 20) % 10] ?? s[v] ?? s[0]}`;
933
+ }
934
+ export {
935
+ buildAgentPrompt,
936
+ finalizePixelFix,
937
+ fixError,
938
+ preparePixelFix,
939
+ runQueue
940
+ };
941
+ //# sourceMappingURL=pixel-fix-UIPF4UIQ.js.map