קוד מעודכן לגרסאות החדשות של CODEX.
& {
$raw = Read-Host "הדבק כאן את ה-ID (או את כל הודעת השגיאה)"
if ($raw -match '((?:rs|cmp)_[a-zA-Z0-9]+)') { $badId = $matches[1] } else { $badId = $raw.Trim() }
if (-not $badId) { Write-Host "לא הוזן מזהה." -ForegroundColor Red; return }
$pyCode = @'
import sys, os, re, json, shutil, sqlite3
bad_id = sys.argv[1].strip()
codex_dir = os.path.expanduser("~/.codex")
sessions_dir = os.path.join(codex_dir, "sessions")
db_path = os.path.join(codex_dir, "thread_history_1.sqlite")
uuid_re = re.compile(r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$", re.I)
id_to_path = {}
all_jsonl = []
for root, _, files in os.walk(sessions_dir):
for fn in files:
if not fn.endswith(".jsonl"):
continue
p = os.path.join(root, fn)
all_jsonl.append(p)
m = uuid_re.search(fn)
if m:
id_to_path[m.group(1).lower()] = p
bad_b = bad_id.encode("ascii")
err_b = b"invalid_encrypted_content"
modified_tids = set()
for p in all_jsonl:
try:
found = False
prev = b""
with open(p, "rb") as f:
while True:
chunk = f.read(4 * 1024 * 1024)
if not chunk:
break
if bad_b in (prev + chunk):
found = True
break
prev = chunk[-128:]
if not found:
continue
shutil.copy2(p, p + ".bak")
with open(p, "rb") as f:
raw_lines = f.readlines()
if not raw_lines:
continue
kept = [raw_lines[0]] + [ln for ln in raw_lines[1:] if bad_b not in ln and err_b not in ln]
removed = len(raw_lines) - len(kept)
if removed > 0:
with open(p, "wb") as f:
f.writelines(kept)
print(f"[JSONL] נוקו {removed} שורות מתוך {os.path.basename(p)}")
m = uuid_re.search(os.path.basename(p))
if m:
modified_tids.add(m.group(1).lower())
except Exception as e:
print(f"[שגיאה בקובץ {os.path.basename(p)}]: {e}")
def find_ordinal_offset(src_path, target_ord):
sz = os.path.getsize(src_path)
def scan_from(start_pos):
first_ord = None
with open(src_path, "rb") as f:
f.seek(start_pos)
if start_pos > 0:
f.readline()
while True:
pos = f.tell()
raw = f.readline()
if not raw:
return (sz, first_ord)
try:
obj = json.loads(raw.decode("utf-8"))
ov = obj.get("ordinal")
if ov is not None:
if first_ord is None:
first_ord = ov
if ov >= target_ord:
return (pos, first_ord)
except Exception:
continue
if sz > 20_000_000:
pos, first_ord = scan_from(sz - 5_000_000)
if first_ord is not None and first_ord < target_ord:
return pos
pos, _ = scan_from(0)
return pos
for _ in range(2):
any_changed = False
for p in all_jsonl:
try:
with open(p, "rb") as f:
first_line = f.readline()
if b'"history_base"' not in first_line:
continue
meta = json.loads(first_line.decode("utf-8"))
hb = meta.get("payload", {}).get("history_base")
if not hb:
continue
base_tid = str(hb.get("thread_id", "")).lower()
end_ord = hb.get("end_ordinal_exclusive")
old_off = hb.get("end_byte_offset")
if base_tid not in id_to_path or end_ord is None or old_off is None:
continue
src_path = id_to_path[base_tid]
src_sz = os.path.getsize(src_path)
if old_off > src_sz or base_tid in modified_tids:
new_off = find_ordinal_offset(src_path, end_ord)
if new_off != old_off:
shutil.copy2(p, p + ".bak")
with open(p, "rb") as f:
raw_all = f.read()
nl = raw_all.find(b"\n")
head, rest = (raw_all[:nl], raw_all[nl:]) if nl != -1 else (raw_all, b"")
pat = rb'("end_byte_offset"\s*:\s*)' + str(old_off).encode("ascii") + rb'\b'
rep = rb'\g<1>' + str(new_off).encode("ascii")
new_head, cnt = re.subn(pat, rep, head, count=1)
if cnt == 1:
with open(p, "wb") as f:
f.write(new_head + rest)
print(f"[Lineage] עודכן {os.path.basename(p)}: {old_off} -> {new_off}")
m = uuid_re.search(os.path.basename(p))
if m:
modified_tids.add(m.group(1).lower())
any_changed = True
except Exception as e:
print(f"[שגיאה ב-Lineage של {os.path.basename(p)}]: {e}")
if not any_changed:
break
if os.path.exists(db_path):
shutil.copy2(db_path, db_path + ".bak")
conn = sqlite3.connect(db_path, timeout=15)
cur = conn.cursor()
cur.execute("DELETE FROM thread_items WHERE item_id = ? OR item_json LIKE ?;", (bad_id, f"%{bad_id}%"))
print(f"[SQLite] נמחקו {cur.rowcount} פריטים מ-thread_items")
cur.execute("UPDATE thread_turns SET error_json = NULL WHERE error_json LIKE ?;", (f"%{bad_id}%",))
print(f"[SQLite] נוקו {cur.rowcount} הודעות שגיאה מ-thread_turns")
cur.execute("SELECT thread_id, next_rollout_byte_offset FROM thread_history_projection_state;")
for tid, db_off in cur.fetchall():
tl = str(tid).lower()
if tl in id_to_path:
real_sz = os.path.getsize(id_to_path[tl])
if db_off > real_sz or tl in modified_tids:
cur.execute("UPDATE thread_history_projection_state SET next_rollout_byte_offset = ? WHERE thread_id = ?;", (real_sz, tid))
cur.execute("UPDATE thread_turns SET rollout_end_byte_offset = ? WHERE thread_id = ? AND rollout_end_byte_offset > ?;", (real_sz, tid, real_sz))
print(f"[SQLite] סונכרן offset של {tid[:8]}...: {db_off} -> {real_sz}")
conn.commit()
conn.close()
print("תוקן וסונכרן בהצלחה!")
'@
$tempPy = "$HOME\.codex\fix_codex_run.py"
[System.IO.File]::WriteAllText($tempPy, $pyCode, (New-Object System.Text.UTF8Encoding($false)))
python $tempPy $badId
Remove-Item $tempPy -ErrorAction SilentlyContinue
}