reliary-agent 0.6.2

Grammar-free code intelligence daemon, CLI, MCP server, and API proxy.
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
const { execFileSync, spawnSync } = require("child_process");
const { existsSync, readFileSync, readdirSync, statSync, unlinkSync } = require("fs");
const { createHash } = require("crypto");

const GATE_VERSION = "2.6.0";

// ── Log levels (matching RELIARY_LOG convention) ──
const LOG_LEVELS = { error: 1, warn: 2, info: 3, debug: 4, trace: 5 };
let LOG_LEVEL = 3; // default: info
try {
  if (process.env.RELIARY_LOG && LOG_LEVELS[process.env.RELIARY_LOG] !== undefined) {
    LOG_LEVEL = LOG_LEVELS[process.env.RELIARY_LOG];
  } else if (process.env.RUST_LOG) {
    const rl = process.env.RUST_LOG;
    if (rl.includes("trace")) LOG_LEVEL = 5;
    else if (rl.includes("debug")) LOG_LEVEL = 4;
    else if (rl.includes("warn")) LOG_LEVEL = 2;
    else if (rl.includes("error")) LOG_LEVEL = 1;
  }
} catch {}

let lastLogTime = Date.now();

function gateLog(level, msg) {
  const lv = LOG_LEVELS[level];
  if (lv === undefined || lv > LOG_LEVEL) return;
  const now = Date.now();
  const dt = ((now - lastLogTime) / 1000).toFixed(1);
  lastLogTime = now;
  const sym = { error: "⛔", warn: "⚠", info: "•", debug: "↓", trace: "·" }[level] || "•";
  console.error(`[gate] ${sym} ${msg} (${dt}s)`);
}

// ── Binary discovery (env var → PATH → hardcoded paths) ──
let RELIARY_BIN = process.env.RELIARY_BIN_PATH || null;
if (!RELIARY_BIN) {
  // Check PATH first
  try {
    const which = execFileSync("which", ["reliary-agent"], { encoding: "utf-8", timeout: 2000 });
    if (which) RELIARY_BIN = which.trim();
  } catch {}
}
if (!RELIARY_BIN) {
  // Check hardcoded paths as fallback
  for (const c of [
    "/usr/local/bin/reliary-agent",
    "/usr/bin/reliary-agent",
  ]) { if (existsSync(c)) { RELIARY_BIN = c; break; } }
}

gateLog("info", `v${GATE_VERSION} — reliary: ${!!RELIARY_BIN}${RELIARY_BIN ? ` (${RELIARY_BIN.split("/").pop()})` : " none"}`);

const CODE_EXTS = new Set([
  ".py", ".rs", ".js", ".ts", ".tsx", ".jsx",
  ".cpp", ".c", ".h", ".hpp", ".go", ".java",
  ".rb", ".swift", ".kt", ".scala",
]);

let blockedCount = 0;
let sessionTurns = 0;
let repoRoot = null;

// ── Config mode: query daemon or env var ──
// ── Gate configuration ──
let GATE_MODE = "strict"; // default (transparent redirect, auto-deescalates to reactive after 5 redirects)
try {
  if (RELIARY_BIN) {
    const modeCmd = execFileSync(RELIARY_BIN, ["config"], { encoding: "utf-8", timeout: 3000, maxBuffer: 512 });
    const m = (modeCmd || "").match(/gate mode: (\w+)/);
    if (m) GATE_MODE = m[1];
  }
} catch { /* daemon query failed — use default */ }
try {
  if (process.env.RELIARY_MODE) {
    GATE_MODE = process.env.RELIARY_MODE;
  }
} catch { /* env var check failed */ }

// ── Feature flags ──
// Each can be disabled via RELIARY_FEATURES env var (e.g. "-healEdit,-convWindow")
const FEATURES = {
  healEdit: true,       // route edit/write/sed through heal-apply
  compress: true,       // inline reasoning compression
  convWindow: true,     // drop old verbose tool results
  readEnrichment: true, // compress non-target read results
};
if (process.env.RELIARY_FEATURES) {
  for (const f of process.env.RELIARY_FEATURES.split(",")) {
    const isDisable = f.startsWith("-");
    const name = isDisable ? f.slice(1) : f.startsWith("+") ? f.slice(1) : f;
    if (name) FEATURES[name] = !isDisable;
  }
}

// ── Reactive safety level ──
// 0 = fast (pure IR compression), 1 = safe (heal-apply + veto), 2 = strict (bash/write blocked)
let safetyLevel = 0;
let safetyExpiresAt = 0;
let readSpiralCount = {}; // path → count of reads without edit

function maybeEscalate(reason, level, turns) {
  if (safetyLevel >= level) return;
  safetyLevel = level;
  safetyExpiresAt = sessionTurns + turns;
  gateLog("warn", `safety ${level} for ${turns}t: ${reason}`);
}

// ── Read dedup cache (daemon-backed, persists across Pi restarts) ──
const readCache = {};

function daemonCmd(cmd) {
  try {
    const args = cmd.split(" ");
    // Use spawnSync with proper array args to avoid path-with-spaces issues
    const r = execFileSync(RELIARY_BIN, args, {
      encoding: "utf-8", timeout: 10000, maxBuffer: 4096,
    });
    return r.trim();
  } catch { return null; }
}

// ── Daemon health check: verify binary exists (TCP check would require daemon running) ──
let DAEMON_HEALTHY = true; // assume healthy — CLI fallback handles gracefully

function cacheRead(path, hash, len) {
  return daemonCmd(`cache-read ${path} ${hash} ${len}`);
}

function checkRead(path, hash) {
  return daemonCmd(`check-read ${path} ${hash}`);
}

function extractWorkdir(msgs) {
  for (const m of msgs) {
    if (m.role !== "user") continue;
    const text = extractMessageText(m);
    if (!text) continue;
    let m2 = text.match(/\/(?:[\w./-]+)\/(?:src|tests?|lib|bin)/);
    if (m2) return m2[0].split("/src")[0];
    m2 = text.match(/\/(?:tmp|home|Users)\/[^\s,;)]{3,120}/);
    if (m2) return m2[0].replace(/\/$/,'');
  }
  return null;
}

// ── Extract text content from the various Pi message block shapes ──
function extractMessageText(m) {
  if (!m) return null;
  const content = m.content;
  if (!content) return m.text || null;
  if (typeof content === "string") return content;
  if (Array.isArray(content)) {
    for (const b of content) {
      if (b.type === "text" && b.text) return b.text;
      if (b.type === "thinking" && b.thinking) return b.thinking;
    }
  }
  return null;
}

function extractText(content) {
  if (!content) return "";
  if (typeof content === "string") return content;
  if (Array.isArray(content)) {
    return content.map(b => b.text || b.thinking || "").filter(Boolean).join("\n");
  }
  return "";
}

function isCodeFile(p) {
  const ext = p.split(".").pop();
  return CODE_EXTS.has("." + (ext || ""));
}

// ── Extract function/class signatures for read enrichment ──
function extractSignatures(text) {
  const names = [];
  const re = /^\s*(pub\s+)?(fn|def|class|struct|enum|trait|function|func)\s+(\w+)/;
  for (const line of text.split("\n")) {
    const m = line.match(re);
    if (m) names.push({ name: m[3], line: line.trim() });
  }
  return { names, found: names.length };
}

// ── Build structured summary from raw file content ──
function buildStructuredSummary(content, filePath) {
  const sigs = extractSignatures(content);
  const header = `[${filePath.split("/").pop()}] ${content.split("\n").length}L | ${sigs.found} defs`;
  const defs = sigs.names.slice(0, 6).map(n => `  ${n.line}`).join("\n");
  let enriched = `${header}${defs ? "\n" + defs : ""}`;
  if (enriched.length > 600) enriched = enriched.slice(0, 600);
  return enriched;
}

// ── Dynamic hook guards (unused but kept for compatibility) ──
function isMature(turns) { return sessionTurns >= turns; }

function qualMaxBlocks() {
  if (!isMature(3)) return 0;
  if (!isMature(6)) return 1;
  if (!isMature(10)) return 2;
  return 3;
}

// ── Strict mode redirect helpers (transparent, LLM never sees "blocked") ──
let strictRedirects = 0;

function redirectBash(cmd, workdir) {
  // cargo test / pytest → test tool
  if (/cargo\s+test|pytest|npm\s+test|python3?\s+-m\s+pytest/.test(cmd)) {
    gateLog("debug", "redirect bash(test)→test");
    const result = runTest(workdir || process.cwd());
    const sifted = siftOutput(result);
    return { block: true, response: sifted !== result ? sifted : result };
  }

  // cat / head / tail file → read tool
  const readMatch = cmd.match(/\b(?:cat|head|tail)\s+(.+)/);
  if (readMatch) {
    const file = readMatch[1].trim();
    gateLog("debug", "redirect bash(cat)→read");
    try {
      const content = readFileSync(file, "utf-8");
      const lines = content.split("\n");
      let result;
      if (lines.length > 50) {
        result = `[${file}] ${lines.length} lines\n\n` + lines.slice(0, 40).join("\n") + `\n... (${lines.length - 40} more lines)\n\n` + lines.slice(-10).join("\n");
      } else {
        result = content;
      }
      return { block: true, response: result };
    } catch (e) {
      return { block: true, response: `ERROR: ${e.message}` };
    }
  }

  // grep / rg → search tool
  if (/grep|rg\b|ripgrep/.test(cmd)) {
    const query = cmd.replace(/.*\bgrep\b\s*/, "").replace(/^['"]|['"]$/g, "").trim();
    gateLog("debug", "redirect bash(grep)→search");
    const result = daemonCmd(`search ${query}`) || "no results";
    return { block: true, response: `[redirected to search]\n${result}` };
  }

  // ls / find → directory listing
  if (/^ls\b/.test(cmd)) {
    const target = cmd.replace(/^ls\s*/, "").trim() || ".";
    gateLog("debug", "redirect bash(ls)→read");
    try {
      const entries = readdirSync(target);
      const lines = entries.slice(0, 40).join("\n");
      return { block: true, response: `${target}/ (${entries.length} entries)\n${lines}` + (entries.length > 40 ? `\n... (${entries.length - 40} more)` : "") };
    } catch (e) {
      return { block: true, response: `ERROR: ${e.message}` };
    }
  }

  // sed → edit via file healing
  const sedEdit = cmd.match(/sed\s+-i\s+['"]?s\/([^/]+)\/([^/]*)\/['"]?\s*(.+)/);
  if (sedEdit) {
    gateLog("debug", "redirect bash(sed)→edit");
    return { block: true, response: `[redirected to edit] Use the edit tool to modify ${sedEdit[3].trim()}` };
  }

  // Fall back to runTest (most commands are test runners)
  gateLog("debug", "redirect bash→test");
  const result = runTest(workdir || process.cwd());
  const sifted = siftOutput(result);
  return { block: true, response: sifted !== result ? sifted : result };
}

function redirectCreate(filePath, content) {
  try {
    writeFileSync(filePath, content, "utf-8");
    return `Created ${filePath} (${content.length} chars)`;
  } catch (e) {
    return `ERROR: ${e.message}`;
  }
}

function redirectEdit(filePath, oldText, newText) {
  try {
    if (!existsSync(filePath)) return `ERROR: ${filePath} does not exist`;
    const content = readFileSync(filePath, "utf-8");
    const modified = oldText ? content.replace(oldText, newText) : newText;
    writeFileSync(filePath, modified, "utf-8");
    return `Updated ${filePath}`;
  } catch (e) {
    return `ERROR: ${e.message}`;
  }
}

// ── Grammar-free test runner via daemon ──
function runTest(workdir) {
  if (!RELIARY_BIN) return "ERROR: reliary-agent not available";
  try {
    const r = execFileSync(RELIARY_BIN, ["test", workdir], {
      encoding: "utf-8", timeout: 120000, maxBuffer: 32768,
    });
    return r.trim();
  } catch (e) {
    return "ERROR: test execution failed";
  }
}

// ── Hook A: tool_result — read dedup + compression ──
function handleToolResult(event) {
  const name = event.toolName;
  const input = event.input || {};
  const text = extractText(event.content);
  if (!text || text.length < 200) return;
  const pathHint = input.path || input.file || null;

  // Read dedup + enrichment + debug spiral detection
  if (name === "read" && pathHint && !input.offset && !input.limit) {
    // Debug spiral: if same file read 3x without edit, escalate to strict
    if (pathHint in readSpiralCount) {
      readSpiralCount[pathHint]++;
      if (readSpiralCount[pathHint] >= 3) {
        maybeEscalate(`debug spiral: ${pathHint} read ${readSpiralCount[pathHint]}x without edit`, 2, 10);
      }
    } else {
      readSpiralCount[pathHint] = 0; // will be incremented on next read
    }
    // Track reads
    readSpiralCount[pathHint] = (readSpiralCount[pathHint] || 0) + 1;

    try {
      const hash = createHash("sha256").update(text).digest("hex").slice(0, 16);
      if (readCache[pathHint] === hash) {
        gateLog("debug", `dedup: ${pathHint} (${text.length}c)`);
        return { content: [{ type: "text", text: `[reliary: ${hash.slice(0,8)}] ${pathHint} — unchanged (${text.length} chars)` }] };
      }
      readCache[pathHint] = hash;
      if (RELIARY_BIN) cacheRead(pathHint, hash.slice(0, 16), text.length);
    } catch {}
  }

  // Read content: build structured summary (grammar-free) or sift for large files
  if (name === "read" && text.length > 1000) {
    // Large files: sift first (collapses structural noise), then fall back to summary
    if (text.length > 5000 && !input.offset && !input.limit) {
      const sifted = siftOutput(text);
      if (sifted !== text) {
        gateLog("debug", `read: ${(pathHint || name).split("/").pop()} ${text.length}→${sifted.length}c (${Math.round((1-sifted.length/text.length)*100)}%)`);
        return { content: [{ type: "text", text: sifted }] };
      }
    }
    // Medium files: structured summary (signatures + callers)
    const enriched = buildStructuredSummary(text, pathHint || name);
    if (enriched && enriched.length < text.length * 0.8) {
      gateLog("debug", `read: ${(pathHint || name).split("/").pop()} ${text.length}→${enriched.length}c (${Math.round((1-enriched.length/text.length)*100)}%)`);
      return { content: [{ type: "text", text: enriched }] };
    }
  }

  // Sift: compress any tool result with repeated patterns
  if (text.length > 300) {
    const compressed = siftOutput(text);
    if (compressed !== text) {
      gateLog("debug", `sift: ${name} ${text.length}→${compressed.length}c (${Math.round((1-compressed.length/text.length)*100)}%)`);
      return { content: [{ type: "text", text: compressed }] };
    }
  }
}

// ── Sift: inline class-line compression ──
function siftOutput(text) {
  if (text.length <= 300) return text;
  const lines = text.split("\n");

  // Classify each line
  const types = lines.map(l => {
    const t = l.trim();
    if (!t) return "blank";
    if (/^(Compiling|Checking|Building|Linking|Running)\b/.test(t)) return "progress";
    if (t === "ok" || /\b\.\.\. ok$/.test(t)) return "ok";
    if (/\b(FAILED|failed|error|Error|ERROR|E\d{4}|Traceback)\b/.test(t)) return "error";
    if (t.startsWith("  --> ") || t.startsWith("   = help") || t.startsWith("   = note")) return "help";
    return "code";
  });

  // Collapse runs of 3+ same-type lines
  const collapsed = [];
  let i = 0;
  while (i < lines.length) {
    const type = types[i];
    let j = i + 1;
    while (j < lines.length && types[j] === type) j++;
    const count = j - i;
    if (count >= 3 && (type === "progress" || type === "ok" || type === "blank")) {
      collapsed.push(type === "ok" ? `[${count} ok]` : type === "blank" ? "" : `[${count} ${lines[i].trim().split(/\s/)[0]} ...]`);
      i = j;
    } else {
      collapsed.push(lines[i]);
      i++;
    }
  }

  const result = collapsed.filter(l => l !== undefined && l !== null).join("\n");
  return result.length < text.length ? result : text;
}

// ── Hook B: tool_call — handle test/explain, pass read/edit through ──
function handleToolCall(event) {
  const name = event.toolName;
  const input = event.input || {};

  // Test tool: run grammar-free test runner via daemon
  if (name === "test") {
    const workdir = input.workdir || input.path || process.cwd();
    gateLog("info", `test: ${workdir}`);
    const result = runTest(workdir);
    const sifted = siftOutput(result);
    return { block: true, response: sifted !== result ? sifted : result };
  }

  // Explain tool: get function context
  if (name === "explain") {
    const file = input.file || input.path || "";
    const func = input.function || input.name || "";
    if (!file || !func) {
      return { block: true, response: "ERROR: explain requires 'file' and 'function' parameters" };
    }
    try {
      const content = readFileSync(file, "utf-8");
      const lines = content.split("\n");
      const sigs = extractSignatures(content);
      const target = sigs.names.find(n => n.name.includes(func) || func.includes(n.name));
      const lineNo = target ? lines.indexOf(target.line) + 1 : 0;
      let result = `[${file.split("/").pop()}] L${lineNo || "?"}: ${target?.line || func}\n`;
      if (sigs.found > 0) result += `defs: ${sigs.names.slice(0, 5).map(n => n.name).join(", ")}${sigs.found > 5 ? " (+" + (sigs.found - 5) + ")" : ""}\n`;
      result += `risk: ${daemonCmd(`risk ${file}`) || "unknown"}`;
      gateLog("debug", `explain: ${file} → ${func}`);
      return { block: true, response: result };
    } catch (e) {
      return { block: true, response: `ERROR: ${e.message}` };
    }
  }

  // Create tool: write new file with content, run heal on project
  if (name === "create") {
    const file = input.file || input.path || "";
    if (!file) return { block: true, response: "ERROR: create requires 'file' parameter" };
    const content = input.content || "";
    if (!content) return { block: true, response: "ERROR: create requires 'content' parameter" };
    try {
      if (existsSync(file)) return { block: true, response: `ERROR: ${file} already exists (use edit to modify)` };
      writeFileSync(file, content, "utf-8");
      gateLog("debug", `create: ${file} (${content.length}c)`);
      return { block: true, response: `Created ${file} (${content.length} chars). Run 'test <workdir>' to verify.` };
    } catch (e) {
      return { block: true, response: `ERROR: ${e.message}` };
    }
  }

  // Bash: intercept and redirect in strict mode, sed-heal in reactive
  if (name === "bash") {
    const cmd = input.command || "";

    // Strict mode: transparent redirect to sandbox tools
    if (safetyLevel >= 2) {
      // Track redirect count for auto-deescalation
      strictRedirects = (strictRedirects || 0) + 1;
      if (strictRedirects >= 5) {
        gateLog("warn", `auto-deescalate: ${strictRedirects} redirects`);
        safetyLevel = 1;
        // Fall through to reactive mode
      } else {
        return redirectBash(cmd, getRepoRoot() || process.cwd());
      }
    }

    // Route sed -i commands through heal-apply (if enabled)
    if (FEATURES.healEdit) {
      const sedMatch = cmd.match(/sed\s+-i\s+['"]?s\/([^/]+)\/([^/]*)\/['"]?\s*(.+)/);
      if (sedMatch) {
        const oldText = sedMatch[1];
        const newText = sedMatch[2];
        const filePath = sedMatch[3].trim();
        gateLog("debug", `heal-sed: ${filePath} "${oldText}" → "${newText}"`);
        const result = daemonCmd(`sed-apply ${filePath} ${oldText} ${newText} ${getRepoRoot() || "."}`);
        return { block: true, response: `Edit applied via healing: ${result || "no match"}` };
      }
    }
    // Fast mode: monitor for destructive patterns, escalate if found
    const dd = /sed\s+-i|rm\s+(?:-rf?\s+)?\S+\.(?:py|rs|js|ts|tsx)|\s>\s*\S+\.(?:py|rs|js|ts|tsx)/i;
    if (dd.test(cmd)) {
      maybeEscalate(`destructive bash: ${cmd.slice(0, 40)}`, 1, 3);
    }
    return; // pass through
  }

  // Write: redirect in strict, heal-apply in reactive
  if (name === "write") {
    const filePath = input.file || input.path || "";
    const content = input.content || "";
    if (safetyLevel >= 2 && filePath && content) {
      strictRedirects = (strictRedirects || 0) + 1;
      if (strictRedirects >= 5) {
        gateLog("warn", `auto-deescalate: ${strictRedirects} redirects`);
        safetyLevel = 1;
      } else if (!existsSync(filePath)) {
        return { block: true, response: redirectCreate(filePath, content) };
      } else {
        return { block: true, response: redirectEdit(filePath, "", content) };
      }
    }
    if (FEATURES.healEdit && filePath && content && existsSync(filePath)) {
      gateLog("debug", `heal-write: ${filePath}`);
      const tmpFile = `/tmp/gate-heal-write-${Date.now()}.tmp`;
      try { writeFileSync(tmpFile, content, "utf-8"); } catch {
        return { block: true, response: `ERROR: could not write temp file` };
      }
      const result = daemonCmd(`apply-edit ${filePath} ${tmpFile} ${getRepoRoot() || "."}`);
      try { unlinkSync(tmpFile); } catch {}
      if (result && result.trim() !== "") {
        return { block: true, response: `Edit applied via healing: ${result}` };
      }
    }
    return; // pass through (reactive mode)
  }

  // Grep: redirect to search in strict mode
  if (name === "grep") {
    if (safetyLevel >= 2) {
      strictRedirects = (strictRedirects || 0) + 1;
      if (strictRedirects >= 5) {
        gateLog("warn", `auto-deescalate: ${strictRedirects} redirects`);
        safetyLevel = 1;
      } else {
        const query = (input.command || input.pattern || "").replace(/^.*?\b(\w+).*$/, "$1");
        gateLog("debug", "grep→search: " + query);
        return { block: true, response: `[redirected to search] ` + (daemonCmd(`search ${query}`) || "no results") };
      }
    }
    return; // pass through
  }

  // Edit: heal-apply with daemon (reactive safety — veto escalates on hallucination)
  if (name === "edit") {
    const path = input.path;
    if (!path || !isCodeFile(path)) return;
    // Clear read spiral count for this file (edit indicates progress)
    delete readSpiralCount[path];

    // Vet the edit
    const edits = input.edits || [];
    if (edits.length > 0 && edits[0].newText && RELIARY_BIN && FEATURES.healEdit) {
      // Veto check at safetyLevel >= 1
      if (safetyLevel >= 1) {
        const vetoResult = reliaryVeto(path, edits[0].newText);
        if (vetoResult && vetoResult.startsWith("ERROR")) {
          maybeEscalate(`veto blocked: ${path} — ${vetoResult.substring(7, 50)}`, 1, 3);
          return { block: true, response: vetoResult };
        }
      }
      try {
        const content = readFileSync(path, "utf-8");
        const oldText = edits[0].oldText || "";
        const newText = edits[0].newText || "";
        const modified = content.replace(oldText, newText);
        if (modified === content) {
          return { block: true, response: `ERROR: could not find oldText in ${path}` };
        }
        const tmpFile = `/tmp/gate-heal-${Date.now()}.tmp`;
        writeFileSync(tmpFile, modified, "utf-8");
        const healResult = daemonCmd(`apply-edit ${path} ${tmpFile} ${getRepoRoot() || ""}`);
        try { unlinkSync(tmpFile); } catch {}
        if (healResult && healResult.startsWith("REVERTED")) {
          maybeEscalate(`heal reverted: ${path}`, 1, 3);
          return { block: true, response: `Edit reverted: ${healResult.substring(9)}` };
        }
        return { block: true, response: `Edit applied and verified: ${healResult || "ok"}` };
      } catch (e) {
        return { block: true, response: `ERROR: ${e.message}` };
      }
    }
  }
}

// ── Compression: reasoning-level IR compression (grammar-free) ──
function compressReasoning(text) {
  if (!text || text.length < 600) return null;
  if (sessionTurns < 3 && text.length < 1500) return null;
  if (text.includes("```") || text.includes("//") || text.includes("/*")
      || text.includes("src/") || text.includes(".rs:") || text.includes(".py:")
      || text.includes("s/") || text.includes(".md")) return null; // contains code — skip

  // Direct reliary-agent compress call
  if (RELIARY_BIN) {
    try {
      const r = spawnSync(RELIARY_BIN, ["-f", "compact", "compress", "--gentle", "---stdin---"], {
        encoding: "utf-8", input: text, timeout: 5000, maxBuffer: 8192,
      });
      if (r.status === 0 && r.stdout) {
        const out = r.stdout.trim();
        if (out && out.length < text.length * 0.85) return out;
      }
    } catch {}
  }
  return null;
}

function applyReasoningCompression(msgs) {
  let count = 0;
  for (let i = 0; i < msgs.length - 2; i++) {
    const m = msgs[i];
    if (m.role !== "assistant") continue;
    if (!Array.isArray(m.content)) continue;
    for (const block of m.content) {
      if (block.type === "thinking" && block.thinking?.length > 300) {
        const compact = compressReasoning(block.thinking);
        if (compact) { block.thinking = compact; count++; }
      }
      if (block.type === "text" && block.text?.length > 400) {
        const compact = compressReasoning(block.text);
        if (compact) { block.text = compact; count++; }
      }
    }
  }
  return count;
}

// ── Edit merge: combine sequential edits to same file ──
function compressEditCalls(msgs) {
  for (let i = 1; i < msgs.length; i++) {
    const m = msgs[i];
    if (m.role !== "assistant") continue;
    const prev = msgs[i - 1];
    if (prev.role !== "assistant") continue;
    let prevEdits = null, curEdits = null;
    if (Array.isArray(prev.content)) {
      for (const b of prev.content) {
        if (b.type === "text" && b.text) {
          const m2 = b.text.match(/\[(edit|tool_call|apply)\]/);
        }
      }
    }
  }
  return msgs;
}

// ── Conversation window: collapse old turns at 10+ messages ──
function applyConversationWindow(msgs) {
  const n = msgs.length;
  if (n < 10) return msgs;
  const keepFirst = 2;
  const keepLast = 6;
  const middle = msgs.slice(keepFirst, n - keepLast);
  if (middle.length < 2) return msgs;
  const summary = middle
    .filter(m => m.role === "assistant")
    .map(m => {
      let text = "";
      if (Array.isArray(m.content)) {
        for (const b of m.content) {
          if (b.type === "text") text += b.text;
          else if (b.type === "thinking") text += b.thinking;
          else if (b.type === "toolCall") text += `[${b.name || "tool"}]`;
        }
      }
      const compressed = compressReasoning(text);
      return compressed || text.slice(0, 100);
    })
    .filter(Boolean)
    .join(" | ");
  if (!summary) return msgs;
  gateLog("debug", `conv-window: collapsed ${middle.length} msgs → ${summary.length}c`);
  return [...msgs.slice(0, keepFirst),
    { role: "system", content: `[collapsed ${middle.length} prior msgs: ${summary.slice(0, 300)}]` },
    ...msgs.slice(n - keepLast)];
}

// ── Hook C: before_provider_request — IR reasoning compression + conv window + prior injection ──
function handleBeforeProviderRequest(event) {
  const payload = event.payload;
  if (!payload || !Array.isArray(payload.messages)) return;
  let msgs = payload.messages;

  let turnCount = 0;
  for (const m of msgs) { if (m.role === "user") turnCount++; }
  if (turnCount > sessionTurns) {
    gateLog("info", `turn ${turnCount} (prev: ${sessionTurns})`);
    sessionTurns = turnCount;
  }

  // Reactive safety expiry: if expired, drop back to fast mode
  if (safetyLevel > 0 && safetyExpiresAt <= sessionTurns) {
    safetyLevel = 0;
    gateLog("info", "safety expired — back to fast mode");
  }

  // Turn 1: inject chronicled prior (Phase 2)
  if (turnCount === 1 && RELIARY_BIN) {
    const workdir = extractWorkdir(msgs);
    if (workdir) {
      try {
        const r = execFileSync(RELIARY_BIN, ["prior", workdir], {
          encoding: "utf-8", timeout: 5000, maxBuffer: 4096,
        });
        const priorBlock = r.trim();
        if (priorBlock) {
          msgs.splice(1, 0, { role: "system", content: priorBlock });
          gateLog("debug", `prior: ${priorBlock.substring(0, 80)}`);
        }
      } catch {}
    }
  }

  // Compress reasoning in all prior assistant messages
  const compCount = applyReasoningCompression(msgs);
  if (compCount > 0) gateLog("debug", `compressed ${compCount} blocks`);

  msgs = applyConversationWindow(msgs);
  msgs = compressEditCalls(msgs);
  return { ...payload, messages: msgs };
}

// ── Export: register hooks ──
// ── Export: register hooks (CommonJS for Pi extension loader) ──
module.exports = function (pi) {
  pi.on("tool_result", handleToolResult);
  pi.on("tool_call", handleToolCall);
  pi.on("before_provider_request", handleBeforeProviderRequest);
  process.on("exit", () => {});
}