Skip to content

Commit a090665

Browse files
author
YZLLM
committed
feat(gate-overlay): arac ani muhafizi - overlay-guard.mjs (PreToolUse kancasi)
Dosya odakli overlay gate'lerinin (file_immutable, forbid_new_files, forbid_dependency_change) yazma araci CAGRILDIGI anda uygulanmasi. Claude Code sozlesmesi: exit 0 = izin, exit 2 = engel; stderr metni modele geri doner. Guvenlik tasarimi (bilincli): - Kurallar DOSYADAN OKUNMAZ, komut satirinda base64 gomulu gelir. Ajan proje icindeki her dosyaya (.mycl dahil) yazabilir - kural dosyasi olsaydi ajan kendi kilidini silebilirdi. Calisan surecin argv'sini degistiremez -> kurallar iterasyon boyunca donuk (AD-3). - Betik alan bilgisi tasimaz: korunan yollar ve bagimlilik dosyasi adlari MyCL'in derleme aninda hesapladigi VERI olarak gelir. - HATA = ENGEL (fail-closed): kurallar cozulmuyorsa, stdin bozuksa, yol alani yoksa exit 2. Patlama yaricapi matcher ile yalniz yazma araclarina sinirli. - Dolambacli yol (sub/../x) resolve ile duzlesir - engel asilamaz. Proje disi yol overlay'in isi degil (kum havuzu yonetir). - SessionStart kanaryasi (--ack): Claude sema gecersiz ayar blogunu SESSIZCE yutuyor (ampirik, 2.1.227) - isaret dosyasi yoksa MyCL kancalarin hic yuklenmedigini anlayip iterasyonu gurultulu durduracak (Faz C baglar). orchestrator/*.mjs tauri resources globu bu betigi otomatik paketler. 18 sozlesme testi (gercek surec + tmpdir).
1 parent 28a0a66 commit a090665

2 files changed

Lines changed: 307 additions & 0 deletions

File tree

‎orchestrator/overlay-guard.mjs‎

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
#!/usr/bin/env node
2+
// overlay-guard — iterasyon gate overlay'inin ARAÇ ANI muhafızı (Claude Code PreToolUse kancası).
3+
//
4+
// NEDEN (2026-08-04, gate overlay planı): overlay'in "dosya odaklı" gate'leri (file_immutable,
5+
// forbid_new_files, forbid_dependency_change) yazma aracı ÇAĞRILDIĞI anda uygulanmalı — iş bittikten
6+
// sonra tespit etmek geç. Claude Code sözleşmesi: PreToolUse kancası exit 0 → izin, exit 2 → engel
7+
// (stderr metni modele geri döner; model engeli görüp yaklaşımını değiştirir).
8+
//
9+
// GÜVENLİK TASARIMI (bilinçli, değiştirme):
10+
// - Kurallar DOSYADAN OKUNMAZ; komut satırında base64 gömülü gelir. Proje içindeki her dosyaya
11+
// (.mycl dahil) kod yazan ajan dokunabilir — kural dosyası olsaydı ajan kendi kilidini silebilirdi.
12+
// Çalışan sürecin argv'sini ise değiştiremez → kurallar iterasyon boyunca DONUK kalır (AD-3).
13+
// - Bu betik alan bilgisi taşımaz: hangi dosyalar korunuyor, bağımlılık dosyası adları — hepsi
14+
// MyCL'in derleme anında hesapladığı VERİ olarak gelir. Tek doğruluk kaynağı orkestratördür.
15+
// - HATA = ENGEL (fail-closed): kurallar çözülemiyorsa ya da araç yükü beklenmedikse exit 2.
16+
// Ayar bloğu Claude tarafından sessizce yutulursa zaten hiç çağrılmayız (o delik için ayrı
17+
// kanarya var: --ack). Çağrıldıysak ve emin değilsek, "yazmaya izin" en yanlış cevap olur.
18+
// Patlama yarıçapı ayarlardaki matcher ile YALNIZ yazma araçlarına sınırlı — okuma/Bash'e
19+
// bu betik hiç uygulanmaz (Bash tarafı için pipeline sonunda taban çizgisi kontrolü var).
20+
//
21+
// Kullanım:
22+
// node overlay-guard.mjs --ack <işaretDosyası> (SessionStart kanaryası: işaret yaz, exit 0)
23+
// node overlay-guard.mjs --rules <base64JSON> (PreToolUse: stdin'den araç yükünü oku, karar ver)
24+
//
25+
// Kural şeması (MyCL üretir): { project_root: string, immutable: string[],
26+
// no_new_files: string[], dependency_file_names: string[] } — yollar proje köküne göre, "/" ayraçlı.
27+
28+
import { existsSync, mkdirSync, writeFileSync } from "node:fs";
29+
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
30+
31+
function readStdin() {
32+
return new Promise((resolveP) => {
33+
let data = "";
34+
process.stdin.setEncoding("utf-8");
35+
process.stdin.on("data", (c) => (data += c));
36+
process.stdin.on("end", () => resolveP(data));
37+
process.stdin.on("error", () => resolveP(data));
38+
});
39+
}
40+
41+
function block(message) {
42+
process.stderr.write(`${message}\n`);
43+
process.exit(2);
44+
}
45+
46+
const argv = process.argv.slice(2);
47+
48+
// ── Kanarya: SessionStart'ta işaret dosyası yaz. Claude ayar bloğunu ŞEMA hatasında sessizce
49+
// yok sayıyor (ampirik, 2.1.227) — işaret yoksa MyCL "kancalar hiç yüklenmedi" diye anlar ve
50+
// iterasyonu gürültülü durdurur (KATI #4: kapısız iterasyon sessizce koşamaz).
51+
const ackIdx = argv.indexOf("--ack");
52+
if (ackIdx !== -1) {
53+
const marker = argv[ackIdx + 1];
54+
try {
55+
if (marker) {
56+
mkdirSync(dirname(marker), { recursive: true });
57+
writeFileSync(marker, JSON.stringify({ at: Date.now(), pid: process.pid }) + "\n", "utf-8");
58+
}
59+
} catch (e) {
60+
// Kanarya yazılamadı → MyCL işareti bulamayınca zaten görünür şekilde duracak; burada
61+
// ayrıca engel üretmek SessionStart'ta anlamsız (bloklayacak araç çağrısı yok).
62+
process.stderr.write(`overlay-guard ack yazilamadi: ${String(e)}\n`);
63+
}
64+
process.exit(0);
65+
}
66+
67+
const rulesIdx = argv.indexOf("--rules");
68+
if (rulesIdx === -1 || !argv[rulesIdx + 1]) {
69+
block("gate-overlay guard: rules argument missing (fail-closed).");
70+
}
71+
72+
let rules;
73+
try {
74+
rules = JSON.parse(Buffer.from(argv[rulesIdx + 1], "base64").toString("utf-8"));
75+
if (typeof rules !== "object" || rules === null) throw new Error("rules not an object");
76+
} catch (e) {
77+
block(`gate-overlay guard: rules could not be decoded (${String(e)}) — failing closed.`);
78+
}
79+
80+
const projectRoot = typeof rules.project_root === "string" ? rules.project_root : "";
81+
const immutable = Array.isArray(rules.immutable) ? rules.immutable.filter((p) => typeof p === "string") : [];
82+
const noNewFiles = Array.isArray(rules.no_new_files)
83+
? rules.no_new_files.filter((p) => typeof p === "string")
84+
: [];
85+
const depNames = Array.isArray(rules.dependency_file_names)
86+
? rules.dependency_file_names.filter((p) => typeof p === "string")
87+
: [];
88+
if (!projectRoot || !isAbsolute(projectRoot)) {
89+
block("gate-overlay guard: project_root invalid — failing closed.");
90+
}
91+
92+
const raw = await readStdin();
93+
let payload;
94+
try {
95+
payload = JSON.parse(raw);
96+
} catch {
97+
block("gate-overlay guard: tool payload unreadable — failing closed.");
98+
}
99+
100+
const toolInput = payload && typeof payload.tool_input === "object" && payload.tool_input !== null
101+
? payload.tool_input
102+
: {};
103+
// Yazma araçlarının dosya alanları: Write/Edit/MultiEdit → file_path, NotebookEdit → notebook_path.
104+
const targetRaw = toolInput.file_path ?? toolInput.notebook_path ?? toolInput.path;
105+
if (typeof targetRaw !== "string" || targetRaw.trim() === "") {
106+
block("gate-overlay guard: write tool without a file path — failing closed.");
107+
}
108+
109+
// Yolu proje köküne göre çöz ve normalize et. `sub/../x` gibi dolambaçlar resolve ile düzleşir —
110+
// dondurulmuş dosyaya dolaylı yoldan yazmak engeli aşamaz.
111+
const resolved = resolve(projectRoot, targetRaw);
112+
const rel = relative(projectRoot, resolved).split(sep).join("/");
113+
if (rel.startsWith("..") || rel === "") {
114+
// Proje DIŞI yol: overlay'in yetki alanı proje; dışarıyı zaten kum havuzu yönetiyor.
115+
process.exit(0);
116+
}
117+
118+
for (const frozen of immutable) {
119+
if (rel === frozen) {
120+
block(
121+
`gate-overlay: "${rel}" is frozen for this iteration (file_immutable). Do not modify it; solve the task another way.`,
122+
);
123+
}
124+
}
125+
126+
if (depNames.includes(basename(rel))) {
127+
block(
128+
`gate-overlay: dependency files may not change this iteration (forbid_dependency_change). "${rel}" is a dependency file.`,
129+
);
130+
}
131+
132+
for (const dir of noNewFiles) {
133+
if ((rel === dir || rel.startsWith(`${dir}/`)) && !existsSync(resolved)) {
134+
block(
135+
`gate-overlay: creating new files under "${dir}" is forbidden this iteration (forbid_new_files). Edit existing files instead.`,
136+
);
137+
}
138+
}
139+
140+
process.exit(0);
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// overlay-guard — araç anı muhafızının sözleşme testleri (gerçek süreç, tmpdir; LLM yok).
2+
//
3+
// Sözleşme (Claude Code PreToolUse): exit 0 = izin, exit 2 = engel (stderr modele döner).
4+
// GÜVENLİK: kurallar argv'de base64 gömülü (ajan dosyayla değiştiremez); hata = ENGEL (fail-closed).
5+
6+
import { describe, expect, it, beforeEach, afterEach } from "vitest";
7+
import { spawnSync } from "node:child_process";
8+
import { promises as fs } from "node:fs";
9+
import { tmpdir } from "node:os";
10+
import { dirname, join, resolve } from "node:path";
11+
import { mkdtemp, rm } from "node:fs/promises";
12+
import { fileURLToPath } from "node:url";
13+
14+
// ESM'de __dirname yok — depodaki desen (tauri-resources.test.ts) fileURLToPath.
15+
const GUARD = resolve(dirname(fileURLToPath(import.meta.url)), "..", "overlay-guard.mjs");
16+
17+
let root = "";
18+
19+
beforeEach(async () => {
20+
root = await mkdtemp(join(tmpdir(), "mycl-guard-"));
21+
await fs.mkdir(join(root, "src"), { recursive: true });
22+
await fs.writeFile(join(root, "src", "config.ts"), "export const x = 1;\n");
23+
await fs.writeFile(join(root, "src", "app.ts"), "export const y = 2;\n");
24+
await fs.writeFile(join(root, "package.json"), "{}\n");
25+
});
26+
27+
afterEach(async () => {
28+
await rm(root, { recursive: true, force: true });
29+
});
30+
31+
function rulesB64(over?: Partial<Record<string, unknown>>): string {
32+
const rules = {
33+
project_root: root,
34+
immutable: ["src/config.ts"],
35+
no_new_files: ["src"],
36+
dependency_file_names: ["package.json", "Cargo.toml"],
37+
...over,
38+
};
39+
return Buffer.from(JSON.stringify(rules), "utf-8").toString("base64");
40+
}
41+
42+
function runGuard(
43+
toolInput: Record<string, unknown>,
44+
opts?: { rules?: string; toolName?: string },
45+
): { status: number | null; stderr: string } {
46+
const res = spawnSync("node", [GUARD, "--rules", opts?.rules ?? rulesB64()], {
47+
input: JSON.stringify({ tool_name: opts?.toolName ?? "Write", tool_input: toolInput }),
48+
encoding: "utf-8",
49+
});
50+
return { status: res.status, stderr: res.stderr };
51+
}
52+
53+
describe("file_immutable — dondurulmuş dosya", () => {
54+
it("dondurulmuş dosyaya yazma ENGELLENİR (exit 2) ve stderr gerekçeyi söyler", () => {
55+
const r = runGuard({ file_path: "src/config.ts" });
56+
expect(r.status).toBe(2);
57+
expect(r.stderr).toContain("file_immutable");
58+
expect(r.stderr).toContain("src/config.ts");
59+
});
60+
61+
it("MUTLAK yolla da engellenir", () => {
62+
const r = runGuard({ file_path: join(root, "src", "config.ts") });
63+
expect(r.status).toBe(2);
64+
});
65+
66+
it("dolambaçlı yol (sub/../) engeli AŞAMAZ", () => {
67+
const r = runGuard({ file_path: "src/nested/../config.ts" });
68+
expect(r.status).toBe(2);
69+
});
70+
71+
it("başka dosyaya yazma serbest (exit 0)", () => {
72+
const r = runGuard({ file_path: "src/app.ts" });
73+
expect(r.status).toBe(0);
74+
});
75+
76+
it("NotebookEdit'in notebook_path alanı da denetlenir", () => {
77+
const r = runGuard({ notebook_path: "src/config.ts" }, { toolName: "NotebookEdit" });
78+
expect(r.status).toBe(2);
79+
});
80+
});
81+
82+
describe("forbid_new_files — dizinde yeni dosya yasağı", () => {
83+
it("dizin altında OLMAYAN dosya (yeni oluşturma) engellenir", () => {
84+
const r = runGuard({ file_path: "src/yeni-dosya.ts" });
85+
expect(r.status).toBe(2);
86+
expect(r.stderr).toContain("forbid_new_files");
87+
});
88+
89+
it("dizin altında VAR OLAN dosyayı düzenlemek serbest", () => {
90+
const r = runGuard({ file_path: "src/app.ts" });
91+
expect(r.status).toBe(0);
92+
});
93+
94+
it("dizin dışında yeni dosya serbest", () => {
95+
const r = runGuard({ file_path: "docs-yeni.md" });
96+
expect(r.status).toBe(0);
97+
});
98+
});
99+
100+
describe("forbid_dependency_change — bağımlılık dosyaları", () => {
101+
it("kökteki package.json engellenir", () => {
102+
const r = runGuard({ file_path: "package.json" });
103+
expect(r.status).toBe(2);
104+
expect(r.stderr).toContain("forbid_dependency_change");
105+
});
106+
107+
it("ALT dizindeki package.json da engellenir (monorepo çalışma alanları)", () => {
108+
const r = runGuard({ file_path: "packages/web/package.json" });
109+
expect(r.status).toBe(2);
110+
});
111+
112+
it("ad listesinde olmayan dosya serbest", () => {
113+
const r = runGuard({ file_path: "paketleme-notu.md" });
114+
expect(r.status).toBe(0);
115+
});
116+
});
117+
118+
describe("fail-closed — hata = engel", () => {
119+
it("bozuk base64 kurallar → exit 2", () => {
120+
const r = runGuard({ file_path: "src/app.ts" }, { rules: "bozuk!!!" });
121+
expect(r.status).toBe(2);
122+
expect(r.stderr).toContain("failing closed");
123+
});
124+
125+
it("stdin'de bozuk JSON → exit 2", () => {
126+
const res = spawnSync("node", [GUARD, "--rules", rulesB64()], {
127+
input: "bu json degil",
128+
encoding: "utf-8",
129+
});
130+
expect(res.status).toBe(2);
131+
});
132+
133+
it("yol alanı olmayan yazma aracı → exit 2", () => {
134+
const r = runGuard({});
135+
expect(r.status).toBe(2);
136+
});
137+
138+
it("--rules hiç verilmemiş → exit 2", () => {
139+
const res = spawnSync("node", [GUARD], {
140+
input: JSON.stringify({ tool_name: "Write", tool_input: { file_path: "x" } }),
141+
encoding: "utf-8",
142+
});
143+
expect(res.status).toBe(2);
144+
});
145+
146+
it("project_root göreli/boş → exit 2", () => {
147+
const r = runGuard({ file_path: "src/app.ts" }, { rules: rulesB64({ project_root: "goreli/yol" }) });
148+
expect(r.status).toBe(2);
149+
});
150+
});
151+
152+
describe("kapsam sınırı", () => {
153+
it("proje DIŞI yol overlay'in işi değil → serbest (kum havuzu yönetir)", () => {
154+
const r = runGuard({ file_path: "/tmp/baska-yer.txt" });
155+
expect(r.status).toBe(0);
156+
});
157+
});
158+
159+
describe("kanarya (--ack)", () => {
160+
it("işaret dosyasını yazar ve exit 0 döner", async () => {
161+
const marker = join(root, ".mycl", "overlay-ack.json");
162+
const res = spawnSync("node", [GUARD, "--ack", marker], { encoding: "utf-8" });
163+
expect(res.status).toBe(0);
164+
const body = JSON.parse(await fs.readFile(marker, "utf-8"));
165+
expect(typeof body.at).toBe("number");
166+
});
167+
});

0 commit comments

Comments
 (0)