#!/usr/bin/env python3 # © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE. """La copia di sicurezza di ciò che c'era prima del collegamento (F777).""" import hashlib, json, os, re, shutil, sys, time exec(__import__('os').environ['DELMINIO_F_PY']) modo, radice, memoria, comune, url, gitdir = sys.argv[1:7] casa = os.path.expanduser('~') config = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.join(casa, '.claude') memoria = os.path.realpath(memoria) if memoria else '' def leggi(p): try: with open(p, encoding='utf-8') as f: return json.load(f) except (OSError, ValueError): return {} scelta, da = ('', '') for f, nome in ((os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(config, 'settings.json'), os.path.join(config, 'settings.json'))): v = leggi(f).get('autoMemoryDirectory') v = os.path.realpath(os.path.expanduser(v)) if isinstance(v, str) and v else '' if v and v != memoria: scelta, da = (v, nome) break progetto = os.environ.get('CLAUDE_CODE_PROJECT_DIR_NAME') or re.sub('[^A-Za-z0-9]', '-', comune) vecchia = scelta or os.path.join(config, 'projects', progetto, 'memory') if modo == 'controlla': if scelta and memoria: print(f'{scelta}\t{da}') sys.exit(0) segno_backup = os.path.join(gitdir, 'delminio-backup') cartella = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.join(casa, '.local', 'share'), 'delminio', 'backup', (re.sub('[^A-Za-z0-9._-]', '-', os.path.basename(comune)) or 'repo') + '-' + hashlib.sha256(comune.encode()).hexdigest()[:12]) try: cartella = open(segno_backup, encoding='utf-8').read().strip() or cartella except OSError: pass def una_copia_c_e(): for c in (cartella, os.path.join(radice, '.claude', 'delminio-prima')): if os.path.isdir(c) and any((os.path.isfile(os.path.join(c, d, 'fatti.json')) for d in os.listdir(c))): return True return False if os.environ.get('DELMINIO_PRIMA_VOLTA') != 'si' and una_copia_c_e(): sys.exit(0) dest = os.path.join(cartella, time.strftime('%Y-%m-%d-%H%M%S')) copie = [] copiati = [] non_copiati = [] peso = 0 SEGRETO = re.compile('(^|/)(auth\\.json|\\.credentials\\.json|oauth_creds\\.json|credentials(\\.json)?|\\.env(\\.[^/]*)?|[^/]*\\.(token|pem|key|p12|pfx)|id_(rsa|ed25519|ecdsa|dsa)[^/]*|\\.netrc|\\.git-credentials)$', re.I) TETTO_FILE = 20 * 1024 * 1024 TETTO = 200 * 1024 * 1024 def mostra(p): p = os.path.abspath(p) if p == radice or p.startswith(radice + os.sep): return os.path.relpath(p, radice) return '~' + p[len(casa):] if p.startswith(casa + os.sep) else p def impronta(p): h = hashlib.sha256() with open(p, 'rb') as f: for pezzo in iter(lambda: f.read(1 << 20), b''): h.update(pezzo) return h.hexdigest() def metti(sorgente, rel, gruppo): global peso if not os.path.isfile(sorgente): return False if SEGRETO.search(sorgente): non_copiati.append({'da': mostra(sorgente), 'perche': 'credenziali'}) return False n = os.path.getsize(sorgente) if n > TETTO_FILE or peso + n > TETTO: non_copiati.append({'da': mostra(sorgente), 'perche': 'grande', 'byte': n}) return False p = os.path.join(dest, rel) os.makedirs(os.path.dirname(p), exist_ok=True) shutil.copy2(sorgente, p) prima, dopo = (impronta(sorgente), impronta(p)) if prima != dopo: print(F('prima_copia_diversa', file=mostra(sorgente)), file=sys.stderr) sys.exit(1) peso += n copiati.append({'da': mostra(sorgente), 'copia': rel, 'sha256': prima, 'byte': n, 'gruppo': gruppo}) return True def metti_cartella(d, rel, gruppo): if not os.path.isdir(d): return for su, cartelle, files in os.walk(d): cartelle[:] = sorted((c for c in cartelle if c not in ('.git', 'node_modules'))) for f in sorted(files): metti(os.path.join(su, f), os.path.join(rel, os.path.relpath(os.path.join(su, f), d)), gruppo) def nel_progetto(rel, gruppo): p = os.path.join(radice, rel) if os.path.isdir(p): metti_cartella(p, rel, gruppo) else: metti(p, rel, gruppo) def in_casa(p, gruppo): p = os.path.abspath(p) rel = os.path.join('casa', os.path.relpath(p, casa)) if p.startswith(casa + os.sep) else os.path.join('fuori', p.lstrip(os.sep)) if os.path.isdir(p): metti_cartella(p, rel, gruppo) else: metti(p, rel, gruppo) codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex') qwen_casa = os.path.join(casa, '.qwen') for rel in (os.environ.get('DELMINIO_KIT_FILE') or '').split() + ['.claude/mneme.sh', '.claude/commands/risveglio.md']: nel_progetto(rel, 'collegamento') for g in ('commit-msg', 'post-commit', 'post-rewrite'): metti(os.path.join(os.environ.get('DELMINIO_GANCI') or os.path.join(gitdir, 'hooks'), g), os.path.join('git', 'hooks', g), 'collegamento') metti(os.path.join(gitdir, 'info', 'exclude'), os.path.join('git', 'info', 'exclude'), 'collegamento') in_casa(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'), 'collegamento') for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md', '.github/instructions', '.cursor/rules', '.windsurf/rules', 'memory-bank', '.serena/memories', '.claude/agents', '.claude/skills'): nel_progetto(rel, 'istruzioni') for p in (os.path.join(config, 'CLAUDE.md'), os.path.join(codex, 'AGENTS.md'), os.path.join(codex, 'AGENTS.override.md'), os.path.join(casa, '.gemini', 'GEMINI.md'), os.path.join(qwen_casa, 'QWEN.md')): in_casa(p, 'istruzioni') for rel in ('.claude/settings.json', '.mcp.json', '.codex/config.toml', '.qwen/commands'): nel_progetto(rel, 'impostazioni') for p in (os.path.join(config, 'settings.json'), os.path.join(codex, 'config.toml'), os.path.join(codex, 'hooks.json'), os.path.join(qwen_casa, 'settings.json')): in_casa(p, 'impostazioni') chiesti = [r.strip() for r in re.split('[\\n:]', os.environ.get('DELMINIO_COPIA_ANCHE') or '') if r.strip()] for r in chiesti: p = os.path.realpath(os.path.join(radice, os.path.expanduser(r))) if not (p.startswith(radice + os.sep) or p.startswith(casa + os.sep)): non_copiati.append({'da': r, 'perche': 'fuori'}) elif not os.path.exists(p): non_copiati.append({'da': r, 'perche': 'assente'}) elif p.startswith(radice + os.sep): nel_progetto(os.path.relpath(p, radice), 'chiesto') else: in_casa(p, 'chiesto') for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', '.claude/settings.local.json', '.codex/hooks.json', '.qwen/settings.json'): if os.path.isfile(os.path.join(radice, rel)): copie.append(rel) for rel in ('.claude/commands/apertura.md', '.claude/commands/chiusura.md', '.qwen/commands/apertura.md', '.qwen/commands/chiusura.md'): p = os.path.join(radice, rel) segno = 'Delminio' if rel.startswith('.qwen/') else 'delminio.sh' if os.path.isfile(p) and segno not in open(p, encoding='utf-8', errors='replace').read(): copie.append(rel) note = sorted((n for n in os.listdir(vecchia) if n.endswith('.md'))) if os.path.isdir(vecchia) and os.path.realpath(vecchia) != memoria else [] if note: metti_cartella(vecchia, 'memoria', 'note') mcp = (leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json')).get('projects', {}).get(radice, {}).get('mcpServers') or {}).get('memoria') if mcp and (not str(mcp.get('url', '')).startswith(url)): os.makedirs(dest, exist_ok=True) with open(os.path.join(dest, 'mcp-memoria.json'), 'w', encoding='utf-8') as f: json.dump(mcp, f, indent=2) copie.append('mcp-memoria.json') else: mcp = None def nostro(testo): return 'delminio.sh' in str(testo) def hook_di(s): out = {} for ev, lista in (s.get('hooks') or {} if isinstance(s.get('hooks'), dict) else {}).items(): n = sum((1 for b in lista or [] if isinstance(b, dict) for h in b.get('hooks') or [] if isinstance(h, dict) and (not nostro(h.get('command', ''))))) if n: out[ev] = n return out def file_in(d, est='.md'): if not os.path.isdir(d): return [] out = [] for n in sorted(os.listdir(d)): p = os.path.join(d, n) if n.endswith(est) and os.path.isfile(p): try: if nostro(open(p, encoding='utf-8', errors='replace').read()): continue except OSError: pass out.append(n[:-len(est)]) return out def cartelle_in(d): return sorted((n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)))) if os.path.isdir(d) else [] conf = {} def segna(dove, cosa, valore): if valore: conf.setdefault(dove, {})[cosa] = valore for f, dove in ((os.path.join(config, 'settings.json'), '~/.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json')): s = leggi(f) if not isinstance(s, dict): continue segna(dove, 'hook', hook_di(s)) segna(dove, 'plugin', sorted((k for k, on in (s.get('enabledPlugins') or {}).items() if on)) if isinstance(s.get('enabledPlugins'), dict) else []) segna(dove, 'stile', s.get('outputStyle') if isinstance(s.get('outputStyle'), str) else '') segna(dove, 'permessi_negati', len((s.get('permissions') or {}).get('deny') or []) if isinstance(s.get('permissions'), dict) else 0) segna(dove, 'hook_spenti', s.get('disableAllHooks') is True) for base, dove in ((config, '~/.claude'), (os.path.join(radice, '.claude'), '.claude')): segna(dove + '/commands', 'comandi', file_in(os.path.join(base, 'commands'))) segna(dove + '/agents', 'agenti', file_in(os.path.join(base, 'agents'))) segna(dove + '/skills', 'skill', cartelle_in(os.path.join(base, 'skills'))) segna(dove + '/output-styles', 'stili', file_in(os.path.join(base, 'output-styles'))) cj = leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json')) def suoi_server(d): return sorted((k for k, s in (d or {}).items() if not (k in ('memoria', 'delminio') and isinstance(s, dict) and str(s.get('url', '')).startswith(url)))) if isinstance(cj, dict): segna('~/.claude.json', 'mcp', suoi_server(cj.get('mcpServers'))) segna('~/.claude.json (' + F('prima_questo_progetto') + ')', 'mcp', suoi_server((cj.get('projects') or {}).get(radice, {}).get('mcpServers'))) mj = leggi(os.path.join(radice, '.mcp.json')) if isinstance(mj, dict): segna('.mcp.json', 'mcp', suoi_server(mj.get('mcpServers'))) codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex') ct = os.path.join(codex, 'config.toml') if os.path.isfile(ct): testo = open(ct, encoding='utf-8', errors='replace').read() segna('~/.codex/config.toml', 'mcp', sorted(set((m for m in re.findall('^\\[mcp_servers\\.([A-Za-z0-9_-]+)\\]', testo, re.M) if m != 'delminio')))) segna('~/.codex/config.toml', 'profili', sorted(set(re.findall('^\\[profiles\\.([A-Za-z0-9_-]+)\\]', testo, re.M)))) segna('~/.codex/hooks.json', 'hook', hook_di(leggi(os.path.join(codex, 'hooks.json')) or {})) segna('~/.codex/prompts', 'comandi', file_in(os.path.join(codex, 'prompts'))) altri = {} def righe_di(p): try: with open(p, encoding='utf-8', errors='replace') as f: testo = f.read() except OSError: return (None, '') return (None, '') if nostro(testo) else (len(testo.splitlines()), testo) def voci_qwen(testo): m = re.search('^##\\s*Qwen Added Memories\\s*$(.*?)(?=^##\\s|\\Z)', testo, re.M | re.S) return sum((1 for r in m.group(1).splitlines() if r.lstrip().startswith('- '))) if m else 0 def file_altro(dove, p, cosa): n, testo = righe_di(p) if n: v = {'cosa': cosa, 'righe': n} if os.path.basename(p) == 'QWEN.md' and (q := voci_qwen(testo)): v['memorie'] = q altri[dove] = v def cartella_altro(dove, d, cosa): if os.path.isdir(d): n = sum((1 for _, _, fs in os.walk(d) for f in fs if f.endswith(('.md', '.mdc', '.txt')))) if n: altri[dove + '/'] = {'cosa': cosa, 'file': n} for rel in ('AGENTS.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md'): if os.path.isfile(os.path.join(radice, rel)): file_altro(rel, os.path.join(radice, rel), 'istruzioni') for rel in ('.cursor/rules', '.windsurf/rules', '.clinerules', '.github/instructions'): cartella_altro(rel, os.path.join(radice, rel), 'istruzioni') for rel in ('memory-bank', '.serena/memories'): cartella_altro(rel, os.path.join(radice, rel), 'memoria') for p, dove in ((os.path.join(config, 'CLAUDE.md'), '~/.claude/CLAUDE.md'), (os.path.join(codex, 'AGENTS.md'), '~/.codex/AGENTS.md'), (os.path.join(casa, '.gemini', 'GEMINI.md'), '~/.gemini/GEMINI.md'), (os.path.join(casa, '.qwen', 'QWEN.md'), '~/.qwen/QWEN.md')): file_altro(dove, p, 'istruzioni personali') for v in altri.values(): if v.get('memorie'): v['cosa'] += ' + memoria' da_ripassare = bool(copie or note or conf or altri or chiesti) os.makedirs(dest, exist_ok=True) with open(os.path.join(dest, 'fatti.json'), 'w', encoding='utf-8') as f: json.dump({'radice': radice, 'copie': copie, 'memoria': {'cartella': vecchia, 'scelta_in': da, 'note': note}, 'configurazioni': conf, 'altri_strumenti': altri, 'file': copiati, 'non_copiati': non_copiati, 'chiesti': chiesti, 'aggancio_di_prima': os.path.isfile(os.path.join(radice, '.claude', 'delminio.sh'))}, f, indent=2, ensure_ascii=False) if not da_ripassare: with open(os.path.join(dest, 'RIPASSATO'), 'w', encoding='utf-8') as f: f.write(time.strftime('%Y-%m-%d %H:%M') + ' ' + F('prima_niente_da_ripassare') + '\n') with open(segno_backup, 'w', encoding='utf-8') as f: f.write(cartella + '\n') DETTO = {'CLAUDE.md': F('prima_claude_md'), '.claude/CLAUDE.md': F('prima_claude_md'), 'CLAUDE.local.md': F('prima_claude_local'), '.claude/settings.local.json': F('prima_settings'), '.codex/hooks.json': F('prima_hook_codex'), '.qwen/settings.json': F('prima_qwen'), '.claude/commands/apertura.md': F('prima_apertura'), '.claude/commands/chiusura.md': F('prima_chiusura'), '.qwen/commands/apertura.md': F('prima_apertura'), '.qwen/commands/chiusura.md': F('prima_chiusura'), 'mcp-delminio.json': F('prima_mcp', nome='delminio'), 'mcp-memoria.json': F('prima_mcp', nome='memoria')} righe = [f'- `{c}` — {DETTO[c]}' for c in copie] if note: righe.append(F('prima_note', n=len(note), cartella=vecchia)) if conf: righe.append(F('prima_configurazioni')) if altri: righe.append(F('prima_altri', elenco=', '.join((f'`{k}`' for k in altri)))) if chiesti: righe.append(F('prima_chiesti', elenco=', '.join((f'`{k}`' for k in chiesti)))) righe.append(F('prima_tutti', n=len(copiati))) PERCHE = {'credenziali': F('prima_perche_credenziali'), 'grande': F('prima_perche_grande'), 'fuori': F('prima_perche_fuori'), 'assente': F('prima_perche_assente')} for v in non_copiati: righe.append(F('prima_non_copiato', file=v['da'], perche=PERCHE[v['perche']])) with open(os.path.join(dest, 'LEGGIMI.md'), 'w', encoding='utf-8') as f: f.write('# ' + F('prima_leggimi_titolo') + '\n\n' + F('prima_leggimi_testa') + '\n\n' + '\n'.join(righe) + '\n\n' + F('prima_leggimi_note') + '\n\n' + F('prima_leggimi_tornare') + '\n') print(mostra(dest))