File size: 29,963 Bytes
765fe0a
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
0a09111
 
 
765fe0a
 
 
 
 
 
0a09111
 
765fe0a
 
 
0a09111
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
765fe0a
 
 
0a09111
765fe0a
 
 
 
 
 
 
 
0a09111
 
 
 
765fe0a
 
 
 
 
 
 
 
 
0a09111
765fe0a
0a09111
765fe0a
0a09111
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
765fe0a
 
 
 
0a09111
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
765fe0a
 
 
 
0a09111
765fe0a
 
 
0a09111
765fe0a
 
0a09111
765fe0a
 
 
 
 
0a09111
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eddef5d
765fe0a
 
 
 
 
 
 
0a09111
765fe0a
 
eddef5d
 
 
0a09111
 
 
eddef5d
 
 
 
765fe0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a09111
 
 
 
765fe0a
 
 
 
 
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
'use strict';
// Project memory for each session folder, so a new conversation does not
// re-read the whole project (the expensive part of starting over):
//
//   .agentweb/MEMORY.md   what Claude learned about the project (Claude keeps it)
//   .agentweb/HANDOFF.md  where the last conversation stopped (Claude keeps it)
//   .agentweb/MAP.md      every file with its size and its functions/classes
//                         with line numbers; built here, without any LLM
//   .agentweb/notes.json  short per-file notes Claude left (share via the
//                         agentweb MCP tool note_file); shown in the map while
//                         the file is unchanged
//   .agentweb/changes.json the last few changes of each file: recorded after
//                         every turn that changed files (the request text), or
//                         the one-line summary given with log_change
//
// Every map line about a file starts with its path ("uses", "used by", recent
// changes), so a Grep for a file name or a word returns all that is known
// about it and the map never has to be read whole.
//
// MEMORY and HANDOFF go into the system prompt when a conversation starts;
// the map is searched (Grep) instead of exploring the tree.

const fs = require('fs');
const fsp = require('fs/promises');
const path = require('path');
const crypto = require('crypto');

let redactText = (t) => t;
try {
  ({ redactText } = require('./redact'));
} catch {
  // redact yoksa metin oldugu gibi
}

const DIR = '.agentweb';
const MAX_FILES = 6000;
const MAX_DEPTH = 10;
const MAX_SYMBOL_FILE_BYTES = 1024 * 1024;
const MAX_LINECOUNT_BYTES = 4 * 1024 * 1024;
const MAX_SYMBOLS_PER_FILE = 150;
const MAX_MAP_BYTES = 2 * 1024 * 1024;
const MAX_MEMORY_CHARS = 8000;
const MAX_HANDOFF_CHARS = 4000;
const MAX_NOTE_CHARS = 400;
const MAX_NOTES = 2000;
const MAX_CHANGES_PER_FILE = 3;
const MAX_CHANGE_FILES = 3000;
const MAX_CHANGE_CHARS = 200;
const MAX_CHANGED_PER_TURN = 40;
const MAX_DEPS_SHOWN = 20;
const MAP_CACHE_VERSION = 4;
const STAT_CONCURRENCY = 16;

const SKIP_DIRS = new Set([
  '.git', '.hg', '.svn', 'node_modules', '.venv', 'venv', 'env', '__pycache__', '.mypy_cache', '.pytest_cache',
  '.ruff_cache', '.tox', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit', '.cache', '.parcel-cache',
  'target', '.gradle', '.idea', '.vs', '.vscode', 'obj', 'coverage', '.terraform', 'Pods', 'DerivedData',
  '.agentweb', 'bower_components', 'jspm_packages', '.turbo', '.yarn', '.pnpm-store', 'site-packages',
]);
// Hidden folders are skipped except these.
const KEEP_HIDDEN = new Set(['.github', '.claude', '.gitlab', '.circleci', '.devcontainer']);
const BINARY_EXT = new Set([
  'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'ico', 'icns', 'tif', 'tiff', 'psd', 'ase', 'aseprite', 'svgz',
  'mp3', 'wav', 'ogg', 'flac', 'm4a', 'aac', 'opus', 'mp4', 'mkv', 'mov', 'webm', 'avi',
  'zip', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'tar', 'jar', 'war', 'apk', 'aab', 'ipa', 'dmg', 'iso',
  'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'odt', 'woff', 'woff2', 'ttf', 'otf', 'eot',
  'exe', 'dll', 'so', 'dylib', 'a', 'o', 'obj', 'class', 'pyc', 'pyo', 'wasm', 'bin', 'dat', 'db', 'sqlite',
  'onnx', 'pt', 'pth', 'safetensors', 'ckpt', 'gguf', 'npz', 'npy', 'pkl', 'xnb', 'rpa', 'rpyc', 'lock',
]);

// Symbol finders per language: [regex, group index of the name, kind].
const JS = [
  [/^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)/, 1],
  [/^\s*(?:export\s+)?(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z_$][\w$]*)/, 1],
  [/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)/, 1],
  [/^\s*(?:export\s+)?(?:declare\s+)?(?:interface|type|enum)\s+([A-Za-z_$][\w$]*)/, 1],
  [/^\s{2,4}(?:static\s+|async\s+|get\s+|set\s+|public\s+|private\s+|protected\s+|readonly\s+)*([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*(?::\s*[^{]+)?\{\s*$/, 1],
];
const LANGS = {
  js: JS, mjs: JS, cjs: JS, jsx: JS, ts: JS, tsx: JS, mts: JS, cts: JS, vue: JS, svelte: JS,
  py: [
    [/^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)/, 1],
    [/^\s*class\s+([A-Za-z_]\w*)/, 1],
  ],
  cs: [
    [/^\s*(?:\[[^\]]*\]\s*)*(?:(?:public|private|protected|internal|static|sealed|abstract|partial|readonly|unsafe)\s+)*(?:class|struct|interface|enum|record)\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:(?:public|private|protected|internal|static|override|virtual|abstract|async|sealed|extern|unsafe|new)\s+)+[\w<>[\],.?\s]+?\s+([A-Za-z_]\w*)\s*(?:<[^>]*>)?\s*\([^;]*$/, 1],
  ],
  java: [
    [/^\s*(?:(?:public|private|protected|static|final|abstract)\s+)*(?:class|interface|enum|record)\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:(?:public|private|protected|static|final|synchronized|abstract)\s+)+[\w<>[\],.?\s]+?\s+([A-Za-z_]\w*)\s*\([^;]*$/, 1],
  ],
  kt: [
    [/^\s*(?:(?:public|private|internal|protected|open|data|sealed|abstract|inner|enum)\s+)*(?:class|interface|object)\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:(?:public|private|internal|protected|override|suspend|inline|open)\s+)*fun\s+(?:<[^>]*>\s*)?(?:[\w.]+\.)?([A-Za-z_]\w*)/, 1],
  ],
  go: [
    [/^func\s+(?:\([^)]*\)\s*)?([A-Za-z_]\w*)/, 1],
    [/^type\s+([A-Za-z_]\w*)/, 1],
  ],
  rs: [
    [/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:unsafe\s+)?fn\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:pub(?:\([^)]*\))?\s+)?(?:struct|enum|trait|mod|type)\s+([A-Za-z_]\w*)/, 1],
    [/^\s*impl(?:<[^>]*>)?\s+(?:[\w:<>]+\s+for\s+)?([A-Za-z_][\w:]*)/, 1],
  ],
  rb: [
    [/^\s*def\s+(?:self\.)?([A-Za-z_]\w*[?!=]?)/, 1],
    [/^\s*(?:class|module)\s+([A-Z][\w:]*)/, 1],
  ],
  php: [
    [/^\s*(?:(?:public|private|protected|static|abstract|final)\s+)*function\s+&?\s*([A-Za-z_]\w*)/, 1],
    [/^\s*(?:abstract\s+|final\s+)?(?:class|interface|trait|enum)\s+([A-Za-z_]\w*)/, 1],
  ],
  lua: [[/^\s*(?:local\s+)?function\s+([\w.:]+)/, 1]],
  gd: [
    [/^\s*(?:static\s+)?func\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:class_name|class)\s+([A-Za-z_]\w*)/, 1],
  ],
  rpy: [
    [/^\s*(label|screen|transform|image)\s+([\w.]+)/, 2],
    [/^\s*(?:define|default)\s+([\w.]+)\s*=/, 1],
  ],
  sh: [[/^\s*(?:function\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{?/, 1]],
  bash: null,
  swift: [
    [/^\s*(?:(?:public|private|internal|fileprivate|open|static|final|override|@\w+)\s+)*func\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:(?:public|private|internal|fileprivate|open|final)\s+)*(?:class|struct|enum|protocol|extension|actor)\s+([A-Za-z_][\w.]*)/, 1],
  ],
  dart: [
    [/^\s*(?:abstract\s+)?(?:class|mixin|enum|extension)\s+([A-Za-z_]\w*)/, 1],
    [/^\s*(?:static\s+|Future<[^>]*>\s+|[\w<>?]+\s+)([a-z_]\w*)\s*\([^;]*\)\s*(?:async\s*)?\{\s*$/, 1],
  ],
  c: [
    [/^(?:static\s+|inline\s+|extern\s+)*[A-Za-z_][\w\s*&:<>,]*?[\s*&]([A-Za-z_][\w:~]*)\s*\([^;]*$/, 1],
    [/^\s*(?:typedef\s+)?(?:struct|enum|union|class|namespace)\s+([A-Za-z_]\w*)\s*[{:]?\s*$/, 1],
  ],
  sql: [[/^\s*create\s+(?:or\s+replace\s+)?(?:table|view|function|procedure|index)\s+(?:if\s+not\s+exists\s+)?([\w."]+)/i, 1]],
  md: [[/^(#{1,3})\s+(.+?)\s*#*\s*$/, 2]],
};
LANGS.bash = LANGS.sh;
LANGS.zsh = LANGS.sh;
for (const ext of ['h', 'hpp', 'hh', 'cc', 'cpp', 'cxx', 'm', 'mm']) LANGS[ext] = LANGS.c;
LANGS.markdown = LANGS.md;
LANGS.mdx = LANGS.md;
LANGS.kts = LANGS.kt;
LANGS.scala = LANGS.kt;

const NOT_NAMES = new Set(['if', 'for', 'while', 'switch', 'catch', 'return', 'function', 'else', 'do', 'try', 'with', 'new', 'typeof', 'await', 'constructor', 'super', 'sizeof', 'elif', 'foreach', 'using', 'lock', 'fixed', 'when']);

function agentwebDir(cwd) {
  return path.join(cwd, DIR);
}

function ensureDir(cwd) {
  const dir = agentwebDir(cwd);
  try {
    fs.mkdirSync(dir, { recursive: true });
    const ignore = path.join(dir, '.gitignore');
    if (!fs.existsSync(ignore)) {
      fs.writeFileSync(ignore, '# Agent Web proje hafizasi (yerel). Paylasmak istersen bu dosyayi sil.\n*\n');
    }
  } catch {
    // klasor yazilamiyorsa hafiza olmadan devam edilir
  }
  return dir;
}

function readText(file, max) {
  try {
    const text = fs.readFileSync(file, 'utf8');
    return max && text.length > max ? `${text.slice(0, max)}\n… (devamı dosyada)` : text;
  } catch {
    return '';
  }
}

function extOf(name) {
  const m = /\.([A-Za-z0-9]+)$/.exec(name);
  return m ? m[1].toLowerCase() : '';
}

function findSymbols(text, ext) {
  const rules = LANGS[ext];
  if (!rules) return [];
  const out = [];
  const lines = text.split('\n');
  for (let i = 0; i < lines.length && out.length < MAX_SYMBOLS_PER_FILE; i += 1) {
    const line = lines[i];
    if (line.length > 400) continue;
    for (const [re, group] of rules) {
      const m = re.exec(line);
      if (!m) continue;
      let name = (m[group] || '').trim();
      if (!name || NOT_NAMES.has(name)) continue;
      if (ext === 'md' || ext === 'markdown' || ext === 'mdx') name = `# ${name.slice(0, 60)}`;
      out.push([i + 1, name]);
      break;
    }
  }
  return out.slice(0, MAX_SYMBOLS_PER_FILE);
}

// Local files a source file refers to (relative imports, <script src>...).
// Raw specs are cached; they are resolved against the file list at render.
const JS_DEP_RES = [
  /\brequire\(\s*['"]([^'"\n]+)['"]\s*\)/g,
  /\bimport\s+(?:[\w*${}\s,]+\s+from\s+)?['"]([^'"\n]+)['"]/g,
  /\bexport\s+[\w*${}\s,]+\s+from\s+['"]([^'"\n]+)['"]/g,
  /\bimport\(\s*['"]([^'"\n]+)['"]\s*\)/g,
];
const HTML_DEP_RE = /<(?:script|link|img|iframe)\b[^>]*?\b(?:src|href)\s*=\s*['"]([^'"#?]+)/gi;
const CSS_DEP_RE = /@import\s+(?:url\()?\s*['"]([^'"]+)['"]/g;
const PY_DEP_RE = /^\s*(?:from\s+(\.*[\w.]*)\s+import\s+([\w*, ]+)|import\s+([\w.]+))/gm;
const DEP_EXT = new Set(['js', 'mjs', 'cjs', 'jsx', 'ts', 'tsx', 'mts', 'cts', 'vue', 'svelte', 'html', 'htm', 'css', 'scss', 'py']);

function findDeps(text, ext) {
  const out = new Set();
  const add = (spec) => {
    if (spec && out.size < 200) out.add(spec);
  };
  if (ext === 'py') {
    for (const m of text.matchAll(PY_DEP_RE)) {
      if (m[3]) add(`py:${m[3]}`);
      else if (m[1] !== undefined) {
        add(`py:${m[1]}`);
        for (const name of m[2].split(',')) if (name.trim() && name.trim() !== '*') add(`py:${m[1]}${m[1].endsWith('.') || !m[1] ? '' : '.'}${name.trim()}`);
      }
    }
    return [...out];
  }
  const res = ext === 'html' || ext === 'htm' ? [HTML_DEP_RE] : ext === 'css' || ext === 'scss' ? [CSS_DEP_RE] : ext === 'vue' || ext === 'svelte' ? [...JS_DEP_RES, HTML_DEP_RE] : JS_DEP_RES;
  if (res === JS_DEP_RES) {
    // require(path.join(__dirname, '..', 'server', 'x.js'))
    for (const m of text.matchAll(/\brequire\(\s*path\.(?:join|resolve)\(\s*__dirname\s*,\s*((?:['"][^'"\n]+['"]\s*,?\s*)+)\)/g)) {
      const parts = [...m[1].matchAll(/['"]([^'"]+)['"]/g)].map((p) => p[1]);
      add(`./${path.posix.join(...parts)}`);
    }
  }
  for (const re of res) {
    for (const m of text.matchAll(re)) {
      const spec = m[1].trim();
      if (/^(?:[a-z]+:)?\/\//i.test(spec) || spec.startsWith('data:')) continue;
      add(spec);
    }
  }
  return [...out];
}

const JS_TRY = ['', '.js', '.ts', '.tsx', '.jsx', '.mjs', '.cjs', '.json', '/index.js', '/index.ts', '/index.tsx'];

// A raw spec of file `rel` -> a path in the map, or null (packages, missing files).
function resolveDep(rel, spec, known) {
  const dir = path.posix.dirname(rel);
  if (spec.startsWith('py:')) {
    const mod = spec.slice(3);
    const dots = /^\.*/.exec(mod)[0].length;
    const parts = mod.slice(dots).split('.').filter(Boolean);
    let bases;
    if (dots) {
      let base = dir;
      for (let i = 1; i < dots; i += 1) base = path.posix.dirname(base);
      bases = [base];
    } else {
      bases = [dir, '.'];
    }
    for (const base of bases) {
      const stem = path.posix.normalize(path.posix.join(base, ...parts));
      for (const cand of [`${stem}.py`, `${stem}/__init__.py`]) if (known.has(cand)) return cand;
    }
    return null;
  }
  let target;
  if (spec.startsWith('/')) target = spec.slice(1);
  else if (spec.startsWith('.')) target = path.posix.join(dir, spec);
  else target = path.posix.join(dir, spec); // <script src="app.js"> ve benzeri
  target = path.posix.normalize(target);
  if (target.startsWith('..')) return null;
  for (const suffix of JS_TRY) {
    if (known.has(target + suffix)) return target + suffix;
  }
  // "/app.js" bir web klasorunden (public/ gibi) sunuluyor olabilir
  if (spec.startsWith('/')) {
    for (const k of known) if (k.endsWith(`/${target}`) && path.posix.dirname(k) === path.posix.dirname(rel)) return k;
  }
  return null;
}

function countLines(buf) {
  let n = 0;
  for (let i = 0; i < buf.length; i += 1) if (buf[i] === 10) n += 1;
  return buf.length && buf[buf.length - 1] !== 10 ? n + 1 : n;
}

function looksBinary(buf) {
  const len = Math.min(buf.length, 8000);
  for (let i = 0; i < len; i += 1) if (buf[i] === 0) return true;
  return false;
}

async function walk(root) {
  const files = [];
  const queue = [{ dir: root, depth: 0 }];
  let truncated = false;
  while (queue.length) {
    const { dir, depth } = queue.shift();
    let entries;
    try {
      entries = await fsp.readdir(dir, { withFileTypes: true });
    } catch {
      continue;
    }
    entries.sort((a, b) => a.name.localeCompare(b.name));
    for (const entry of entries) {
      const name = entry.name;
      const abs = path.join(dir, name);
      if (entry.isDirectory()) {
        if (SKIP_DIRS.has(name)) continue;
        if (name.startsWith('.') && !KEEP_HIDDEN.has(name)) continue;
        if (depth + 1 <= MAX_DEPTH) queue.push({ dir: abs, depth: depth + 1 });
      } else if (entry.isFile()) {
        if (name === '.DS_Store') continue;
        if (files.length >= MAX_FILES) {
          truncated = true;
          continue;
        }
        files.push(abs);
      }
    }
  }
  return { files, truncated };
}

async function mapLimit(items, limit, fn) {
  const results = new Array(items.length);
  let next = 0;
  async function worker() {
    while (next < items.length) {
      const i = next;
      next += 1;
      results[i] = await fn(items[i], i);
    }
  }
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
  return results;
}

function loadNotes(cwd) {
  try {
    const notes = JSON.parse(fs.readFileSync(path.join(agentwebDir(cwd), 'notes.json'), 'utf8'));
    return notes && typeof notes === 'object' && !Array.isArray(notes) ? notes : {};
  } catch {
    return {};
  }
}

function fileHash(abs) {
  try {
    return crypto.createHash('sha1').update(fs.readFileSync(abs)).digest('hex').slice(0, 16);
  } catch {
    return '';
  }
}

// Saves Claude's short note about a file (from the agentweb MCP tool too).
function saveNote(cwd, relPath, note) {
  const rel = String(relPath || '').replace(/^\.\/+/, '');
  const abs = path.resolve(cwd, rel);
  if (!abs.startsWith(path.resolve(cwd) + path.sep)) throw new Error('Dosya proje klasörünün dışında.');
  if (!fs.existsSync(abs)) throw new Error('Dosya bulunamadı.');
  const text = String(note || '').replace(/\s+/g, ' ').trim().slice(0, MAX_NOTE_CHARS);
  const notes = loadNotes(cwd);
  const key = path.relative(cwd, abs);
  if (text) notes[key] = { note: text, hash: fileHash(abs), at: Date.now() };
  else delete notes[key];
  const keys = Object.keys(notes);
  if (keys.length > MAX_NOTES) {
    keys.sort((a, b) => (notes[a].at || 0) - (notes[b].at || 0));
    for (const k of keys.slice(0, keys.length - MAX_NOTES)) delete notes[k];
  }
  ensureDir(cwd);
  fs.writeFileSync(path.join(agentwebDir(cwd), 'notes.json'), JSON.stringify(notes, null, 1));
  return key;
}

function loadChanges(cwd) {
  try {
    const data = JSON.parse(fs.readFileSync(path.join(agentwebDir(cwd), 'changes.json'), 'utf8'));
    return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
  } catch {
    return {};
  }
}

function saveChanges(cwd, changes) {
  const keys = Object.keys(changes);
  if (keys.length > MAX_CHANGE_FILES) {
    const latest = (k) => (changes[k][0] && changes[k][0].at) || 0;
    keys.sort((a, b) => latest(a) - latest(b));
    for (const k of keys.slice(0, keys.length - MAX_CHANGE_FILES)) delete changes[k];
  }
  ensureDir(cwd);
  fs.writeFileSync(path.join(agentwebDir(cwd), 'changes.json'), JSON.stringify(changes, null, 1));
}

function cleanSummary(text) {
  return redactText(String(text || '')).replace(/\s+/g, ' ').trim().slice(0, MAX_CHANGE_CHARS);
}

function pushChange(changes, rel, entry) {
  const list = Array.isArray(changes[rel]) ? changes[rel] : [];
  list.unshift(entry);
  changes[rel] = list.slice(0, MAX_CHANGES_PER_FILE);
}

// What was done to files, in one line (the agentweb MCP tool log_change).
function logChange(cwd, relPaths, summary) {
  const text = cleanSummary(summary);
  if (!text) throw new Error('Özet boş.');
  const root = path.resolve(cwd);
  const changes = loadChanges(cwd);
  const keys = [];
  for (const p of relPaths) {
    const abs = path.resolve(cwd, String(p || '').replace(/^\.\/+/, ''));
    if (!abs.startsWith(root + path.sep)) throw new Error(`${p}: proje klasörünün dışında.`);
    const key = path.relative(cwd, abs);
    pushChange(changes, key, { at: Date.now(), s: text });
    keys.push(key);
  }
  saveChanges(cwd, changes);
  return keys;
}

// Files a turn changed (found by the map refresh), when the model gave no summary for them.
function recordTurnChanges(cwd, rels, { request, since } = {}) {
  if (!rels.length) return;
  const changes = loadChanges(cwd);
  const text = cleanSummary(request) || 'ayrıntı yok';
  const at = Date.now();
  for (const rel of rels.slice(0, MAX_CHANGED_PER_TURN)) {
    const latest = Array.isArray(changes[rel]) ? changes[rel][0] : null;
    if (latest && !latest.auto && since && latest.at >= since) continue;
    pushChange(changes, rel, { at, s: `istek: ${text}`, auto: true });
  }
  saveChanges(cwd, changes);
}

function formatBytes(n) {
  if (n < 1024) return `${n}B`;
  if (n < 1024 * 1024) return `${Math.round(n / 1024)}K`;
  return `${(n / (1024 * 1024)).toFixed(1)}M`;
}

// Builds (or refreshes) .agentweb/MAP.md. Unchanged files (same size and
// mtime) reuse the previous scan from map-cache.json.
// `change` ({ request, since }): the refresh after a turn that changed files;
// files that differ from the previous scan are recorded in changes.json.
async function buildMap(cwd, change = null) {
  const started = Date.now();
  const dir = ensureDir(cwd);
  const cacheFile = path.join(dir, 'map-cache.json');
  let cache = {};
  try {
    const saved = JSON.parse(await fsp.readFile(cacheFile, 'utf8'));
    cache = saved.v >= 2 && saved.v <= MAP_CACHE_VERSION ? saved.files || {} : {};
    if (saved.v !== MAP_CACHE_VERSION) for (const k of Object.keys(cache)) cache[k] = { ...cache[k], stale: true };
  } catch {
    cache = {};
  }
  const hadCache = Object.keys(cache).length > 0;
  const changed = [];
  const { files, truncated } = await walk(cwd);
  const nextCache = {};
  let scanned = 0;
  const rows = await mapLimit(files, STAT_CONCURRENCY, async (abs) => {
    const rel = path.relative(cwd, abs);
    let stat;
    try {
      stat = await fsp.stat(abs);
    } catch {
      return null;
    }
    const prev = cache[rel];
    const same = prev && prev.size === stat.size && prev.mtime === Math.round(stat.mtimeMs);
    if (same && !prev.stale) {
      nextCache[rel] = prev;
      return { rel, ...prev };
    }
    if (!same && hadCache) changed.push(rel);
    const entry = { size: stat.size, mtime: Math.round(stat.mtimeMs), lines: null, symbols: [] };
    const ext = extOf(rel);
    if (!BINARY_EXT.has(ext) && stat.size <= MAX_LINECOUNT_BYTES) {
      try {
        const buf = await fsp.readFile(abs);
        if (!looksBinary(buf)) {
          entry.lines = countLines(buf);
          if (stat.size <= MAX_SYMBOL_FILE_BYTES && LANGS[ext]) entry.symbols = findSymbols(buf.toString('utf8'), ext);
          if (stat.size <= MAX_SYMBOL_FILE_BYTES && DEP_EXT.has(ext)) {
            const deps = findDeps(buf.toString('utf8'), ext);
            if (deps.length) entry.deps = deps;
          }
        }
      } catch {
        // okunamadi
      }
      scanned += 1;
    }
    nextCache[rel] = entry;
    return { rel, ...entry };
  });
  if (change && changed.length) recordTurnChanges(cwd, changed.sort(), change);
  const notes = loadNotes(cwd);
  const changes = loadChanges(cwd);
  const list = rows.filter(Boolean);
  const known = new Set(list.map((r) => r.rel.split(path.sep).join('/')));
  const uses = new Map();
  const usedBy = new Map();
  for (const r of list) {
    const rel = r.rel.split(path.sep).join('/');
    const found = new Set();
    for (const spec of Array.isArray(r.deps) ? r.deps : []) {
      const target = resolveDep(rel, spec, known);
      if (target && target !== rel) found.add(target);
    }
    if (!found.size) continue;
    uses.set(rel, [...found].sort());
    for (const target of found) {
      if (!usedBy.has(target)) usedBy.set(target, []);
      usedBy.get(target).push(rel);
    }
  }
  const listOf = (items) => (items.length > MAX_DEPS_SHOWN ? `${items.slice(0, MAX_DEPS_SHOWN).join(', ')} (+${items.length - MAX_DEPS_SHOWN})` : items.join(', '));
  const day = (at) => new Date(at).toISOString().slice(0, 16).replace('T', ' ');
  const totalLines = list.reduce((sum, r) => sum + (r.lines || 0), 0);
  const header = [
    '# Proje haritası (Agent Web, otomatik üretilir, elle düzenleme)',
    `# ${new Date().toISOString().slice(0, 16).replace('T', ' ')} UTC · ${list.length} dosya · ${totalLines} satır${truncated ? ` · ilk ${MAX_FILES} dosya` : ''}`,
    '# Biçim: "yol [N satır]" (dosya notu "— not:" ile), altında "yol:satır sembol", "yol → kullanır: ...", "yol ← kullanan: ...", "yol ~ tarih: son değişiklik" satırları.',
    '# Kullanım: bu dosyayı bütün okuma; Grep ile ara (dosya adı, sembol ya da kelime): her satır yolu taşır. Sonra dosyanın sadece gereken satır aralığını aç.',
    '',
  ];
  const render = (maxSymbols) => {
    const out = [];
    for (const r of list) {
      const size = r.lines !== null && r.lines !== undefined ? `${r.lines} satır` : formatBytes(r.size);
      let line = `${r.rel} [${size}]`;
      const note = notes[r.rel];
      if (note && note.note) {
        const fresh = !note.hash || note.hash === fileHash(path.join(cwd, r.rel));
        line += ` — ${fresh ? '' : '(dosya değişti, not eski olabilir) '}not: ${note.note}`;
      }
      out.push(line);
      const key = r.rel.split(path.sep).join('/');
      if (uses.has(key)) out.push(`  ${r.rel} → kullanır: ${listOf(uses.get(key))}`);
      if (usedBy.has(key)) out.push(`  ${r.rel} ← kullanan: ${listOf(usedBy.get(key).sort())}`);
      for (const c of Array.isArray(changes[r.rel]) ? changes[r.rel] : []) {
        if (c && c.s) out.push(`  ${r.rel} ~ ${day(c.at)}: ${c.s}`);
      }
      const symbols = Array.isArray(r.symbols) ? r.symbols : [];
      for (const sym of symbols.slice(0, maxSymbols)) {
        if (Array.isArray(sym)) out.push(`  ${r.rel}:${sym[0]} ${sym[1]}`);
      }
      if (symbols.length > maxSymbols) out.push(`  ${r.rel} (+${symbols.length - maxSymbols} sembol daha)`);
    }
    return header.join('\n') + out.join('\n') + '\n';
  };
  let text = render(MAX_SYMBOLS_PER_FILE);
  // Too big: fewer symbols per file, at worst only the paths.
  for (const max of [40, 10, 0]) {
    if (Buffer.byteLength(text) <= MAX_MAP_BYTES) break;
    text = render(max);
  }
  await fsp.writeFile(path.join(dir, 'MAP.md'), text);
  await fsp.writeFile(cacheFile, JSON.stringify({ v: MAP_CACHE_VERSION, files: nextCache }));
  return { files: list.length, lines: totalLines, scanned, changed: change ? changed.length : 0, ms: Date.now() - started, truncated };
}

// One refresh at a time per folder; a request during a build runs once more after it.
const builds = new Map();
function refreshMap(cwd, change = null) {
  const current = builds.get(cwd);
  if (current) {
    current.again = true;
    if (change) current.change = mergeChange(current.change, change);
    return current.promise;
  }
  const job = { again: false, change, promise: null };
  job.promise = (async () => {
    let result = null;
    try {
      do {
        job.again = false;
        const next = job.change;
        job.change = null;
        result = await buildMap(cwd, next);
      } while (job.again);
    } catch (err) {
      result = { error: err.message };
    } finally {
      builds.delete(cwd);
    }
    return result;
  })();
  builds.set(cwd, job);
  return job.promise;
}

function mergeChange(a, b) {
  if (!a) return b;
  if (!b) return a;
  return { request: b.request || a.request, since: Math.min(a.since || Infinity, b.since || Infinity) };
}

function mapAge(cwd) {
  try {
    return Date.now() - fs.statSync(path.join(agentwebDir(cwd), 'MAP.md')).mtimeMs;
  } catch {
    return Infinity;
  }
}

function mapStats(cwd) {
  // Only the header line is needed (the map can be megabytes).
  let text = '';
  try {
    const fd = fs.openSync(path.join(agentwebDir(cwd), 'MAP.md'), 'r');
    const buf = Buffer.alloc(400);
    const n = fs.readSync(fd, buf, 0, 400, 0);
    fs.closeSync(fd);
    text = buf.subarray(0, n).toString('utf8');
  } catch {
    text = '';
  }
  const m = /· (\d+) dosya · (\d+) satır/.exec(text);
  return m ? { files: Number(m[1]), lines: Number(m[2]) } : null;
}

// The map entry of one file (its symbols, for the big-read guard).
function mapEntry(cwd, rel) {
  try {
    const cache = JSON.parse(fs.readFileSync(path.join(agentwebDir(cwd), 'map-cache.json'), 'utf8')).files || {};
    return cache[rel] || null;
  } catch {
    return null;
  }
}

function noteFor(cwd, rel) {
  const note = loadNotes(cwd)[rel];
  if (!note || !note.note) return null;
  const fresh = !note.hash || note.hash === fileHash(path.join(cwd, rel));
  return { text: note.note, fresh };
}

function readMemory(cwd) {
  const dir = agentwebDir(cwd);
  return {
    memory: readText(path.join(dir, 'MEMORY.md'), MAX_MEMORY_CHARS).trim(),
    handoff: readText(path.join(dir, 'HANDOFF.md'), MAX_HANDOFF_CHARS).trim(),
  };
}

function writeFile(cwd, name, text) {
  ensureDir(cwd);
  fs.writeFileSync(path.join(agentwebDir(cwd), name), text);
}

// The system-prompt section a new conversation starts with. Frozen for the
// whole conversation (the chat keeps it in state.json), so the prompt cache
// prefix never changes mid-conversation.
function buildPrimer(cwd, { previousChat, engine } = {}) {
  ensureDir(cwd);
  const { memory, handoff } = readMemory(cwd);
  const stats = mapStats(cwd);
  const lines = [
    '',
    '# Project memory (Agent Web)',
    `The folder ${DIR}/ in the working directory keeps what earlier conversations learned, so a new conversation does not have to re-read the project. Re-reading a project costs the user a large part of their usage limit; avoid it.`,
    `- ${DIR}/MAP.md: every file with its line count, its functions/classes with line numbers, which project files it uses and is used by, and its last changes${stats ? ` (${stats.files} files, ${stats.lines} lines)` : ''}. Generated automatically after each turn. Never read it whole: search it (a file name, symbol or word); every line starts with the file path, so the matching lines alone tell where something is, what depends on it and what was last done to it. Search it before listing folders or opening files, and do not guess paths.`,
    `- ${DIR}/MEMORY.md (shown below): durable knowledge about the project. Keep it current: when you learn something worth knowing next time (purpose, architecture, where things live, how to build/run/test, conventions, decisions and their reasons, pitfalls), add or correct it concisely. Keep it under ~150 lines; replace stale lines instead of appending forever.`,
    `- ${DIR}/HANDOFF.md (shown below): where the work stands. Before you finish a substantial piece of work (and whenever the user is about to leave), overwrite it with: what was done, the current state, next steps, open questions (under ~40 lines).`,
    engine === 'gemini'
      ? null
      : '- After you have read and understood a large file, call mcp__agentweb__note_file with a 1-3 line summary of what it contains; the map shows the note next time, so the file need not be read again just to know what is in it.',
    engine === 'gemini'
      ? '- After finishing a change to files, call the log_change tool of the "agentweb" MCP server once (when available) with the changed paths and a one-line summary of what was done; it is shown under each file in the map.'
      : '- After finishing a change to files, call mcp__agentweb__log_change once with the changed paths and a one-line summary of what was done (searchable words); it is shown under each file in the map. Changed files are also recorded automatically with the request text.',
    engine === 'gemini'
      ? '- Read only what the task needs: search the map first, then read just the relevant line ranges. Do not read whole large files or whole folders "to get context".'
      : '- Read only what the task needs: use the map, Grep and Read with offset/limit for the relevant line ranges. Do not read whole large files or whole folders "to get context".',
  ].filter((line) => line !== null);
  lines.push('', '<project_memory file=".agentweb/MEMORY.md">', memory || '(empty: this project has no memory yet; write MEMORY.md as you learn the project)', '</project_memory>');
  if (handoff) lines.push('', '<handoff file=".agentweb/HANDOFF.md">', handoff, '</handoff>');
  if (previousChat) lines.push('', '<previous_conversation_summary>', previousChat, '</previous_conversation_summary>');
  return lines.join('\n');
}

module.exports = {
  DIR,
  agentwebDir,
  ensureDir,
  buildMap,
  refreshMap,
  mapAge,
  mapStats,
  mapEntry,
  noteFor,
  saveNote,
  logChange,
  mergeChange,
  findDeps,
  resolveDep,
  readMemory,
  writeFile,
  buildPrimer,
  findSymbols,
};