Delminio — the client
Clonegit clone https://git.delminio.com/delminio-client2026.11.26-b027f1c · 26 Nov 2026

delminio-client / kit / en / aggancia.sh

raw · sha256 ec1fa370a66e9bb670e0d50568c8574190bc3199d99b364b480dfd05be9bd5e6

1#!/usr/bin/env bash
2# © 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.
3set -euo pipefail
4
5URL="${DELMINIO_URL:-__DELMINIO_URL__}"
6URL="${URL%/}"
7
8muori() { printf '❌ %s\n' "$*" >&2; exit 1; }
9_no_del_motore() {
10  local c=${1##*$'\n'} e
11  case "$c" in
12    200) return 0 ;;
13    ''|000) [ -n "${2:-}" ] || return 0
14            e=$(_f "$M_non_risponde" url "$URL"); muori "$(_f "$M_rifiutato" motivo "$e")" ;;
15    *) e=$(printf '%s' "${1%$'\n'*}" | campo error); muori "$(_f "$M_rifiutato" motivo "HTTP $c${e:+: $e}")" ;;
16  esac
17}
18
19: '⟦frasi: aggancia⟧'
20M_agente_opencode_domanda='
21   OpenCode works with a provider'"'"'s models. Do you have its key? [c] I'"'"'ll add it now — or [g] I'"'"'ll try OpenCode'"'"'s free models, no key: '
22M_agente_opencode_gratuito='   The free model answering right now is {modello}: fine for trying; to work for real you need a provider'"'"'s key.'
23M_agente_opencode_nessuno='no free OpenCode model answers right now: run this command again and choose a provider'"'"'s key'
24M_agente_opencode_chiave_no='the key was not added: run this command again, or choose the free models'
25M_agente_opencode_senza_terminale='   OpenCode is installed. To start it needs a terminal: run this command again from there, and choose the key or the free models.'
26M_agente_non_installato='{cli} did not install (the reason is in the lines above): run this command again, and if it stops again show those lines to the person who gave you Delminio'
27M_agente_quale='“--agente” wants claude, codex, qwen or opencode and the version (you wrote “{cli} {versione}”)'
28M_agente_frase='Read {url}/aggancia.en.md with curl -fsSL and follow that text word for word.'
29M_agente_entra_account='the first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes.'
30M_agente_entra_qwen='the first time it asks which model to connect to: a Qwen account, or a provider with its key (pick it from the list and paste the key). Then, if it asks, say you trust this folder.'
31M_agente_entra_opencode='with the key or the free model you chose.'
32M_agente_parte='
33   Done: {cli} is on this computer. It starts now: {entra}
34   We already gave it the sentence: it reads Delminio'"'"'s guide and takes you through every step — git, the project, the memory copy, the connection. What you already know how to do, tell it and it skips it.
35   If it closes halfway, run the same command again: it downloads nothing new, and reopens it with the sentence.
36'
37M_manca='“{c}” is missing: install it and run this command again (on Ubuntu and Debian: sudo apt install {c})'
38M_non_parte='“{c}” is there ({dove}) but does not run: {perche}. Fix it and run this command again.'
39M_mac_strumenti='On this Mac git and python3 are Apple'"'"'s, and they only run with Apple'"'"'s command line tools (about 1 GB, one click).
40   I asked the Mac to install them: in Apple'"'"'s window press “Install”, wait for it to finish and run this command again.
41   If the window did not open, run: xcode-select --install'
42M_argomento_ignoto='I don'"'"'t know “{arg}”: the arguments are --installa claude, codex or qwen, and --agente claude, codex, qwen or opencode with the version'
43M_installa_quale='“--installa” wants claude, codex or qwen (you wrote “{cli}”)'
44M_chi_sei_nome='git does not know who you are yet. The name that will sign your work (for example Mary Smith): '
45M_chi_sei_mail='Your email: '
46M_installo_cli='   Installing {cli} on this machine, at the version chosen in Delminio: a few minutes the first time.'
47M_installa_non_riuscita='the computer is connected, but {cli} was not installed (the reason is in the lines above): run this command again, and if it stops again show those lines to your administrator'
48M_parto_codex='   With Codex, after the folder: type /hooks and choose “Trust all”, just once. Without it Codex starts but does not hear Delminio.
49'
50M_parto_qwen='   With Qwen Code the model and provider are those of the agent in the Agents view, and it reads the provider key from your environment.
51'
52M_fuori_dal_clone='run it inside the clone of the repository you want to connect'
53M_progetto_nome='There is no git project here ({dove}). I'"'"'ll create a new one, in a new folder inside this one, with a git on this computer only.
54What should I call it? [progetto] '
55M_progetto_nome_no='“{nome}” is not a good folder name: use letters without accents, digits, “-” and “_”, and do not start with a dot'
56M_progetto_esiste='{cartella} already exists and I won'"'"'t touch it: run again choosing another name, or go inside it and run again if it already is your project'
57M_progetto_creato='   The project is in the folder {cartella}, with a git on this computer only. When you want it on GitHub or another git host too, the agent explains how.'
58M_progetto_primo_commit='The project begins'
59M_parto='
60   Done. {nome} is starting. The first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes.
61   When it is ready type {apertura}: from there the agent guides you. Next time open the terminal in {cartella} and type {dopo}.
62'
63M_rito_apertura=/opening
64M_rito_apertura_codex=opening
65M_comando_occupato='{file} already exists and isn'"'"'t Delminio'"'"'s: I leave it alone. Without the “delminio” command, the commands are written in full, from the project folder: bash .claude/delminio.sh …'
66M_comando_fuori='delminio: there is no project connected to Delminio here. Go into the project folder, or one of its subfolders, and try again.'
67M_chi_sei='git doesn'"'"'t know who you are: git config --global user.name "Name" && git config --global user.email you@example.com'
68M_senza_origin='this repository has no “origin” remote: handoffs and merges stay on this machine, and anyone working from another one doesn'"'"'t see them'
69M_non_pusha='you can'"'"'t push to {origine} (git: {errore}): handoffs and merges will stay on this machine until you fix the credentials'
70M_codice_apri='  Open this address and press Approve:'
71M_codice_oppure='  (or: Delminio → Access, enter the code {codice} and press Approve)'
72M_codice_vale='  Valid for 10 minutes. This machine introduces itself as “{macchina}”.
73  Waiting for approval…'
74M_approvato='  ✅ approved'
75M_scaduto='  ❌ the code has expired: run the command again'
76M_senza_terminale='no terminal to ask for the token: pass it in DELMINIO_TOKEN'
77M_domanda_token='The Delminio token (app → Access → Connect a repository): '
78M_nessun_token='no token'
79M_non_risponde='Delminio is not responding at {url}'
80M_token_rifiutato='Delminio at {url} rejects this token (HTTP {codice})'
81M_rifiutato='not connected: {motivo}'
82M_tiene_gia='⚠️  Other repositories are already connected to this Delminio space: {altri}.
83   A space holds a single project: several repositories are fine if they belong to the same
84   work, with the same team. A different project goes in another space.'
85M_stessa_storia='   Is {repo} part of the same project? [y/N] '
86M_altra_storia='not connected: if it'"'"'s another project, create another space (in the app, “Spaces”) and connect it there; if it'"'"'s the same one, run the command again and answer yes'
87M_app_codex_domanda='   The Codex app is on this computer: shall I add Delminio to it too? I only add the Delminio plugin and the permission for its two tools to ~/.codex/config.toml. [y/N] '
88M_clone_fermo='the memory clone in {cartella} isn'"'"'t updating: it'"'"'s retried at every opening'
89M_clone_https='   memories: ssh to {remoto} doesn'"'"'t get through from here, cloned over https ({https})'
90M_clonate='   memories: cloned from {remoto} into {cartella} — the CLI finds the index there'
91M_memorie_vuote='the memory repository ({remoto}) is still empty: Delminio puts the base there as soon as its push goes through (Settings → “Memories on git”: the deploy key, with write access). The clone in {cartella} updates itself; while it'"'"'s empty the agent starts without the index, and is told so'
92M_clone_negato='the memory repository ({remoto}) can'"'"'t be read from this computer with your git credentials: that'"'"'s fine, the agent gets the memory index from Delminio when it starts. If you also want the local copy, ask the person who owns the repository for read access and run the connection again'
93M_codex_indice='   Codex and Qwen Code receive the memory index in Delminio'"'"'s opening: they need neither a local git clone nor an initial call to list.'
94M_senza_embedder='Delminio has no embedder: until the admin configures it (Settings → Embedder) memories are searched by words, without semantic search'
95M_embedder_muto='the embedder configured in Delminio is not responding ({risposta}): until it'"'"'s back, search is by words'
96M_note_sue='📦 Your CLI keeps its notes in {cartella} (says {fonte}).
97   From now on Delminio would keep them and that folder wouldn'"'"'t be read any more. First I make a backup
98   outside the repo, the agent proposes the notes to you as memories, and with
99   “delminio disconnect” everything goes back to how it was.'
100M_va_bene='   OK? [y/N] '
101M_memoria_sua_resta='not connected: your memory stays where it is. If it'"'"'s OK, run it again and answer yes (or DELMINIO_MEMORIA_SUA=si)'
102M_prima_non_salva='I can'"'"'t back up what was there before: I haven'"'"'t touched anything'
103M_prima_copia_diversa='the copy of {file} doesn'"'"'t match the original: I'"'"'m stopping before touching anything'
104M_mcp_fallito='claude mcp add failed'
105M_mcp_senza_claude='Claude Code is not in this shell'"'"'s PATH: the Delminio tool is not registered, and a Claude started here would have no memory. With Claude Code installed (and `claude` in the PATH), run this connection again: it only redoes what is missing.'
106M_senza_client='Delminio doesn'"'"'t provide the client ({indirizzo})'
107M_comando_tuo='{file} is a /{c} of yours, and it wins over Delminio'"'"'s in every project: here /{c} won'"'"'t be Delminio'"'"'s. If you want that one, rename yours (for example to /{c}-mine)'
108M_mcp_col_nome_nostro='{file} has an MCP server of its own called “memoria”, like Delminio'"'"'s: in {cli} it takes its place, and the agent is left without memory. Give it another name.'
109M_json_non_valido='{file} isn'"'"'t valid JSON: fix it and run again'
110M_codex_sotto_git='.codex/hooks.json is tracked by git: Codex here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again'
111M_qwen_sotto_git='.qwen/settings.json is tracked by git: Qwen Code here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again'
112M_senza_client_cantiere='Delminio doesn'"'"'t provide the Backlog client ({indirizzo})'
113M_senza_client_eseguibili='Delminio doesn'"'"'t provide the agents client ({indirizzo})'
114M_senza_client_cassaforte='Delminio doesn'"'"'t provide the vault client ({indirizzo})'
115M_apertura_muta='the opening hook gets no answer from Delminio: look at delminio apertura'
116M_nello_spazio=' in the space “{spazio}”'
117M_collegato='✅ {repo} is connected to Delminio ({url}){dove} as {chi}.'
118M_sempre_nello_spazio='   An agent opened in this folder always works{dove}: for another space, use another clone connected from there.'
119M_prima_al_sicuro='📦 What was there before is safe in {cartella}, outside the repo (the LEGGIMI.md in there says what).
120   The agent goes through it with you at the first session. To go back to how it was: delminio disconnect'
121M_apri_eseguibile='   Open the agent in here with your Delminio command, and type /opening.'
122M_scrivi_eseguibile='   The agent starts best from Delminio'"'"'s command, with the rules at the top:
123   delminio agents   writes it on this machine (the name in the Agents view); then /opening.'
124M_path_nuovo='   ℹ️  The “delminio” command is in {cartella}, which isn'"'"'t in this terminal'"'"'s PATH: until it is, write it in full,
125   {comando}. On Linux a new terminal usually finds it by name.'
126M_con_codex='   With Codex: if it'"'"'s already open, close it and start it again from Delminio'"'"'s command (the one “eseguibili” writes):
127   a Codex opened before the connection doesn'"'"'t see Delminio. At the first start Codex asks whether to trust the
128   folder and the hooks (/hooks → Trust all): say yes, then type opening, without the slash.'
129M_senza_cli='   This machine doesn'"'"'t have an agent CLI yet (claude, codex, qwen or opencode). To install one, run the
130   connection again with the one you want: the right command is in Delminio → Agents →
131   “Connect another computer” → “I don'"'"'t have an agent”.'
132M_con_qwen='   With Qwen Code: start it from Delminio'"'"'s command (the one “delminio agents” writes), which gives it the model
133   chosen in the Agents view and its key from the environment; a Qwen opened before the connection doesn'"'"'t see
134   Delminio. Then type /opening.'
135M_con_opencode='   With OpenCode: open it in this folder (restart one that is already open): memory, /opening and /closing
136   come with Delminio'"'"'s plugin in .opencode/plugins. Then type /opening.'
137M_qwen_ripiego='Delminio'"'"'s extension did not link in Qwen Code ({agente}): the hooks and /opening and /closing stay in the project, as before the package.'
138M_solo_claude='   With plain claude, or from the desktop app, it starts with the standard prompt: /opening brings it the rules.'
139M_gancio_tuo='⚠️  {file} is already there and isn'"'"'t Delminio'"'"'s: add this line to it yourself  {riga}'
140M_gancio_globale='⚠️  git hooks here come from {dir}, which isn'"'"'t this repository'"'"'s (global core.hooksPath): it applies to all your repositories, and Delminio doesn'"'"'t write there. Add to {file} yourself  {riga}'
141M_prima_questo_progetto='this project'
142M_prima_claude_md='the project'"'"'s instructions for Claude'
143M_prima_claude_local='your personal instructions for this project'
144M_prima_settings='the CLI'"'"'s local settings for this project, as they were'
145M_prima_hook_codex='Codex'"'"'s hooks for this project, as they were'
146M_prima_qwen='Qwen Code'"'"'s settings for this project, as they were'
147M_prima_apertura='your /opening command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one'
148M_prima_chiusura='your /closing command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one'
149M_prima_mcp='the “{nome}” MCP server you had before (it contains its token)'
150M_prima_note='- `memoria/` — the {n} notes the CLI had written for itself, from `{cartella}`'
151M_prima_configurazioni='- your CLI configurations (hooks, commands, agents, MCP servers, plugins): **not touched**, they stay where they are; the settings files are also in this backup, `fatti.json` has the list, and the agent tells you what works alongside Delminio and what doesn'"'"'t'
152M_prima_altri='- the instructions you wrote for other tools and the memories other tools keep ({elenco}): **copied here and not touched**, the originals stay where they are; `fatti.json` says what they are, and the agent proposes them to you along with the notes'
153M_prima_chiesti='- what you asked to back up before the connection ({elenco})'
154M_prima_tutti='- {n} files in all, each with its fingerprint in `fatti.json`: that'"'"'s how the copy is checked against the original'
155M_prima_non_copiato='- `{file}`: not copied ({perche})'
156M_prima_perche_credenziali='it holds credentials: it stays only where it is, and the connection doesn'"'"'t touch it'
157M_prima_perche_grande='too big for the backup: it stays where it is, and the connection doesn'"'"'t touch it'
158M_prima_perche_fuori='it'"'"'s outside the repo and your home folder'
159M_prima_perche_assente='it isn'"'"'t there'
160M_prima_niente_da_ripassare='nothing of yours to go through: the backup is there anyway'
161M_prima_leggimi_titolo='What was there before Delminio'
162M_prima_leggimi_testa='Before touching anything, the connection to Delminio copied here what this project had on this machine. Nothing was deleted: the originals are still in place.'
163M_prima_leggimi_note='From now on the CLI'"'"'s notes aren'"'"'t read any more: the CLI reads Delminio'"'"'s index. The agent proposes them to you as memories, one by one, and only what you approve is created; you can keep the CLAUDE.md files as they are, or move them to Delminio.'
164M_prima_leggimi_tornare='To go back to how it was: `delminio disconnect`. It restores the previous settings, commands and MCP server, and the CLI goes back to reading its notes; what was created in Delminio stays in Delminio.'
165M_qwen_comando_apertura='Delminio: open the session with your role'"'"'s briefing — what you write after the command goes as your message'
166M_qwen_comando_chiusura='Delminio: end the session — what you write after the command goes as your message'
167M_senza_client_plugin='Delminio doesn'"'"'t provide the package client for the CLIs ({indirizzo})'
168M_senza_client_squadra='Delminio does not serve the team client ({indirizzo})'
169M_kit_non_firmato='{file} from {url} doesn'"'"'t carry Delminio'"'"'s release signature, or isn'"'"'t the signed file: not installing it. If this Delminio is a development build and you know it, run again with DELMINIO_KIT_SENZA_FIRMA=1.'
170: '⟦fine frasi⟧'
171export ${!M_@}   # anche ai python (F, fra gli aiutanti qui sotto)
172
173
174PORTABILI=$(cat <<'PORTABILI'
175ha_terminale() { { : </dev/tty; } 2>/dev/null; }
176_f() {  # _f "$M_<chiave>" [segnaposto valore]... → la frase coi {segnaposto} riempiti
177  local t=$1 k v fuori
178  shift
179  while [ $# -ge 2 ]; do
180    k="{$1}"; v=$2; fuori=""
181    while [ "${t#*"$k"}" != "$t" ]; do fuori=$fuori${t%%"$k"*}$v; t=${t#*"$k"}; done
182    t=$fuori$t; shift 2
183  done
184  printf '%s\n' "$t"
185}
186export DELMINIO_F_PY='def F(chiave, **s):
187    t = __import__("os").environ.get("M_" + chiave, chiave)
188    for k, v in s.items():
189        t = t.replace("{" + k + "}", str(v))
190    return t'
191_sha16() {  # stdin → i primi 16 dello sha256 (il nome del file del token: uguale ovunque)
192  if command -v sha256sum >/dev/null 2>&1; then sha256sum
193  elif command -v shasum >/dev/null 2>&1; then shasum -a 256
194  else python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())'
195  fi | cut -c1-16
196}
197_tempo() {  # _tempo <secondi> <comando…> — come timeout: 124 se scade
198  if command -v timeout >/dev/null 2>&1; then timeout "$@"
199  elif command -v gtimeout >/dev/null 2>&1; then gtimeout "$@"
200  else python3 -c 'import subprocess, sys
201try: sys.exit(subprocess.run(sys.argv[2:], timeout=float(sys.argv[1])).returncode)
202except subprocess.TimeoutExpired: sys.exit(124)
203except OSError: sys.exit(127)' "$@"
204  fi
205}
206_staccato() {  # _staccato <comando…> — in una sessione sua: la CLI che esce non se lo porta via
207  if command -v setsid >/dev/null 2>&1; then setsid nohup "$@"
208  else nohup python3 -c 'import os, sys
209try: os.setsid()
210except OSError: pass
211os.execvp(sys.argv[1], sys.argv[1:])' "$@"
212  fi
213}
214_mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; }
215_lucchetto() {  # _lucchetto <secondi> — esclusivo sull'fd 9, come flock -w
216  if command -v flock >/dev/null 2>&1; then flock -w "$1" 9
217  else python3 -c 'import fcntl, sys, time
218fine = time.time() + float(sys.argv[1])
219while True:
220    try:
221        fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB); break
222    except BlockingIOError:
223        if time.time() > fine: sys.exit(1)
224        time.sleep(0.5)' "$1"
225  fi
226}
227_assoluto() { python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"; }
228_args() {  # _args <pid> → gli argomenti del processo, uno per riga, coi loro confini
229  if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; return; fi
230  python3 -c 'import ctypes, ctypes.util, struct, sys
231pid = int(sys.argv[1]); libc = ctypes.CDLL(ctypes.util.find_library("c"))
232def leggi(mib):
233    m = (ctypes.c_int * len(mib))(*mib); n = ctypes.c_size_t(0)
234    if libc.sysctl(m, len(mib), None, ctypes.byref(n), None, 0): sys.exit(1)
235    b = ctypes.create_string_buffer(n.value)
236    if libc.sysctl(m, len(mib), b, ctypes.byref(n), None, 0): sys.exit(1)
237    return b.raw[:n.value]
238if sys.platform == "darwin":
239    r = leggi([1, 49, pid])                 # KERN_PROCARGS2: argc, il percorso, NUL, gli argomenti
240    argc = struct.unpack("i", r[:4])[0]; r = r[4:]
241    args = r[r.index(b"\0"):].lstrip(b"\0").split(b"\0")[:argc]
242else:
243    args = leggi([1, 14, 7, pid]).rstrip(b"\0").split(b"\0")   # KERN_PROC_ARGS
244print("\n".join(a.decode(errors="replace") for a in args))' "$1" 2>/dev/null \
245    || ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n'
246}
247_chiave() { printf 'header = "Authorization: Bearer %s"\n' "$1"; }
248KIT_FIRMA='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0'
249_firmato() {  # _firmato <indirizzo> <nome servito> <file> → 0 se il file sta nella firma del kit
250  [ -n "${DELMINIO_KIT_SENZA_FIRMA:-}" ] && return 0
251  local d r=1
252  d=$(mktemp -d) || return 1
253  if curl -fsS -m 30 "$1/static/kit/FIRMA" -o "$d/f" 2>/dev/null \
254     && curl -fsS -m 30 "$1/static/kit/FIRMA.sig" -o "$d/f.sig" 2>/dev/null \
255     && printf 'rilasci@delminio.com %s\n' "$KIT_FIRMA" > "$d/chi" \
256     && ssh-keygen -Y verify -f "$d/chi" -I rilasci@delminio.com -n delminio-kit -s "$d/f.sig" < "$d/f" >/dev/null 2>&1 \
257     && python3 -c 'import hashlib, sys
258i = hashlib.sha256(open(sys.argv[3], "rb").read()).hexdigest()
259righe = open(sys.argv[1], encoding="utf-8").read().splitlines()
260sys.exit(0 if righe[:1] and righe[0].startswith("delminio-kit ") and i + " " + sys.argv[2] in righe[1:] else 1)' \
261          "$d/f" "$2" "$3"; then
262    r=0
263  fi
264  rm -rf "$d"
265  return $r
266}
267campo() {  # campo <chiave> < json → il valore, o "" (anche su un corpo che non è JSON)
268  python3 -c 'import json,sys
269try: print(json.load(sys.stdin).get(sys.argv[1]) or "")
270except Exception: print("")' "$1"
271}
272json_stringa() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"; }  # una stringa JSON
273export DELMINIO_GANCI_PY='def nostro(h, cosa=None):
274    c = h.get("command", "")
275    return ".claude/mneme.sh" in c or ("delminio.sh" in c and (cosa is None or c.endswith(" " + cosa)))
276def togli_ganci(s, cosa=None):
277    for evento, lista in list((s.get("hooks") or {}).items()):
278        for b in lista:
279            b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
280        lista[:] = [b for b in lista if b.get("hooks")]
281        if not lista:
282            del s["hooks"][evento]
283    if not s.get("hooks"):
284        s.pop("hooks", None)
285def metti_ganci(s, comando, gesti, matcher_sempre=False):
286    for evento, cosa, extra, matcher in gesti:
287        lista = s.setdefault("hooks", {}).setdefault(evento, [])
288        for b in lista:
289            b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
290        lista[:] = [b for b in lista if b.get("hooks")]
291        lista.append({**({"matcher": matcher} if matcher or matcher_sempre else {}),
292                      "hooks": [{"type": "command", "command": comando + " " + cosa, **extra}]})'
293KIT_FILE=".claude/delminio.sh .claude/lanciatori.sh .claude/ganci-git.sh .claude/worktree.sh .claude/consumi.py .claude/cantiere.py .claude/backlog.py .claude/eseguibili.py .claude/cassaforte.py .claude/firme.py .claude/plugin.py .claude/squadra.py .claude/settings.local.json .claude/commands/apertura.md .claude/commands/chiusura.md .claude/commands/start.md .claude/commands/handoff.md .claude/commands/opening.md .claude/commands/closing.md .claude/rules/delminio.md .codex/hooks.json .qwen/settings.json .qwen/commands/apertura.md .qwen/commands/chiusura.md .qwen/commands/start.md .qwen/commands/handoff.md .qwen/commands/opening.md .qwen/commands/closing.md .claude/opencode.js .opencode/plugins/delminio.js"
294KIT_DI_PRIMA=".claude/guardia.py .claude/commands/risveglio.md"
295PORTABILI
296)
297eval "$PORTABILI"
298
299installa=""
300agente_cli=""; agente_versione=""
301while [ $# -gt 0 ]; do
302  case "$1" in
303    --installa) installa=${2:-}; [ $# -ge 2 ] && shift; shift ;;
304    --agente) agente_cli=${2:-}; agente_versione=${3:-}; shift; [ $# -gt 0 ] && shift; [ $# -gt 0 ] && shift ;;
305    *) muori "$(_f "$M_argomento_ignoto" arg "$1")" ;;
306  esac
307done
308case "$installa" in ''|claude|codex|qwen) ;; *) muori "$(_f "$M_installa_quale" cli "$installa")" ;; esac
309if [ -n "$agente_cli" ]; then
310  case "$agente_cli" in claude|codex|qwen|opencode) ;; *) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
311  case "$agente_versione" in ''|*[!A-Za-z0-9.]*) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
312fi
313
314segnaposto_apple() {
315  local d
316  [ "$(uname -s)" = Darwin ] || return 1
317  case "$1" in git|python3) ;; *) return 1 ;; esac   # curl di /usr/bin è vero
318  case "$(command -v "$1")" in /usr/bin/*) ;; *) return 1 ;; esac
319  d=$(xcode-select -p 2>/dev/null) && [ -d "$d" ] && return 1
320  return 0
321}
322for c in curl git python3; do
323  command -v "$c" >/dev/null || muori "$(_f "$M_manca" c "$c")"
324  if segnaposto_apple "$c"; then
325    xcode-select --install >/dev/null 2>&1 || true
326    muori "$M_mac_strumenti"
327  fi
328  case $c in
329    curl) perche=$(curl --version 2>&1 >/dev/null) ;;
330    git) perche=$(git --version 2>&1 >/dev/null) ;;
331    python3) perche=$(python3 -c 'import json, ssl, urllib.request' 2>&1) ;;
332  esac || {
333    dove_c=$(command -v "$c"); perche=$(printf '%s' "${perche:-?}" | tail -1)
334    muori "$(_f "$M_non_parte" c "$c" dove "$dove_c" perche "$perche")"
335  }
336done
337if [ -n "$agente_cli" ]; then
338  cartella_agente=$(mktemp -d) || muori "$(_f "$M_installa_non_riuscita" cli "$agente_cli")"
339  curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
340    || muori "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
341  _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
342    || muori "$(_f "$M_kit_non_firmato" file eseguibili-client url "$URL")"
343  case $agente_cli in claude) nome_cli="Claude Code" ;; codex) nome_cli=Codex ;; qwen) nome_cli="Qwen Code" ;; *) nome_cli=OpenCode ;; esac
344  _f "$M_installo_cli" cli "$nome_cli"
345  uscita=$(python3 "$cartella_agente/eseguibili.py" installa-agente "$agente_cli" "$agente_versione") \
346    && lancia=$(printf '%s\n' "$uscita" | tail -1) && [ -x "$lancia" ] \
347    || { rm -rf "$cartella_agente"; muori "$(_f "$M_agente_non_installato" cli "$nome_cli")"; }
348  rm -rf "$cartella_agente"
349  nodo=$(printf '%s\n' "$uscita" | sed -n 's/^DELMINIO_NODE=//p' | tail -1)
350  [ -n "$nodo" ] && PATH="$nodo:$PATH" && export PATH
351  case $0 in /dev/fd/*|/proc/self/fd/*) cat "$0" >/dev/null 2>&1 || true ;; esac
352  frase=$(_f "$M_agente_frase" url "$URL")
353  primo=("$frase"); entra=$M_agente_entra_account
354  [ "$agente_cli" = qwen ] && primo=(-i "$frase") && entra=$M_agente_entra_qwen
355  export QWEN_CODE_SKIP_UPDATE_CHECK_ONCE=true OPENCODE_DISABLE_AUTOUPDATE=1
356  if [ "$agente_cli" = opencode ]; then
357    primo=(--standalone)
358    entra=$M_agente_entra_opencode
359    ha_terminale || { echo "$M_agente_opencode_senza_terminale"; exit 0; }
360    risposta=""; read -rp "$M_agente_opencode_domanda" risposta </dev/tty || true
361    case "$risposta" in
362      g|G)
363        cartella_agente=$(mktemp -d)
364        curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
365          && _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
366          && modello=$(python3 "$cartella_agente/eseguibili.py" modello-gratuito "$lancia") || modello=""
367        rm -rf "$cartella_agente"
368        [ -n "$modello" ] || muori "$M_agente_opencode_nessuno"
369        _f "$M_agente_opencode_gratuito" modello "$modello"
370        OPENCODE_CONFIG_CONTENT=$(DELMINIO_M="$modello" python3 -c 'import json, os; print(json.dumps({"model": os.environ["DELMINIO_M"]}))')
371        export OPENCODE_CONFIG_CONTENT
372        primo+=(--prompt "$frase") ;;
373      *)
374        "$lancia" auth login </dev/tty || muori "$M_agente_opencode_chiave_no"
375        primo+=(--prompt "$frase") ;;
376    esac
377  fi
378  _f "$M_agente_parte" cli "$nome_cli" entra "$entra"
379  ha_terminale || exit 0
380  if [ -t 0 ]; then exec "$lancia" "${primo[@]}"; fi
381  exec "$lancia" "${primo[@]}" </dev/tty
382fi
383cli_presente() {
384  local d
385  case $1 in
386    claude) d=${DELMINIO_VERSIONI:-$HOME/.local/share/claude/versions} ;;
387    codex) d=${DELMINIO_VERSIONI_CODEX:-$HOME/.local/share/codex/versions} ;;
388    qwen) d=${DELMINIO_VERSIONI_QWEN:-$HOME/.local/share/qwen-code/versions} ;;
389    opencode) d=${DELMINIO_OPENCODE_BIN:-$HOME/.opencode/bin} ;;
390  esac
391  command -v "$1" >/dev/null || [ -n "$(ls -A "$d" 2>/dev/null)" ] \
392    || { [ "$1" = opencode ] && [ -n "$(ls -A "${DELMINIO_VERSIONI_OPENCODE:-$HOME/.local/share/delminio/opencode/versions}" 2>/dev/null)" ]; }
393}
394senza_cli=""
395cli_presente claude || cli_presente codex || cli_presente qwen || cli_presente opencode || senza_cli=1
396chiedi_una_riga() {  # chiedi_una_riga <domanda> → la risposta, richiesta finché è vuota (tre volte)
397  local r="" giri=0
398  while [ -z "$r" ] && [ $giri -lt 3 ]; do read -rp "$1" r </dev/tty; giri=$((giri + 1)); done
399  printf '%s' "$r"
400}
401if [ -n "$installa" ] && ha_terminale && { [ -z "$(git config user.name)" ] || [ -z "$(git config user.email)" ]; }; then
402  chi_nome=$(git config user.name || true); [ -n "$chi_nome" ] || chi_nome=$(chiedi_una_riga "$M_chi_sei_nome")
403  chi_mail=$(git config user.email || true); [ -n "$chi_mail" ] || chi_mail=$(chiedi_una_riga "$M_chi_sei_mail")
404  [ -n "$chi_nome" ] && [ -n "$chi_mail" ] || muori "$M_chi_sei"
405  git config --global user.name "$chi_nome"
406  git config --global user.email "$chi_mail"
407fi
408progetto_nuovo=""
409if ! radice=$(git rev-parse --show-toplevel 2>/dev/null); then
410  [ -n "$installa" ] && ha_terminale || muori "$M_fuori_dal_clone"
411  domanda=$(_f "$M_progetto_nome" dove "$PWD")
412  read -rp "$domanda" nome_progetto </dev/tty
413  nome_progetto=${nome_progetto:-progetto}
414  case "$nome_progetto" in
415    .*|*[!A-Za-z0-9._-]*) muori "$(_f "$M_progetto_nome_no" nome "$nome_progetto")" ;;
416  esac
417  [ -e "$nome_progetto" ] && muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
418  mkdir "$nome_progetto" && git -C "$nome_progetto" init -q || muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
419  radice=$(cd "$nome_progetto" && pwd)
420  progetto_nuovo=1
421fi
422cd "$radice"
423
424avvisa() { printf '⚠️  %s\n' "$*" >&2; }
425senza_credenziali() { sed -E 's#([A-Za-z][A-Za-z0-9+.-]*://)[^/[:space:]]*@#\1#g'; }
426[ -n "$(git config user.name)" ] && [ -n "$(git config user.email)" ] || muori "$M_chi_sei"
427if [ -n "$progetto_nuovo" ]; then
428  git commit -q --allow-empty -m "$M_progetto_primo_commit"
429  _f "$M_progetto_creato" cartella "$radice"
430fi
431if ! git remote get-url origin >/dev/null 2>&1; then
432  avvisa "$M_senza_origin"
433elif ! perche=$(GIT_TERMINAL_PROMPT=0 git push --dry-run -q origin "HEAD:refs/heads/delminio-prova-del-push-$$" 2>&1); then
434  origine=$(git remote get-url origin | senza_credenziali)
435  errore_git=$(printf '%s' "$perche" | tail -1 | senza_credenziali)
436  avvisa "$(_f "$M_non_pusha" origine "$origine" errore "$errore_git")"
437fi
438
439aggancio_col_codice() {
440  local r codice disp c giri=0 macchina
441  macchina=$(hostname 2>/dev/null || echo "?")
442  r=$(python3 -c 'import json,sys; print(json.dumps({"macchina": sys.argv[1]}))' "$macchina" \
443      | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
444          "$URL/api/aggancio/inizia" 2>/dev/null) || return 1
445  [ "${r##*$'\n'}" = 200 ] || return 1
446  r=${r%$'\n'*}
447  codice=$(printf '%s' "$r" | campo codice)
448  disp=$(printf '%s' "$r" | campo dispositivo)
449  [ -n "$codice" ] && [ -n "$disp" ] || return 1
450  {
451    echo
452    echo "$M_codice_apri"
453    echo
454    echo "        $URL/?aggancio=$codice"
455    echo
456    _f "$M_codice_oppure" codice "$codice"
457    echo
458    _f "$M_codice_vale" macchina "$macchina"
459  } >&2
460  while [ $giri -lt 220 ]; do
461    sleep 3; giri=$((giri + 1))
462    r=$(python3 -c 'import json,sys; print(json.dumps({"dispositivo": sys.argv[1]}))' "$disp" \
463        | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
464            "$URL/api/aggancio/ritira" 2>/dev/null) || continue
465    c=${r##*$'\n'}
466    case "$c" in
467      200) printf '%s' "${r%$'\n'*}" | campo token
468           echo "$M_approvato" >&2; return 0 ;;
469      410) echo "$M_scaduto" >&2; return 1 ;;
470    esac
471  done
472  return 1
473}
474
475token="${DELMINIO_TOKEN:-}"
476[ -n "$token" ] || token=$(aggancio_col_codice) || token=""
477if [ -z "$token" ]; then
478  ha_terminale || muori "$M_senza_terminale"
479  read -rsp "$M_domanda_token" token </dev/tty
480  echo
481fi
482[ -n "$token" ] || muori "$M_nessun_token"
483
484risposta=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/auth/check" 2>&1) \
485  || muori "$(_f "$M_non_risponde" url "$URL")"
486codice=${risposta##*$'\n'}
487[ "$codice" = 200 ] || muori "$(_f "$M_token_rifiutato" url "$URL" codice "$codice")"
488if frasi=$(curl -fsS -m 10 -K <(_chiave "$token") "$URL/aggancia.sh" 2>/dev/null | python3 -c '
489import re, shlex, sys
490m = re.search(r"^: .⟦frasi: aggancia⟧.\n(.*?)^: .⟦fine frasi⟧.\n", sys.stdin.read(), re.S | re.M)
491voci = shlex.split(m.group(1), comments=True) if m else []
492if voci and all(re.fullmatch(r"M_\w+=.*", v, re.S) for v in voci):
493    print("".join("%s=%s\n" % (k, shlex.quote(v)) for k, _, v in (x.partition("=") for x in voci)))
494') && [ -n "$frasi" ]; then
495  eval "$frasi"; export ${!M_@}
496fi
497chi=$(python3 -c 'import json,sys; u=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("utente") or {}; print((u.get("mostrato") or u.get("nome") or "?") + " (" + (u.get("ruolo_detto") or u.get("ruolo") or "?") + ")")' <<<"$risposta")
498etichetta=$(python3 -c 'import json,sys; print(json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("etichetta") or "")' <<<"$risposta" 2>/dev/null)
499remoto_repo=$(git remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#' || true)
500conferma=false
501{ [ -f .claude/delminio.sh ] || [ "${DELMINIO_STESSA_STORIA:-}" = si ]; } && conferma=true
502remoto_prima=$(sed -n 's/^REMOTO=//p' .claude/delminio.sh 2>/dev/null | head -1 | sed 's/\\\(.\)/\1/g' || true)
503corpo_repo=$(python3 -c 'import json,sys; print(json.dumps({"remoto": sys.argv[1], "nome": sys.argv[2], "conferma": sys.argv[3] == "true", "prima": sys.argv[4]}))' "$remoto_repo" "$(basename "$radice")" "$conferma" "$remoto_prima")
504repo=$(curl -sS -m 10 -w '\n%{http_code}' -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" 2>/dev/null) || repo=""
505_no_del_motore "$repo"; repo=${repo%$'\n'*}
506no=$(printf '%s' "$repo" | campo rifiuta)
507[ -z "$no" ] || muori "$(_f "$M_rifiutato" motivo "$no")"
508if [ -n "$repo" ] \
509   && altri=$(printf '%s' "$repo" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(", ".join(d.get("altri") or []) if d.get("chiede") else "")' 2>/dev/null) \
510   && [ -n "$altri" ]; then
511  _f "$M_tiene_gia" altri "$altri"
512  risposta_storia="${DELMINIO_STESSA_STORIA:-}"
513  if [ -z "$risposta_storia" ] && ha_terminale; then
514    nome_repo=$(basename "$radice")
515    read -rp "$(_f "$M_stessa_storia" repo "$nome_repo")" risposta_storia </dev/tty
516  fi
517  case "$risposta_storia" in
518    s|S|si|sì|y|yes) corpo_repo=$(python3 -c 'import json,sys; d=json.loads(sys.argv[1]); d["conferma"]=True; print(json.dumps(d))' "$corpo_repo")
519       curl -sS -m 10 -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" >/dev/null 2>&1 || true ;;
520    *) muori "$M_altra_storia" ;;
521  esac
522fi
523
524imp=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/impostazioni" 2>/dev/null || true)
525_no_del_motore "$imp" si; imp=${imp%$'\n'*}
526emb=$(printf '%s' "$imp" | python3 -c 'import json,sys
527try: e = json.load(sys.stdin).get("embedder") or {}
528except Exception: e = {}
529print(json.dumps({"url": e.get("url") or "", "modello": e.get("modello") or ""}) if not e.get("di_delminio") else "di_delminio")')
530memoria=$(printf '%s' "$imp" | campo memoria_sul_disco)
531kit=$(printf '%s' "$imp" | campo versione)
532[ -n "$memoria" ] && [ ! -d "$memoria" ] && memoria=""
533clone=""
534if [ -z "$memoria" ]; then
535  remoto_memorie=$(printf '%s' "$imp" | campo memorie_remoto)
536  dest="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$radice" | _sha16)/memoria"
537  ssh_muto=${GIT_SSH_COMMAND:-ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new}
538  if [ -d "$dest/.git" ]; then
539    GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 30 git -C "$dest" pull -q --ff-only >/dev/null 2>&1 \
540      || avvisa "$(_f "$M_clone_fermo" cartella "$dest")"
541    memoria=$dest; clone=si
542  elif [ -n "$remoto_memorie" ] && command -v claude >/dev/null; then
543    mkdir -p "$(dirname "$dest")"
544    in_https=$(python3 -c 'import sys
545r = sys.argv[1].strip()
546if r.startswith("ssh://"):
547    host, _, p = r[6:].split("@", 1)[-1].partition("/")
548    host = host.split(":", 1)[0]
549elif "://" not in r and "@" in r and ":" in r.split("@", 1)[1]:
550    host, _, p = r.split("@", 1)[1].partition(":")
551else:
552    sys.exit(1)
553print("https://" + host + "/" + p.lstrip("/"))' "$remoto_memorie" 2>/dev/null || true)
554    if GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$remoto_memorie" "$dest" 2>/dev/null \
555       || { [ -n "$in_https" ] && rm -rf "$dest" && GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$in_https" "$dest" 2>/dev/null \
556            && _f "$M_clone_https" remoto "$remoto_memorie" https "$in_https"; }; then
557      memoria=$dest; clone=si
558      if [ -f "$dest/MEMORY.md" ]; then
559        _f "$M_clonate" remoto "$remoto_memorie" cartella "$dest"
560      else
561        avvisa "$(_f "$M_memorie_vuote" remoto "$remoto_memorie" cartella "$dest")"
562      fi
563    else
564      _f "$M_clone_negato" remoto "$remoto_memorie"
565    fi
566  elif ! command -v claude >/dev/null && { cli_presente codex || cli_presente qwen; }; then
567    echo "$M_codex_indice"
568  fi
569fi
570if [ "$emb" != di_delminio ]; then
571  case "$emb" in *'"url": ""'*)
572    avvisa "$M_senza_embedder" ;;
573  esac
574  prova=$(curl -sS -m 30 -w '\n%{http_code}' -X POST -K <(_chiave "$token") \
575            -H "Content-Type: application/json" --data-binary "$emb" "$URL/api/impostazioni/embedder/prova" 2>/dev/null || true)
576  if [ "${prova##*$'\n'}" = 200 ] && ! printf '%s' "${prova%$'\n'*}" | grep -q '"ok": *true'; then
577    risposta_emb="${prova%$'\n'*}"
578    avvisa "$(_f "$M_embedder_muto" risposta "$risposta_emb")"
579  fi
580fi
581
582scarica_client() {  # nome, destinazione, errore già composto nella lingua dello spazio
583  local nuovo indirizzo="$URL/static/kit/$1"
584  case $1 in *.*) ;; *) indirizzo+=-client ;; esac
585  nuovo=$(mktemp "$2.XXXXXX") || muori "$3"
586  if ! curl -fsS -K <(_chiave "$token") "$indirizzo" -o "$nuovo"; then
587    rm -f "$nuovo"
588    muori "$3"
589  fi
590  if ! _firmato "$URL" "${indirizzo##*/}" "$nuovo"; then
591    rm -f "$nuovo"
592    muori "$(_f "$M_kit_non_firmato" file "${indirizzo##*/}" url "$URL")"
593  fi
594  mv -f "$nuovo" "$2"
595}
596cartella_copia=$(mktemp -d) || muori "$M_prima_non_salva"
597scarica_client copia "$cartella_copia/copia.py" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/copia-client")"
598prima_volta=si; [ -f .claude/delminio.sh ] && prima_volta=""
599gitdir=$(_assoluto "$(git rev-parse --git-common-dir)")
600comune=$(dirname "$gitdir")
601if [ -n "$prima_volta" ]; then
602  sua=$(python3 "$cartella_copia/copia.py" controlla "$radice" "$memoria" "$comune" "$URL" "$gitdir")
603  if [ -n "$sua" ]; then
604    cartella_sua="${sua%%$'\t'*}"; chi_lo_dice="${sua#*$'\t'}"
605    _f "$M_note_sue" cartella "$cartella_sua" fonte "$chi_lo_dice"
606    risposta_sua="${DELMINIO_MEMORIA_SUA:-}"
607    if [ -z "$risposta_sua" ] && ha_terminale; then
608      read -rp "$M_va_bene" risposta_sua </dev/tty
609    fi
610    case "$risposta_sua" in
611      s|S|si|sì|y|yes) ;;
612      *) muori "$M_memoria_sua_resta" ;;
613    esac
614  fi
615fi
616salvato=$(umask 077; DELMINIO_PRIMA_VOLTA="${prima_volta:+si}" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" \
617  DELMINIO_GANCI="$(git config --local core.hooksPath || git rev-parse --git-path hooks)" \
618  python3 "$cartella_copia/copia.py" salva "$radice" "$memoria" "$comune" "$URL" "$gitdir") \
619  || muori "$M_prima_non_salva"
620rm -rf "$cartella_copia"
621
622
623mkdir -p .claude
624rm -f .claude/mneme.sh   # il client di prima della rinomina (0cfdde7): i suoi hook li toglie il passo 2
625cartella_token="${XDG_CONFIG_HOME:-$HOME/.config}/delminio"
626mkdir -p "$cartella_token" && chmod 700 "$cartella_token"
627file_token="$cartella_token/$(printf '%s' "$radice" | _sha16).token"
628( umask 077; printf '%s' "$token" > "$file_token" )
629
630scarica_client plugin .claude/plugin.py "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/plugin-client")"
631scarica_client squadra .claude/squadra.py "$(_f "$M_senza_client_squadra" indirizzo "$URL/static/kit/squadra-client")"
632mcp_locali() {  # mcp_locali togli|da-parte
633  python3 - "$1" "${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" "$radice" "$URL" \
634    "$(_assoluto "$(git rev-parse --git-common-dir)")/delminio-backup" <<'MCP_LOCALI' || true
635import glob, json, os, subprocess, sys
636gesto, cj, radice, url, segno = sys.argv[1:6]
637try:
638    server = json.load(open(cj, encoding="utf-8"))["projects"][radice]["mcpServers"] or {}
639except (OSError, ValueError, KeyError, TypeError):
640    server = {}
641for nome in ("memoria", "delminio"):
642    s = server.get(nome)
643    if not isinstance(s, dict):
644        continue
645    if str(s.get("url", "")).startswith(url):
646        if gesto == "togli":
647            subprocess.run(["claude", "mcp", "remove", nome, "-s", "local"], capture_output=True, timeout=60)
648    elif gesto == "da-parte" and nome == "memoria":
649        try:
650            prime = sorted(glob.glob(os.path.join(open(segno, encoding="utf-8").read().strip(), "*", "fatti.json")))
651        except OSError:
652            prime = []
653        dest = os.path.join(os.path.dirname(prime[-1]), "mcp-memoria.json") if prime else ""
654        if dest and not os.path.exists(dest):
655            os.umask(0o077)
656            with open(dest, "w", encoding="utf-8") as f:
657                json.dump(s, f, indent=2)
658MCP_LOCALI
659}
660con_plugin=""
661if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && command -v claude >/dev/null && python3 .claude/plugin.py claude "$radice"; then
662  con_plugin=si
663  mcp_locali togli
664else
665  python3 .claude/plugin.py rimuovi "$radice" >/dev/null 2>&1 || true
666fi
667scarica_client opencode-client.js .claude/opencode.js "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/opencode-client.js")"
668if cli_presente opencode || [ -f .opencode/plugins/delminio.js ]; then
669  python3 .claude/plugin.py opencode "$radice" || true
670fi
671ganci_claude_nel_progetto=""
672if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || { [ -z "$con_plugin" ] && command -v claude >/dev/null; }; then
673  ganci_claude_nel_progetto=si
674fi
675
676if [ -z "$con_plugin" ] && command -v claude >/dev/null; then
677  mcp_locali togli
678  mcp_locali da-parte
679  claude mcp remove memoria -s local >/dev/null 2>&1 || true
680  cj="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json"
681  conf=$(python3 -c 'import json,sys
682url, f, cj, radice = sys.argv[1:5]
683try:
684    fidato = json.load(open(cj, encoding="utf-8")).get("projects", {}).get(radice, {}).get("hasTrustDialogAccepted") is True
685except (OSError, ValueError, AttributeError):
686    fidato = False
687h = "printf %s \"$(cat %s)\"" % (chr(39) + "{\"Authorization\":\"Bearer %s\"}" + chr(39), chr(39) + f + chr(39))
688if not fidato or chr(39) in f or not all(32 <= ord(c) < 127 for c in h):
689    sys.exit(1)
690print(json.dumps({"type": "http", "url": url + "/mcp", "headersHelper": h}))' "$URL" "$file_token" "$cj" "$radice" 2>/dev/null || true)
691  if [ -z "$conf" ] || ! claude mcp add-json -s local memoria "$conf" >/dev/null 2>&1 \
692     || ! python3 -c 'import json,sys
693s = json.load(open(sys.argv[1], encoding="utf-8"))["projects"][sys.argv[2]]["mcpServers"]["memoria"]
694sys.exit(0 if s.get("headersHelper") else 1)' "$cj" "$radice" 2>/dev/null; then
695    claude mcp remove memoria -s local >/dev/null 2>&1 || true
696    ponte=$(python3 -c 'import json,sys; print(json.dumps({"type": "stdio", "command": "bash", "args": [sys.argv[1], "ponte"]}))' \
697      "$radice/.claude/delminio.sh") || muori "$M_mcp_fallito"
698    claude mcp add-json -s local memoria "$ponte" >/dev/null || muori "$M_mcp_fallito"
699  fi
700elif [ -z "$con_plugin" ] && [ -z "$installa" ] && ! cli_presente codex && ! cli_presente qwen; then
701  avvisa "$M_mcp_senza_claude"
702fi
703for parte in lanciatori:lanciatori.sh ganci-git:ganci-git.sh worktree:worktree.sh consumi:consumi.py firme:firme.py; do
704  scarica_client "${parte%%:*}" ".claude/${parte#*:}" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/${parte%%:*}-client")"
705done
706client_scaricato=$(mktemp) || muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"
707curl -fsS -K <(_chiave "$token") "$URL/static/kit/delminio-client" -o "$client_scaricato" \
708  || { rm -f "$client_scaricato"; muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"; }
709_firmato "$URL" delminio-client "$client_scaricato" \
710  || { rm -f "$client_scaricato"; muori "$(_f "$M_kit_non_firmato" file delminio-client url "$URL")"; }
711{
712  echo '#!/usr/bin/env bash'
713  echo "# Il client di Delminio per gli hook di Claude Code, scritto da aggancia.sh."
714  echo "# Il token sta fuori dal repo, nel file qui sotto (600). Per cambiarlo, rilancia l'aggancio."
715  printf 'URL=%q\nFILE_TOKEN=%q\nMEMORIA=%q\nCLONE=%q\nKIT=%q\nREMOTO=%q\n' "$URL" "$file_token" "$memoria" "$clone" "$kit" "$remoto_repo"
716  echo 'TOKEN=$(cat "$FILE_TOKEN" 2>/dev/null || true)'
717  printf '%s\n' "$PORTABILI"
718  cat "$client_scaricato"
719} > .claude/delminio.sh.nuovo
720rm -f "$client_scaricato"
721mv -f .claude/delminio.sh.nuovo .claude/delminio.sh
722chmod 700 .claude/delminio.sh
723comando_client=$(python3 -c 'import shlex,sys; print("bash " + shlex.quote(sys.argv[1]))' "$radice/.claude/delminio.sh")
724
725mkdir -p .claude/commands
726if [ -f .claude/commands/risveglio.md ] && grep -q 'delminio.sh' .claude/commands/risveglio.md; then
727  rm -f .claude/commands/risveglio.md
728fi
729if [ -z "$ganci_claude_nel_progetto" ]; then
730  for c in apertura chiusura opening closing start handoff; do
731    f=".claude/commands/$c.md"
732    [ -f "$f" ] || continue
733    if grep -q 'delminio.sh' "$f"; then rm -f "$f"
734    elif [ -n "$con_plugin" ] && { [ "$c" = apertura ] || [ "$c" = chiusura ]; }; then rm -f "$f"; fi
735  done
736  rmdir .claude/commands 2>/dev/null || true
737else
738cat > .claude/commands/apertura.md <<COMANDO
739---
740description: "${M_qwen_comando_apertura//\"/\'}"
741argument-hint: "[cosa vuoi dirgli subito]"
742allowed-tools: Bash(bash:*)
743---
744!\`$comando_client prompt\`
745
746\$ARGUMENTS
747COMANDO
748
749cat > .claude/commands/chiusura.md <<COMANDO
750---
751description: "${M_qwen_comando_chiusura//\"/\'}"
752argument-hint: "[cosa fare prima di chiudere]"
753allowed-tools: Bash(bash:*)
754---
755!\`$comando_client chiusura\`
756
757\$ARGUMENTS
758COMANDO
759for coppia in opening:apertura closing:chiusura start:apertura handoff:chiusura; do
760  f=".claude/commands/${coppia%%:*}.md"
761  [ -f "$f" ] && ! grep -q 'delminio.sh' "$f" && continue
762  cp ".claude/commands/${coppia#*:}.md" "$f"
763done
764fi
765while IFS=$'\t' read -r f cli; do
766  [ -n "$f" ] && avvisa "$(_f "$M_mcp_col_nome_nostro" file "$f" cli "$cli")"
767done < <(python3 - "$radice" "$URL" <<'NOME_NOSTRO' 2>/dev/null || true
768import json, os, re, sys
769radice, url = sys.argv[1:3]
770def suo(s):
771    return isinstance(s, dict) and not str(s.get("url") or s.get("httpUrl") or "").startswith(url) \
772        and "delminio" not in json.dumps([s.get("command"), s.get("args")])
773f = os.path.join(radice, ".qwen", "settings.json")
774try:
775    if suo((json.load(open(f, encoding="utf-8")).get("mcpServers") or {}).get("memoria")):
776        print(f"{f}\tQwen Code")
777except (OSError, ValueError, AttributeError):
778    pass
779for f, sempre in ((os.path.join(radice, ".codex", "config.toml"), True),
780                  (os.path.expanduser("~/.codex/config.toml"), False)):
781    try:
782        testo = open(f, encoding="utf-8").read()
783    except OSError:
784        continue
785    if re.search(r"(?m)^\[mcp_servers\.memoria\]", testo) and (sempre or re.search(r"(?m)^\[marketplaces\.delminio\]", testo)):
786        print(f"{f}\tCodex")
787NOME_NOSTRO
788)
789for c in apertura chiusura opening closing start handoff; do
790  f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/commands/$c.md"
791  if [ -f "$f" ] && ! grep -q 'delminio.sh' "$f"; then
792    avvisa "$(_f "$M_comando_tuo" file "$f" c "$c")"
793  fi
794done
795
796python3 - "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "$radice" <<'GESTITE' || true
797import glob, json, os, runpy, sys
798config, radice = sys.argv[1], sys.argv[2]
799cartelle = os.environ.get("DELMINIO_GESTITE_DIRS",
800                          "/etc/claude-code:/Library/Application Support/ClaudeCode:/mnt/c/Program Files/ClaudeCode").split(":")
801def leggi(f):
802    try:
803        with open(f, encoding="utf-8") as h:
804            return json.load(h)
805    except Exception:
806        return None
807def dice(testo):
808    print("⚠️  " + testo, file=sys.stderr)
809for d in cartelle:
810    for f in [os.path.join(d, "managed-settings.json")] + sorted(glob.glob(os.path.join(d, "managed-settings.d", "*.json"))):
811        s = leggi(f)
812        if not isinstance(s, dict):
813            continue
814        if s.get("disableAllHooks") is True:
815            dice(f"{f} (impostazioni gestite di questa macchina) spegne TUTTI gli hook: gli agenti nascono senza l'apertura di Delminio, senza la posta e senza i controlli. Chiedi a chi amministra la macchina di togliere disableAllHooks, o di mettere gli hook di Delminio fra quelli gestiti.")
816        if s.get("allowManagedHooksOnly") is True:
817            dice(f"{f} lascia partire solo gli hook gestiti (allowManagedHooksOnly): quelli di Delminio no. Chiedi a chi amministra la macchina di aggiungerli fra quelli gestiti.")
818        nomi = lambda lista: [str((x or {}).get("serverName") or (x or {}).get("serverUrl") or "") for x in (lista or []) if isinstance(x, dict)]
819        consentiti = s.get("allowedMcpServers")
820        di_delminio = lambda n: "delminio" in n.lower() or n.lower() == "memoria"
821        if (isinstance(consentiti, list) and not any(di_delminio(n) for n in nomi(consentiti))) \
822                or any(di_delminio(n) for n in nomi(s.get("deniedMcpServers"))):
823            dice(f"{f} non lascia collegare il server MCP «memoria» di Delminio: l'agente non raggiungerà la memoria. Chiedi di aggiungerlo fra i server consentiti.")
824        if s.get("allowManagedPermissionRulesOnly") is True:
825            try:
826                nomi_tool = " e ".join(runpy.run_path(".claude/plugin.py")["TOOLS_CLAUDE"])
827            except Exception:
828                nomi_tool = "mcp__plugin_delminio_memoria__delminio e mcp__plugin_delminio_memoria__delminio_write"
829            dice(f"{f} tiene solo i permessi gestiti: ogni chiamata a Delminio chiederà il permesso. Chiedi di consentire {nomi_tool} fra i permessi gestiti.")
830for f in (os.path.join(config, "settings.json"), os.path.join(radice, ".claude", "settings.json"),
831          os.path.join(radice, ".claude", "settings.local.json")):
832    s = leggi(f)
833    if isinstance(s, dict) and s.get("disableAllHooks") is True:
834        dice(f"{f} ha disableAllHooks: true — è tua e non la tocco, ma con quella gli hook di Delminio non partono.")
835for f in ("/etc/codex/requirements.toml", "/etc/codex/managed_config.toml"):
836    if os.path.isfile(f):
837        dice(f"{f}: ci sono regole gestite di Codex su questa macchina. Delminio non le legge: se Codex non fa partire i ganci o il server MCP di Delminio, guarda lì.")
838GESTITE
839
840python3 - "$comando_client" "$memoria" "$con_plugin" "$ganci_claude_nel_progetto" <<'IMPOSTA' || muori "$(_f "$M_json_non_valido" file .claude/settings.local.json)"
841import json, pathlib, runpy, sys
842exec(__import__("os").environ["DELMINIO_GANCI_PY"])
843comando, memoria, con_plugin, nel_progetto = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
844pacchetto = runpy.run_path(".claude/plugin.py")
845p = pathlib.Path(".claude/settings.local.json")
846testo = p.read_text(encoding="utf-8") if p.exists() else ""
847s = json.loads(testo) if testo.strip() else {}
848if nel_progetto:
849    metti_ganci(s, comando, pacchetto["GANCI_CLAUDE"])
850else:
851    togli_ganci(s)
852if memoria:
853    s["autoMemoryDirectory"] = memoria
854allow = s.setdefault("permissions", {}).setdefault("allow", [])
855progetto = pacchetto["TOOLS_CLAUDE_PROGETTO"]
856tools, vecchi = ((progetto, pacchetto["TOOLS_CLAUDE"]) if nel_progetto
857                 else (pacchetto["TOOLS_CLAUDE"], progetto))
858vecchi = (*vecchi, *pacchetto["TOOLS_CLAUDE_DI_PRIMA"])
859allow[:] = [a for a in allow if a not in vecchi]
860allow.extend(t for t in tools if t not in allow)
861def scelte(f):
862    try:
863        v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("skillOverrides")
864    except (OSError, ValueError, AttributeError):
865        return {}
866    return v if isinstance(v, dict) else {}
867gia = {**scelte(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json"),
868       **scelte(".claude/settings.json")}
869mie = s.get("skillOverrides") if isinstance(s.get("skillOverrides"), dict) else {}
870import subprocess
871try:
872    comune = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
873                            capture_output=True, text=True, timeout=10).stdout.strip()
874except (OSError, subprocess.SubprocessError):
875    comune = ""
876segno_f844 = pathlib.Path(comune) / "delminio-skill-f844" if comune else None
877if segno_f844 and not segno_f844.exists():
878    prima = pacchetto.get("SKILL_CLAUDE_F811") or {}
879    mie = {n: (pacchetto["SKILL_CLAUDE"].get(n, v) if prima.get(n) == v else v) for n, v in mie.items()}
880    if mie:
881        s["skillOverrides"] = mie
882else:
883    segno_f844 = None
884nuove = {n: v for n, v in pacchetto["SKILL_CLAUDE"].items() if n not in mie and n not in gia}
885if nuove:
886    s["skillOverrides"] = {**mie, **nuove}
887def regole(f):
888    try:
889        v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("permissions") or {}
890    except (OSError, ValueError, AttributeError):
891        return []
892    return [r for k in ("allow", "ask", "deny") for r in (v.get(k) or []) if isinstance(r, str)] if isinstance(v, dict) else []
893sue = regole(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json") \
894    + regole(".claude/settings.json") \
895    + [r for k in ("allow", "deny") for r in (s.get("permissions", {}).get(k) or []) if isinstance(r, str)]
896ask = s.setdefault("permissions", {}).setdefault("ask", [])
897for tool in pacchetto.get("CHIEDI_CLAUDE") or ():
898    if tool not in ask and not any(r == tool or r.startswith(tool + "(") for r in sue):
899        ask.append(tool)
900if not ask:
901    s["permissions"].pop("ask")
902p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
903if segno_f844:
904    try:
905        segno_f844.touch()
906    except OSError:
907        pass
908IMPOSTA
909
910if git ls-files --error-unmatch .codex/hooks.json >/dev/null 2>&1; then
911  avvisa "$M_codex_sotto_git"
912else
913mkdir -p .codex
914python3 - "$comando_client" "${DELMINIO_SENZA_PLUGIN:-}" <<'CODEX' || muori "$(_f "$M_json_non_valido" file .codex/hooks.json)"
915import json, pathlib, runpy, sys
916exec(__import__("os").environ["DELMINIO_GANCI_PY"])
917comando, senza_plugin = sys.argv[1], sys.argv[2]
918p = pathlib.Path(".codex/hooks.json")
919testo = p.read_text(encoding="utf-8") if p.exists() else ""
920s = json.loads(testo) if testo.strip() else {}
921if senza_plugin:
922    metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_CODEX"])
923else:
924    togli_ganci(s)
925if s or p.exists():
926    p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
927CODEX
928rmdir .codex 2>/dev/null || true   # vuota: non era dell'umano, e il plugin non la usa
929fi
930
931qwen_senza_plugin=${DELMINIO_SENZA_PLUGIN:-}
932if [ -z "$qwen_senza_plugin" ] && cli_presente qwen; then
933  for w in "${DELMINIO_BIN:-$HOME/.local/bin}"/*; do
934    [ -f "$w" ] && grep -q '^export DELMINIO_CLI_NOME=qwen' "$w" 2>/dev/null || continue
935    grep -q 'DELMINIO_NASCITA=porta' "$w" && continue
936    if ! ( eval "$(grep -E '^export (QWEN_HOME|PATH|DELMINIO_CLI)=' "$w")"
937           [ -n "${QWEN_HOME:-}" ] && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" \
938             python3 .claude/plugin.py qwen "$QWEN_HOME" >/dev/null 2>&1 ); then
939      avvisa "$(_f "$M_qwen_ripiego" agente "$(basename "$w")")"
940      qwen_senza_plugin=si
941    fi
942  done
943fi
944if git ls-files --error-unmatch .qwen/settings.json >/dev/null 2>&1; then
945  avvisa "$M_qwen_sotto_git"
946else
947mkdir -p .qwen
948python3 - "$comando_client" "$qwen_senza_plugin" <<'QWEN' || muori "$(_f "$M_json_non_valido" file .qwen/settings.json)"
949import json, pathlib, runpy, sys
950exec(__import__("os").environ["DELMINIO_GANCI_PY"])
951comando, senza_plugin = sys.argv[1], sys.argv[2]
952p = pathlib.Path(".qwen/settings.json")
953testo = p.read_text(encoding="utf-8") if p.exists() else ""
954s = json.loads(testo) if testo.strip() else {}
955if senza_plugin:
956    metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_QWEN"], matcher_sempre=True)
957else:
958    togli_ganci(s)
959if s or p.exists():
960    p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
961QWEN
962if [ -z "$qwen_senza_plugin" ]; then
963  for parola in apertura chiusura opening closing start handoff; do
964    f=".qwen/commands/$parola.md"
965    [ -f "$f" ] && grep -q 'Delminio' "$f" && rm -f "$f"
966  done
967  rmdir .qwen/commands .qwen 2>/dev/null || true
968else
969mkdir -p .qwen/commands
970for parola in apertura chiusura opening closing start handoff; do
971  f=".qwen/commands/$parola.md"
972  [ -f "$f" ] && ! grep -q 'Delminio' "$f" && continue
973  case $parola in
974    apertura|opening|start) descrizione=$M_qwen_comando_apertura ;;
975    *) descrizione=$M_qwen_comando_chiusura ;;
976  esac
977  printf -- '---\ndescription: "%s"\n---\n%s\n' "${descrizione//\"/\'}" "$parola" > "$f"
978done
979fi
980fi
981
982mkdir -p .claude/rules
983cat > .claude/rules/delminio.md <<REGOLA
984# Questo repo è agganciato a Delminio
985
986Se in questa sessione non ti è arrivato niente da Delminio — né l'apertura (il
987contesto che comincia con «# Delminio —») né l'avviso che Delminio non risponde —,
988la CLI è partita da fuori di questo repo, o prima dell'aggancio, o (Codex) senza
989il comando di Delminio: niente memoria, niente posta, niente consegna verificata, e
990il tool \`delminio\` non c'è. Prima di continuare dillo al tuo umano: chiudere e
991rilanciare l'agente dentro $radice (o una sua sottocartella), col comando che scrive
992\`delminio eseguibili\` — con Codex è l'unico modo, perché è il
993lancio a dargli Delminio.
994REGOLA
995
996scarica_client cantiere .claude/cantiere.py "$(_f "$M_senza_client_cantiere" indirizzo "$URL/static/kit/cantiere-client")"
997ln -sfn cantiere.py .claude/backlog.py
998scarica_client eseguibili .claude/eseguibili.py "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
999bin_delminio="${DELMINIO_BIN:-$HOME/.local/bin}"
1000comando_delminio="$bin_delminio/delminio"
1001if [ -e "$comando_delminio" ] && ! grep -q '^# delminio-comando$' "$comando_delminio" 2>/dev/null; then
1002  avvisa "$(_f "$M_comando_occupato" file "$comando_delminio")"
1003else
1004  mkdir -p "$bin_delminio"
1005  {
1006    cat <<'COMANDO'
1007#!/usr/bin/env bash
1008# delminio-comando
1009# Scritto da aggancia.sh: i gesti di Delminio da qualunque cartella di un progetto collegato.
1010r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""
1011if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
1012  c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")
1013fi
1014if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
1015COMANDO
1016    printf '  echo %q >&2\n' "$M_comando_fuori"
1017    cat <<'COMANDO'
1018  exit 1
1019fi
1020# Tutto al client, anche il Backlog: i nomi dei comandi in ogni lingua li sa lui (F666).
1021exec bash "$r/.claude/delminio.sh" "$@"
1022COMANDO
1023  } > "$comando_delminio.nuovo" && chmod 755 "$comando_delminio.nuovo" && mv -f "$comando_delminio.nuovo" "$comando_delminio"
1024fi
1025scarica_client cassaforte .claude/cassaforte.py "$(_f "$M_senza_client_cassaforte" indirizzo "$URL/static/kit/cassaforte-client")"
1026rm -f .claude/guardia.py
1027
1028ganci_globali=""
1029if ! git config --local core.hooksPath >/dev/null 2>&1 && git config core.hooksPath >/dev/null 2>&1; then
1030  ganci_globali=$(git config core.hooksPath)
1031fi
1032ganci=$(git config --local core.hooksPath || git rev-parse --git-path hooks)
1033mkdir -p "$ganci"
1034for g in commit-msg post-commit post-rewrite; do
1035  if [ -n "$ganci_globali" ]; then
1036    _f "$M_gancio_globale" dir "$ganci_globali" file "$ganci_globali/$g" riga "$comando_client $g \"\$@\""
1037    continue
1038  fi
1039  f="$ganci/$g"
1040  if [ -e "$f" ] && ! sed -n 2p "$f" | grep -qE '^# (Delminio|Mneme) \(aggancia\.sh\)'; then
1041    grep -q "delminio.sh" "$f" \
1042      || { riga_gancio="$comando_client $g \"\$@\""; _f "$M_gancio_tuo" file "$f" riga "$riga_gancio"; }
1043    continue
1044  fi
1045  printf '#!/bin/sh\n# Delminio (aggancia.sh): la chiusura giudicata dal motore. Gli altri commit passano.\nexec %s %s "$@"\n' "$comando_client" "$g" > "$f"
1046  chmod +x "$f"
1047done
1048
1049pubblico=$(printf '%s' "$repo" | python3 -c 'import json,sys
1050try: d = json.load(sys.stdin)
1051except Exception: sys.exit(0)
1052d = d.get("repo", d) if isinstance(d, dict) else {}
1053print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null || true)
1054segno="$(git rev-parse --path-format=absolute --git-common-dir)/delminio-pubblico"
1055case "$pubblico" in si) : > "$segno" ;; no) rm -f "$segno" ;; esac
1056
1057escludi=$(git rev-parse --git-path info/exclude)
1058mkdir -p "$(dirname "$escludi")"
1059for f in $KIT_FILE .claude/delminio-prima/ .claude/delminio-personali/; do
1060  case "$f" in .codex/hooks.json|.qwen/settings.json) git ls-files --error-unmatch "$f" >/dev/null 2>&1 && continue ;; esac
1061  grep -qxF "$f" "$escludi" 2>/dev/null || echo "$f" >> "$escludi"
1062done
1063
1064DELMINIO_PROVA=1 bash .claude/delminio.sh apertura < /dev/null > /dev/null \
1065  || muori "$M_apertura_muta"
1066
1067spazio=$(python3 .claude/eseguibili.py spazio --da .claude/delminio.sh 2>/dev/null || printf '%s' "${URL%/}")
1068case "$spazio" in
1069  *"#"*) nome_spazio="${etichetta:-${spazio##*#}}"; dove=$(_f "$M_nello_spazio" spazio "$nome_spazio") ;;
1070  *) dove=""
1071     python3 -c 'import json,sys; d=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]); sys.exit(0 if len(d.get("spazi") or []) > 1 else 1)' <<<"$risposta" 2>/dev/null \
1072       && dove=$(_f "$M_nello_spazio" spazio principale) ;;
1073esac
1074nome_repo=$(basename "$radice")
1075_f "$M_collegato" repo "$nome_repo" url "$URL" dove "$dove" chi "$chi"
1076[ -n "$dove" ] && _f "$M_sempre_nello_spazio" dove "$dove"
1077if [ -n "$salvato" ]; then
1078  _f "$M_prima_al_sicuro" cartella "$salvato"
1079fi
1080if ha_terminale && [ -f .claude/plugin.py ] && [ "$(python3 .claude/plugin.py app-codex stato 2>/dev/null)" = manca ]; then
1081  risposta_app=""; read -rp "$M_app_codex_domanda" risposta_app </dev/tty || true
1082  case "$risposta_app" in
1083    s|S|si|sì|y|yes) bash .claude/delminio.sh app-codex || true ;;
1084    n|N|no) bash .claude/delminio.sh app-codex no || true ;;
1085  esac
1086fi
1087if [ -n "$installa" ]; then
1088  _f "$M_installo_cli" cli "$installa"
1089  primo=$(mktemp)
1090  bash .claude/delminio.sh eseguibili allinea --vuoi "$installa" --primo "$primo" || true
1091  lancia=$(cat "$primo" 2>/dev/null || true); rm -f "$primo"
1092  [ -n "$lancia" ] && [ -x "$lancia" ] || muori "$(_f "$M_installa_non_riuscita" cli "$installa")"
1093  nome_agente=$(basename "$lancia")
1094  apertura=$M_rito_apertura; [ "$installa" = codex ] && apertura=$M_rito_apertura_codex   # Codex: senza la barra
1095  case ":$PATH:" in *":$(dirname "$lancia"):"*) dopo=$nome_agente ;; *) dopo=$lancia ;; esac
1096  _f "$M_parto" nome "$nome_agente" apertura "$apertura" cartella "$radice" dopo "$dopo"
1097  case "$installa" in
1098    codex) echo "$M_parto_codex" ;;
1099    qwen) echo "$M_parto_qwen" ;;
1100  esac
1101  ha_terminale || exit 0
1102  if [ -t 0 ]; then exec "$lancia"; fi
1103  exec "$lancia" </dev/tty
1104fi
1105case ":$PATH:" in *":$bin_delminio:"*) ;; *) _f "$M_path_nuovo" cartella "$bin_delminio" comando "$comando_delminio" ;; esac
1106if python3 -c 'import json,os,sys
1107try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
1108except Exception: r = {}
1109u = sys.argv[1].rstrip("/")
1110s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
1111miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
1112sys.exit(0 if not s.get("rifiutato") and any(os.path.isfile(p) for p in miei) else 1)' "$spazio"; then
1113  bash .claude/delminio.sh eseguibili allinea || true
1114  echo "$M_apri_eseguibile"
1115else
1116  echo "$M_scrivi_eseguibile"
1117fi
1118if cli_presente codex; then
1119  echo "$M_con_codex"
1120fi
1121if [ -n "$senza_cli" ]; then
1122  echo "$M_senza_cli"
1123fi
1124if cli_presente qwen; then
1125  echo "$M_con_qwen"
1126fi
1127if [ -f .opencode/plugins/delminio.js ]; then
1128  echo "$M_con_opencode"
1129fi
1130if command -v claude >/dev/null; then
1131  echo "$M_solo_claude"
1132fi