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

delminio-client / kit / en / delminio-client

raw · sha256 9a25849365861962bcacd6f453448d48d3f55fe15ca4916a62eee11b1e119194

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.
3_conto_t0=${EPOCHREALTIME:-}
4: '⟦frasi: client⟧'
5M_delminio_risponde_prompt='⚠️ Delminio is not responding at {url}: the opening prompt didn'"'"'t arrive.'
6M_sandbox_senza_rete='Codex'"'"'s sandbox doesn'"'"'t let commands reach the network, so Delminio ({url}) can'"'"'t be reached from here: ask the user to approve this command, or the ones that start with “delminio”'
7M_delminio_dato_system='⚠️  Delminio ({url}) didn'"'"'t provide the system prompt of the agent role “{porta}” (HTTP {codice}).'
8M_agente_parte_meta='   The agent doesn'"'"'t start half-ready. It can be opened as before, with the standard prompt: claude, then /opening.'
9M_ruolo_sola_sua='⚠️  An agent role with only its own half isn'"'"'t available on Codex yet: the role'"'"'s memory has no channel there.'
10M_agente_parte_meta_2='   The agent doesn'"'"'t start half-ready.'
11M_opencode_gratuito_scelgo='   Picking a free OpenCode model that answers right now (once a day, a few seconds)…'
12M_opencode_gratuito_nessuno='⚠️  No free OpenCode model answers right now: OpenCode starts with its default model. Not to depend on the free ones, give the agent {nome} a provider you have a key for, in the Agents view.'
13M_delminio_argomenti_codex='⚠️  Delminio: Codex'"'"'s arguments can'"'"'t be put back together (python3?). The agent doesn'"'"'t start half-ready.'
14M_ruolo_sola_sua_2='⚠️  The role'"'"'s channel is missing on this machine: run `delminio agents` again, it prepares it.'
15M_delminio_mcp_qwen='⚠️  Delminio: the MCP for Qwen Code can'"'"'t be assembled (python3?). The agent doesn'"'"'t start half-ready.'
16M_ponte_muto='Delminio is not answering right now (restarting?): try again in a few seconds. If it stays silent, tell the user.'
17M_guardia_cartella_gira='⛔ The check doesn'"'"'t know which folder this command runs in: {incerto}. Repeat it with `cd <absolute path> && …` at the start of the command, without workdir'
18M_piu_agenti_insieme='❌ “Multiple agents” is switched off by the admin in this project: no session worktree.'
19M_chi_sei_bash='❌ I don'"'"'t know who you are: delminio {gesto} S<N>'
20M_gia_entraci_smontalo='❌ {wt} already exists: go into it, or remove it if it'"'"'s finished.'
21M_principale_aggiorna_remoto='⚠️  the main worktree doesn'"'"'t update from the remote: I'"'"'m starting from what'"'"'s there'
22M_ramo='✅ {wt} on the branch {ramo}.'
23M_codex_resta_dov='   Codex stays where it is: put `cd {wt} && …` at the start of every command, and absolute paths in patches.'
24M_entraci_col_tool='   Go into it with the EnterWorktree tool (a cd isn'"'"'t enough for the CLI);'
25M_lavoro_tocca_altro='   if the work touches another repository, git doesn'"'"'t get through there: ExitWorktree with keep, then an absolute cd in every command.'
26M_tua_cli_modo='   If your CLI has no way to go into it, put `cd {wt} && …` at the start of every command and absolute paths in files.'
27M_merge_lancia_tuo='❌ the merge is run from your worktree ({wt}), not from {dove}'
28M_hai_lavoro_committato='❌ you have uncommitted work: commit first.'
29M_altro_merge_corso='❌ another merge has been in progress for 10 minutes: ask on the channel.'
30M_principale_lavoro_staging='❌ in the main worktree there'"'"'s someone else'"'"'s work IN STAGING: ask them to commit.'
31M_principale_aggiorna_remoto_2='❌ the main worktree doesn'"'"'t update from the remote (git pull --ff-only): look at it first.'
32M_merge_toccherebbe_file='❌ the merge would touch files that are modified and uncommitted in the main worktree:'
33M_principale_senza_remoto='✅ {ramo} is in the main worktree (no remote: it stays on this machine).'
34M_mergiato_locale_push='❌ merged locally but the push failed: look at it before ending.'
35M_principale_remoto='✅ {ramo} is in the main worktree and on the remote.'
36M_nessun_worktree='no worktree {wt}'
37M_file_committati_smonta='❌ {wt} has uncommitted files: it is NOT removed. Look at them: git -C {wt} status'
38M_principale_prima_merge='❌ {ramo} isn'"'"'t in the main worktree: merge first (delminio merge).'
39M_smontato_tolto='✅ {wt} removed, {ramo} deleted.'
40M_nessuna_track_misurata='No track measured: .delminio/audit/ is empty. You build the half that gets counted'
41M_revisione_memoria_meta='(“Memory review” § The half that gets counted) — today everything is read by hand.'
42M_track_pulite_finding='— {pulite} clean tracks, {con} with findings. The rest of the review is read (the tracks without a script).'
43M_chi_sei_bash_2='❌ I don'"'"'t know who you are: delminio focus "what you touch" S<N>'
44M_chi_sei_sandbox='❌ from inside Codex’s sandbox I can’t see your session: ask the user to approve this command, or the ones that start with “delminio”. Don’t add a session number at random: outside the sandbox, the command knows who you are.'
45M_quali_bash_claude='❌ which ones? delminio focus "what you touch"'
46M_lavora_altre_sessioni='✅ {nome} works on: {valore} — the other sessions see it when they start.'
47M_chi_sei_bash_3='❌ I don'"'"'t know who you are: delminio title "your name" S<N>'
48M_quale_bash_claude='❌ which one? delminio title "your name"'
49M_chiama='✅ {nome} is called: {valore}'
50M_prompt_chiusura_arrivato='⚠️ {perche}: the closing prompt didn'"'"'t arrive. Wrap up anyway:'
51M_lavoro_committato_pushato='the work committed and pushed; where you are, and one single question (“anything else?”); then a commit'
52M_vuoto_git_commit='empty (git commit --allow-empty) “Handoff S<N> — …” with the sections Summary and Where we are,'
53M_push_commit_passera='and push. The commit will go through without verification: tell me.'
54M_chiusura_stata_consegnata='❌ {perche}: the handoff wasn'"'"'t delivered. Try again shortly; if Delminio stays silent, tell the user.'
55M_ripassato_copia_prima='✅ reviewed ({n}): the backup stays in {cartella}, and “delminio disconnect” can still put it back.'
56M_stacca_lancia_terminale='❌ “delminio disconnect” is run from your own terminal, not from an agent: open a terminal outside the agent, in this folder'
57M_stacca_lancia_clone='❌ stacca is run from the main clone, not from a worktree'
58M_rimetto_cio_era='   Putting back what was there before, from {prima}'
59M_copia_prima_tolgo='   ⚠️ there'"'"'s no earlier copy: I only remove Delminio'"'"'s pieces.'
60M_niente_fatto='Nothing done.'
61M_tue_memorie_personali='   your {n} personal memories are in {personali}'
62M_tue_memorie_personali_2='   ⚠️ {perche}: your personal memories stay in Delminio as long as your account exists: get them from the app (after disconnecting, this client is gone)'
63M_server_mcp_delminio='   the previous “{nome}” MCP server is back'
64M_server_mcp_prima='   ⚠️ the previous MCP server didn'"'"'t come back: its definition is in {prima}/mcp-{nome}.json'
65M_tuo_chiama_delminio='   ⚠️ {f} is yours and calls Delminio: remove the .claude/delminio.sh line yourself'
66M_revocare_questo_token='   ⚠️ I can'"'"'t revoke this token: do it from Delminio'"'"'s app (Access)'
67M_token_resta_valido='   the token stays valid: {altri} other projects connected on this machine use it'
68M_token_questo_aggancio='   this connection'"'"'s token is revoked'
69M_token_revocato_fallo='   ⚠️ the token wasn'"'"'t revoked ({perche}): do it from Delminio'"'"'s app (Access)'
70M_tolto_clone_memorie='   removed this machine'"'"'s memory clone (the memories live in their repository)'
71M_restano_worktree_sessioni='   ⚠️ {wt} session worktrees remain (git worktree list): if the work is merged, git worktree remove <folder>'
72M_staccato_cli_torna='✅ disconnected. The CLI goes back to reading its notes; the project'"'"'s memories stay in the memory repository.'
73M_tue_personali='   Your personal ones: {personali}'
74M_copia_prima_resta='   The earlier copy stays in {prima}: connecting again redoes it from scratch.'
75M_accetta_lancia_terminale='❌ “delminio accept” is run from your own terminal, not from an agent: open a terminal outside the agent, in this folder'
76M_lock_duri_sono='⚠️  {perche}: the protected decisions that block were not checked on this commit.'
77M_chiusura_passa_senza='⚠️  {perche}: the handoff goes through without verification, and Delminio won'"'"'t know you'"'"'ve ended.'
78M_delminio_chiusa_chi='   Delminio: {n} ended. The next session will read this handoff.'
79M_opere_avevi_mano='   The tasks you had in progress are free again: {m}.'
80M_risultera_morta_senza='⚠️  {perche}: {n} will show as ended without a handoff.'
81M_lancialo_dentro_repo='❌ run it inside a connected repository'
82M_spazio_repo_aggiunge='The space has no repositories: the admin adds them, from Git.'
83M_repo_dello_spazio='The space'"'"'s repositories, on this machine:'
84M_clonato_qui='  · {nome}: not cloned here'
85M_gia_collegato='  ✅ {nome}: already connected ({dove})'
86M_uso_bash_claude='usage: delminio why <file>:<line>'
87M_nessun_albero='no known worktree'
88M_albero_sporco='worktree {albero} with {n} uncommitted files'
89M_albero_pulito='worktree {albero} clean'
90M_merge_non_pulito='❌ the merge isn'"'"'t clean: rebase your branch on the main one (git rebase {ramo}) and try again.'
91M_stacco='Disconnecting {repo} from Delminio ({url}), on this machine.'
92M_procedo='   Go ahead? [y/N] '
93M_collegato_qui='  ✅ {nome}: connected ({dove})'
94M_collegamento_fallito='  ❌ {nome}: the connection in {dove} didn'"'"'t go through — {errore}'
95M_segno_non_versione='the existing mark isn'"'"'t a version, I won'"'"'t replace it'
96M_informativa_non_segnata='Delminio: Codex notice not marked as seen ({errore}).'
97M_non_risponde_5s='{script} didn'"'"'t respond within 5 seconds'
98M_client_fermo='⚠️ This project'"'"'s Delminio client is stuck at {kit}, Delminio is at {serve}: the automatic connection didn'"'"'t go through ({errore}). Tell the user: the connection is run again from Delminio'"'"'s panel.'
99M_parte_manca='⚠️ {file} is missing, a piece of the Delminio client: the connection didn'"'"'t complete. Tell the user: the connection is run again from Delminio'"'"'s panel.'
100M_riprova_al_primo=' It retries by itself at the user'"'"'s first message.'
101M_nasce_al_primo='Delminio: this chat started in the background or from a fork, and gets its name, with the memory, the messages and the other sessions, at your user'"'"'s first message.'
102M_nasce_senza_memoria='⚠️ {perche}. This session starts WITHOUT memory and without the other sessions: tell the user right away, before anything else.{riprova}'
103M_posta_non_arriva='⚠️ {perche}: the other sessions'"'"' messages don'"'"'t reach you. It retries at every message; this notice appears only once, tell the user.'
104M_invia_uso='usage: delminio send <file> ["note"]'
105M_invia_non_trovato='❌ {file} doesn'"'"'t exist or can'"'"'t be read'
106M_invia_senza_sessione='❌ Run it from an agent: the file leaves from its session.'
107M_invia_fallito='❌ The file wasn'"'"'t sent: {perche}'
108M_invia_fatto='✅ Sent: “{nome}”. The user finds it in the Delminio app, under Files, and gets a notification.'
109M_posta_arrivata='📬 Delminio: a message has arrived from another session — you'"'"'ll find it below.'
110M_chiave_nel_messaggio='⛔ This message contains an access key and wasn'"'"'t sent: here the model would read it, and it would stay in the saved conversation.
111   The command with the key is pasted in the TERMINAL, inside the project folder.
112   If you'"'"'ve already sent it elsewhere, revoke it: Delminio → Access.
113'
114M_gesto_umano='The user wrote “{parola}”: it'"'"'s THEIR action, like /{parola} on Claude.'
115M_lock_del_comando='🔒 {codice} — {cosa} (the admin'"'"'s decision on this command)
116   why: {perche}
117   If your command breaks it, ask them before running it.'
118M_guardie_giu='⚠️ Delminio is not responding: the checks on actions (memories as files, add -A, backticks, pkill -f) didn'"'"'t look at your actions. Be careful yourself, until it'"'"'s back.'
119M_dove_albero_sporco='Worktree: {n} uncommitted files.'
120M_dove_albero_pulito='Worktree clean.'
121M_commit_non_pushati='{n} commits not pushed on {ramo}.'
122M_tutto_pushato='Everything pushed.'
123M_ramo_senza_remoto='The branch {ramo} has no remote: it isn'"'"'t pushed.'
124M_worktree_in_piu='{n} worktrees besides the main one: {alberi}.'
125M_script_non_risponde='⚠️ {script} didn'"'"'t respond: {errore}'
126M_chiusura_rifiutata='❌ Delminio rejects this handoff:'
127M_aggiunge_trailer='   Delminio adds “{trailer}”.'
128M_aggiunge_trailer_perche='   Delminio adds “{trailer}”: {perche}.'
129M_chiusa_nel_repo='✅ {nome} ended: the handoff is in the memory repository ({hash}). The next session will read it.'
130M_perche_tornata='the sessions you crossed paths with'
131M_perche_memoria='the memories, committed by Delminio (if the push didn'"'"'t go through, it says so below)'
132M_questo_repo='this repository'
133M_tocco_ospite='🤝 {repo} belongs to the space “{di}”, which shares it with this one: you work on it as a guest. What you learn goes into this space'"'"'s memories; the protected decisions of “{di}” on its files apply to you too, and the ones touching the file I tell you below.'
134M_tocco_altro_spazio_tuo='🧭 {repo} is connected to the space “{suo}”, and this session writes memories in the space “{mio}”: what you learn here ends up in “{mio}”. If the work belongs to “{suo}”, tell the user: the agent is opened inside {repo}.'
135M_tocco_non_condiviso='🧭 {repo} belongs to the space “{di}”, and isn'"'"'t shared with this one: what you learn here ends up in this space'"'"'s memories, and the protected decisions of “{di}” can'"'"'t be seen from here. If the work belongs to “{di}”, tell the user.'
136M_tocco_lock='🔒 You'"'"'re about to touch {file}: an admin'"'"'s protected decision applies there. Read it before writing — if your change breaks it, ask them.'
137M_tocco_duro=' (BLOCKING: at commit its check runs, and if it fails a member'"'"'s commit stops)'
138M_tocco_duro_ospite=' (BLOCKING in the owning space: its check doesn'"'"'t run here, respect it yourself)'
139M_tocco_dello_spazio=' (from the space “{spazio}”)'
140M_tocco_voce='
141{codice}{di} — {cosa}{duro}
142   why: {perche}
143   verified by: {guardia}'
144M_tocco_nessuno='NOBODY — if you break it, nothing complains'
145M_accetta_domanda='
146{codice} — {cosa}
147  written by: {chi}
148  the command that will run here, at every commit:
149
150    {comando}
151
152Do you accept it? [y/N] '
153M_accetta_si='y yes'
154M_accettate='✅ {nuove} accepted now · {tutte} in total · the list: {file}'
155M_perche_non_committata='{dove} isn'"'"'t committed yet: the why is in the current work.'
156M_perche_commit='{dove} → the commit {commit} of {data}, by {autore}: “{soggetto}”'
157M_perche_senza_sessione='   No Delminio session on this commit: it predates Delminio, or was made by hand.
158   The rest is told by the commit: git show {commit}'
159M_perche_sessione_muto='   → the session {sessione}; Delminio is not responding ({errore}), and it knows the rest.'
160M_perche_sessione='   → the session {sessione}{agente}{chi}{nata}'
161M_perche_con=', with {chi}'
162M_perche_nata=', started on {data}'
163M_perche_senza_chiusura='   It didn'"'"'t leave a handoff: the why is in its commits (git log --grep '"'"'Delminio-Sessione: {sessione}'"'"').'
164M_perche_chiusa='   → it ended on {data} with the commit {commit}{repo}: {comando}'
165M_perche_in_repo=' in {repo}'
166M_perche_memorie='   → the memories it touched:'
167M_perche_nessuna_memoria='   → no memory touched in that handoff.'
168M_perche_memorie_nel_commit='   → the memories touched are in the commit {commit} of the memory repository.'
169M_perche_le_memorie='   → the memories: {memorie}'
170M_fermato_codex='Stopped by Delminio: the agent received the why.'
171M_consegna_di_uso='❌ which one? delminio handoff-of S<N>'
172M_consegna_di_curata='⟳ The handoff of S{numero} is CORRECTED: this is the version to read, don'"'"'t open the original with git.'
173M_consegna_di_vuota='The handoff of S{numero} no longer has its text in the service: someone with permission deleted it.'
174M_codex_senza_plugin='Delminio'"'"'s plugin did not install in Codex'"'"'s folder: the memory comes with the launch, but the hooks (opening, messages, checks) don'"'"'t. Reconnect the project with DELMINIO_SENZA_PLUGIN=1 to put them back in the project.'
175M_app_codex_fatto='Done: the Codex app now has Delminio. In ~/.codex/config.toml I only added the Delminio plugin and the permission for its two tools. Reopen the app, open a connected repository and approve the Delminio hooks in “Review hooks” (or in Settings → Hooks), just once; then type opening. To remove it: delminio app-codex via'
176M_app_codex_assente='I can'"'"'t find the Codex app on this computer (ChatGPT for Mac or Linux): there is nothing to do. On the Mac the app exists only for Apple Silicon.'
177M_app_codex_non_riuscito='I couldn'"'"'t add Delminio to the Codex app. Close the app and run delminio app-codex again; if it stops again, show this message to the admin.'
178M_app_codex_tolto='Removed: the Codex app no longer has Delminio, and the rest of ~/.codex/config.toml is as it was.'
179M_app_codex_no='All right: I won'"'"'t suggest it again on this computer. If you change your mind: delminio app-codex'
180M_app_codex_uso='usage: delminio app-codex [via|no|stato]'
181M_qwen_senza_plugin='Delminio'"'"'s extension did not link in Qwen Code'"'"'s folder: the memory comes with the launch, but the hooks (opening, messages, checks) don'"'"'t. Reconnect the project with DELMINIO_SENZA_PLUGIN=1 to put them back in the project.'
182M_script_da_accettare='⏸ {n} project scripts in .delminio/ don'"'"'t run on this computer until your user accepts them: they come from commits by {chi}. Ask them to run, from their own terminal: delminio accept'
183M_accetta_script_elenco='
184The project scripts that run on this computer at the opening or the closing, which came from other people'"'"'s commits and aren'"'"'t accepted yet:
185'
186M_accetta_script_riga='  {percorso} — {chi}, {quando}, {righe} lines'
187M_accetta_script_domanda='
188They will run with your permissions. Do you accept them? [a = all · o = one by one, reading them · N = none] '
189M_accetta_script_uno='
190{percorso} — {chi}, {quando}
191
192{testo}
193
194Do you accept it? [y/N] '
195M_accetta_script_tutti_si='a all'
196M_accetta_script_uno_si='o one'
197M_script_accettati='✅ scripts: {nuovi} accepted now · {fermi} stay stopped (if one changes, I'"'"'ll ask again)'
198M_pulito_ultimo='   It was the last project connected on this computer: also removed the plugin, the Codex and Qwen Code versions Delminio downloaded, and its cache.
199   These stay, because they'"'"'re yours: the Claude Code versions in ~/.local/share/claude/versions (it'"'"'s your Claude'"'"'s folder) and the agents'"'"' folders in ~/.local/share/delminio/codex and /qwen, which hold their conversations.'
200M_perche_muto='Delminio is not responding at {url}'
201M_perche_token='Delminio at {url} refuses this link'"'"'s token (HTTP {codice})'
202M_perche_rifiuta='Delminio at {url} said no (HTTP {codice}: {errore})'
203M_perche_errore='Delminio at {url} answered with an error (HTTP {codice}{errore})'
204M_prompt_rifiutato='⚠️ Delminio at {url} didn'"'"'t give the opening prompt (HTTP {codice}{errore}): tell the user.'
205M_guardie_errore='⚠️ Delminio answered with an error (HTTP {codice}): the checks on actions (memories as files, add -A, backticks, pkill -f) didn'"'"'t look at this action. Be careful yourself, and tell the user.'
206M_piu_agenti_non_concessa='❌ “Multiple agents” isn'"'"'t in this space'"'"'s licence: no session worktree.'
207M_guardia_non_accettata='⚠️  the check for {codice} is new or changed, and nobody on this machine has accepted it yet — I didn'"'"'t run it:
208     {comando}
209   Read it and, if you trust it, from a terminal of yours: delminio accept
210   The commit goes through, but this protected decision is not enforced on this machine until someone accepts the check.'
211M_lock_grida_muto='⚠️  {codice} cried out but Delminio is not responding: the commit goes through, and the admin won'"'"'t know.'
212M_lock_grida_errore='⚠️  {codice} cried out but Delminio answered with an error (HTTP {codice_http}): the commit goes through, and the admin won'"'"'t know. Tell the user.'
213M_guardia_dice='   the check says:'
214M_gesto_controllo_non_accettato='⚠️  {codice} — {cosa}: its check before this command is new or changed, and on this machine nobody has accepted it yet — I did not run it:
215     {comando}
216   The command goes through, but this protected decision is not enforced on this machine until the check is accepted. Tell your user to read it and, if they trust it, to run from their own terminal: delminio accept'
217M_accetta_domanda_gesto='
218{codice} — {cosa}
219  written by: {chi}
220  the check that will run here, before every command matching {gesti}:
221
222    {comando}
223
224Do you accept it? [y/N] '
225M_sessione_non_viva='❌ {nome} isn'"'"'t an open session: nothing written. Your name is in the opening.'
226M_skill_nomi_pulita='✅ team skills: every path they name is in the repo (pieces checked: {n})'
227M_skill_nomi_finding='❌ {pezzo} ({file}): “{nome}” is not in the repo'
228M_skill_nomi_voluti='   A skill naming a file that no longer exists needs fixing (Skills view). If the name is meant — a file that will come later, or in another repo —, write it in .delminio/skill-nomi-voluti.txt, one per line.'
229M_skill_nomi_nessuna='— the team has no skills, commands or agents to check against the repo.'
230M_skill_nomi_cieca='⚠️ team skills were not checked against the repo: Delminio does not answer ({perche}). It does not mean they are fine.'
231M_squadra_mcp_da_accettare='⏸ {n} team MCP servers do not start on this computer until your user accepts them: they come from the space'"'"'s team and would run with their permissions. Ask them to run, from their own terminal: delminio accept'
232M_squadra_plugin_da_accettare='⏸ {n} team plugins are not installed on this computer until your user accepts them: they come from the space'"'"'s team and would run with their permissions. Ask them to run, from their own terminal: delminio accept'
233M_riaggancio_non_firmato='The connection update from {url} doesn'"'"'t carry Delminio'"'"'s release signature: it wasn'"'"'t installed, and the previous connection stays. If you moved Delminio back to an earlier version, run the connection again by hand from the terminal.'
234M_eseguibili_da_accettare='⏸ {n} agent commands don'"'"'t update on this computer until your user accepts their arguments or environment variables: they come from the space'"'"'s registry and would run with their permissions. Ask them to run, from their own terminal: delminio accept'
235M_aiuto='Delminio'"'"'s commands: run them in the folder of a connected project.
236
237  delminio agents                   writes this space'"'"'s agents on this computer (Agents view)
238  delminio agents status            which agents are on this computer, and at which version
239  delminio accept                   accepts the agents'"'"' options and the team'"'"'s servers
240  delminio connect-all              connects in one go the space'"'"'s projects that are on this computer
241  delminio backlog help             the Backlog from the terminal: search, open, close items
242  delminio vault list               the secrets agents can ask for, if the vault is on
243  delminio why <file>:<line>        which session wrote that line, and its handoff
244  delminio handoff-of S<number>     a session'"'"'s whole handoff
245  delminio errors [days]           the tool calls that failed on this computer, in short
246  delminio review                   the project'"'"'s automatic checks, those of the review
247  delminio send <file> ["note"]     sends a file to the people you work with: they find it in the Files view
248  delminio app-codex [via|no]       Delminio in the Codex desktop app
249  delminio signoffs check [a..b]     a branch'"'"'s changes: signed, to sign, with changed words
250  delminio signoffs description [a..b] the text of a pull request: the person'"'"'s words and the facts
251  delminio signoffs report [a..b]      the report commit by commit, for the auditor
252  delminio disconnect               disconnects this project from Delminio and puts everything back as it was
253
254The other commands are run by the agent itself. Each one is explained in the guide, on the “Commands” page.'
255M_comando_sconosciuto='unknown command “{nome}”.'
256M_uso_clona='usage: delminio clone <repository name> [--no]'
257M_clona_non_dello_spazio='“{nome}” isn'"'"'t a repository of this space: the opening lists them, or the app'"'"'s Git page.'
258M_clona_no='All right: I won'"'"'t suggest “{nome}” on this computer again. If it'"'"'s needed, delminio clone {nome}'
259M_clona_occupata='{dove} already exists and isn'"'"'t a clone of this repository: I'"'"'m leaving it alone. Tell the user, who chooses where to put it.'
260M_clona_in_corso='Cloning “{nome}” from {url} into {dove}…'
261M_clona_fallito='❌ “{nome}” can'"'"'t be cloned from {url}: {errore}. If git says access is denied or the repository doesn'"'"'t exist, this person has no permission on it: the admin grants it, on the git server.'
262M_gesto_controllo_non_parte_fermo='⛔ {codice} — {cosa}: its check does not start ({comando}), and this decision blocks, so the command is stopped. The check needs fixing: make sure the command exists and is executable. Until then, the command only goes through with an exception from the admin.'
263M_guardia_non_parte_fermo='⛔ the check for {codice} does not start ({comando}), and this decision blocks, so the commit is stopped. The check needs fixing: make sure the command exists and is executable. Until then, the commit only goes through with an exception from the admin.'
264M_gesto_controllo_lento_fermo='⛔ {codice} — {cosa}: its check did not answer within {secondi} seconds ({comando}), and this decision stops when its check doesn'"'"'t answer, so the command is stopped. Try again. If it happens again, the check needs to be faster, or the admin can give it more time.'
265M_guardia_lento_fermo='⛔ the check for {codice} did not answer within {secondi} seconds ({comando}), and this decision blocks, so the commit is stopped. Try again. If it happens again, the check needs to be faster.'
266M_gesto_controllo_lento_passa='⚠️  the check for {codice} did not answer within {secondi} seconds ({comando}). The command goes through unchecked, as set for this decision. If it happens often, the admin can give it more time or choose to block.'
267M_gesto_controllo_non_parte_passa='⚠️  the check for {codice} does not start ({comando}). The command goes through: this decision warns and does not block. The check needs fixing: make sure the command exists and is executable.'
268M_controllo_non_parte_breve='the check does not start ({comando}): make sure the command exists and is executable.'
269M_controllo_lento_breve='the check did not answer within {secondi} seconds ({comando}).'
270: '⟦fine frasi⟧'
271export ${!M_@}
272IFS= read -r -d '' DELMINIO_FIDATI_PY <<'FIDATI' || true
273import hashlib as _hl, os as _os, subprocess as _sp
274def _git_in(albero, *a):
275    r = _sp.run(["git", "-C", albero, *a], capture_output=True, text=True)
276    return r.returncode, r.stdout.strip()
277def accettati_file(albero):
278    rc, c = _git_in(albero, "rev-parse", "--path-format=absolute", "--git-common-dir")
279    return _os.path.join(c, "delminio-script-accettati") if rc == 0 and c else ""
280def accettati(albero):
281    try:
282        return set(open(accettati_file(albero), encoding="utf-8").read().split())
283    except OSError:
284        return set()
285def impronta_script(albero, f):
286    with open(f, "rb") as h:
287        return _hl.sha256(_os.path.relpath(f, albero).encode() + b"\0" + h.read()).hexdigest()
288def di_chi(albero, f):
289    rel = _os.path.relpath(f, albero)
290    if _git_in(albero, "ls-files", "--error-unmatch", "--", rel)[0] != 0:
291        return None
292    if _git_in(albero, "diff", "--quiet", "HEAD", "--", rel)[0] != 0:
293        return None
294    io = _git_in(albero, "config", "user.email")[1].lower()
295    ae, an, ad = (_git_in(albero, "log", "-1", "--format=%ae%x1f%an%x1f%ad", "--date=short", "--", rel)[1].split("\x1f") + ["", "", ""])[:3]
296    if io and ae.lower() == io:
297        return None
298    return (an or ae or "?", ad)
299def da_fidarsi(albero, f, gia):
300    return di_chi(albero, f) is None or impronta_script(albero, f) in gia
301def lascito_del_progetto(albero):
302    """F903 — .delminio/lascito.sh gira alla morte della CLI: come gli altri script
303    del progetto, solo se è di chi lavora qui o una persona l'ha accettato."""
304    f = _os.path.join(albero, ".delminio", "lascito.sh") if albero else ""
305    return [f] if f and _os.path.isfile(f) and _os.access(f, _os.X_OK) else []
306def script_del_progetto(albero, cartelle):
307    out = []
308    for d in cartelle:
309        c = _os.path.join(albero, ".delminio", d)
310        for s in (sorted(_os.listdir(c)) if albero and _os.path.isdir(c) else []):
311            f = _os.path.join(c, s)
312            if _os.path.isfile(f) and _os.access(f, _os.X_OK):
313                out.append(f)
314    return out
315FIDATI
316export DELMINIO_FIDATI_PY
317: '⟦protocollo⟧'
318P_CLOSE='Chiusura|Handoff|Close Session'
319P_TRAILER_TORNATA=Parallel-session
320P_TRAILER_AUDIT='Audit|Review'
321P_TRAILER_MEMORIA='Memoria|Memory'
322export P_CLOSE P_TRAILER_TORNATA P_TRAILER_AUDIT P_TRAILER_MEMORIA
323: '⟦fine protocollo⟧'
324STATO="${TMPDIR:-/tmp}/delminio-$(id -u)"
325mkdir -p "$STATO" 2>/dev/null; chmod 700 "$STATO" 2>/dev/null
326if [ -L "$STATO" ] || [ ! -O "$STATO" ]; then
327  STATO="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-stato"
328  mkdir -p "$STATO" && chmod 700 "$STATO"
329fi
330spazza_stato() {
331  local f p
332  for f in "$STATO"/{attesa,volo,no,nasci,fork,lock-detti,condiviso,avvisato,visto,sessione,cuore,posta-muta}-*; do
333    [ -e "$f" ] || continue
334    p=${f##*-}
335    case $p in *[!0-9]*|'') continue ;; esac
336    kill -0 "$p" 2>/dev/null || rm -f -- "$f"
337  done
338  find "$STATO" -maxdepth 1 -name 'volo-sid-*' -mmin +60 -delete 2>/dev/null || true
339  find "$STATO" -maxdepth 1 -name 'conto-*' -mmin +1440 -delete 2>/dev/null || true
340  find "$STATO" -maxdepth 1 -name 'skill-*' -mmin +1440 -delete 2>/dev/null || true
341}
342in_sottofondo() {
343  [ "${CLAUDE_CODE_SESSION_KIND:-}" = bg ] && return 0
344  [ -r "/proc/$1/environ" ] && tr '\0' '\n' < "/proc/$1/environ" 2>/dev/null | grep -qx 'CLAUDE_CODE_SESSION_KIND=bg'
345}
346madri_del_fork() {
347  printf '%s' "$1" | python3 -c 'import json, sys
348io = sys.argv[1]
349try:
350    t = json.loads(sys.stdin.read() or "{}").get("transcript_path") or ""
351except (ValueError, AttributeError):
352    t = ""
353viste = []
354try:
355    with open(t, encoding="utf-8", errors="replace") as h:
356        for riga in h:
357            try:
358                d = json.loads(riga)
359            except ValueError:
360                continue
361            for k in ("session_id", "sessionId"):
362                v = d.get(k) if isinstance(d, dict) else None
363                if isinstance(v, str) and v and v != io:
364                    if v in viste:
365                        viste.remove(v)
366                    viste.append(v)
367except OSError:
368    pass
369print(json.dumps(viste[::-1][:5]))' "$2" 2>/dev/null || echo '[]'
370}
371zitta_la_prima() {
372  local prima q conv a
373  prima=$(printf '%s' "$1" | campo processo_di_prima)
374  [ -n "$prima" ] && [ "${prima%:*}" = "$(hostname)" ] || return 0
375  q=${prima##*:}
376  case $q in ''|*[!0-9]*) return 0 ;; esac
377  [ "$q" != "$2" ] || return 0
378  rm -f "$STATO/sessione-$q"
379  a=$(cat "$STATO/attesa-$q" 2>/dev/null || true)
380  [ -n "$a" ] && kill "$a" 2>/dev/null
381  rm -f "$STATO/attesa-$q"
382  conv=$(printf '%s' "$1" | campo conversazione_di_prima)
383  if [ -n "$conv" ] && kill -0 "$q" 2>/dev/null; then printf '%s' "$conv" > "$STATO/nasci-$q"; fi
384  return 0
385}
386cli_pid() {
387  if [ -n "${DELMINIO_CLI_PID:-}" ] && kill -0 "$DELMINIO_CLI_PID" 2>/dev/null; then
388    printf '%s' "$DELMINIO_CLI_PID"; return 0
389  fi
390  local p=$$ q exe stato args
391  for _ in 1 2 3 4 5 6 7 8; do
392    if [ -r "/proc/$p/stat" ]; then
393      read -r stato < "/proc/$p/stat"; stato=${stato##*) }; q=${stato#* }; q=${q%% *}
394    else
395      q=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d ' ')
396    fi
397    { [ -z "$q" ] || [ "$q" -le 1 ]; } 2>/dev/null && return 1
398    exe=$(readlink -f "/proc/$q/exe" 2>/dev/null || true)
399    case "$exe" in */claude|*/claude/*|*/versions/*|*/ccd-cli/*|*/bin/codex|*/bin/opencode) printf '%s' "$q"; return 0 ;; esac
400    case "$exe" in ''|*/node*) e_qwen "$q" && { printf '%s' "$q"; return 0; } ;; esac
401    if [ -r "/proc/$q/cmdline" ]; then
402      args=$(tr '\0' ' ' < "/proc/$q/cmdline")
403    else
404      args=$(ps -o args= -p "$q" 2>/dev/null)
405    fi
406    [[ " $args" =~ (^|/|\ )(claude|codex)(\ |$)|/versions/|/ccd-cli/ ]] && { printf '%s' "$q"; return 0; }
407    p=$q
408  done
409  return 1
410}
411_conto_segna() {
412  local t1=${EPOCHREALTIME:-} a b
413  [ -n "$t1" ] && [ -n "${_conto_t0:-}" ] || return 0
414  a=${_conto_t0/[.,]/}; b=${t1/[.,]/}
415  printf '%s %s\n' "$_conto_gesto" $(( (10#$b - 10#$a) / 1000 )) >> "$STATO/conto-$_conto_sid" 2>/dev/null || true
416}
417_conto_somme() {
418  local f="$STATO/conto-${_conto_sid:-}"
419  [ -n "${_conto_sid:-}" ] && [ -s "$f" ] || return 0
420  mv -f "$f" "$f.invio" 2>/dev/null || return 0
421  awk '$1 ~ /^[a-z]+$/ && $2 ~ /^[0-9]+$/ {v[$1]++; m[$1]+=$2}
422       END {s=""; for (g in v) s=s (s ? "," : "") "\"" g "\":[" v[g] "," m[g] "]"; printf "%s", s}' "$f.invio"
423  rm -f "$f.invio"
424}
425_skill_voci() {
426  local sid=${_skill_sid:-${_conto_sid:-}} s=""
427  local f="$STATO/skill-$sid"
428  [ -n "$sid" ] && [ -s "$f" ] || return 0
429  mv -f "$f" "$f.invio" 2>/dev/null || return 0
430  while read -r tipo nome; do
431    [[ $tipo =~ ^(skill|comando)$ && $nome =~ ^[A-Za-z0-9_.:-]+$ ]] || continue
432    s+="${s:+,}[\"$tipo\",\"$nome\"]"
433  done < "$f.invio"
434  rm -f "$f.invio"
435  printf '%s' "$s"
436}
437_quota() {
438  local LC_ALL=C s=$1 i c o=""
439  for ((i = 0; i < ${#s}; i++)); do
440    c=${s:i:1}
441    case $c in
442      [a-zA-Z0-9._~-]) o+=$c ;;
443      *) if [ "$c" = / ] && [ "${2-/}" = / ]; then o+=/; else printf -v c '%%%02X' "'$c"; o+=$c; fi ;;
444    esac
445  done
446  printf '%s' "$o"
447}
448_guardia_serve() {
449  local e=$1 m=${MEMORIA%/} cwd=""
450  [[ $e == *'`'* || $e == *pkill* || $e == *workdir* || $e == *'\u0060'* ]] && return 0
451  [ -n "$m" ] || return 1
452  [[ $e == *"$(basename "$(dirname "$m")")"* || $e == *"$(basename "$m")/"* ]] && return 0
453  [[ $e =~ \"cwd\":\ ?\"([^\"]*)\" ]] && cwd=${BASH_REMATCH[1]}
454  [ -n "$cwd" ] && [[ $m == "${cwd%/}"/* || $m == "$cwd" ]]
455}
456e_codex() { _args "$1" | head -1 | grep -qE '(^|/)codex$'; }
457e_qwen() {
458  _args "$1" | head -1 | grep -qE '(^|/)node[0-9.]*$' || return 1
459  _args "$1" | sed -n 2,4p | grep -v '^-' | head -1 | grep -qE '(^|/)qwen$|/@qwen-code/qwen-code/'
460}
461e_opencode() {
462  [ "$1" = "${DELMINIO_CLI_PID:-}" ] && [ "${DELMINIO_CLI_NOME:-}" = opencode ] && return 0
463  case "$(readlink -f "/proc/$1/exe" 2>/dev/null || true)" in */bin/opencode) return 0 ;; esac
464  _args "$1" | head -1 | grep -qE '(^|/)opencode$'
465}
466cli_di() {
467  if e_codex "$1" 2>/dev/null; then echo codex; elif e_qwen "$1" 2>/dev/null; then echo qwen
468  elif e_opencode "$1" 2>/dev/null; then echo opencode; else echo claude; fi
469}
470headless() {
471  if e_qwen "$1"; then
472    _args "$1" | python3 -c 'import re, sys
473CON_VALORE = {"-m", "--model", "-s", "--sandbox", "--approval-mode", "--mcp-config", "--input-file",
474              "--system-prompt", "--append-system-prompt", "-o", "--output-format", "--input-format",
475              "--session-id", "--include-directories", "--add-dir", "--allowed-tools", "--exclude-tools",
476              "--core-tools", "-e", "--extensions", "--auth-type", "--openai-api-key", "--openai-base-url",
477              "--openai-logging-dir", "--max-session-turns", "--max-wall-time", "--max-tool-calls",
478              "--max-subagent-depth", "--channel", "--json-fd", "--json-file", "--json-schema", "--proxy",
479              "--fallback-model", "--advisor", "--output-style", "--disabled-slash-commands",
480              "--allowed-mcp-server-names", "--disable-mcp-server", "--sandbox-image"}
481a = sys.stdin.read().split("\n")
482script = next((k for k, x in enumerate(a[1:4], 1)
483               if not x.startswith("-") and re.search(r"(^|/)qwen$|/@qwen-code/qwen-code/", x)), None)
484if script is None: sys.exit(1)
485a = a[script + 1:]; i = 0
486while i < len(a):
487    x = a[i]
488    if x in ("-i", "--prompt-interactive") or x.startswith("--prompt-interactive="): sys.exit(1)
489    if x in ("-p", "--prompt") or x.startswith("--prompt="): sys.exit(0)
490    if x == "--": sys.exit(0 if any(a[i + 1:]) else 1)
491    if x in CON_VALORE: i += 2; continue
492    if x in ("-r", "--resume"):
493        i += 2 if i + 1 < len(a) and a[i + 1] and not a[i + 1].startswith("-") else 1
494        continue
495    if x.startswith("-") or not x: i += 1; continue
496    sys.exit(0)
497sys.exit(1)'
498  elif e_opencode "$1"; then
499    [ "$1" = "${DELMINIO_CLI_PID:-}" ] && return 1
500    local chi=$1 su
501    if _args "$chi" | grep -qx -- --service; then
502      if [ -r "/proc/$chi/stat" ]; then read -r su < "/proc/$chi/stat"; su=${su##*) }; su=${su#* }; su=${su%% *}
503      else su=$(ps -o ppid= -p "$chi" 2>/dev/null | tr -d ' '); fi
504      [ -n "$su" ] && e_opencode "$su" && chi=$su
505    fi
506    _args "$chi" | sed 1d | python3 -c 'import sys
507CON_VALORE = {"-m", "--model", "--agent", "-s", "--session", "--port", "--hostname", "--log-level", "--prompt"}
508a = sys.stdin.read().split("\n"); i = 0
509while i < len(a):
510    x = a[i]
511    if x in CON_VALORE: i += 2; continue
512    if x.startswith("-") or not x: i += 1; continue
513    sys.exit(0 if x == "run" else 1)
514sys.exit(1)'
515  elif _args "$1" | head -1 | grep -qE '(^|/)codex$'; then
516    _args "$1" | sed 1d | python3 -c 'import sys
517CON_VALORE = {"-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a",
518              "--ask-for-approval", "-C", "--cd", "--add-dir", "-i", "--image", "--enable", "--disable",
519              "--remote", "--remote-auth-token-env", "--local-provider"}
520a = sys.stdin.read().split("\n"); i = 0
521while i < len(a):
522    x = a[i]
523    if x == "--": sys.exit(1)
524    if x in CON_VALORE: i += 2; continue
525    if x.startswith("-"): i += 1; continue
526    sys.exit(0 if x in ("exec", "e", "review") else 1)
527sys.exit(1)'
528  else
529    _args "$1" | grep -qxE -- '-p|--print'
530  fi
531}
532cartella_backup() {  # dove sta la copia di sicurezza di questo clone (F777): la scrive il collegamento in .git
533  cat "$(git rev-parse --git-common-dir 2>/dev/null)/delminio-backup" 2>/dev/null || true
534}
535PY_SKILL_NOMI='
536import json, os, re, subprocess, sys
537radice = sys.argv[1]
538p = json.load(sys.stdin)
539plugin = p.get("plugin") or "squadra"
540pezzi = [x for x in p.get("pezzi") or [] if x.get("tipo") in ("skill", "comando", "agente")]
541if not pezzi:
542    print("NESSUNA"); sys.exit(0)
543fatti = subprocess.run(["git", "-C", radice, "ls-files", "-co", "--exclude-standard"],
544                       capture_output=True, text=True).stdout.split("\n")
545fatti = {f for f in fatti if f and os.path.lexists(os.path.join(radice, f))}   # tolto dal disco e ancora fra i file di git: non conta
546cartelle = {os.path.dirname(f) for f in fatti}
547while any("/" in c and os.path.dirname(c) not in cartelle for c in cartelle):
548    cartelle |= {os.path.dirname(c) for c in cartelle}
549nomi_base = {os.path.basename(f) for f in fatti}
550try:
551    voluti = {r.strip() for r in open(os.path.join(radice, ".delminio", "skill-nomi-voluti.txt"), encoding="utf-8")
552              if r.strip() and not r.startswith("#")}
553except OSError:
554    voluti = set()
555EST = ("py sh bash md json yml yaml toml js mjs ts tsx jsx go rs java kt rb php sql css html txt cfg ini "
556       "conf csv xml env lock ps1").split()
557def parole(testo):
558    pezzi = re.findall(r"```[^\n]*\n(.*?)```", testo, re.S)
559    resto = re.sub(r"```.*?```", " ", testo, flags=re.S)
560    pezzi += re.findall(r"`([^`\n]+)`", resto)
561    for x in pezzi:
562        for w in re.split(r"[\s;,]+", x):
563            yield w.strip("\"\x27:.()")
564def percorso(w):
565    if not w or w.startswith(("~", "/", "-", "@", "$")) or "://" in w or re.search(r"[<>{}$*?|()\[\]=]", w):
566        return False
567    w = w[2:] if w.startswith("./") else w
568    return ("/" in w and re.fullmatch(r"[\w.@+-]+(/[\w.@+-]+)*/?", w) is not None) \
569        or (re.fullmatch(r"[\w@+-][\w.@+-]*\.(" + "|".join(EST) + ")", w) is not None)
570def c_e(w):
571    w = (w[2:] if w.startswith("./") else w).rstrip("/")
572    if w in fatti or w in cartelle or os.path.exists(os.path.join(radice, w)):
573        return True
574    if "/" not in w:
575        return w in nomi_base
576    return any(f.endswith("/" + w) for f in fatti) or any(c.endswith("/" + w) for c in cartelle)
577trovati = 0
578for x in pezzi:
579    for rel, testo in sorted((x.get("file") or {}).items()):
580        if not rel.endswith(".md"):
581            continue
582        visti = set()
583        for w in parole(testo):
584            if w in visti or w in voluti or not percorso(w):
585                continue
586            visti.add(w)
587            if not c_e(w):
588                trovati += 1
589                print("\t".join(("F", plugin + ":" + x["nome"], rel, w)))
590if trovati:
591    sys.exit(1)
592print("OK\t" + str(len(pezzi)))
593'
594chiedi() {  # chiedi GET|POST <percorso> [json] → corpo; esce 1 se Delminio non risponde 200
595  local r c
596  local h=(-H "Content-Type: application/json")
597  [ -n "${CHIEDI_SESSIONE:-}" ] && h+=(-H "X-Delminio-Sessione: $CHIEDI_SESSIONE")
598  if [ -n "${3:-}" ]; then
599    r=$(printf '%s' "$3" | curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
600          "${h[@]}" --data-binary @- "$URL$2" 2>/dev/null)
601  else
602    r=$(curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
603          "${h[@]}" "$URL$2" 2>/dev/null)
604  fi
605  c=${r##*$'\n'}
606  if [ "$c" != 200 ]; then
607    local e; e=$(printf '%s' "${r%$'\n'*}" | campo error); e=${e//[$'\t\n']/ }
608    printf '%s\t%s' "${c:-000}" "$e" > "$STATO/no-$$" 2>/dev/null || true
609    return 1
610  fi
611  printf '%s' "${r%$'\n'*}"
612}
613
614carta_richiesta() {  # stdin: l'evento della CLI · $1 la sessione
615  local f; f="$(cd "$(dirname "$0")" && pwd)/firme.py"
616  [ -f "$f" ] || return 0
617  DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_STATO="$STATO" python3 "$f" _richiesta "$1" 2>/dev/null || true
618}
619
620cure() {
621  local r d
622  d=$(git rev-parse --git-common-dir 2>/dev/null) || return 0
623  r=$(chiedi GET /api/cure) || return 0
624  printf '%s' "$r" | python3 -c '
625import json, os, re, subprocess, sys
626r, messe_file = json.load(sys.stdin), sys.argv[1]
627def git(*a, inp=None, vero=False):
628    pre = [] if vero else ["--no-replace-objects"]
629    return subprocess.run(["git", *pre, *a], input=inp, capture_output=True, text=True,
630                          encoding="utf-8", errors="surrogateescape").stdout
631def testa_senza_firma(testa):
632    fuori, out = False, []
633    for riga in testa.split("\n"):
634        if riga.startswith(("gpgsig ", "gpgsig-sha256 ")):
635            fuori = True
636            continue
637        if fuori and riga.startswith(" "):
638            continue
639        fuori = False
640        out.append(riga)
641    return "\n".join(out)
642try:
643    messe = set(open(messe_file, encoding="utf-8").read().split())
644except OSError:
645    messe = set()
646vive = set()
647for k in r.get("cure") or []:
648    h, n = str(k.get("hash") or ""), int(k.get("numero") or 0)
649    if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h):
650        continue
651    full = git("rev-parse", "-q", "--verify", h + "^{commit}").strip()
652    if not full:
653        continue                      # quel close non sta in questo repo
654    testa, _, msg = git("cat-file", "commit", full).partition("\n\n")
655    sogg = msg.split("\n", 1)[0]
656    if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), sogg):
657        continue                      # non è il close di quel numero: non si tocca
658    vive.add(full)                    # viva anche se qui sotto qualcosa cade: non esce dal git per un giro
659    trailer = git("interpret-trailers", "--parse", inp=msg).strip()
660    corpo = (sogg + "\n\n" + str(k.get("intestazione") or "").strip() + "\n\n" + str(k.get("testo") or "").strip()
661             + "\n" + ("\n" + trailer + "\n" if trailer else ""))
662    nuovo = git("hash-object", "-t", "commit", "-w", "--stdin", inp=testa_senza_firma(testa) + "\n\n" + corpo).strip()
663    if not nuovo:
664        continue
665    if git("rev-parse", "-q", "--verify", "refs/replace/" + full).strip() != nuovo:
666        git("replace", "-f", full, nuovo, vero=True)
667for orig in messe - vive:             # tolta nel motore: esce, ma solo se è nostra
668    git("replace", "-d", orig, vero=True)
669with open(messe_file + ".nuovo", "w", encoding="utf-8") as f:
670    f.write("\n".join(sorted(vive)) + ("\n" if vive else ""))
671os.replace(messe_file + ".nuovo", messe_file)
672' "$(_assoluto "$d")/delminio-cure" 2>/dev/null || true
673}
674
675_remoto() { git ${1:+-C "$1"} remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#'; }
676_urlenc() { python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$1"; }
677REPO_NO="${XDG_CONFIG_HOME:-$HOME/.config}/delminio/repo-no.json"
678repo_no_qui() {  # → la lista JSON dei «no» di questo collegamento
679  DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" <<'REPO_NO' 2>/dev/null || printf '[]'
680import json, os, sys
681try:
682    d = json.load(open(sys.argv[1], encoding="utf-8"))
683except (OSError, ValueError):
684    d = {}
685v = d.get(os.environ["DELMINIO_CHI"]) if isinstance(d, dict) else None
686print(json.dumps([str(x) for x in v] if isinstance(v, list) else []))
687REPO_NO
688}
689_collega_clone() {  # _collega_clone <nome> <cartella>: il clone si collega allo spazio, col token di qui
690  local log="$STATO/collega-$$.log" errore_log
691  if ( cd "$2" && f=$(mktemp) && curl -fsS "$URL/aggancia.sh?segnaposto=1" -o "$f" \
692         && { _firmato "$URL" aggancia.sh "$f" || { _f "$M_riaggancio_non_firmato" url "$URL" > "$log"; rm -f "$f"; exit 1; }; } \
693         && DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" bash "$f" < /dev/null > "$log" 2>&1; r=$?; rm -f "$f"; exit $r ) \
694      && [ -x "$2/.claude/delminio.sh" ]; then
695    rm -f "$log"; _f "$M_collegato_qui" nome "$1" dove "$2"; return 0
696  fi
697  errore_log=$(grep -v '^[[:space:]]*$' "$log" 2>/dev/null | tail -1 | cut -c1-200)
698  rm -f "$log"; _f "$M_collegamento_fallito" nome "$1" dove "$2" errore "$errore_log"; return 1
699}
700
701_segno_pubblico() { local d; d=$(git rev-parse --git-common-dir 2>/dev/null) || return 1; printf '%s/delminio-pubblico' "$(_assoluto "$d")"; }
702pubblico_segna() {  # pubblico_segna <json con «pubblico»>: il file segue il motore
703  local f v
704  f=$(_segno_pubblico) || return 0
705  v=$(printf '%s' "$1" | python3 -c 'import json,sys
706try: d = json.load(sys.stdin)
707except Exception: sys.exit(0)
708d = d.get("repo", d) if isinstance(d, dict) else {}
709print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null)
710  case "$v" in si) : > "$f" ;; no) rm -f "$f" ;; esac
711}
712repo_stato() {  # nel cuore: chi cambia l'interruttore lo vede qui entro un giro
713  local remoto r
714  remoto=$(_remoto) || return 0
715  [ -n "$remoto" ] || return 0
716  r=$(chiedi GET "/api/repo/stato?remoto=$(_urlenc "$remoto")") || return 0
717  pubblico_segna "$r"
718}
719
720testi() {
721  local r remoto corpo
722  remoto=$(_remoto) || return 0
723  [ -n "$remoto" ] || return 0
724  r=$(chiedi GET "/api/chiusure/testi?remoto=$(_urlenc "$remoto")") || return 0
725  corpo=$(printf '%s' "$r" | python3 -c '
726import json, os, re, subprocess, sys
727def git(*a):
728    return subprocess.run(["git", "--no-replace-objects", *a], capture_output=True, text=True,
729                          encoding="utf-8", errors="replace").stdout
730testi, peso = [], 0
731for c in (json.load(sys.stdin).get("chiusure") or [])[:50]:
732    h, n = str(c.get("hash") or ""), int(c.get("numero") or 0)
733    if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h) or not git("rev-parse", "-q", "--verify", h + "^{commit}").strip():
734        continue                      # non sta in questo git: lo porterà chi lo ha
735    testo = git("log", "-1", "--format=%B", h)
736    if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), testo):
737        continue
738    voce = {"numero": n, "hash": h, "testo": testo}
739    p = len(json.dumps(voce, ensure_ascii=False).encode())
740    if p > 100_000:
741        continue                      # da solo non passerebbe mai: resta da leggere nel git
742    if peso + p > 100_000:
743        break
744    testi.append(voce)
745    peso += p
746print(json.dumps({"testi": testi}, ensure_ascii=False) if testi else "")
747' 2>/dev/null) || return 0
748  [ -n "$corpo" ] || return 0
749  chiedi POST /api/chiusure/testi "$corpo" >/dev/null || true
750}
751
752perche_no() {  # la frase vera dopo un chiedi fallito
753  local c="" e=""
754  IFS=$'\t' read -r c e < "$STATO/no-$$" 2>/dev/null || true
755  rm -f "$STATO/no-$$"
756  case "$c" in
757    ''|000) if [ "${CODEX_SANDBOX_NETWORK_DISABLED:-}" = 1 ]; then _f "$M_sandbox_senza_rete" url "$URL"
758            else _f "$M_perche_muto" url "$URL"; fi ;;
759    401) _f "$M_perche_token" url "$URL" codice "$c" ;;
760    403) if [ -n "$e" ] && [ "$e" != unauthorized ]; then _f "$M_perche_rifiuta" url "$URL" codice "$c" errore "$e"
761         else _f "$M_perche_token" url "$URL" codice "$c"; fi ;;
762    *) _f "$M_perche_errore" url "$URL" codice "$c" errore "${e:+: $e}" ;;
763  esac
764}
765mia_sessione() { cat "$STATO/sessione-$1" 2>/dev/null; }
766chi_sei_no() {
767  if [ "${DELMINIO_CLI_NOME:-}" = codex ] || [ -n "${CODEX_SANDBOX_NETWORK_DISABLED:-}${CODEX_SANDBOX:-}" ]; then
768    echo "$M_chi_sei_sandbox" >&2
769  else
770    echo "$1" >&2
771  fi
772}
773albero_di() {
774  git worktree list --porcelain 2>/dev/null | awk -v n="$1" '
775    /^worktree /{w=substr($0, 10)} /^branch /{b=$2; sub(".*/", "", b); if (b == n) {print w; exit}}' \
776    || true
777}
778avvia_ritiro() {  # avvia_ritiro <sessione> <albero>
779  local l="$STATO/ritiro-$1" v
780  v=$(cat "$l" 2>/dev/null || true)
781  [ -n "$v" ] && kill -0 "$v" 2>/dev/null && return 0
782  _staccato bash "$0" ritira-file "$1" "$2" >/dev/null 2>&1 < /dev/null &
783}
784ritira_file() {  # ritira_file <sessione> <albero>
785  local nome=$1 albero=$2 r dir ex id nm dest tmp
786  [ -n "$albero" ] && [ -d "$albero" ] || return 1
787  r=$(chiedi GET "/api/file/in-arrivo?sessione=$(_urlenc "$nome")") || return 1
788  dir="$albero/.delminio/file"
789  mkdir -p "$dir" && chmod 700 "$dir" || return 1
790  if ex=$(git -C "$albero" rev-parse --git-path info/exclude 2>/dev/null); then
791    case $ex in /*) ;; *) ex="$albero/$ex" ;; esac
792    grep -qxF '/.delminio/file/' "$ex" 2>/dev/null || { mkdir -p "$(dirname "$ex")" && printf '/.delminio/file/\n' >> "$ex"; }
793  fi
794  find "$dir" -maxdepth 1 -type f -mtime +7 -delete 2>/dev/null || true
795  printf '%s' "$r" | python3 -c 'import json, sys
796for f in json.load(sys.stdin).get("file") or []:
797    print(f["id"] + "\t" + f["nome"].replace("\t", " ").replace("\n", " "))' | while IFS=$'\t' read -r id nm; do
798    dest=$(python3 -c 'import os, re, sys, unicodedata
799d, n = sys.argv[1], re.split(r"[\\/]", sys.argv[2])[-1]
800n = "".join(c for c in n if not unicodedata.category(c).startswith("C")).strip().lstrip(".-").strip() or "file"
801b, e = os.path.splitext(n); k, p = 1, os.path.join(d, n)
802while os.path.lexists(p):
803    k += 1; p = os.path.join(d, f"{b} ({k}){e}")
804print(p)' "$dir" "$nm") || continue
805    tmp="$dir/.in-arrivo-$id"
806    if ! curl -sS -f -m 900 -K <(_chiave "$TOKEN") -o "$tmp" "$URL/api/file/$id?scarica=1" 2>/dev/null; then
807      rm -f "$tmp"; continue
808    fi
809    chmod 600 "$tmp" && mv -f "$tmp" "$dest" || { rm -f "$tmp"; continue; }
810    chiedi POST "/api/file/$id/ritirato" "{\"sessione\":$(json_stringa "$nome"),\"percorso\":$(json_stringa "$dest")}" >/dev/null || true
811  done
812}
813chiave_in_uso() {
814  [ -n "${ANTHROPIC_API_KEY:-}" ] && [ "$(uname -s)" = Linux ] || return 0
815  [ -e "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json" ] && return 0
816  printf '%s' "$ANTHROPIC_API_KEY" | sha256sum | cut -c1-16
817}
818fatti_codex() {  # cli, evento, fatti JSON
819  [ "$1" = codex ] || { printf '%s' "$3"; return; }
820  local programma
821  IFS= read -r -d '' programma <<'CODEX_FATTI' || true
822import json, os, sys
823from pathlib import Path
824d = json.load(os.fdopen(3))
825try:
826    evento = json.loads(sys.stdin.read() or '{}')
827except (ValueError, TypeError):
828    evento = {}
829if not isinstance(evento, dict):
830    evento = {}
831modo = evento.get('permission_mode', '')
832d['permission_mode'] = modo if modo in ('default', 'acceptEdits', 'plan', 'dontAsk', 'bypassPermissions') else ''
833scelta = os.environ.get('DELMINIO_PERMESSI', '')
834d['permessi_al_lancio'] = scelta if scelta in ('chiede', 'modifiche', 'classificatore') else ''
835casa = os.environ.get('CODEX_HOME')
836segno = Path(casa) / 'delminio-informativa-permessi' if casa else None
837try:
838    d['informativa_codex_vista'] = 0 if segno is None or segno.is_symlink() else int(segno.read_text().strip())
839except (OSError, ValueError):
840    d['informativa_codex_vista'] = 0
841d['sandbox_linux'] = os.environ.get('DELMINIO_SANDBOX_LINUX', '')
842print(json.dumps(d))
843CODEX_FATTI
844  python3 -c "$programma" 3<<< "$3" <<< "$2"
845}
846evento_dove() {
847  local programma
848  IFS= read -r -d '' programma <<'DOVE' || true
849import json, os, re, sys
850e = json.loads(sys.stdin.read() or "{}")
851t = e.get("tool_input") if isinstance(e.get("tool_input"), dict) else {}
852comando = t.get("command") if isinstance(t.get("command"), str) else ""
853base = e.get("cwd") or os.getcwd()
854
855def stringa(s, i):
856    """Il letterale JS che comincia in s[i] → (valore o None se ha ${…}, fine)."""
857    q, j, out = s[i], i + 1, []
858    while j < len(s) and s[j] != q:
859        if s[j] == "\\" and j + 1 < len(s):
860            c = s[j + 1]
861            if c == "u" and re.match(r"[0-9a-fA-F]{4}", s[j + 2:j + 6]):
862                out.append(chr(int(s[j + 2:j + 6], 16))); j += 6; continue
863            out.append({"n": "\n", "t": "\t", "r": "\r", "0": "\0"}.get(c, c)); j += 2; continue
864        if q == "`" and s.startswith("${", j):
865            return None, s.find(q, j) + 1 or len(s)
866        out.append(s[j]); j += 1
867    return "".join(out), j + 1
868
869def salta(js, i):
870    """Se in js[i] comincia un commento o una stringa, dove finisce; se no None."""
871    if js.startswith("//", i):
872        j = js.find("\n", i); return len(js) if j < 0 else j
873    if js.startswith("/*", i):
874        j = js.find("*/", i + 2); return len(js) if j < 0 else j + 2
875    if js[i] in "\"'`":
876        return stringa(js, i)[1]
877    return None
878
879def in_chiave(js, i):
880    """js[i] sta dove comincia una chiave: dopo «{» o «,»."""
881    j = i - 1
882    while j >= 0 and js[j].isspace():
883        j -= 1
884    return j >= 0 and js[j] in "{,"
885
886def chiamate_js(js):
887    """Le exec_command({…}) del CODICE (non di un commento o di una stringa):
888    (cmd, workdir), dove None = non letterale e "" = workdir assente.
889    ⚠️ Ogni altro modo di arrivarci è una chiamata muta (None, None): l'alias
890    (const f = tools.exec_command, tools["exec_command"]), che altrimenti spariva
891    dietro una chiamata letterale con lo stesso cmd scritta lì per finta."""
892    i = 0
893    while i < len(js):
894        if js[i] in "\"'`":
895            v, fine = stringa(js, i)
896            if v == "exec_command":
897                yield None, None
898            i = fine; continue
899        fine = salta(js, i)
900        if fine is not None:
901            i = fine; continue
902        m = re.match(r"exec_command\s*\(\s*(\{)?", js[i:i + 64])
903        if not m or (i and re.match(r"[\w$]", js[i - 1])):
904            if re.match(r"exec_command\b", js[i:i + 13]) and not (i and re.match(r"[\w$]", js[i - 1])):
905                yield None, None
906                i += 12; continue
907            i += 1; continue
908        if not m.group(1):  # exec_command(args): una variabile, non si legge
909            yield None, None
910            i += m.end(); continue
911        i, prof, chiavi = i + m.end(), 1, {}
912        while i < len(js) and prof:
913            k = re.match(r"""(["']?)(cmd|workdir)\1\s*:\s*""", js[i:i + 16]) if prof == 1 else None
914            if k and not re.match(r"[\w$]", js[i - 1]):
915                i += k.end()
916                v = None
917                if i < len(js) and js[i] in "\"'`":
918                    v, i = stringa(js, i)
919                    if not re.match(r"\s*[,}]", js[i:i + 64]):
920                        v = None
921                chiavi[k.group(2)] = v
922                continue
923            a = re.match(r"(cmd|workdir)\s*(?=[,}])", js[i:i + 16]) if prof == 1 and in_chiave(js, i) else None
924            if a:
925                chiavi[a.group(1)] = None
926                i += a.end(); continue
927            if prof == 1 and js[i] == "[" and in_chiave(js, i):
928                chiavi = {"cmd": None, "workdir": None}
929            if prof == 1 and js.startswith("...", i):
930                chiavi = {"cmd": None, "workdir": None}
931                i += 3; continue
932            fine = salta(js, i)
933            if fine is not None:
934                i = fine; continue
935            if js[i] in "{[(":
936                prof += 1
937            elif js[i] in "}])":
938                prof -= 1
939            i += 1
940        yield chiavi.get("cmd"), chiavi.get("workdir", "")
941
942def ultime_chiamate(percorso):
943    """Le chiamate dell'ultima risposta del modello, dalla coda del rollout. None se
944    il rollout non si legge o non mostra ancora la chiamata in corso (l'ultima cosa
945    scritta è un'uscita): mai le chiamate di prima al posto di questa."""
946    try:
947        with open(percorso, "rb") as f:
948            f.seek(max(0, os.path.getsize(percorso) - 524288))
949            righe = f.read().decode("utf-8", "replace").splitlines()
950    except OSError:
951        return None
952    viste, voci = [], 0
953    for r in reversed(righe):
954        try:
955            p = json.loads(r).get("payload") or {}
956        except ValueError:
957            continue
958        if p.get("type") == "custom_tool_call" and p.get("name") == "exec":
959            voci += 1
960            viste += list(chiamate_js(p.get("input") or ""))
961        elif p.get("type") == "function_call":
962            voci += 1
963            try:
964                a = json.loads(p.get("arguments") or "{}")
965            except ValueError:
966                a = None
967            if not isinstance(a, dict):
968                viste.append((None, None)); continue
969            if not ({"cmd", "command", "workdir"} & set(a)):
970                continue
971            c = a.get("cmd", a.get("command"))
972            viste.append((c if isinstance(c, str) else None,
973                          a.get("workdir", "") if isinstance(a.get("workdir", ""), str) else None))
974        elif p.get("type") in ("custom_tool_call_output", "function_call_output"):
975            if not voci:
976                return None
977            break
978        elif p.get("type") in ("message", "reasoning") and voci:
979            break
980    return viste if voci else None
981
982def cd_letterale(testo):
983    """Un cd iniziale riuscito solo con &&, senza espansioni indovinate.
984    Restituisce destinazione e resto; la stessa prova assolve il rollout assente.
985    """
986    m = re.match(r"""\s*cd\s+("[^"]+"|'[^']+'|[^\s;&|]+)\s*&&""", testo)
987    if not m:
988        return None, testo
989    token = m.group(1)
990    casa = os.path.expanduser("~")
991    if token.startswith("'"):
992        d = token[1:-1]
993    elif token.startswith('"'):
994        d = re.sub(r"^\$(HOME\b|\{HOME\})", lambda _: casa, token[1:-1])
995        if any(c in d for c in ('$', '`', '\\')):
996            return None, testo
997    else:
998        d = re.sub(r"^(~(?=/|$)|\$HOME\b|\$\{HOME\})", lambda _: casa, token)
999        if re.search(r"[$`\\~*?\[\]{}()<>\"']", d):
1000            return None, testo
1001    return d, testo[m.end():]
1002
1003cwd, incerto = base, ""
1004rollout = e.get("transcript_path") or ""
1005if e.get("tool_name") == "Bash" and comando and os.path.basename(rollout).startswith("rollout-"):
1006    viste = ultime_chiamate(rollout)
1007    if viste is None:
1008        viste, e["dove_non_visto"] = [], 1
1009        incerto = "il rollout di Codex non mostra la chiamata di questo comando"
1010    mie = {w for c, w in viste if c == comando}
1011    possibili = mie | {w for c, w in viste if c is None}
1012    if e.get("dove_non_visto"):
1013        pass
1014    elif not possibili:
1015        incerto = "non trovo nel code mode la chiamata che lancia questo comando"
1016    elif len(possibili) == 1 and None not in possibili:
1017        w = possibili.pop()
1018        cwd = os.path.join(base, os.path.expanduser(w)) if w else base
1019    elif len(mie) > 1:
1020        incerto = "lo stesso comando ha più cartelle in questa chiamata"
1021    elif None in mie:
1022        incerto = "la sua cartella (workdir) non è scritta per esteso"
1023    else:
1024        incerto = "nella chiamata ci sono un comando o una cartella non scritti per esteso"
1025primo, _ = cd_letterale(comando)
1026if primo is not None and os.path.isabs(primo):
1027    cwd, incerto = base, ""
1028resto = comando
1029while not incerto:
1030    d, dopo = cd_letterale(resto)
1031    if d is None:
1032        if re.match(r"\s*cd\b", resto) and os.path.basename(rollout).startswith("rollout-"):
1033            incerto = "il cd iniziale non è una destinazione letterale seguita da &&"
1034        break
1035    cwd, resto = os.path.join(cwd, d), dopo
1036e["cwd"] = os.path.normpath(cwd)
1037if incerto:
1038    e["dove_incerto"] = incerto
1039print(json.dumps(e))
1040DOVE
1041  python3 -c "$programma"
1042}
1043segna_informativa_codex() {  # risposta del motore; solo dopo una consegna riuscita a una CLI vera
1044  local programma
1045  IFS= read -r -d '' programma <<'CODEX_VISTA' || true
1046import json, os, sys, tempfile
1047from pathlib import Path
1048exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
1049v = json.load(sys.stdin).get('informativa_codex')
1050if not isinstance(v, int) or isinstance(v, bool) or v < 1:
1051    sys.exit(0)
1052casa = os.environ.get('CODEX_HOME')
1053if not casa:
1054    sys.exit(0)  # un Codex nudo non autorizza scritture nella casa personale
1055casa = Path(casa)
1056segno = casa / 'delminio-informativa-permessi'
1057try:
1058    casa.mkdir(parents=True, exist_ok=True)
1059    if segno.exists() and (segno.is_symlink() or not segno.read_text().strip().isdigit()):
1060        raise ValueError(F("segno_non_versione"))
1061    with tempfile.NamedTemporaryFile(mode='w', dir=casa, prefix='.delminio-permessi-', delete=False) as f:
1062        f.write(str(v))
1063        nome = f.name
1064    os.replace(nome, segno)
1065except (OSError, ValueError) as e:
1066    print(F("informativa_non_segnata", errore=e), file=sys.stderr)
1067CODEX_VISTA
1068  python3 -c "$programma" <<< "$1"
1069}
1070strumenti_vivi() {
1071  local f r k
1072  read -r k _ <<<"$(printf '%s' "$URL$TOKEN" | cksum)"
1073  f="$STATO/strumenti-$k"
1074  if [ -n "$(find "$f" -mmin -1 2>/dev/null)" ]; then printf '%s' "$(<"$f")"; return 0; fi
1075  if r=$(CHIEDI_TEMPO=3 chiedi GET /api/lock/strumenti); then
1076    printf '%s' "$r" | python3 -c 'import json,sys
1077print("\n".join(g for g in json.load(sys.stdin).get("strumenti") or [] if isinstance(g, str)))' > "$f.$$" 2>/dev/null \
1078      && mv -f "$f.$$" "$f"
1079  else
1080    touch "$f" 2>/dev/null   # un minuto senza richiedere: un motore muto non costa a ogni tool
1081  fi
1082  [ -f "$f" ] && printf '%s' "$(<"$f")"
1083  return 0
1084}
1085accettate_file() {
1086  local c w
1087  c="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || echo .git)/delminio-guardie-accettate"
1088  w=$(git rev-parse --path-format=absolute --git-path delminio-guardie-accettate 2>/dev/null || true)
1089  if [ -n "$w" ] && [ "$w" != "$c" ] && [ -s "$w" ]; then
1090    sort -u "$w" "$c" 2>/dev/null > "$c.$$" && mv -f "$c.$$" "$c" && rm -f "$w"
1091  fi
1092  printf '%s' "$c"
1093}
1094modello_dal_transcript() {  # modello_dal_transcript <pid> <sessione> <evento json>
1095  [ -z "${DELMINIO_MODELLO:-}" ] || return 0
1096  local m
1097  m=$(printf '%s' "$3" | _tempo 2 python3 -c '
1098import json, os, sys
1099try:
1100    e = json.load(sys.stdin)
1101    if isinstance(e.get("model"), str) and e["model"].strip():
1102        print(e["model"].strip()[:80]); sys.exit(0)
1103    p = e.get("transcript_path") or ""
1104    with open(p, "rb") as f:
1105        f.seek(max(0, os.path.getsize(p) - 524288))
1106        righe = f.read().decode("utf-8", "replace").splitlines()
1107except Exception:
1108    sys.exit(0)
1109for r in reversed(righe):
1110    try:
1111        d = json.loads(r)
1112    except ValueError:
1113        continue
1114    if not isinstance(d, dict):
1115        continue
1116    m = ((d.get("payload") or {}).get("model") if d.get("type") == "turn_context"
1117         else ((d.get("message") if isinstance(d.get("message"), dict) else {}).get("model") or d.get("model"))
1118         if d.get("type") == "assistant" else None)
1119    if isinstance(m, str) and m.strip() and not m.startswith("<"):   # «<synthetic>» di Claude non è un modello
1120        print(m.strip()[:80])
1121        break
1122' 2>/dev/null || true)
1123  [ -n "$m" ] || return 0
1124  [ "$m" = "$(cat "$STATO/modello-$1" 2>/dev/null || true)" ] && return 0
1125  CHIEDI_TEMPO=2 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$2"),\"agente\":$(json_stringa "$m")}" >/dev/null 2>&1 \
1126    && printf '%s' "$m" > "$STATO/modello-$1"
1127  return 0
1128}
1129consumi_dal_transcript() {  # consumi_dal_transcript <file di stato> <evento json>
1130  printf '%s' "$2" | _tempo 5 python3 "$(dirname "$0")/consumi.py" "$1" 2>/dev/null || true
1131}
1132totale_cli_qwen() {  # totale_cli_qwen <evento json>
1133  [ -n "${QWEN_HOME:-}" ] || return 0
1134  printf '%s' "$1" | _tempo 7 python3 -c '
1135import json, os, sys, time
1136try:
1137    e = json.load(sys.stdin)
1138except Exception:
1139    sys.exit(0)
1140sid = str(e.get("session_id") or "")
1141if e.get("hook_event_name") != "SessionEnd" or not sid:
1142    sys.exit(0)
1143f = os.path.join(os.environ["QWEN_HOME"], "usage_record.jsonl")
1144riga = None
1145for _ in range(25):                      # la CLI lo scrive mentre si spegne
1146    try:
1147        with open(f, encoding="utf-8") as h:
1148            for r in h:
1149                if sid in r:
1150                    d = json.loads(r)
1151                    if d.get("sessionId") == sid:
1152                        riga = d
1153    except (OSError, ValueError):
1154        pass
1155    if riga:
1156        break
1157    time.sleep(0.2)
1158if not riga:
1159    sys.exit(0)
1160t = {"input": 0, "cache_letta": 0, "cache_scritta": 0, "output": 0, "risposte": 0}
1161for m in (riga.get("models") or {}).values():
1162    letta = int(m.get("cachedTokens") or 0)
1163    t["input"] += max(0, int(m.get("inputTokens") or 0) - letta)
1164    t["cache_letta"] += letta
1165    t["output"] += int(m.get("outputTokens") or 0) + int(m.get("thoughtsTokens") or 0)
1166    t["risposte"] += int(m.get("requests") or 0)
1167print(json.dumps({"conversazione": sid[:80], "cli": "qwen", "totale_cli": t}))
1168' 2>/dev/null || true
1169}
1170fatti_nascita() {  # fatti_nascita <pid> <evento json> [si = al primo messaggio]
1171  local cli senza="" base programma; cli=$(cli_di "$1"); [ "$cli" = claude ] || senza=1
1172  IFS= read -r -d '' programma <<'FATTI' || true
1173import json, os, subprocess, sys
1174exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
1175processo, albero, agente, dove, memoria, primo, remoto = sys.argv[1:8]
1176def chiavi(var):   # i nomi di un trailer in ogni lingua (F665), come li vuole git
1177    return ",".join("key=" + k for k in os.environ[var].split("|"))
1178try:
1179    conversazione = str(json.loads(sys.stdin.read() or "{}").get("session_id") or "")
1180except Exception:
1181    conversazione = ""
1182commit = subprocess.run(["git", "log", "-200", "--format=%h%x1f%s%x1f"
1183                         "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
1184                         "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)"],
1185                        capture_output=True, text=True).stdout.splitlines()
1186avvisi = []
1187exec(os.environ["DELMINIO_FIDATI_PY"])
1188gia, fermi = (accettati(albero) if albero else set()), []
1189for f in lascito_del_progetto(albero):
1190    if not da_fidarsi(albero, f, gia):
1191        fermi.append(di_chi(albero, f)[0])
1192for f in script_del_progetto(albero, ("apertura", "opening")):
1193    s = os.path.basename(f)
1194    if not da_fidarsi(albero, f, gia):
1195        fermi.append(di_chi(albero, f)[0])
1196        continue
1197    try:
1198        out = subprocess.run([f], cwd=albero, capture_output=True, text=True, timeout=5).stdout
1199    except (OSError, subprocess.TimeoutExpired):
1200        out = F("non_risponde_5s", script=s)
1201    avvisi += [r.strip() for r in out.splitlines() if r.strip()][:3]
1202if fermi:
1203    avvisi.insert(0, F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
1204import glob
1205mcp_fermi = 0
1206for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
1207                                "delminio", "squadre", "*", ".mcp-fermi.json")):
1208    try:
1209        with open(x, encoding="utf-8") as h:
1210            mcp_fermi += len(json.load(h))
1211    except (OSError, ValueError, TypeError):
1212        pass
1213if mcp_fermi:
1214    avvisi.insert(0, F("squadra_mcp_da_accettare", n=mcp_fermi))
1215plugin_fermi = 0
1216for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
1217                                "delminio", "squadre", "*", ".plugin-fermi.json")):
1218    try:
1219        with open(x, encoding="utf-8") as h:
1220            plugin_fermi += len(json.load(h))
1221    except (OSError, ValueError, TypeError):
1222        pass
1223if plugin_fermi:
1224    avvisi.insert(0, F("squadra_plugin_da_accettare", n=plugin_fermi))
1225try:
1226    with open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
1227              encoding="utf-8") as h:
1228        righe_ferme = sum(len(sp.get("fermi") or []) for sp in (json.load(h).get("spazi") or {}).values()
1229                          if isinstance(sp, dict))
1230except (OSError, ValueError, TypeError, AttributeError):
1231    righe_ferme = 0
1232if righe_ferme:
1233    avvisi.insert(0, F("eseguibili_da_accettare", n=righe_ferme))
1234propri = 0
1235for d in ("apertura", "opening", "dove-siamo", "status"):
1236    c = os.path.join(albero, ".delminio", d) if albero else ""
1237    propri += sum(1 for s in (os.listdir(c) if c and os.path.isdir(c) else [])
1238                  if os.path.isfile(os.path.join(c, s)) and os.access(os.path.join(c, s), os.X_OK))
1239prima = []
1240if albero:
1241    cartelle = [os.path.join(albero, ".claude", "delminio-prima")]
1242    try:
1243        cartelle.append(open(os.path.join(albero, ".git", "delminio-backup"), encoding="utf-8").read().strip())
1244    except OSError:
1245        pass
1246    for c in cartelle:
1247        for d in sorted(os.listdir(c) if c and os.path.isdir(c) else []):
1248            if os.path.isfile(os.path.join(c, d, "fatti.json")) and not os.path.exists(os.path.join(c, d, "RIPASSATO")):
1249                p = os.path.join(c, d)
1250                prima.append(os.path.relpath(p, albero) if p.startswith(albero + os.sep) else p)
1251print(json.dumps({"processo": processo, "albero": albero, "agente": agente, "dove": dove,
1252                  "commit": commit, "avvisi": avvisi[:12], "propri": propri, "remoto": remoto,
1253                  "repo_no": json.loads(os.environ.get("DELMINIO_REPO_NO") or "[]"),
1254                  "conversazione": conversazione, "prima": prima,
1255                  "madri": json.loads(os.environ.get("DELMINIO_MADRI") or "[]"),
1256                  "indice": bool(memoria) and os.path.isfile(os.path.join(memoria, "MEMORY.md"))
1257                            and not os.environ.get("DELMINIO_SENZA_INDICE"),
1258                  "al_primo_messaggio": primo == "si",
1259                  "contesto": int(os.environ.get("DELMINIO_CONTESTO") or 0) if (os.environ.get("DELMINIO_CONTESTO") or "").isdigit() else 0,
1260                  "sistema": bool(os.environ.get("DELMINIO_SISTEMA")),
1261                  "ruolo": os.environ.get("DELMINIO_PORTA", ""),
1262                  "eseguibile": os.environ.get("DELMINIO_ESEGUIBILE", ""),
1263                  "app_codex": os.environ.get("DELMINIO_APP_CODEX", ""),
1264                  "cli": os.environ.get("DELMINIO_CLI_NOME") or "claude"}))
1265FATTI
1266  base=$(DELMINIO_CLI_NOME="$cli" DELMINIO_SENZA_INDICE="$senza" DELMINIO_REPO_NO="$(repo_no_qui)" \
1267    python3 -c "$programma" "$(hostname):$1" "$(git rev-parse --show-toplevel 2>/dev/null)" \
1268    "${DELMINIO_MODELLO:-}" "$(hostname)" "$MEMORIA" "${3:-}" "$(_remoto)" <<< "$2"
1269  ) || return
1270  fatti_codex "$cli" "$2" "$base"
1271}
1272eseguibili_indietro() {  # eseguibili_indietro <impronta voluta> [giorno] → 0 se va riallineato
1273  [ -z "${DELMINIO_PROVA:-}" ] && [ "${DELMINIO_ESEGUIBILE:-}" = si ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 1
1274  python3 -c 'import json,os,sys,time
1275try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
1276except Exception: r = {}
1277m = (r.get("spazi") or {}).get(sys.argv[2], {} if r.get("spazi") else r)
1278vecchio = sys.argv[3] == "giorno" and time.time() - (m.get("quando") or 0) > 86400
1279sys.exit(0 if (sys.argv[1] and m.get("registro") != sys.argv[1]) or vecchio else 1)' "$1" "$(spazio_qui)" "${2:-}"
1280}
1281riaggancio_stato() { printf '%s/riaggancio-%s' "$STATO" "$(printf '%s\n' "$1" | cksum | cut -d' ' -f1)"; }
1282riaggancia() {
1283  [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] && [ "$1" != "${KIT:-}" ] && [ -d "$2" ] || return 0
1284  ra=$(riaggancio_stato "$2")
1285  if [ "${3:-}" = presto ] && [ "$(cat "$ra.verso" 2>/dev/null)" = "$1" ] && [ -e "$ra.log" ] \
1286     && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -lt 3600 ]; then
1287    return 0
1288  fi
1289  printf '%s' "$1" > "$ra.verso"
1290  export -f _firmato
1291  export KIT_FIRMA
1292  ( cd "$2" && DELMINIO_TOKEN="$TOKEN" _staccato bash -c \
1293      'f=$(mktemp) && curl -fsS "$0/aggancia.sh?segnaposto=1" -o "$f" || exit 1
1294       _firmato "$0" aggancia.sh "$f" || { printf "%s\n" "$1" >&2; rm -f "$f"; exit 1; }
1295       DELMINIO_URL="$0" bash "$f"; r=$?; rm -f "$f"; exit $r' \
1296      "$URL" "$(_f "$M_riaggancio_non_firmato" url "$URL")" > "$ra.log" 2>&1 < /dev/null & )
1297}
1298fratelli_indietro() {
1299  [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] || return 0
1300  s="$STATO/fratelli.verso"
1301  if [ "$(cat "$s" 2>/dev/null)" = "$1" ] && [ $(( $(date +%s) - $(_mtime "$s") )) -lt 3600 ]; then return 0; fi
1302  printf '%s' "$1" > "$s"
1303  ( _staccato bash "$0" riaggancia-fratelli "$1" > "$STATO/fratelli.log" 2>&1 < /dev/null & )
1304}
1305allinea_staccato() {
1306  _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit allinea \
1307    > "$STATO/eseguibili.log" 2>&1 < /dev/null &
1308}
1309skill_staccato() {
1310  [ -z "${DELMINIO_PROVA:-}" ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 0
1311  _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" skill \
1312    > "$STATO/skill.log" 2>&1 < /dev/null &
1313}
1314spazio_qui() { python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" spazio 2>/dev/null || printf '%s' "${URL%/}"; }
1315stato_eseguibile() { DELMINIO_SPAZIO="$(spazio_qui)" python3 - <<'STATO_ESEGUIBILE'
1316import json, os
1317try:
1318    r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
1319                       encoding="utf-8"))
1320except Exception:
1321    r = {}
1322u = os.environ["DELMINIO_SPAZIO"].rstrip("/")
1323s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
1324miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
1325print("rifiutato" if s.get("rifiutato") else "si" if any(os.path.isfile(p) for p in miei) else "no")
1326STATO_ESEGUIBILE
1327}
1328
1329
1330: '⟦comandi⟧'
1331_comando() {  # _comando <gruppo> <nome> → il nome canonico
1332  case "$1:$2" in
1333    client:rivisto) printf '%s\n' ripassato ;;
1334    client:revisione) printf '%s\n' audit ;;
1335    client:backlog) printf '%s\n' cantiere ;;
1336    client:firme) printf '%s\n' carta ;;
1337    client:accept) printf '%s\n' accetta ;;
1338    client:focus) printf '%s\n' domini ;;
1339    client:title) printf '%s\n' titolo ;;
1340    client:new) printf '%s\n' nuovo ;;
1341    client:teardown) printf '%s\n' smonta ;;
1342    client:kit-files) printf '%s\n' file-del-kit ;;
1343    client:send) printf '%s\n' invia ;;
1344    client:agents) printf '%s\n' eseguibili ;;
1345    client:vault) printf '%s\n' cassaforte ;;
1346    client:reviewed) printf '%s\n' ripassato ;;
1347    client:disconnect) printf '%s\n' stacca ;;
1348    client:why) printf '%s\n' perche ;;
1349    client:handoff) printf '%s\n' consegna ;;
1350    client:handoff-of) printf '%s\n' consegna-di ;;
1351    client:errors) printf '%s\n' errori ;;
1352    client:connect-all) printf '%s\n' agganciali ;;
1353    client:review) printf '%s\n' audit ;;
1354    client:help) printf '%s\n' aiuto ;;
1355    client:clone) printf '%s\n' clona ;;
1356    client:signoffs) printf '%s\n' carta ;;
1357    client:domains) printf '%s\n' domini ;;
1358    eseguibili:status) printf '%s\n' stato ;;
1359    eseguibili:rename) printf '%s\n' rinomina ;;
1360    eseguibili:test) printf '%s\n' prova ;;
1361    eseguibili:sync) printf '%s\n' allinea ;;
1362    cassaforte:list) printf '%s\n' elenco ;;
1363    cassaforte:propose) printf '%s\n' proponi ;;
1364    cassaforte:open) printf '%s\n' apri ;;
1365    cassaforte:access) printf '%s\n' finestre ;;
1366    cassaforte:close) printf '%s\n' chiudi ;;
1367    cassaforte:deposit) printf '%s\n' deposita ;;
1368    cassaforte:windows) printf '%s\n' finestre ;;
1369    carta:check) printf '%s\n' controlla ;;
1370    carta:description) printf '%s\n' descrizione ;;
1371    carta:report) printf '%s\n' resoconto ;;
1372    carta:export) printf '%s\n' esporta ;;
1373    carta:chain) printf '%s\n' catena ;;
1374    carta:review) printf '%s\n' revisione ;;
1375    carta:checks) printf '%s\n' prove ;;
1376    *) printf '%s\n' "$2" ;;
1377  esac
1378}
1379export DELMINIO_COMANDI='{"backlog": {"aiuto": "aiuto", "answer": "rispondi", "apri": "apri", "ask": "chiedi", "aspetta": "aspetta", "assegna": "assegna", "assegnate": "assegnate", "assign": "assegna", "assigned": "assegnate", "autochecks": "sonde", "cerca": "cerca", "chiedi": "chiedi", "chiudi": "chiudi", "close": "chiudi", "concept": "concept", "correggi": "correggi", "domande": "domande", "edit": "correggi", "ferma": "ferma", "follow-up": "veglia", "follow-ups": "veglie", "help": "aiuto", "hold": "ferma", "lega": "lega", "link": "lega", "list": "lista", "lista": "lista", "mie": "mie", "mine": "mie", "molla": "molla", "mostra": "mostra", "note": "tocca", "open": "apri", "postpone": "rinvia", "prendi": "prendi", "questions": "domande", "release": "molla", "reopen": "riapri", "riapri": "riapri", "rinvia": "rinvia", "rispondi": "rispondi", "search": "cerca", "show": "mostra", "sonde": "sonde", "take": "prendi", "to-decide": "concept", "tocca": "tocca", "veglia": "veglia", "veglie": "veglie", "wait": "aspetta"}, "backlog_opzioni": {"a-meta": "a-meta", "asked": "chiesto", "aspetta": "aspetta", "autocheck": "sonda", "chiesto": "chiesto", "chiusura": "chiusura", "concept": "concept", "danno": "danno", "decide": "decide", "decision": "concept", "different-from": "diversa-da", "diversa-da": "diversa-da", "domain": "dominio", "domanda": "domanda", "dominio": "dominio", "done-when": "chiusura", "ferma": "ferma", "follow-up": "veglia", "half-done": "a-meta", "hold": "ferma", "memoria": "memoria", "memory": "memoria", "must-be-true": "verifica", "owner": "owner", "priorita": "priorita", "priority": "priorita", "quando": "quando", "question": "domanda", "remove": "togli", "replace": "sostituisci", "risk": "danno", "sonda": "sonda", "sostituisci": "sostituisci", "tipo": "tipo", "title": "titolo", "titolo": "titolo", "to-decide": "decide", "togli": "togli", "type": "tipo", "veglia": "veglia", "verifica": "verifica", "wait-for": "aspetta", "when": "quando"}, "backlog_owner": {"admin": "capo", "agent": "agente", "agente": "agente", "capo": "capo", "insieme": "insieme", "together": "insieme", "umano": "umano", "user": "umano", "utente": "umano"}, "backlog_tipo": {"action": "mani", "decision": "decisione", "decisione": "decisione", "mani": "mani"}, "carta": {"catena": "catena", "chain": "catena", "check": "controlla", "checks": "prove", "ci": "ci", "controlla": "controlla", "description": "descrizione", "descrizione": "descrizione", "esporta": "esporta", "export": "esporta", "prove": "prove", "report": "resoconto", "resoconto": "resoconto", "review": "revisione", "revisione": "revisione"}, "cassaforte": {"access": "finestre", "apri": "apri", "chiudi": "chiudi", "close": "chiudi", "deposit": "deposita", "deposita": "deposita", "elenco": "elenco", "finestre": "finestre", "list": "elenco", "open": "apri", "proponi": "proponi", "propose": "proponi", "windows": "finestre"}, "client": {"accept": "accetta", "accetta": "accetta", "agents": "eseguibili", "agganciali": "agganciali", "aiuto": "aiuto", "audit": "audit", "backlog": "cantiere", "cantiere": "cantiere", "carta": "carta", "cassaforte": "cassaforte", "clona": "clona", "clone": "clona", "connect-all": "agganciali", "consegna": "consegna", "consegna-di": "consegna-di", "disconnect": "stacca", "domains": "domini", "domini": "domini", "errori": "errori", "errors": "errori", "eseguibili": "eseguibili", "file-del-kit": "file-del-kit", "firme": "carta", "focus": "domini", "handoff": "consegna", "handoff-of": "consegna-di", "help": "aiuto", "invia": "invia", "kit-files": "file-del-kit", "merge": "merge", "new": "nuovo", "nuovo": "nuovo", "perche": "perche", "review": "audit", "reviewed": "ripassato", "revisione": "audit", "ripassato": "ripassato", "rivisto": "ripassato", "send": "invia", "signoffs": "carta", "smonta": "smonta", "stacca": "stacca", "teardown": "smonta", "title": "titolo", "titolo": "titolo", "vault": "cassaforte", "why": "perche"}, "eseguibili": {"allinea": "allinea", "no": "no", "prova": "prova", "rename": "rinomina", "rinomina": "rinomina", "stato": "stato", "status": "stato", "sync": "allinea", "test": "prova"}, "operazioni": {"avvio": "risveglio", "chiusura": "chiusura", "correct_handoff": "cura_close", "cura_close": "cura_close", "handoff_steps": "chiusura", "risveglio": "risveglio", "startup": "risveglio"}, "riti": {"apertura": "apertura", "chiusura": "chiusura", "closing": "chiusura", "handoff": "chiusura", "opening": "apertura", "start": "apertura"}}'
1380: '⟦fine comandi⟧'
1381if [ $# -gt 0 ]; then set -- "$(_comando client "$1")" "${@:2}"; fi
1382case "${1:-}" in eseguibili|cassaforte|carta) [ $# -gt 1 ] && set -- "$1" "$(_comando "$1" "$2")" "${@:3}" ;; esac
1383
1384case "${1:-}" in guardia|condiviso|gesto|tocco|volo|umano|memorie|segreto|rito|attesa)
1385  if [ -n "${EPOCHREALTIME:-}" ] && [ -z "${DELMINIO_NO_CODEX:-}" ] && [ ! -t 0 ]; then
1386    _conto_gesto=$1
1387    _conto_ev=$(cat); exec 0<<<"$_conto_ev"
1388    [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _conto_sid=${BASH_REMATCH[1]}
1389    [ -n "${_conto_sid:-}" ] && [ "$1" != attesa ] && trap '_conto_segna' EXIT
1390  fi ;;
1391esac
1392case "${1:-}" in volo|umano)
1393  if [ ! -t 0 ] && [ -z "${DELMINIO_NO_CODEX:-}" ]; then
1394    [ -n "${_conto_ev+x}" ] || { _conto_ev=$(cat); exec 0<<<"$_conto_ev"; }
1395    _skill_voce=""
1396    if [ "$1" = volo ] && [[ $_conto_ev =~ \"tool_name\":\ ?\"([A-Za-z_]+)\" ]] \
1397       && [[ ${BASH_REMATCH[1]} = [Ss]kill ]] \
1398       && [[ $_conto_ev =~ \"skill\":\ ?\"([A-Za-z0-9_.:-]{1,161})\" ]]; then
1399      _skill_voce="skill ${BASH_REMATCH[1]}"
1400    elif [ "$1" = umano ] && [[ $_conto_ev =~ \"prompt\":\ ?\"/([A-Za-z0-9_.:-]{1,161})([\ \"\\]|$) ]]; then
1401      _skill_voce="comando ${BASH_REMATCH[1]}"
1402    fi
1403    [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _skill_sid=${BASH_REMATCH[1]}
1404    if [ -n "$_skill_voce" ] && [ -n "${_skill_sid:-}" ]; then
1405      printf '%s\n' "$_skill_voce" >> "$STATO/skill-$_skill_sid" 2>/dev/null || true
1406    fi
1407  fi ;;
1408esac
1409case "${1:-}" in condiviso|gesto|guardia|tocco)
1410  if [ -z "${DELMINIO_NO_CODEX:-}" ] && pid_cli=$(cli_pid) && e_codex "$pid_cli"; then
1411    entrata=$(mktemp); uscita=$(mktemp); errori=$(mktemp)
1412    cat > "$entrata"
1413    DELMINIO_NO_CODEX=1 bash "$0" "$@" < "$entrata" > "$uscita" 2> "$errori"; rc=$?
1414    if [ "$rc" = 2 ]; then
1415      python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
1416        "permissionDecision": "deny", "permissionDecisionReason": sys.argv[1],
1417        "additionalContext": open(sys.argv[2], encoding="utf-8", errors="replace").read()}}))' "$M_fermato_codex" "$errori"
1418      rc=0
1419    else
1420      cat "$uscita"; cat "$errori" >&2
1421    fi
1422    rm -f "$entrata" "$uscita" "$errori"; exit "$rc"
1423  fi ;;
1424esac
1425
1426parte() {  # parte <file accanto al client>
1427  [ -f "$(dirname "$0")/$1" ] && return 0
1428  _f "$M_parte_manca" file "$(dirname "$0")/$1" >&2
1429  exit 1
1430}
1431
1432case "${1:-}" in
1433  cantiere) shift; exec python3 "$(dirname "$0")/cantiere.py" "$@" ;;
1434  apertura)
1435    pid=$(cli_pid || true)
1436    cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
1437    if [ -n "$pid" ] && headless "$pid"; then pid=""; fi   # un -p non è una sessione
1438    [ -n "${DELMINIO_PROVA:-}" ] && pid=""
1439    DELMINIO_ESEGUIBILE=$(stato_eseguibile 2>/dev/null || true); export DELMINIO_ESEGUIBILE
1440    DELMINIO_APP_CODEX=""
1441    if [ -f "$(dirname "$0")/plugin.py" ]; then
1442      _tempo 20 python3 "$(dirname "$0")/plugin.py" app-codex allinea >/dev/null 2>&1 || true
1443      DELMINIO_APP_CODEX=$(python3 "$(dirname "$0")/plugin.py" app-codex stato 2>/dev/null || true)
1444    fi
1445    export DELMINIO_APP_CODEX
1446    senza=""; [ "$cli" = claude ] || senza=1
1447    fatti=$(DELMINIO_CLI_NOME="$cli" DELMINIO_SENZA_INDICE="$senza" python3 -c 'import json,os,sys; m=sys.argv[1]; print(json.dumps({"indice": bool(m) and os.path.isfile(os.path.join(m, "MEMORY.md")) and not os.environ.get("DELMINIO_SENZA_INDICE"), "sistema": bool(os.environ.get("DELMINIO_SISTEMA")), "ruolo": os.environ.get("DELMINIO_PORTA", ""), "eseguibile": os.environ.get("DELMINIO_ESEGUIBILE", ""), "app_codex": os.environ.get("DELMINIO_APP_CODEX", ""), "cli": os.environ.get("DELMINIO_CLI_NOME") or "claude"}))' "$MEMORIA")
1448    evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
1449    if [ -n "$pid" ] && [ -z "${DELMINIO_PROVA:-}" ]; then
1450      sorgente=$(printf '%s' "$evento" | campo source)
1451      sid=$(printf '%s' "$evento" | campo session_id)
1452      if [ -n "$sid" ] && { [ "$sorgente" = fork ] || in_sottofondo "$pid"; }; then
1453        rm -f "$STATO/sessione-$pid"
1454        printf '%s' "$sid" > "$STATO/nasci-$pid"
1455        if [ "$sorgente" = fork ]; then madri_del_fork "$evento" "$sid" > "$STATO/fork-$pid"; else rm -f "$STATO/fork-$pid"; fi
1456        python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$M_nasce_al_primo"
1457        exit 0
1458      fi
1459    fi
1460    if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
1461      GIT_TERMINAL_PROMPT=0 _tempo 5 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true
1462    fi
1463    if [ -n "$pid" ]; then fatti=$(fatti_nascita "$pid" "$evento")
1464    else fatti=$(fatti_codex "$cli" "$evento" "$fatti"); fi
1465    cure
1466    if r=$(chiedi POST /api/apertura "$fatti"); then
1467      [ "$cli" != codex ] || [ -z "$pid" ] || [ -n "${DELMINIO_PROVA:-}" ] || segna_informativa_codex "$r"
1468      nome=$(printf '%s' "$r" | campo sessione); stato=$(printf '%s' "$r" | campo stato)
1469      if [ -n "$pid" ] && [ -n "$nome" ]; then
1470        rm -f "$STATO/nasci-$pid"
1471        if [ "$stato" = chiusa ]; then
1472          rm -f "$STATO/sessione-$pid"
1473          [ "$(printf '%s' "$r" | campo al_primo_messaggio)" = True ] && \
1474            printf '%s' "$evento" | campo session_id > "$STATO/nasci-$pid"
1475        else
1476          printf '%s' "$nome" > "$STATO/sessione-$pid"
1477          zitta_la_prima "$r" "$pid"
1478          _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
1479        fi
1480      fi
1481      serve=$(printf '%s' "$r" | campo versione)
1482      ra=$(riaggancio_stato "$(git rev-parse --show-toplevel 2>/dev/null)")
1483      indietro=""
1484      if [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$serve" ] && [ "$serve" != "${KIT:-}" ] && [ -s "$ra.log" ] \
1485         && [ "$(cat "$ra.verso" 2>/dev/null)" = "$serve" ] \
1486         && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -gt 120 ]; then   # più giovane: è ancora in corsa
1487        indietro=$(_f "$M_client_fermo" kit "${KIT:-?}" serve "$serve" errore "$(grep -v '^[[:space:]]*$' "$ra.log" | tail -1 | cut -c1-200)")
1488      fi
1489      riaggancia "$serve" "$(git rev-parse --show-toplevel 2>/dev/null)"
1490      fratelli_indietro "$serve"
1491      voluto=$(printf '%s' "$r" | campo eseguibili)
1492      eseguibili_indietro "$voluto" giorno && allinea_staccato
1493      skill_staccato
1494      pubblico_segna "$r"
1495      printf '%s' "$r" | DELMINIO_INDIETRO="$indietro" python3 -c 'import json,os,sys
1496h = json.load(sys.stdin)["hookSpecificOutput"]
1497if os.environ.get("DELMINIO_INDIETRO"):
1498    h["additionalContext"] = os.environ["DELMINIO_INDIETRO"] + "\n\n" + h.get("additionalContext", "")
1499print(json.dumps({"hookSpecificOutput": h}))'
1500      exit 0
1501    fi
1502    perche=$(perche_no)
1503    riprova=""
1504    if [ -n "$pid" ]; then
1505      sid=$(printf '%s' "$evento" | campo session_id)
1506      [ -n "$sid" ] && printf '%s' "$sid" > "$STATO/nasci-$pid" && riprova=$M_riprova_al_primo
1507    fi
1508    python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$(_f "$M_nasce_senza_memoria" perche "$perche" riprova "$riprova")"
1509    [ -z "${DELMINIO_PROVA:-}" ] || exit 3
1510    ;;
1511  cuore)
1512    pid="$2"; processo="$3"
1513    io="$STATO/cuore-$pid"
1514    altro=$(cat "$io" 2>/dev/null || true)
1515    [ -n "$altro" ] && [ "$altro" != "$$" ] && kill -0 "$altro" 2>/dev/null && exit 0
1516    echo "$$" > "$io"
1517    spazza_stato
1518    albero=$(git rev-parse --show-toplevel 2>/dev/null || true)
1519    P=$(json_stringa "$processo")
1520    fresco() { [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ] && \
1521      GIT_TERMINAL_PROMPT=0 _tempo 20 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true; }
1522    principale=$(dirname "$(_assoluto "$(git rev-parse --git-common-dir 2>/dev/null)")")
1523    riservo() {
1524      local r b corpo rif nome
1525      [ -n "$principale" ] && [ "$principale" != . ] || return 0
1526      r=$(chiedi GET /api/riservo) || return 0
1527      b="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$principale" | _sha16)"
1528      printf '%s' "$r" | (umask 077; python3 -c '
1529import hashlib, json, os, re, shutil, sys
1530b = sys.argv[1]
1531r = json.load(sys.stdin)
1532ist, rad = r.get("istanza") or "", r.get("radice") or ""
1533if not rad:
1534    sys.exit(0)
1535d = os.path.join(b, rad[:16], "riservo")
1536def leggi(p):
1537    try:
1538        return open(p, encoding="utf-8").read().strip()
1539    except OSError:
1540        return ""
1541if not os.path.isdir(d) and ist and leggi(os.path.join(b, "riservo", "istanza")) == ist:
1542    os.makedirs(os.path.dirname(d), exist_ok=True)
1543    os.rename(os.path.join(b, "riservo"), d)
1544def nome_file(n):
1545    return (re.sub(r"[^a-z0-9]+", "_", n.lower()).strip("_")[:60] or "memoria") + "-" + hashlib.sha1(n.encode()).hexdigest()[:8] + ".md"
1546def nome_md(testo):
1547    m = re.search(r"^name:\s*(.+?)\s*$", testo, re.M)
1548    v = m.group(1) if m else ""
1549    try:
1550        return json.loads(v) if v.startswith("\"") else v.strip("\x27")
1551    except ValueError:
1552        return v
1553remoti = {k: {m["name"] for m in r.get(k) or []} for k in ("personali", "riservate")}
1554if leggi(os.path.join(d, "radice")) == rad:
1555    rif = os.path.join(d, "rifiutate")
1556    no = set(leggi(rif).splitlines())
1557    manca = []
1558    for k in ("personali", "riservate"):
1559        cart = os.path.join(d, k)
1560        for f in sorted(os.listdir(cart)) if os.path.isdir(cart) else []:
1561            testo = open(os.path.join(cart, f), encoding="utf-8").read()
1562            n = nome_md(testo)
1563            if n and n not in remoti[k] and n not in no:
1564                manca.append(rif + "\t" + n + "\t" + json.dumps({"md": testo, "riservata": k == "riservate", "radice": rad}, ensure_ascii=False))
1565    if manca:
1566        print("\n".join(manca))
1567        sys.exit(0)
1568nuova = d + ".nuova"
1569shutil.rmtree(nuova, ignore_errors=True)
1570for k in ("personali", "riservate"):
1571    os.makedirs(os.path.join(nuova, k))
1572    for m in r.get(k) or []:
1573        with open(os.path.join(nuova, k, nome_file(m["name"])), "w", encoding="utf-8") as f:
1574            f.write(m["md"])
1575for n, v in (("istanza", ist), ("radice", rad)):
1576    with open(os.path.join(nuova, n), "w", encoding="utf-8") as f:
1577        f.write(v)
1578os.makedirs(os.path.dirname(d), exist_ok=True)
1579vecchia = d + ".vecchia"
1580shutil.rmtree(vecchia, ignore_errors=True)
1581if os.path.isdir(d):
1582    os.rename(d, vecchia)
1583os.rename(nuova, d)
1584shutil.rmtree(vecchia, ignore_errors=True)
1585' "$b") | { umask 077; while IFS=$'\t' read -r rif nome corpo; do
1586        if r=$(chiedi POST /api/riservo/riporta "$corpo"); then
1587          printf '%s' "$r" | grep -q '"riportata": *false' && printf '%s\n' "$nome" >> "$rif"
1588        else
1589          case $(cut -f1 "$STATO/no-$$" 2>/dev/null) in 400|409) printf '%s\n' "$nome" >> "$rif" ;; esac
1590        fi
1591      done; }
1592    }
1593    giri=0
1594    provata=""   # l'impronta che questo cuore ha già provato ad allineare: una volta sola
1595    passo=${DELMINIO_CUORE_SECONDI:-20}
1596    case $passo in ''|*[!0-9]*|0) passo=20 ;; esac
1597    while kill -0 "$pid" 2>/dev/null; do
1598      vero=$(albero_di "$(mia_sessione "$pid")"); [ -n "$vero" ] && albero="$vero"
1599      A=$(json_stringa "$albero")
1600      b=$(chiedi POST /api/canale/battito "{\"processo\":$P,\"cuore\":true,\"albero\":$A}" || true)
1601      voluto=$(printf '%s' "$b" | campo eseguibili)
1602      if [ -n "$voluto" ] && [ "$voluto" != "$provata" ] && eseguibili_indietro "$voluto"; then
1603        provata=$voluto
1604        allinea_staccato
1605      fi
1606      giri=$((giri + 1)); [ $((giri % 15)) -eq 0 ] && fresco
1607      { [ "$giri" -eq 1 ] || [ $((giri % 15)) -eq 0 ]; } && { cure; testi; repo_stato; riservo; }
1608      sleep "$passo"
1609    done
1610    fresco
1611    lascito=""
1612    [ -n "$albero" ] && [ -x "$albero/.delminio/lascito.sh" ] && \
1613      python3 -c 'import os,sys
1614exec(os.environ["DELMINIO_FIDATI_PY"])
1615a, f = sys.argv[1:]
1616sys.exit(0 if da_fidarsi(a, f, accettati(a)) else 1)' "$albero" "$albero/.delminio/lascito.sh" 2>/dev/null && \
1617      lascito=$(_tempo 30 bash "$albero/.delminio/lascito.sh" "$pid" "$albero" 2>/dev/null | head -c 1500 || true)
1618    if [ -z "$lascito" ]; then
1619      lascito="$M_nessun_albero"
1620      if [ -n "$albero" ]; then
1621        n=$(git -C "$albero" status --porcelain 2>/dev/null | grep -c . || true)
1622        if [ "${n:-0}" -gt 0 ]; then lascito=$(_f "$M_albero_sporco" albero "$albero" n "$n")
1623        else lascito=$(_f "$M_albero_pulito" albero "$albero"); fi
1624      fi
1625    fi
1626    L=$(json_stringa "$lascito")
1627    chiedi POST /api/sessioni/muori "{\"processo\":$P,\"lascito\":$L}" >/dev/null || true
1628    rm -f -- "$STATO"/*-"$pid"
1629    ;;
1630  segreto)
1631    python3 -c '
1632import json, re, sys
1633exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
1634try:
1635    p = json.load(sys.stdin).get("prompt") or ""
1636except Exception:
1637    sys.exit(0)
1638if re.search(r"eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}|DELMINIO_TOKEN=\S", p):
1639    sys.stderr.write(F("chiave_nel_messaggio"))
1640    sys.exit(2)
1641'
1642    exit $?
1643    ;;
1644  umano|volo|attesa)
1645    if [ "$1" = volo ]; then
1646      ev=$(_tempo 2 cat 2>/dev/null || true)
1647      if [[ $ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]]; then
1648        presto="$STATO/volo-sid-${BASH_REMATCH[1]}"
1649        [ -f "$presto" ] && [ $(( $(date +%s) - $(_mtime "$presto") )) -lt 10 ] && exit 0
1650        touch "$presto"
1651      fi
1652    fi
1653    pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
1654    headless "$pid" && exit 0
1655    if e_qwen "$pid" && [ "$1" = umano ]; then
1656      letto=""; [ -t 0 ] || letto=$(_tempo 2 cat 2>/dev/null || true)
1657      [ -n "$(printf '%s' "$letto" | campo prompt)" ] || exit 0
1658    fi
1659    if e_codex "$pid" || e_qwen "$pid" || e_opencode "$pid"; then
1660      if [ "$1" = attesa ]; then
1661        sid=$(_tempo 2 cat 2>/dev/null | campo session_id || true)
1662        if [ -n "$sid" ]; then
1663          _staccato bash "$0" attesa-codex "$pid" "$sid" >/dev/null 2>&1 < /dev/null &
1664        fi
1665        echo '{}'; exit 0
1666      fi
1667      [ "$1" = umano ] && { v=$(cat "$STATO/attesa-$pid" 2>/dev/null || true); [ -n "$v" ] && kill "$v" 2>/dev/null; rm -f "$STATO/attesa-$pid"; }
1668    fi
1669    if [ "$1" = volo ]; then
1670      if grep -q '"agent_id"' <<<"$ev" && [ -n "$(printf '%s' "$ev" | campo agent_id)" ]; then exit 0; fi
1671    fi
1672    if [ "$1" = umano ] && [ -f "$STATO/nasci-$pid" ]; then
1673      evento=${letto:-}; [ -n "$evento" ] || [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
1674      if [ "$(printf '%s' "$evento" | campo session_id)" != "$(cat "$STATO/nasci-$pid" 2>/dev/null)" ]; then
1675        rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
1676      elif madri=$(cat "$STATO/fork-$pid" 2>/dev/null || true) \
1677           && { [ ! -f "$STATO/fork-$pid" ] || [ "$madri" != '[]' ] || madri=$(madri_del_fork "$evento" "$(cat "$STATO/nasci-$pid")"); } \
1678           && r=$(chiedi POST /api/apertura "$(DELMINIO_MADRI="$madri" fatti_nascita "$pid" "$evento" si)"); then
1679        e_codex "$pid" && segna_informativa_codex "$r"
1680        rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
1681        nome=$(printf '%s' "$r" | campo sessione)
1682        case "$(printf '%s' "$r" | campo stato)" in nuova|ripresa|adottata)
1683          if [ -n "$nome" ]; then
1684            printf '%s' "$nome" > "$STATO/sessione-$pid"
1685            zitta_la_prima "$r" "$pid"
1686            _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
1687            printf '%s' "$r" | python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": json.load(sys.stdin)["hookSpecificOutput"]}))'
1688            exit 0
1689          fi ;;
1690        esac
1691      fi
1692    fi
1693    nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
1694    if [ "$1" = volo ]; then
1695      ultima="$STATO/volo-$pid"
1696      [ -f "$ultima" ] && [ $(( $(date +%s) - $(_mtime "$ultima") )) -lt 10 ] && exit 0
1697      touch "$ultima"
1698    fi
1699    N=$(json_stringa "$nome")
1700    albero=$(albero_di "$nome")
1701    A=$(json_stringa "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}")
1702    giri=0
1703    if [ "$1" = attesa ]; then
1704      io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
1705      [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
1706      echo "$$" > "$io"
1707    fi
1708    avviso=""
1709    while :; do
1710      somme=$(_conto_somme)
1711      voci=$(_skill_voci)
1712      if [ -n "$voci" ]; then
1713        cli=claude; e_codex "$pid" && cli=codex; e_qwen "$pid" && cli=qwen; e_opencode "$pid" && cli=opencode
1714        voci=",\"cli\":\"$cli\",\"skill\":[$voci]"
1715      fi
1716      if b=$(chiedi POST /api/canale/battito "{\"sessione\":$N,\"albero\":$A${somme:+,\"ganci\":{$somme\}}$voci}"); then
1717        rm -f "$STATO/posta-muta-$pid"
1718        case "$b" in *'"carta":true'*) : > "$STATO/carta"; rm -f "$STATO/carta-no" ;;
1719                     *) rm -f "$STATO/carta"; : > "$STATO/carta-no" ;; esac
1720        ultimo=$(printf '%s' "$b" | campo ultimo)
1721        [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}"
1722      else
1723        ultimo=""
1724        if [ "$1" = umano ] && [ ! -f "$STATO/posta-muta-$pid" ]; then
1725          touch "$STATO/posta-muta-$pid"
1726          avviso=$(_f "$M_posta_non_arriva" perche "$(perche_no)")
1727        fi
1728      fi
1729      cursore="$STATO/visto-$pid"; [ "$1" = attesa ] && cursore="$STATO/visto-attesa-$pid"
1730      if [ -n "$ultimo" ] && [ "$(cat "$cursore" 2>/dev/null)" != "$ultimo" ] \
1731         && t=$(chiedi GET "/api/canale/posta/testo?sessione=$nome&momento=$1"); then
1732        printf '%s' "$ultimo" > "$cursore"
1733        testo=$(printf '%s' "$t" | campo testo)
1734        [ -n "$testo" ] && printf '%s' "$ultimo" > "$STATO/visto-$pid"
1735        if [ -n "$testo" ]; then
1736          if [ "$1" != attesa ]; then
1737            evento=PostToolUse; [ "$1" = umano ] && evento=UserPromptSubmit
1738            python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": sys.argv[1], "additionalContext": sys.stdin.read()}}))' "$evento" <<<"$testo"
1739            exit 0
1740          fi
1741          printf '%s\n' "$testo" >&2; exit 2
1742        fi
1743      fi
1744      if [ -n "$avviso" ]; then
1745        python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.argv[1]}}))' "$avviso"
1746        exit 0
1747      fi
1748      [ "$1" != attesa ] && exit 0
1749      kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ] || exit 0
1750      giri=$((giri + 1))
1751      sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
1752    done
1753    ;;
1754  consumi|consumi-tool)
1755    pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
1756    nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
1757    passo="$STATO/consumi-$pid"
1758    if [ "$1" = consumi-tool ] && [ -f "$passo" ] && [ $(( $(date +%s) - $(_mtime "$passo") )) -lt 30 ]; then exit 0; fi
1759    touch "$passo"
1760    evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
1761    [ -n "$evento" ] || exit 0
1762    printf '%s' "$evento" > "$STATO/consumi-evento-$pid"
1763    _staccato bash "$0" consumi-manda "$pid" "$nome" >/dev/null 2>&1 < /dev/null &
1764    exit 0
1765    ;;
1766  consumi-manda)
1767    exec 9>"$STATO/consumi-lock-$2"
1768    command -v flock >/dev/null 2>&1 && { flock -w 10 9 || exit 0; }
1769    evento=$(cat "$STATO/consumi-evento-$2" 2>/dev/null)
1770    corpo=$(consumi_dal_transcript "$STATO/consumi-stato-$2" "$evento")
1771    [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
1772    corpo=$(totale_cli_qwen "$evento")
1773    [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
1774    ;;
1775  memorie)
1776    pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
1777    headless "$pid" && exit 0
1778    nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
1779    evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
1780    modello_dal_transcript "$pid" "$nome" "$evento"
1781    if [ -f "$STATO/carta" ] || [ ! -f "$STATO/carta-no" ]; then
1782      printf '%s' "$evento" | carta_richiesta "$nome"
1783    fi
1784    corpo=$(printf '%s' "$evento" | python3 -c '
1785import json, os, sys
1786try:
1787    e = json.load(sys.stdin)
1788except Exception:
1789    sys.exit(0)
1790testo = (e.get("prompt") or "").strip()
1791if not testo:
1792    sys.exit(0)
1793
1794def risposta(ev):
1795    if not isinstance(ev, dict):
1796        return ""
1797    if ev.get("type") == "response_item":
1798        p = ev.get("payload") or {}
1799        if p.get("type") == "message" and p.get("role") == "assistant":
1800            return "\n".join(b.get("text", "") for b in p.get("content") or []
1801                             if isinstance(b, dict) and b.get("type") == "output_text").strip()
1802        return ""
1803    if ev.get("type") != "assistant" or not isinstance(ev.get("message"), dict):
1804        return ""
1805    m = ev["message"]
1806    if m.get("parts") is not None:
1807        return "\n".join(x.get("text", "") for x in m["parts"] if isinstance(x, dict)
1808                         and isinstance(x.get("text"), str) and not x.get("thought")).strip()
1809    return "\n".join(b.get("text", "") for b in m.get("content") or []
1810                     if isinstance(b, dict) and b.get("type") == "text").strip()
1811
1812coda = e.get("coda") if isinstance(e.get("coda"), str) else ""
1813try:
1814    with open("" if coda else (e.get("transcript_path") or ""), "rb") as f:
1815        f.seek(0, os.SEEK_END)
1816        f.seek(max(0, f.tell() - 2_000_000))
1817        for riga in reversed(f.read().decode("utf-8", "replace").splitlines()):
1818            try:
1819                coda = risposta(json.loads(riga))
1820            except ValueError:
1821                continue
1822            if coda:
1823                break
1824except OSError:
1825    pass
1826print(json.dumps({"testo": testo[:1500], "coda": coda[-1200:]}, ensure_ascii=False))
1827' 2>/dev/null || true)
1828    [ -n "$corpo" ] || exit 0
1829    r=$(CHIEDI_TEMPO=2 CHIEDI_SESSIONE="$nome" chiedi POST /api/memorie/messaggio "$corpo") || exit 0
1830    testo=$(printf '%s' "$r" | campo testo)
1831    [ -n "$testo" ] || exit 0
1832    python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.stdin.read()}}))' <<<"$testo"
1833    ;;
1834  rito)
1835    pid=$(cli_pid || true); [ -n "$pid" ] && { e_codex "$pid" || e_qwen "$pid"; } || exit 0
1836    evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
1837    rito=$(printf '%s' "$evento" | python3 -c 'import json,re,sys
1838try:
1839    p = (json.load(sys.stdin).get("prompt") or "").strip()
1840except Exception:
1841    sys.exit(0)
1842prima, _, resto = p.partition("\n")
1843riti = json.loads(__import__("os").environ.get("DELMINIO_COMANDI") or "{}").get("riti") or {"apertura": "apertura", "chiusura": "chiusura"}
1844nomi = "|".join(re.escape(n) for n in sorted(riti, key=len, reverse=True))
1845m = (re.fullmatch(r"/(" + nomi + r")(?:\s+(.*))?", prima.strip(), re.I | re.S)
1846     or re.fullmatch(r"(" + nomi + r")\s*(?::\s*(.*))?", prima.strip(), re.I | re.S))
1847if m and re.match(r"/" + m.group(1) + r"\b", resto.strip(), re.I):
1848    resto = resto.strip()[len(m.group(1)) + 1:]
1849if m:
1850    print(riti.get(m.group(1).lower(), m.group(1).lower()) + "\t" + " ".join(x for x in ((m.group(2) or "").strip(), resto.strip()) if x))' || true)
1851    [ -n "$rito" ] || exit 0
1852    parola=${rito%%$'\t'*}; dopo=${rito#*$'\t'}
1853    if [ "$parola" = apertura ]; then testo=$(bash "$0" prompt); else testo=$(bash "$0" chiusura "$dopo"); fi
1854    python3 -c 'import json,sys
1855print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext":
1856    sys.argv[1] + "\n\n" + sys.stdin.read()}}))' "$(_f "$M_gesto_umano" parola "$parola")" <<<"$testo"
1857    ;;
1858  ritira-file)
1859    echo "$$" > "$STATO/ritiro-$2"
1860    ritira_file "$2" "$3"
1861    rm -f "$STATO/ritiro-$2"
1862    ;;
1863  invia)
1864    f=${2:-}; nota=${3:-}
1865    [ -n "$f" ] || { echo "$M_invia_uso" >&2; exit 1; }
1866    [ -f "$f" ] && [ -r "$f" ] || { _f "$M_invia_non_trovato" file "$f" >&2; exit 1; }
1867    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
1868    [ -n "$nome" ] || { echo "$M_invia_senza_sessione" >&2; exit 1; }
1869    tipo=$(python3 -c 'import mimetypes, sys; print(mimetypes.guess_type(sys.argv[1])[0] or "application/octet-stream")' "$f")
1870    q="verso=persona&sessione=$(_urlenc "$nome")&nome=$(_urlenc "$(basename "$f")")&nota=$(_urlenc "$nota")"
1871    r=$(curl -sS -m 900 -w '\n%{http_code}' -K <(_chiave "$TOKEN") -H "Content-Type: $tipo" \
1872          --data-binary @"$f" "$URL/api/file?$q" 2>/dev/null)
1873    c=${r##*$'\n'}; r=${r%$'\n'*}
1874    if [ "$c" != 200 ]; then
1875      e=$(printf '%s' "$r" | campo error); _f "$M_invia_fallito" perche "${e:-HTTP ${c:-000}}" >&2; exit 1
1876    fi
1877    _f "$M_invia_fatto" nome "$(printf '%s' "$r" | campo nome)"
1878    ;;
1879  attesa-codex)
1880    pid=$2; sid=$3
1881    [ -n "$sid" ] || exit 0
1882    nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
1883    io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
1884    [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
1885    echo "$$" > "$io"
1886    N=$(json_stringa "$nome")
1887    giri=0
1888    albero=$(albero_di "$nome"); albero=${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}
1889    while kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ]; do
1890      b=$(chiedi POST /api/canale/battito "{\"sessione\":$N}" || true)
1891      ultimo=$(printf '%s' "$b" | campo ultimo)
1892      [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "$albero"
1893      if [ -n "$ultimo" ] && [ "$ultimo" != "${guardato:-}" ] \
1894         && [ "$(cat "$STATO/visto-$pid" 2>/dev/null)" != "$ultimo" ] \
1895         && [ "$(cat "$STATO/avvisato-$pid" 2>/dev/null)" != "$ultimo" ]; then
1896        guardato=$ultimo
1897        per_lei=$(chiedi GET "/api/canale/posta?sessione=$nome&segna=0" | python3 -c 'import json,sys
1898try:
1899    r = json.load(sys.stdin); print(r["sveglie"] if "sveglie" in r else len(r.get("messaggi") or []))
1900except Exception: print(0)')
1901        [ "${per_lei:-0}" -gt 0 ] || { giri=$((giri + 1)); sleep 3; continue; }
1902        avviso_posta=$M_posta_arrivata
1903        if e_opencode "$pid"; then
1904          printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
1905          printf '%s\n' "$avviso_posta"
1906        elif e_qwen "$pid"; then
1907          f="${DELMINIO_QWEN_POSTA:-}"
1908          if [ -n "$f" ] && [ -f "$f" ] && python3 -c 'import json,sys; print(json.dumps({"type": "submit", "text": sys.argv[1]}, ensure_ascii=False))' "$avviso_posta" >> "$f"; then
1909            printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
1910          fi
1911        elif "${DELMINIO_CLI:-codex}" queue --thread "$sid" --message "$avviso_posta" >/dev/null 2>&1; then
1912          printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
1913        fi
1914        rm -f "$io"; exit 0
1915      fi
1916      giri=$((giri + 1))
1917      sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
1918    done
1919    ;;
1920  prompt)
1921    porta="${DELMINIO_PORTA:-${DELMINIO_MODELLO:-}}"
1922    r=$(curl -sS -m 15 -G -w '\n%{http_code}' -K <(_chiave "$TOKEN") \
1923          --data-urlencode "ordine=$porta" --data-urlencode "sistema=$([ -n "${DELMINIO_SISTEMA:-}" ] && echo 1 || echo 0)" \
1924          "$URL/api/porte/prompt" 2>/dev/null)
1925    codice=${r##*$'\n'}
1926    case "$codice" in
1927      ''|000) _f "$M_delminio_risponde_prompt" url "$URL" ;;
1928      200)    printf '%s\n' "${r%$'\n'*}" ;;
1929      *)      e=$(printf '%s' "${r%$'\n'*}" | campo error 2>/dev/null || true)
1930              _f "$M_prompt_rifiutato" url "$URL" codice "$codice" errore "${e:+: $e}" ;;
1931    esac
1932    ;;
1933  claude|codex|app-codex|qwen|opencode)
1934    parte lanciatori.sh && . "$(dirname "$0")/lanciatori.sh" "$@"
1935    ;;
1936  cassaforte)
1937    shift
1938    python3 "$(cd "$(dirname "$0")" && pwd)/cassaforte.py" "$@"
1939    ;;
1940  eseguibili|eseguibile)
1941    shift
1942    [ $# -eq 0 ] && set -- allinea
1943    python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit "$@"
1944    ;;
1945  condiviso)
1946    evento=$(cat)
1947    if [[ $evento == *'cd '* || $evento == *workdir* || $evento == *exec_command* || $evento == *rollout-* ]]; then
1948      evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
1949    fi
1950    dove=$(printf '%s' "$evento" | campo cwd)
1951    radice=$(git -C "${dove:-.}" rev-parse --show-toplevel 2>/dev/null) || radice=""
1952    if [ -z "$radice" ] || [ ! -f "$radice/.delminio/condivisi" ]; then
1953      radice=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
1954    fi
1955    [ -f "$radice/.delminio/condivisi" ] || exit 0
1956    corpo=$(printf '%s' "$evento" | python3 -c '
1957import json, re, sys
1958try:
1959    c = (json.load(sys.stdin).get("tool_input") or {}).get("command") or ""
1960except Exception:
1961    c = ""
1962for r in open(sys.argv[1], encoding="utf-8"):
1963    r = r.strip()
1964    if c and r and not r.startswith("#"):
1965        try:
1966            if re.search(r, c, re.I):
1967                print(json.dumps({"sessione": sys.argv[2], "comando": c}))
1968                break
1969        except re.error:
1970            pass' "$radice/.delminio/condivisi" "")
1971    [ -n "$corpo" ] || exit 0
1972    pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
1973    nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
1974    tregua="$STATO/condiviso-$pid"
1975    if [ -f "$tregua" ] && [ $(( $(date +%s) - $(_mtime "$tregua") )) -lt 600 ]; then exit 0; fi
1976    corpo=$(printf '%s' "$corpo" | python3 -c 'import json,sys; d = json.load(sys.stdin); d["sessione"] = sys.argv[1]; print(json.dumps(d))' "$nome")
1977    [ -n "$corpo" ] || exit 0
1978    r=$(chiedi POST /api/condiviso "$corpo") || exit 0
1979    if DELMINIO_R="$r" python3 -c 'import json,os,sys
1980r = json.loads(os.environ["DELMINIO_R"])
1981if r.get("ferma"):
1982    print(r.get("testo", ""), file=sys.stderr)
1983    sys.exit(2)'; then exit 0; fi
1984    touch "$tregua"; exit 2
1985    ;;
1986  gesto)
1987    evento=$(cat)
1988    strumento=""; [[ $evento =~ \"tool_name\":\ ?\"([^\"]+)\" ]] && strumento=${BASH_REMATCH[1]}
1989    case "$strumento" in Bash|exec_command|run_shell_command|"") di_shell=1 ;; *) di_shell="" ;; esac
1990    if [ -z "$di_shell" ]; then
1991      globi=$(strumenti_vivi) && [ -n "$globi" ] || exit 0
1992      combacia=""; shopt -s nocasematch
1993      while IFS= read -r g; do
1994        [ -n "$g" ] && [[ $strumento == $g ]] && { combacia=1; break; }
1995      done <<<"$globi"
1996      shopt -u nocasematch
1997      [ -n "$combacia" ] || exit 0
1998    fi
1999    dove_fatto=""
2000    if [ -n "$di_shell" ] && [[ $evento == *'"workdir"'* || $evento =~ \"command\":\ ?\"[[:space:]]*cd[[:space:]] ]]; then
2001      evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
2002    fi
2003    gira="$PWD"; [[ $evento =~ \"cwd\":\ ?\"([^\"]+)\" ]] && gira=${BASH_REMATCH[1]}
2004    repo_gesto=$(_remoto "$gira" || true)
2005    corpo=$(printf '%s' "$evento" | python3 -c 'import json,sys
2006try:
2007    e = json.load(sys.stdin)
2008    c = (e.get("tool_input") or {}).get("command") or "" if sys.argv[1] else ""
2009except Exception:
2010    c = ""
2011d = {"comando": c} if c else {}
2012if sys.argv[2]:
2013    d["strumento"] = sys.argv[2]
2014if d and sys.argv[3]:
2015    d["repo"] = sys.argv[3]
2016print(json.dumps(d) if d else "")' "$di_shell" "$strumento" "$repo_gesto")
2017    [ -n "$corpo" ] || exit 0
2018    r=$(chiedi POST /api/lock "$corpo") || exit 0
2019    [[ $r == *'"lock":[]}' || $r == *'"lock": []}' ]] && exit 0
2020    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2021    detti="${pid:+$STATO/lock-detti-$pid}"
2022    if [ -z "$dove_fatto" ] && [[ $r =~ \"comando_gesto\":\ ?\"[^\"] ]]; then
2023      evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
2024    fi
2025    read -r -d '' _gesto_py <<'GESTO' || true
2026import hashlib, json, os, subprocess, sys
2027exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2028detti_f = sys.argv[1]
2029try:
2030    detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
2031except OSError:
2032    detti = set()
2033lock = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
2034ATTESA_DI_SERIE = 5   # B938: come lock.ATTESA_DI_SERIE nel motore
2035evento = sys.stdin.read()
2036try:
2037    accettate = set(open(os.environ.get("DELMINIO_ACCETTATE") or "", encoding="utf-8").read().split())
2038except OSError:
2039    accettate = set()
2040nuovi_detti = []
2041
2042
2043def una_volta(segno, testo):
2044    if segno not in detti and segno not in nuovi_detti:
2045        nuovi_detti.append(segno)
2046        print("dire", json.dumps(testo))
2047
2048
2049def cieco(l, motivo, secondi):
2050    """B938 — il controllo non ha detto niente: si conta sempre. In una decisione che
2051    blocca, se non parte (o è lento e la decisione lo vuole) il comando si ferma come per
2052    una violazione: decide il motore (l'amministratore passa con un avviso). Se no passa."""
2053    cmd = l["comando_gesto"]
2054    print("cieco", l["codice"], motivo)
2055    if l.get("duro") and (motivo == "non_parte" or l.get("se_lento")):
2056        if motivo == "non_parte":
2057            fermo = F("gesto_controllo_non_parte_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd)
2058            breve = F("controllo_non_parte_breve", comando=cmd)
2059        else:
2060            fermo = F("gesto_controllo_lento_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd, secondi=secondi)
2061            breve = F("controllo_lento_breve", comando=cmd, secondi=secondi)
2062        print("viola_cieco", json.dumps({"codice": l["codice"], "breve": breve, "fermo": fermo}))
2063        return
2064    if motivo == "non_parte":
2065        una_volta("?" + l["codice"], F("gesto_controllo_non_parte_passa", codice=l["codice"], comando=cmd))
2066    else:
2067        una_volta("?" + l["codice"], F("gesto_controllo_lento_passa", codice=l["codice"], comando=cmd, secondi=secondi))
2068
2069
2070def prova(l):
2071    """Il controllo di una decisione prima del comando: (gridato, uscita) o None se
2072    non ha potuto dire niente — e allora l'ha già detto, o l'ha passato a ``cieco``."""
2073    cmd = l["comando_gesto"]
2074    impronta = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + cmd).encode()).hexdigest()
2075    if impronta not in accettate:
2076        una_volta("?" + l["codice"], F("gesto_controllo_non_accettato", codice=l["codice"], cosa=l["cosa"], comando=cmd))
2077        return None
2078    try:
2079        e = json.loads(evento)
2080    except ValueError:
2081        e = {}
2082    dove = str(e.get("cwd") or "")
2083    radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True,
2084                            cwd=dove if os.path.isdir(dove) else None).stdout.strip() or "."
2085    comando = str((e.get("tool_input") or {}).get("command") or "")
2086    amb = {**os.environ, "DELMINIO_CWD": str(e.get("cwd") or os.getcwd())}
2087    if len(comando) < 100000:
2088        amb["DELMINIO_COMANDO"] = comando
2089    secondi = int(l.get("attesa") or 0) or ATTESA_DI_SERIE
2090    try:
2091        p = subprocess.run(cmd, shell=True, cwd=radice, input=evento, capture_output=True, text=True,
2092                           timeout=secondi, env=amb)
2093    except subprocess.TimeoutExpired:
2094        cieco(l, "lento", secondi)
2095        return None
2096    except OSError:
2097        p = None
2098    if p is None or p.returncode in (126, 127):
2099        cieco(l, "non_parte", secondi)
2100        return None
2101    return p.returncode != 0, (p.stdout + p.stderr).strip()
2102
2103
2104for l in lock:
2105    if l.get("comando_gesto"):
2106        esito = prova(l)
2107        if not esito or not esito[0]:
2108            continue
2109        uscita = esito[1]
2110        if l.get("duro"):
2111            print("viola", l["codice"], json.dumps(uscita[-3000:]))
2112        else:
2113            righe = "".join("\n     " + r for r in uscita.splitlines()[-15:])
2114            testo = F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"])
2115            print("dire", json.dumps(testo + ("\n" + F("guardia_dice") + righe if righe else "")))
2116            print("conta", l["codice"])
2117        continue
2118    if l.get("duro"):
2119        print("duro", l["codice"])
2120    else:
2121        una_volta(l["codice"], F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"]))
2122if nuovi_detti and detti_f:
2123    with open(detti_f, "a", encoding="utf-8") as f:
2124        f.write("".join(x + "\n" for x in nuovi_detti))
2125GESTO
2126    piano=$(printf '%s' "$evento" | DELMINIO_LOCK="$r" DELMINIO_ACCETTATE="$(accettate_file 2>/dev/null)" python3 -c "$_gesto_py" "$detti")
2127    [ -n "$piano" ] || exit 0
2128    contesto=""; impronta=$(chiave_in_uso)
2129    descr=$(printf '%s' "$evento" | python3 -c 'import json,sys
2130try:
2131    e = json.load(sys.stdin)
2132except Exception:
2133    e = {}
2134t = e.get("tool_input") or {}
2135if sys.argv[1]:
2136    print("comando: " + str(t.get("command") or ""), end="")
2137else:
2138    print("strumento: " + sys.argv[2] + " · " + json.dumps(t, ensure_ascii=False)[:300], end="")' "$di_shell" "$strumento")
2139    sullo_strumento=false; [ -z "$di_shell" ] && sullo_strumento=true
2140    while read -r tipo resto; do
2141      case "$tipo" in
2142        dire) contesto="$contesto$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]))' "$resto")"$'\n' ;;
2143        duro)
2144          corpo=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys; print(json.dumps({"codice": sys.argv[1], "uscita": sys.stdin.read(), "sessione": sys.argv[2], "gesto": True, "strumento": sys.argv[3] == "true", "chiave": os.environ.get("IMPRONTA", ""), "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))' "$resto" "$nome" "$sullo_strumento")
2145          v=$(chiedi POST /api/lock/violazione "$corpo") || continue
2146          esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
2147          if [ "$esito" = ferma ]; then echo "🔒 $msg" >&2; exit 2; fi
2148          [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n' ;;
2149        cieco)
2150          corpo_k=$(python3 -c 'import json,sys; c, m = sys.argv[1].split(" ", 1); print(json.dumps({"codice": c, "motivo": m, "sessione": sys.argv[2]}))' "$resto" "$nome")
2151          CHIEDI_TEMPO=2 chiedi POST /api/lock/cieco "$corpo_k" >/dev/null 2>&1 || true ;;
2152        viola_cieco)
2153          corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
2154c = json.loads(sys.argv[1])
2155print(json.dumps({"codice": c["codice"], "uscita": sys.stdin.read() + "\n" + c["breve"], "sessione": sys.argv[2], "gesto": True, "strumento": sys.argv[3] == "true", "chiave": os.environ.get("IMPRONTA", ""), "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))' "$resto" "$nome" "$sullo_strumento")
2156          v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
2157          esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
2158          if [ "$esito" = ferma ]; then
2159            printf '%s' "$resto" | campo fermo >&2
2160            echo "🔒 $msg" >&2; exit 2
2161          fi
2162          [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n'"$(printf '%s' "$resto" | campo breve)"$'\n' ;;
2163        conta)
2164          corpo_c=$(printf '%s' "$descr" | python3 -c 'import json,sys; print(json.dumps({"codice": sys.argv[1], "uscita": sys.stdin.read(), "sessione": sys.argv[2], "gesto": True, "strumento": sys.argv[3] == "true"}))' "$resto" "$nome" "$sullo_strumento")
2165          CHIEDI_TEMPO=2 chiedi POST /api/lock/violazione "$corpo_c" >/dev/null 2>&1 || true ;;
2166        viola)
2167          corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
2168codice, uscita = sys.argv[1].split(" ", 1)
2169uscita = json.loads(uscita)
2170print(json.dumps({"codice": codice, "uscita": sys.stdin.read() + ("\n" + uscita if uscita else ""), "sessione": sys.argv[2], "gesto": True, "strumento": sys.argv[3] == "true", "chiave": os.environ.get("IMPRONTA", ""), "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))' "$resto" "$nome" "$sullo_strumento")
2171          v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
2172          esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
2173          dice=$(printf '%s' "$resto" | python3 -c 'import json,sys
2174_, u = sys.stdin.read().split(" ", 1)
2175print("".join("\n     " + r for r in json.loads(u).splitlines()[-15:]), end="")')
2176          if [ "$esito" = ferma ]; then printf '🔒 %s%s\n' "$msg" "${dice:+$'\n'$M_guardia_dice$dice}" >&2; exit 2; fi
2177          [ -n "$msg" ] && contesto="$contesto🔒 $msg${dice:+$'\n'$M_guardia_dice$dice}"$'\n' ;;
2178      esac
2179    done <<<"$piano"
2180    [ -n "$contesto" ] && python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$contesto"
2181    exit 0
2182    ;;
2183  dove)
2184    evento=$(cat); printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"
2185    ;;
2186  guardia)
2187    evento=$(cat)
2188    dove_fatto=""
2189    if [[ $evento == *rollout-* || $evento =~ \"tool_name\":\ ?\"apply_patch\" ]]; then
2190      evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
2191    fi
2192    if [ -z "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
2193      _guardia_serve "$evento" || exit 0
2194      evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
2195    fi
2196    if incerto=$(printf '%s' "$evento" | campo dove_incerto) && [ -n "$incerto" ]; then
2197      _f "$M_guardia_cartella_gira" incerto "$incerto" >&2
2198      exit 2
2199    fi
2200    if [ -n "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
2201      _guardia_serve "$evento" || exit 0
2202    fi
2203    corpo=$(printf '%s' "$evento" | DELMINIO_MEMORIA="$MEMORIA" IMPRONTA="$(chiave_in_uso)" python3 -c 'import json,os,re,sys
2204try:
2205    e = json.load(sys.stdin)
2206except Exception:
2207    sys.exit(0)
2208t = e.get("tool_input") or {}
2209cwd = os.path.realpath(e.get("cwd") or os.getcwd())
2210scritti = [t.get("file_path") or t.get("notebook_path") or ""]
2211if e.get("tool_name") == "apply_patch":
2212    patch = t.get("command") or t.get("input") or t.get("patch") or ""
2213    scritti += [p.strip() for p in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M)]
2214veri = {p: os.path.realpath(os.path.join(cwd, os.path.expanduser(p))) for p in scritti if p}
2215m = os.environ.get("DELMINIO_MEMORIA") or ""
2216print(json.dumps({"memoria": os.path.realpath(m) if m else "", "home": os.path.expanduser("~"),
2217                  "cwd": cwd, "evento": e, "veri": veri, "chiave": os.environ.get("IMPRONTA", ""),
2218                  "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))') || exit 0
2219    [ -n "$corpo" ] || exit 0
2220    r=$(printf '%s' "$corpo" | curl -sS -m 3 -w '\n%{http_code}' -X POST -K <(_chiave "$TOKEN") \
2221          -H "Content-Type: application/json" --data-binary @- "$URL/api/guardia" 2>/dev/null)
2222    if [ "${r##*$'\n'}" != 200 ]; then
2223      giu="$STATO/guardia-giu"
2224      if [ ! -f "$giu" ] || [ $(( $(date +%s) - $(_mtime "$giu") )) -ge 600 ]; then
2225        touch "$giu"
2226        case "${r##*$'\n'}" in ''|000) avviso=$M_guardie_giu ;; *) avviso=$(_f "$M_guardie_errore" codice "${r##*$'\n'}") ;; esac
2227        python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$avviso"
2228      fi
2229      exit 0
2230    fi
2231    [[ ${r%$'\n'*} == '{"ferma":false}' || ${r%$'\n'*} == '{"ferma": false}' ]] && exit 0
2232    DELMINIO_R="${r%$'\n'*}" python3 -c 'import json,os,sys
2233try:
2234    r = json.loads(os.environ["DELMINIO_R"])
2235except Exception:
2236    sys.exit(0)
2237if r.get("ferma"):
2238    print(r.get("testo", ""), file=sys.stderr)
2239    sys.exit(2)'
2240    ;;
2241  nuovo|merge|smonta)
2242    parte worktree.sh && . "$(dirname "$0")/worktree.sh" "$@"
2243    ;;
2244  audit)
2245    radice=$(git rev-parse --show-toplevel)
2246    cartella="$radice/.delminio/audit"
2247    if squadra=$(chiedi GET /api/skill/squadra); then
2248      nomi=$(printf '%s' "$squadra" | python3 -c "$PY_SKILL_NOMI" "$radice"); e=$?
2249      while IFS=$'\t' read -r k a b c; do
2250        [ "$k" = F ] && _f "$M_skill_nomi_finding" pezzo "$a" file "$b" nome "$c"
2251      done <<<"$nomi"
2252      case "$e:$nomi" in
2253        0:NESSUNA*) echo "$M_skill_nomi_nessuna" ;;
2254        0:OK*) _f "$M_skill_nomi_pulita" n "${nomi#OK$'\t'}" ;;
2255        1:*) echo "$M_skill_nomi_voluti" ;;
2256        *) _f "$M_skill_nomi_cieca" perche "python3 $e" ;;
2257      esac
2258    else
2259      _f "$M_skill_nomi_cieca" perche "$(perche_no)"
2260    fi
2261    if [ ! -d "$cartella" ] || [ -z "$(ls -A "$cartella" 2>/dev/null)" ]; then
2262      echo "$M_nessuna_track_misurata"
2263      echo "$M_revisione_memoria_meta"
2264      exit 0
2265    fi
2266    pulite=0; con=0
2267    for s in "$cartella"/*; do
2268      [ -f "$s" ] && [ -x "$s" ] || continue
2269      out=$(cd "$(git rev-parse --show-toplevel)" && _tempo 300 "$s" 2>&1); e=$?
2270      if [ $e = 0 ]; then pulite=$((pulite + 1)); echo "✅ $(basename "$s")"
2271      else con=$((con + 1)); echo "❌ $(basename "$s") (uscita $e)"; printf '%s\n' "$out" | head -20 | sed 's/^/   /'
2272      fi
2273    done
2274    _f "$M_track_pulite_finding" pulite "$pulite" con "$con"
2275    ;;
2276  domini)
2277    pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2278    [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_2"; exit 1; }
2279    [ -n "${2:-}" ] || { echo "$M_quali_bash_claude" >&2; exit 1; }
2280    D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "domini": sys.argv[2]}))' "$nome" "$2")
2281    r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
2282    printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
2283    _f "$M_lavora_altre_sessioni" nome "$nome" valore "$2"
2284    ;;
2285  titolo)
2286    pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2287    [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_3"; exit 1; }
2288    [ -n "${2:-}" ] || { echo "$M_quale_bash_claude" >&2; exit 1; }
2289    D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "titolo": sys.argv[2]}))' "$nome" "$2")
2290    r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
2291    printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
2292    _f "$M_chiama" nome "$nome" valore "$2"
2293    ;;
2294  file-del-kit)
2295    printf '%s\n' $KIT_FILE
2296    ;;
2297  ambiente)
2298    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2299    printf '%s\n%s\n%s\n' "$URL" "$FILE_TOKEN" "$nome"
2300    ;;
2301  chiusura)
2302    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2303    cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
2304    corpo=$(DELMINIO_CLI_NOME="$cli" python3 - "$nome" "${2:-}" "$(_remoto)" <<'CHIUSURA'
2305import json, os, subprocess, sys
2306def git(*a):
2307    return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
2308def chiavi(var):   # i nomi di un trailer in ogni lingua (F665), come li vuole git
2309    return ",".join("key=" + k for k in os.environ[var].split("|"))
2310exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2311commit = git("log", "-200", "--format=%h%x1f%s%x1f"
2312             "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
2313             "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)").splitlines()
2314import re, time
2315NOMI_COMUNI = 100
2316def nomi_cambiati(sessione):
2317    if not sessione:
2318        return []
2319    hh = []
2320    for riga in git("log", "-300", "--no-merges",
2321                    "--format=%H%x1f%(trailers:key=Delminio-Sessione,valueonly,separator=%x20)").splitlines():
2322        h, _, chi = riga.partition("\x1f")
2323        if sessione in chi.split():
2324            hh.append(h)
2325    if not hh:
2326        return []
2327    try:
2328        diff = subprocess.run(["git", "show", "-U0", "--format=", *hh], capture_output=True,
2329                              text=True, errors="replace", timeout=20).stdout
2330    except subprocess.TimeoutExpired:
2331        return []
2332    saldo = {}
2333    for l in diff.splitlines():
2334        if not l or l[0] not in "+-" or l.startswith(("+++", "---")):
2335            continue
2336        segno = 1 if l[0] == "+" else -1
2337        for n in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", l[1:]):
2338            if "_" in n.strip("_") or re.search(r"[a-z][A-Z]", n) or (n.isupper() and len(n) >= 4):
2339                saldo[n] = saldo.get(n, 0) + segno
2340    fuori, inizio = [], time.time()
2341    for n in sorted((n for n, v in saldo.items() if v), key=lambda n: -abs(saldo[n]))[:150]:
2342        if time.time() - inizio > 10:
2343            break
2344        if len(git("grep", "-lwF", "-e", n, "--", ".").splitlines()) <= NOMI_COMUNI:
2345            fuori.append(n)
2346    return fuori
2347righe = []
2348sporchi = [r for r in git("status", "--porcelain").splitlines() if r.strip()]
2349righe.append(F("dove_albero_sporco", n=len(sporchi)) if sporchi else F("dove_albero_pulito"))
2350if git("rev-parse", "--abbrev-ref", "@{u}"):
2351    n = git("rev-list", "--count", "@{u}..HEAD")
2352    righe.append(F("commit_non_pushati", n=n, ramo=git("rev-parse", "--abbrev-ref", "@{u}"))
2353                 if n not in ("", "0") else F("tutto_pushato"))
2354else:
2355    righe.append(F("ramo_senza_remoto", ramo=git("rev-parse", "--abbrev-ref", "HEAD")))
2356alberi = [r for r in git("worktree", "list", "--porcelain").splitlines() if r.startswith("worktree ")]
2357if len(alberi) > 1:
2358    righe.append(F("worktree_in_piu", n=len(alberi) - 1, alberi=", ".join(a[9:] for a in alberi[1:])))
2359exec(os.environ["DELMINIO_FIDATI_PY"])
2360radice = git("rev-parse", "--show-toplevel")
2361gia, fermi = accettati(radice), []
2362for f in script_del_progetto(radice, ("dove-siamo", "status")):
2363    s = os.path.basename(f)
2364    if not da_fidarsi(radice, f, gia):
2365        fermi.append(di_chi(radice, f)[0])
2366        continue
2367    try:
2368        out = subprocess.run([f], capture_output=True, text=True, timeout=30).stdout.strip()
2369    except (OSError, subprocess.TimeoutExpired) as e:
2370        out = F("script_non_risponde", script=s, errore=e)
2371    righe += [r for r in out.splitlines() if r.strip()][:3]
2372if fermi:
2373    righe.append(F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
2374print(json.dumps({"sessione": sys.argv[1], "richieste": sys.argv[2], "commit": commit,
2375                  "dove_siamo": righe, "remoto": sys.argv[3], "nomi": nomi_cambiati(sys.argv[1]),
2376                  "cli": os.environ.get("DELMINIO_CLI_NOME") or "claude"}))
2377CHIUSURA
2378)
2379    if r=$(chiedi POST /api/chiusura/prompt "$corpo"); then
2380      printf '%s' "$r" | campo testo
2381    else
2382      echo "Chiudiamo. ${2:-}"
2383      echo
2384      _f "$M_prompt_chiusura_arrivato" perche "$(perche_no)"
2385      echo "$M_lavoro_committato_pushato"
2386      echo "$M_vuoto_git_commit"
2387      echo "$M_push_commit_passera"
2388    fi
2389    ;;
2390  consegna)
2391    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
2392    corpo=$(python3 -c 'import json,sys; print(json.dumps({"messaggio": sys.stdin.read(), "sessione": sys.argv[1], "remoto": sys.argv[2]}))' \
2393      "$nome" "$(_remoto)") || exit 1
2394    if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/consegna "$corpo"); then
2395      _f "$M_chiusura_stata_consegnata" perche "$(perche_no)" >&2
2396      exit 1
2397    fi
2398    printf '%s' "$r" | python3 -c 'import json,sys
2399exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2400r = json.load(sys.stdin)
2401if not r.get("ok"):
2402    print(F("chiusura_rifiutata"), file=sys.stderr)
2403    for m in r.get("motivi") or []:
2404        print(f"   • {m}", file=sys.stderr)
2405    sys.exit(1)
2406for k, v in (r.get("aggiunti") or {}).items():
2407    print(F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
2408for a in r.get("avvisi") or []:
2409    print(f"⚠️  {a}", file=sys.stderr)
2410nome, h = r.get("sessione"), r.get("hash")
2411print(F("chiusa_nel_repo", nome=nome, hash=h))
2412if r.get("mollate"):
2413    print(F("opere_avevi_mano", m=", ".join(r["mollate"])))'
2414    ;;
2415  consegna-di)
2416    n=${2:-}; n=${n#[Ss]}
2417    [[ "$n" =~ ^[0-9]+$ ]] || { echo "$M_consegna_di_uso" >&2; exit 1; }
2418    r=$(chiedi GET "/api/chiusure/$n") || { echo "❌ $(perche_no)" >&2; exit 1; }
2419    printf '%s' "$r" | M_CURATA="$(_f "$M_consegna_di_curata" numero "$n")" \
2420      M_VUOTA="$(_f "$M_consegna_di_vuota" numero "$n")" python3 -c '
2421import json, os, sys
2422c = json.load(sys.stdin)
2423if c.get("cura"):
2424    print(os.environ["M_CURATA"] + "\n\n" + c["cura"]["testo"])
2425elif c.get("testo"):
2426    print(c["testo"])
2427else:
2428    print(os.environ["M_VUOTA"])'
2429    ;;
2430  tocco)
2431    percorsi=$(python3 -c 'import json,os,re,sys
2432try:
2433    e = json.load(sys.stdin); t = e.get("tool_input") or {}
2434except Exception:
2435    sys.exit(0)
2436if e.get("tool_name") == "apply_patch":
2437    patch = t.get("command") or t.get("input") or t.get("patch") or ""
2438    for f in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M):
2439        print(os.path.join(e.get("cwd") or os.getcwd(), f.strip()))
2440else:
2441    print(t.get("file_path") or t.get("notebook_path") or "")')
2442    percorso=$(printf '%s\n' "$percorsi" | head -1)
2443    [ -n "$percorso" ] || exit 0
2444    altro=""
2445    cima=$(python3 -c 'import os,sys
2446d = os.path.dirname(os.path.abspath(sys.argv[1]))
2447while d != os.path.dirname(d) and not os.path.exists(os.path.join(d, ".git")):
2448    d = os.path.dirname(d)
2449print(d if os.path.exists(os.path.join(d, ".git")) else "")' "$percorso" 2>/dev/null || true)
2450    qui=$(cd "$(dirname "$0")/.." && pwd)
2451    remoto_cima=$(_remoto "${cima:-$qui}" || true)
2452    if [ -n "$cima" ] && [ "$cima" != "$qui" ] && [ -f "$cima/.claude/delminio.sh" ] && [ -f "$cima/.claude/eseguibili.py" ]; then
2453      suo=$(python3 "$cima/.claude/eseguibili.py" spazio --da "$cima/.claude/delminio.sh" 2>/dev/null || true)
2454      mio=$(spazio_qui)
2455      if [ -n "$suo" ] && [ "$suo" != "$mio" ]; then
2456        altro=$(python3 -c 'import sys
2457n = lambda k: k.rsplit("#", 1)[1] if "#" in k else "principale"
2458a, b = n(sys.argv[2]), n(sys.argv[3])
2459if a == b: a, b = sys.argv[2], sys.argv[3]
2460print(sys.argv[1] + "\t" + a + "\t" + b)' "$cima" "$suo" "$mio")
2461      fi
2462    fi
2463    r='{"lock": []}'; con_lock=""
2464    qrepo=""
2465    [ -z "$remoto_cima" ] || qrepo="&repo=$(_quota "$remoto_cima" "")"
2466    while IFS= read -r x; do
2467      [ -n "$x" ] || continue
2468      uno=$(chiedi GET "/api/lock?percorso=$(_quota "$x" /)$qrepo") || continue
2469      printf '%s' "$uno" | grep -q '"codice"' || continue
2470      con_lock="$con_lock$x"$'\n'
2471      r=$(python3 -c 'import json,sys
2472a, b = json.loads(sys.argv[1]), json.loads(sys.argv[2])
2473visti = {(l.get("spazio"), l["codice"]) for l in a.get("lock") or []}
2474a["lock"] = (a.get("lock") or []) + [l for l in b.get("lock") or [] if (l.get("spazio"), l["codice"]) not in visti]
2475a.update({k: b[k] for k in ("condiviso_da", "altro_spazio") if b.get(k)})
2476print(json.dumps(a))' "$r" "$uno" 2>/dev/null || printf '%s' "$r")
2477    done <<< "$percorsi"
2478    pid=$(cli_pid || true); detti="${pid:+$STATO/lock-detti-$pid}"
2479    DELMINIO_LOCK="$r" DELMINIO_ALTRO="$altro" DELMINIO_CIMA="$cima" DELMINIO_PERCORSI="${con_lock:-$percorso}" python3 - "$detti" "$percorso" <<'TOCCO'
2480import json, os, sys
2481exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2482detti_f, percorso = sys.argv[1], sys.argv[2]
2483try:
2484    detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
2485except OSError:
2486    detti = set()
2487righe, segni = [], []
2488risposta = json.loads(os.environ["DELMINIO_LOCK"])
2489cima = os.environ.get("DELMINIO_CIMA", "")
2490nome_cima = os.path.basename(cima) or F("questo_repo")
2491altro = os.environ.get("DELMINIO_ALTRO", "").split("\t")
2492if risposta.get("condiviso_da") and ("condiviso:" + cima) not in detti:
2493    di = risposta["condiviso_da"]
2494    segni.append("condiviso:" + cima)
2495    righe.append(F("tocco_ospite", repo=nome_cima, di=di))
2496elif len(altro) == 3 and ("spazio:" + altro[0]) not in detti:
2497    cima, suo, mio = altro
2498    segni.append("spazio:" + cima)
2499    righe.append(F("tocco_altro_spazio_tuo", repo=os.path.basename(cima), suo=suo, mio=mio))
2500elif risposta.get("altro_spazio") and ("spazio:" + cima) not in detti:
2501    di = risposta["altro_spazio"]
2502    segni.append("spazio:" + cima)
2503    righe.append(F("tocco_non_condiviso", repo=nome_cima, di=di))
2504nuovi = [l for l in risposta.get("lock") or []
2505         if (l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"]) not in detti]
2506segni += [l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"] for l in nuovi]
2507if not righe and not nuovi:
2508    sys.exit(0)
2509if detti_f:
2510    with open(detti_f, "a", encoding="utf-8") as f:
2511        f.write("".join(x + "\n" for x in segni))
2512if nuovi:
2513    tocchi = ", ".join(os.path.basename(x) for x in os.environ.get("DELMINIO_PERCORSI", percorso).split("\n") if x)
2514    righe.append(F("tocco_lock", file=tocchi))
2515for l in nuovi:
2516    duro = F("tocco_duro") if l.get("duro") else ""
2517    if l.get("spazio"):
2518        duro = F("tocco_duro_ospite") if l.get("duro") else ""
2519    di = F("tocco_dello_spazio", spazio=l["spazio"]) if l.get("spazio") else ""
2520    guardia = l.get("guardia") or F("tocco_nessuno")
2521    righe.append(F("tocco_voce", codice=l["codice"], di=di, cosa=l["cosa"], duro=duro, perche=l["perche"], guardia=guardia))
2522print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
2523                                         "additionalContext": "\n".join(righe)}}))
2524TOCCO
2525    ;;
2526  ripassato)
2527    radice=$(git rev-parse --show-toplevel) || exit 1
2528    n=0; cartella=$(cartella_backup)
2529    copie_fatte=("$radice"/.claude/delminio-prima/*/)
2530    [ -n "$cartella" ] && copie_fatte+=("$cartella"/*/)
2531    for d in "${copie_fatte[@]}"; do
2532      [ -f "$d/fatti.json" ] && [ ! -e "$d/RIPASSATO" ] || continue
2533      date '+%Y-%m-%d %H:%M' > "$d/RIPASSATO"; n=$((n + 1))
2534    done
2535    _f "$M_ripassato_copia_prima" n "$n" cartella "${cartella:-.claude/delminio-prima}"
2536    ;;
2537  stacca)
2538    { exec 3</dev/tty; } 2>/dev/null || { echo "$M_stacca_lancia_terminale" >&2; exit 1; }
2539    radice=$(git rev-parse --show-toplevel) || exit 1
2540    [ "$(_assoluto "$(git rev-parse --git-common-dir)")" = "$(_assoluto "$radice/.git")" ] \
2541      || { echo "$M_stacca_lancia_clone" >&2; exit 1; }
2542    cd "$radice"
2543    cartella=$(cartella_backup)
2544    prima=$( { [ -n "$cartella" ] && ls -d "$cartella"/*/fatti.json 2>/dev/null; } | tail -1 || true)
2545    prima=${prima%fatti.json}
2546    [ -n "$prima" ] || prima=$(ls -d .claude/delminio-prima/*/ 2>/dev/null | tail -1 || true)
2547    [ -n "$cartella" ] || cartella=$(python3 -c 'import hashlib, os, re, sys
2548c = os.path.realpath(sys.argv[1])
2549print(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share"), "delminio", "backup",
2550                   (re.sub(r"[^A-Za-z0-9._-]", "-", os.path.basename(c)) or "repo") + "-" + hashlib.sha256(c.encode()).hexdigest()[:12]))' "$radice")
2551    nome_repo=$(basename "$radice")
2552    _f "$M_stacco" repo "$nome_repo" url "$URL"
2553    [ -n "$prima" ] && _f "$M_rimetto_cio_era" prima "$prima" \
2554                    || echo "$M_copia_prima_tolgo"
2555    read -rp "$M_procedo" si <&3
2556    case "$si" in s|S|si|sì|y|yes) ;; *) echo "$M_niente_fatto"; exit 0 ;; esac
2557    personali="$cartella/personali-$(date +%Y-%m-%d-%H%M%S)"
2558    if r=$(chiedi GET /api/personali); then
2559      n=$(umask 077; printf '%s' "$r" | python3 -c '
2560import json, os, re, sys
2561dest = sys.argv[1]
2562mie = json.load(sys.stdin).get("personali") or []
2563for m in mie:
2564    os.makedirs(dest, exist_ok=True)
2565    nome = re.sub(r"[^a-z0-9]+", "_", m["name"].lower()).strip("_")[:80] or "memoria"
2566    i = 1
2567    while True:
2568        percorso = os.path.join(dest, nome + ("" if i == 1 else "_" + str(i)) + ".md")
2569        try:
2570            f = open(percorso, "x", encoding="utf-8")
2571        except FileExistsError:
2572            i += 1
2573            continue
2574        with f:
2575            f.write(m["md"])
2576        break
2577print(len(mie))' "$personali") || exit 1
2578      if [ "${n:-0}" -gt 0 ] 2>/dev/null; then _f "$M_tue_memorie_personali" n "$n" personali "$personali"; else personali=""; fi
2579    else
2580      personali=""
2581      _f "$M_tue_memorie_personali_2" perche "$(perche_no)"
2582    fi
2583    if [ -f .claude/plugin.py ]; then python3 .claude/plugin.py rimuovi "$radice" || true; fi
2584    DELMINIO_PRIMA="$prima" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" python3 - <<'STACCA'
2585import json, os, pathlib, shutil
2586exec(os.environ["DELMINIO_GANCI_PY"])
2587prima = os.environ.get("DELMINIO_PRIMA", "").rstrip("/")
2588try:
2589    fatti = json.load(open(os.path.join(prima, "fatti.json"), encoding="utf-8")) if prima else {}
2590except (OSError, ValueError):
2591    fatti = {}
2592copie = set(fatti.get("copie") or [])
2593p = pathlib.Path(".claude/settings.local.json")
2594if p.exists():
2595    s = json.loads(p.read_text(encoding="utf-8") or "{}")
2596    togli_ganci(s)
2597    allow = (s.get("permissions") or {}).get("allow")
2598    if allow is not None:
2599        nostri = ({f"mcp__{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")}
2600                  | {f"mcp__plugin_delminio_{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")})
2601        allow[:] = [a for a in allow if a not in nostri]
2602    s.pop("autoMemoryDirectory", None)
2603    if (fatti.get("memoria") or {}).get("scelta_in") == ".claude/settings.local.json":
2604        s["autoMemoryDirectory"] = fatti["memoria"]["cartella"]
2605    if s or ".claude/settings.local.json" in copie:
2606        p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
2607    else:
2608        p.unlink()
2609e = pathlib.Path(".qwen/.env")
2610if e.is_file() and e.read_text(encoding="utf-8", errors="replace").strip() == "# delminio":
2611    e.unlink()
2612    try:
2613        e.parent.rmdir()
2614    except OSError:
2615        pass
2616for c in (pathlib.Path(".codex/hooks.json"), pathlib.Path(".qwen/settings.json")):
2617  if c.exists():
2618    try:
2619        s = json.loads(c.read_text(encoding="utf-8") or "{}")
2620    except ValueError:
2621        s = None
2622    if s is not None:
2623        togli_ganci(s)
2624        if s or str(c) in copie:
2625            c.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
2626        else:
2627            c.unlink()
2628            try:
2629                c.parent.rmdir()   # solo se vuota: il resto di .codex e di .qwen è dell'umano
2630            except OSError:
2631                pass
2632for rel in (f for f in os.environ["DELMINIO_KIT_FILE"].split() if "/commands/" in f):
2633    if rel in copie:
2634        os.makedirs(os.path.dirname(rel), exist_ok=True)
2635        shutil.copy2(os.path.join(prima, rel), rel)
2636    elif os.path.isfile(rel) and ("Delminio" if rel.startswith(".qwen/") else "delminio.sh") in open(rel, encoding="utf-8").read():
2637        os.unlink(rel)
2638STACCA
2639    mcp_claude_nostro() {  # mcp_claude_nostro <nome>: il server locale di questo repo è il nostro (punta qui)
2640      python3 -c 'import json, os, sys
2641f = os.path.join(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~"), ".claude.json")
2642try:
2643    s = json.load(open(f, encoding="utf-8"))["projects"][sys.argv[1]]["mcpServers"][sys.argv[2]]
2644except (OSError, ValueError, KeyError, TypeError):
2645    sys.exit(1)
2646sys.exit(0 if str(s.get("url", "")).startswith(sys.argv[3]) else 1)' "$radice" "$1" "$URL" 2>/dev/null
2647    }
2648    for n in memoria delminio; do
2649      mcp_claude_nostro "$n" && claude mcp remove "$n" -s local >/dev/null 2>&1
2650      if [ -n "$prima" ] && [ -f "$prima/mcp-$n.json" ]; then
2651        claude mcp add-json -s local "$n" "$(cat "$prima/mcp-$n.json")" >/dev/null \
2652          && _f "$M_server_mcp_delminio" nome "$n" \
2653          || _f "$M_server_mcp_prima" prima "$prima" nome "$n"
2654      fi
2655    done
2656    ganci=$(git config core.hooksPath || git rev-parse --git-path hooks)
2657    for g in commit-msg post-commit post-rewrite; do
2658      f="$ganci/$g"
2659      [ -f "$f" ] && grep -q "delminio.sh" "$f" || continue
2660      if sed -n 2p "$f" | grep -q '^# Delminio (aggancia.sh)'; then rm -f "$f"
2661      else _f "$M_tuo_chiama_delminio" f "$f"; fi
2662    done
2663    escludi=$(git rev-parse --git-path info/exclude)
2664    if [ -f "$escludi" ]; then
2665      printf '%s\n' $KIT_FILE $KIT_DI_PRIMA $([ -e .qwen/.env ] || echo .qwen/.env) | grep -vxF -f - "$escludi" > "$escludi.delminio" || true
2666      mv -f "$escludi.delminio" "$escludi"
2667    fi
2668    messe="$(git rev-parse --git-common-dir)/delminio-cure"
2669    if [ -f "$messe" ]; then
2670      while read -r h; do [ -n "$h" ] && git replace -d "$h" >/dev/null 2>&1 || true; done < "$messe"
2671    fi
2672    for s in delminio-guardie-accettate delminio-sonde-accettate delminio-script-accettati delminio-pubblico delminio-merge.lock delminio-cure delminio-backup delminio-skill-f844; do
2673      rm -f "$(git rev-parse --git-path "$s")" "$(git rev-parse --git-common-dir)/$s" 2>/dev/null || true
2674    done
2675    jti=$(printf '%s' "$TOKEN" | python3 -c '
2676import base64, json, sys
2677try:
2678    p = sys.stdin.read().split(".")[1]
2679    print(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))).get("jti") or "")
2680except Exception:
2681    print("")')
2682    altri=$(grep -lxF -- "$TOKEN" "$(dirname "$FILE_TOKEN")"/*.token 2>/dev/null | grep -vxF "$FILE_TOKEN" | wc -l)
2683    if [ -z "$jti" ]; then
2684      echo "$M_revocare_questo_token"
2685    elif [ "$altri" -gt 0 ]; then
2686      _f "$M_token_resta_valido" altri "$altri"
2687    elif chiedi DELETE "/api/tokens/$jti" >/dev/null; then
2688      echo "$M_token_questo_aggancio"
2689    else
2690      _f "$M_token_revocato_fallo" perche "$(perche_no)"
2691    fi
2692    if [ "$altri" -eq 0 ] 2>/dev/null && [ -f .claude/eseguibili.py ]; then
2693      python3 .claude/eseguibili.py --url "$URL" --token-file "$FILE_TOKEN" lascia || true
2694    fi
2695    rm -f "$FILE_TOKEN"
2696    if ! ls "$(dirname "$FILE_TOKEN")"/*.token >/dev/null 2>&1; then
2697      dati="${XDG_DATA_HOME:-$HOME/.local/share}"; cache="${XDG_CACHE_HOME:-$HOME/.cache}"
2698      if [ -f .claude/plugin.py ]; then
2699        esito=0; python3 .claude/plugin.py app-codex lascia >/dev/null 2>&1 || esito=$?
2700        [ "$esito" -eq 2 ] && echo "$M_app_codex_tolto"
2701      fi
2702      rm -rf "$dati/delminio/plugin" "$dati/codex/versions" "$dati/qwen-code/versions" "$dati/delminio/opencode" \
2703             "$cache"/delminio-stato "$cache"/delminio-eseguibili "$cache"/delminio-cassaforte 2>/dev/null || true
2704      comando="${DELMINIO_BIN:-$HOME/.local/bin}/delminio"
2705      grep -q '^# delminio-comando$' "$comando" 2>/dev/null && rm -f "$comando"
2706      echo "$M_pulito_ultimo"
2707    fi
2708    for f in $KIT_FILE $KIT_DI_PRIMA; do
2709      case "$f" in .claude/*.py|.claude/rules/*) rm -f "$f" ;; esac   # il resto l'ha già rimesso il python
2710    done
2711    rmdir .claude/rules "$(dirname "$FILE_TOKEN")" 2>/dev/null || true
2712    if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
2713      case "$MEMORIA" in "${XDG_DATA_HOME:-$HOME/.local/share}"/delminio/*/memoria) rm -rf "$(dirname "$MEMORIA")"
2714        echo "$M_tolto_clone_memorie" ;; esac
2715    fi
2716    wt=$(git worktree list --porcelain | grep -c '^branch refs/heads/sessione/' || true)
2717    [ "$wt" -gt 0 ] && _f "$M_restano_worktree_sessioni" wt "$wt"
2718    echo "$M_staccato_cli_torna"
2719    [ -n "$personali" ] && _f "$M_tue_personali" personali "$personali"
2720    [ -n "$prima" ] && _f "$M_copia_prima_resta" prima "$prima"
2721    rm -f .claude/delminio.sh
2722    exit 0
2723    ;;
2724  accetta)
2725    { exec 3</dev/tty; } 2>/dev/null || { echo "$M_accetta_lancia_terminale" >&2; exit 1; }
2726    DELMINIO_ALBERO="$(git rev-parse --show-toplevel)" python3 - <<'SCRIPT'
2727import os
2728exec(os.environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2729exec(os.environ["DELMINIO_FIDATI_PY"])
2730albero = os.environ["DELMINIO_ALBERO"]
2731gia = accettati(albero)
2732fermi = [f for f in script_del_progetto(albero, ("apertura", "opening", "dove-siamo", "status")) + lascito_del_progetto(albero)
2733         if not da_fidarsi(albero, f, gia)]
2734if fermi:
2735    tty_in, tty = open("/dev/tty"), open("/dev/tty", "w")
2736    tty.write(F("accetta_script_elenco"))
2737    for f in fermi:
2738        chi, quando = di_chi(albero, f)
2739        righe = sum(1 for _ in open(f, encoding="utf-8", errors="replace"))
2740        tty.write(F("accetta_script_riga", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, righe=righe) + "\n")
2741    tty.write(F("accetta_script_domanda"))
2742    tty.flush()
2743    r, scelti = tty_in.readline().strip().lower(), []
2744    if r in F("accetta_script_tutti_si").split():
2745        scelti = fermi
2746    elif r in F("accetta_script_uno_si").split():
2747        for f in fermi:
2748            chi, quando = di_chi(albero, f)
2749            testo = open(f, encoding="utf-8", errors="replace").read()
2750            tty.write(F("accetta_script_uno", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, testo=testo[:4000]))
2751            tty.flush()
2752            if tty_in.readline().strip().lower() in F("accetta_si").split():
2753                scelti.append(f)
2754    if scelti:
2755        with open(accettati_file(albero), "w", encoding="utf-8") as out:
2756            out.write("".join(x + "\n" for x in sorted(gia | {impronta_script(albero, f) for f in scelti})))
2757    print(F("script_accettati", nuovi=len(scelti), fermi=len(fermi) - len(scelti)))
2758SCRIPT
2759    if [ -f "$(dirname "$0")/squadra.py" ]; then python3 "$(dirname "$0")/squadra.py" accetta || true; fi
2760    if [ -f "$(dirname "$0")/eseguibili.py" ]; then
2761      python3 "$(dirname "$0")/eseguibili.py" accetta && [ -z "${DELMINIO_PROVA:-}" ] && allinea_staccato || true
2762    fi
2763    tutti=$(chiedi GET /api/lock) || { echo "❌ $(perche_no)" >&2; exit 1; }
2764    DELMINIO_LOCK="$tutti" DELMINIO_ACCETTATE="$(accettate_file)" python3 - <<'ACCETTA'
2765import hashlib, json, os
2766exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
2767tutti = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
2768lock = [l for l in tutti if (l.get("duro") or l.get("firme")) and l.get("comando")]
2769prima = [l for l in tutti if l.get("comando_gesto")]   # su comandi e strumenti (F903)
2770f = os.environ["DELMINIO_ACCETTATE"]
2771try:
2772    accettate = set(open(f, encoding="utf-8").read().split())
2773except OSError:
2774    accettate = set()
2775tty_in, tty = open("/dev/tty"), open("/dev/tty", "w")   # r+ vuole un seek, e un terminale non lo ha
2776nuove = 0
2777for l in lock:
2778    h = hashlib.sha256((l["codice"] + "\0" + l["comando"]).encode()).hexdigest()
2779    if h in accettate:
2780        continue
2781    tty.write(F("accetta_domanda", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", comando=l["comando"]))
2782    tty.flush()
2783    if tty_in.readline().strip().lower() in F("accetta_si").split():
2784        accettate.add(h); nuove += 1
2785for l in prima:
2786    h = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + l["comando_gesto"]).encode()).hexdigest()
2787    if h in accettate:
2788        continue
2789    gesti = ", ".join((l.get("gesti") or []) + (l.get("strumenti") or []))
2790    tty.write(F("accetta_domanda_gesto", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", gesti=gesti, comando=l["comando_gesto"]))
2791    tty.flush()
2792    if tty_in.readline().strip().lower() in F("accetta_si").split():
2793        accettate.add(h); nuove += 1
2794with open(f, "w", encoding="utf-8") as out:
2795    out.write("".join(x + "\n" for x in sorted(accettate)))
2796print(F("accettate", nuove=nuove, tutte=len(accettate), file=f))
2797ACCETTA
2798    ;;
2799  commit-msg|post-rewrite|post-commit|post-rewrite-dopo|post-commit-dopo)
2800    parte ganci-git.sh && . "$(dirname "$0")/ganci-git.sh" "$@"
2801    ;;
2802  errore)
2803    [ -f "$(dirname "$0")/eseguibili.py" ] || exit 0
2804    evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
2805    [ -n "$evento" ] || exit 0
2806    pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid" 2>/dev/null || true)
2807    printf '%s' "$evento" | DELMINIO_SESSIONE_NOME="$nome" _tempo 4 python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori-registra >/dev/null 2>&1 || true
2808    exit 0
2809    ;;
2810  errori)
2811    shift; exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori "$@"
2812    ;;
2813  pulizia)
2814    [ -n "${DELMINIO_CONVERSAZIONI:-}" ] || exit 0
2815    exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" pulizia
2816    ;;
2817  ponte)
2818    DELMINIO_T="$TOKEN" exec bash "$0" ponte-mcp "$URL"
2819    ;;
2820  ponte-mcp)
2821    programma=$(cat <<'PONTE'
2822import json, os, sys, time, urllib.error, urllib.request
2823
2824URL = sys.argv[1].rstrip("/") + "/mcp"
2825TESTA = {"Authorization": "Bearer " + os.environ.pop("DELMINIO_T", ""),
2826         "X-Delminio-Modello": os.environ.get("DELMINIO_MODELLO", ""),
2827         "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
2828MUTO = os.environ.get("DELMINIO_PONTE_MUTO", "Delminio non risponde.")
2829RIFIUTO = os.environ.get("DELMINIO_PONTE_RIFIUTO", "HTTP {codice}")
2830stato = {"sessione": None, "versione": "2025-06-18"}
2831
2832
2833def _sessione():
2834    try:
2835        with open(os.environ.get("DELMINIO_SESSIONE_FILE") or "/nonesiste", encoding="utf-8") as f:
2836            return f.read().strip()[:40]
2837    except OSError:
2838        return ""
2839
2840
2841def manda(msg, timeout=120):
2842    h = dict(TESTA)
2843    if s := _sessione():
2844        h["X-Delminio-Sessione"] = s
2845    if stato["sessione"]:
2846        h["Mcp-Session-Id"] = stato["sessione"]
2847        h["MCP-Protocol-Version"] = stato["versione"]
2848    r = urllib.request.Request(URL, data=json.dumps(msg).encode(), headers=h, method="POST")
2849    with urllib.request.urlopen(r, timeout=timeout) as risp:
2850        sid, tipo = risp.headers.get("mcp-session-id"), risp.headers.get("content-type", "")
2851        corpo = risp.read().decode("utf-8", "replace")
2852    if "id" not in msg:
2853        return None, sid
2854    if tipo.startswith("text/event-stream"):
2855        for riga in corpo.splitlines():
2856            if riga.startswith("data:"):
2857                d = json.loads(riga[5:].strip())
2858                if d.get("id") == msg["id"]:
2859                    return d, sid
2860        raise OSError("lo stream non porta la risposta")
2861    return json.loads(corpo), sid
2862
2863
2864def apri():
2865    stato["sessione"] = None
2866    d, sid = manda({"jsonrpc": "2.0", "id": "ponte", "method": "initialize",
2867                    "params": {"protocolVersion": stato["versione"], "capabilities": {},
2868                               "clientInfo": {"name": "delminio-ponte", "version": "1"}}}, 15)
2869    stato["sessione"], stato["versione"] = sid, d["result"].get("protocolVersion", stato["versione"])
2870    manda({"jsonrpc": "2.0", "method": "notifications/initialized"}, 15)
2871    return d["result"]
2872
2873
2874def chiedi(metodo, params, tentativi):
2875    """La domanda al motore; a un errore riapre la sessione e riprova (il motore
2876    riavviato non conosce più la sessione di prima)."""
2877    for n in range(tentativi):
2878        try:
2879            if stato["sessione"] is None:
2880                apri()
2881            d, _ = manda({"jsonrpc": "2.0", "id": "p", "method": metodo, "params": params})
2882            return d   # anche un errore JSON-RPC: è del motore, non della sessione
2883        except urllib.error.HTTPError as e:
2884            if e.code in (401, 403):
2885                return {"result": {"content": [{"type": "text", "text": RIFIUTO.replace("{codice}", str(e.code))}],
2886                                   "isError": True}}
2887        except Exception:  # noqa: BLE001
2888            pass
2889        stato["sessione"] = None
2890        time.sleep(min(2 * (n + 1), 6))
2891    return None
2892
2893
2894inizio = tools = None
2895for n in range(8):
2896    try:
2897        inizio = apri()
2898        tools = manda({"jsonrpc": "2.0", "id": "t", "method": "tools/list", "params": {}})[0]["result"]["tools"]
2899        break
2900    except Exception:  # noqa: BLE001
2901        time.sleep(1)
2902inizio = inizio or {"serverInfo": {"name": "Delminio", "version": "?"}}
2903VUOTI = {"prompts/list": "prompts", "resources/list": "resources",
2904         "resources/templates/list": "resourceTemplates"}
2905
2906for riga in sys.stdin:
2907    try:
2908        m = json.loads(riga)
2909    except ValueError:
2910        continue
2911    if "id" not in m:
2912        continue   # le notifiche di Qwen non servono al motore
2913    metodo, rid = m.get("method"), m["id"]
2914    if metodo == "initialize":
2915        res = {"protocolVersion": m.get("params", {}).get("protocolVersion", stato["versione"]),
2916               "capabilities": {"tools": {"listChanged": False}},
2917               "serverInfo": inizio.get("serverInfo"), "instructions": inizio.get("instructions", "")}
2918    elif metodo == "tools/list":
2919        res = {"tools": tools or []}
2920    elif metodo == "tools/call":
2921        d = chiedi("tools/call", m.get("params", {}), 4)
2922        if d is not None and "error" in d:
2923            print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": d["error"]}, ensure_ascii=False), flush=True)
2924            continue
2925        res = (d or {}).get("result") or {"content": [{"type": "text", "text": MUTO}], "isError": True}
2926    elif metodo in VUOTI:
2927        res = {VUOTI[metodo]: []}
2928    elif metodo == "ping":
2929        res = {}
2930    else:
2931        print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": metodo}}), flush=True)
2932        continue
2933    print(json.dumps({"jsonrpc": "2.0", "id": rid, "result": res}, ensure_ascii=False), flush=True)
2934PONTE
2935)
2936    p_cli=$(cli_pid || true)
2937    DELMINIO_SESSIONE_FILE="${p_cli:+$STATO/sessione-$p_cli}" \
2938    DELMINIO_PONTE_MUTO="$M_ponte_muto" DELMINIO_PONTE_RIFIUTO="$(_f "$M_perche_token" url "${2:-$URL}" codice "{codice}")" \
2939      exec python3 -c "$programma" "${2:-$URL}"
2940    ;;
2941  riaggancia-fratelli)
2942    serve=${2:-}; [ -n "$serve" ] || exit 0
2943    qui=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd -P)
2944    python3 - "$qui" "$URL" "$serve" "${DELMINIO_CERCA_IN:-}" <<'FRATELLI' | while IFS=$'\t' read -r dove tf suo; do
2945import os, shlex, sys
2946qui, url, serve = sys.argv[1:4]
2947radici = [os.path.dirname(qui), os.path.expanduser("~")] + [x for x in sys.argv[4].split(":") if x]
2948visti = {os.path.realpath(qui)}
2949for radice in radici:
2950    for d, sotto, _ in os.walk(radice):
2951        livello = d[len(radice):].count(os.sep)
2952        c = os.path.join(d, ".claude", "delminio.sh")
2953        if os.path.isdir(os.path.join(d, ".git")) and os.path.isfile(c) and os.path.realpath(d) not in visti:
2954            visti.add(os.path.realpath(d))
2955            testa = {}
2956            try:
2957                for i, riga in zip(range(30), open(c, encoding="utf-8", errors="replace")):
2958                    k, _, v = riga.strip().partition("=")
2959                    if k in ("URL", "FILE_TOKEN", "KIT") and v and k not in testa:
2960                        testa[k] = (shlex.split(v) or [""])[0]
2961            except (OSError, ValueError):
2962                continue
2963            if testa.get("URL", "").rstrip("/") == url.rstrip("/") and testa.get("KIT") != serve and testa.get("FILE_TOKEN"):
2964                print(os.path.realpath(d) + "\t" + testa["FILE_TOKEN"] + "\t" + testa.get("KIT", ""))
2965        sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
2966FRATELLI
2967      [ -r "$tf" ] || continue
2968      TOKEN=$(cat "$tf") KIT="${suo:-?}" riaggancia "$serve" "$dove" presto
2969      echo "$dove"
2970    done
2971    ;;
2972  clona)
2973    nome="${2:-}"; [ -n "$nome" ] && [ "$nome" != --no ] || { echo "$M_uso_clona" >&2; exit 2; }
2974    qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
2975    r=$(chiedi GET /api/repo/spazio) || { echo "❌ $(perche_no)" >&2; exit 1; }
2976    riga=$(printf '%s' "$r" | python3 -c 'import json,re,sys
2977n = sys.argv[1]
2978ok = lambda c: bool(re.fullmatch(r"[\w.-]+", c)) and c not in (".", "..") and not c.startswith("-")
2979for x in json.load(sys.stdin).get("repo") or []:
2980    if n in (x.get("nome"), x.get("chiave")):
2981        k = str(x.get("chiave") or "")
2982        c = str(x.get("nome") or "")
2983        if not ok(c):
2984            c = re.split(r"[/:]", k.rstrip("/"))[-1].removesuffix(".git")
2985        print(k); print(c if ok(c) else ""); break' "$nome")
2986    { read -r chiave; read -r cartella; } <<<"$riga"
2987    [ -n "$chiave" ] && [ -n "$cartella" ] || { _f "$M_clona_non_dello_spazio" nome "$nome" >&2; exit 1; }
2988    if [ "${3:-}" = --no ]; then
2989      DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" "$chiave" <<'REPO_NO_SCRIVI' || exit 1
2990import json, os, sys
2991f, chiave = sys.argv[1], sys.argv[2]
2992try:
2993    d = json.load(open(f, encoding="utf-8"))
2994except (OSError, ValueError):
2995    d = {}
2996d = d if isinstance(d, dict) else {}
2997v = [x for x in d.get(os.environ["DELMINIO_CHI"]) or [] if x != chiave] + [chiave]
2998d[os.environ["DELMINIO_CHI"]] = v
2999os.makedirs(os.path.dirname(f), exist_ok=True)
3000nuovo = f + ".nuovo"
3001with open(nuovo, "w", encoding="utf-8") as h:
3002    json.dump(d, h, ensure_ascii=False, indent=1)
3003os.replace(nuovo, f)
3004REPO_NO_SCRIVI
3005      _f "$M_clona_no" nome "$nome"; exit 0
3006    fi
3007    url=$(python3 - "$(git -C "$qui" remote get-url origin 2>/dev/null)" "$chiave" <<'CLONA_URL'
3008import sys
3009PUBBLICI = {"github.com", "gitlab.com", "codeberg.org", "bitbucket.org", "gitea.com", "git.sr.ht"}
3010def parti(u):
3011    """(host, percorso, come si rifà l'indirizzo con un altro percorso)"""
3012    if "://" in u:
3013        schema, resto = u.split("://", 1)
3014        autorita, _, percorso = resto.partition("/")
3015        return autorita.rsplit("@", 1)[-1].split(":", 1)[0].lower(), percorso, lambda q: f"{schema}://{autorita}/{q}"
3016    if ":" in u and not u.startswith("/"):
3017        testa, _, percorso = u.partition(":")
3018        return testa.split("@", 1)[-1].lower(), percorso, lambda q: f"{testa}:{q}"
3019    return "", u, None
3020origine, chiave = sys.argv[1], sys.argv[2]
3021ho, po, rifai = parti(origine)
3022ht, pt, _ = parti(chiave)
3023pt = pt.strip("/")
3024if rifai and ht and pt and (ht == ho or (ht not in PUBBLICI and ho not in PUBBLICI)):
3025    print(rifai(pt.removesuffix(".git") + (".git" if po.rstrip("/").endswith(".git") else "")))
3026else:
3027    print(chiave)
3028CLONA_URL
3029)
3030    dove="$(dirname "$qui")/$cartella"
3031    if [ -e "$dove" ]; then
3032      if [ -d "$dove/.git" ] && corpo=$(python3 -c 'import json,sys; print(json.dumps({"remoti": [sys.argv[1]]}))' "$(_remoto "$dove")") \
3033         && r2=$(chiedi POST /api/repo/riconosci "$corpo") \
3034         && printf '%s' "$r2" | python3 -c 'import json,sys
3035sys.exit(0 if any(x.get("chiave") == sys.argv[1] and x.get("trovati") for x in json.load(sys.stdin)["repo"]) else 1)' "$chiave"; then
3036        _collega_clone "$nome" "$dove"; exit $?
3037      fi
3038      _f "$M_clona_occupata" dove "$dove" >&2; exit 1
3039    fi
3040    _f "$M_clona_in_corso" nome "$nome" url "$url" dove "$dove"
3041    log="$STATO/clona-$$.log"
3042    if ! GIT_TERMINAL_PROMPT=0 _tempo 600 git clone -q -- "$url" "$dove" > "$log" 2>&1; then
3043      errore_log=$(grep -v '^[[:space:]]*$' "$log" | tail -1 | cut -c1-200); rm -f "$log"
3044      _f "$M_clona_fallito" nome "$nome" url "$url" errore "$errore_log" >&2; exit 1
3045    fi
3046    rm -f "$log"
3047    _collega_clone "$nome" "$dove"
3048    ;;
3049  agganciali)
3050    qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
3051    trovati=$(python3 - "$qui" "${DELMINIO_CERCA_IN:-}" <<'CERCA'
3052import json, os, subprocess, sys
3053qui, altre = sys.argv[1], [x for x in sys.argv[2].split(":") if x]
3054radici = [os.path.dirname(qui), os.path.expanduser("~")] + altre
3055visti, cloni = set(), []
3056for radice in radici:
3057    for d, sotto, _ in os.walk(radice):
3058        livello = d[len(radice):].count(os.sep)
3059        if ".git" in sotto and os.path.isdir(os.path.join(d, ".git")):   # un clone, non un worktree
3060            p = os.path.realpath(d)
3061            if p not in visti:
3062                visti.add(p)
3063                r = subprocess.run(["git", "-C", d, "remote", "get-url", "origin"], capture_output=True, text=True)
3064                if r.returncode == 0 and r.stdout.strip():
3065                    cloni.append((p, r.stdout.strip()))
3066        sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
3067print(json.dumps({"cloni": cloni}))
3068CERCA
3069)
3070    corpo=$(printf '%s' "$trovati" | python3 -c 'import json,re,sys
3071c = json.load(sys.stdin)["cloni"]
3072print(json.dumps({"remoti": [re.sub(r"^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@", r"\1", r) for _, r in c]}))')
3073    r=$(chiedi POST /api/repo/riconosci "$corpo") || { echo "❌ $(perche_no)" >&2; exit 1; }
3074    elenco=$(DELMINIO_CLONI="$trovati" python3 -c 'import json,os,sys
3075cloni = json.loads(os.environ["DELMINIO_CLONI"])["cloni"]
3076for x in json.load(sys.stdin)["repo"]:
3077    dove = [cloni[i][0] for i in x["trovati"]]
3078    print(x["nome"] + "\t" + (dove[0] if dove else ""))' <<< "$r")
3079    [ -n "$elenco" ] || { echo "$M_spazio_repo_aggiunge"; exit 0; }
3080    echo "$M_repo_dello_spazio"
3081    falliti=0
3082    while IFS=$'\t' read -r nome dove; do
3083      if [ -z "$dove" ]; then _f "$M_clonato_qui" nome "$nome"; continue; fi
3084      if [ -x "$dove/.claude/delminio.sh" ]; then _f "$M_gia_collegato" nome "$nome" dove "$dove"; continue; fi
3085      _collega_clone "$nome" "$dove" || falliti=$((falliti + 1))
3086    done <<< "$elenco"
3087    [ "$falliti" -eq 0 ]
3088    ;;
3089  carta)
3090    shift
3091    pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
3092    DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_SESSIONE="$sess" DELMINIO_STATO="$STATO" \
3093      python3 "$(cd "$(dirname "$0")" && pwd)/firme.py" "$@"
3094    ;;
3095  perche)
3096    dove="${2:-}"
3097    case "$dove" in *:[0-9]*) ;; *) echo "$M_uso_bash_claude" >&2; exit 2 ;; esac
3098    DELMINIO_U="$URL" DELMINIO_T="$TOKEN" python3 - "$dove" <<'PERCHE'
3099import json, os, shlex, subprocess, sys, urllib.parse, urllib.request
3100exec(__import__("os").environ["DELMINIO_F_PY"])   # F(): le frasi del client (F665)
3101f, _, riga = sys.argv[1].rpartition(":")
3102q = shlex.quote
3103
3104def g(*a):
3105    return subprocess.run(["git", *a], capture_output=True, text=True)
3106
3107def delminio(q):
3108    req = urllib.request.Request(os.environ["DELMINIO_U"] + "/api/perche?" + urllib.parse.urlencode(q),
3109                                 headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"]})
3110    return json.loads(urllib.request.urlopen(req, timeout=8).read())
3111
3112b = g("blame", "-L", f"{riga},{riga}", "--porcelain", "--", f)
3113if b.returncode:
3114    sys.exit(f"❌ {b.stderr.strip()}")
3115h = b.stdout.split()[0]
3116if set(h) == {"0"}:
3117    sys.exit(print(F("perche_non_committata", dove=f"{f}:{riga}")))
3118info = g("log", "-1", "--date=short", "--format=%h%x00%an%x00%ad%x00%s%x00%(trailers:key=Delminio-Sessione,valueonly)", h)
3119corto, autore, data, soggetto, sess = (info.stdout.split("\0") + [""] * 5)[:5]
3120print(F("perche_commit", dove=f"{f}:{riga}", commit=corto, data=data, autore=autore, soggetto=soggetto))
3121sess = (sess.strip().splitlines() or [""])[0].strip()
3122if not sess:
3123    print(F("perche_senza_sessione", commit=corto))
3124    sys.exit(0)
3125try:
3126    r = delminio({"sessione": sess})
3127except Exception as e:
3128    sys.exit(print(F("perche_sessione_muto", sessione=sess, errore=e)))
3129agente = f" ({r['agente']})" if r.get("agente") else ""
3130con = F("perche_con", chi=r["chi"]) if r.get("chi") else ""
3131nata = F("perche_nata", data=r["nata"][:10]) if r.get("nata") else ""
3132print(F("perche_sessione", sessione=r["sessione"], agente=agente, chi=con, nata=nata))
3133c = r.get("chiusura")
3134h = (c or {}).get("hash") or ""
3135if c and not (7 <= len(h) <= 40 and all(x in "0123456789abcdef" for x in h)):
3136    c = None
3137if not c:
3138    sys.exit(print(F("perche_senza_chiusura", sessione=sess)))
3139qui = g("cat-file", "-e", f"{c['hash']}^{{commit}}").returncode == 0
3140in_repo = F("perche_in_repo", repo=c["repo"]) if c.get("repo") else ""
3141comando = (f"git show {q(c['hash'])}" if qui or not c.get("remoto")
3142           else f"git fetch -q {q(c['remoto'])} && git show {q(c['hash'])}")
3143print(F("perche_chiusa", data=(c.get("quando") or "?")[:10], commit=c["hash"], repo=in_repo, comando=comando))
3144mem = g("log", "-1", "--format=%(trailers:" + ",".join("key=" + k for k in os.environ["P_TRAILER_MEMORIA"].split("|"))
3145        + ",valueonly)", c["hash"]).stdout.strip() if qui else ""
3146primo = mem.split()[0] if mem else ""
3147if primo and all(x in "0123456789abcdef" for x in primo) and len(primo) >= 7:
3148    try:
3149        nomi = delminio({"sessione": sess, "memoria": primo}).get("memorie")
3150    except Exception:
3151        nomi = None
3152    if nomi:
3153        print(F("perche_memorie") + "\n" + "\n".join(f"     · {n}" for n in nomi))
3154    elif nomi == []:
3155        print(F("perche_nessuna_memoria"))
3156    else:
3157        print(F("perche_memorie_nel_commit", commit=primo))
3158elif mem:
3159    print(F("perche_le_memorie", memorie=mem))
3160PERCHE
3161    ;;
3162  ""|aiuto|-h|--help) echo "$M_aiuto" ;;
3163  *) _f "$M_comando_sconosciuto" nome "$1" >&2; echo "$M_aiuto" >&2; exit 2 ;;
3164esac