Delminio 2026.11.26-7fac9ff 2026.11.26-7fac9ff
26 Nov 2026 · 800f3006668cd3167728ebadf7342ef3d893dce9
CHANGELOG.md | 624 +++++++ FIRMA | 23 + FIRMA.sig | 6 + README.md | 88 + SECURITY.md | 24 + agent/aggancia.en.md | 191 ++ agent/aggancia.md | 374 ++++ agent/stacca.en.md | 76 + agent/stacca.md | 126 ++ enterprise/INFORMATIVA.md | 100 ++ enterprise/INSTALLA.en.md | 177 ++ enterprise/INSTALLA.md | 320 ++++ enterprise/LEGGIMI.en.md | 88 + enterprise/LEGGIMI.md | 218 +++ enterprise/LICENZA.md | 284 +++ enterprise/TERZE-PARTI.md | 92 + enterprise/docker-compose.yml | 78 + enterprise/frasi.en.sh | 107 ++ enterprise/installa.sh | 500 ++++++ kit/en/aggancia.sh | 1131 ++++++++++++ kit/en/cantiere-client | 535 ++++++ kit/en/cassaforte-client | 625 +++++++ kit/en/consumi-client | 477 +++++ kit/en/copia-client | 286 +++ kit/en/delminio-client | 3164 +++++++++++++++++++++++++++++++++ kit/en/eseguibili-client | 3884 +++++++++++++++++++++++++++++++++++++++++ kit/en/firme-client | 1357 ++++++++++++++ kit/en/ganci-git-client | 224 +++ kit/en/lanciatori-client | 230 +++ kit/en/opencode-client.js | 174 ++ kit/en/plugin-client | 474 +++++ kit/en/squadra-client | 753 ++++++++ kit/en/worktree-client | 71 + kit/it/aggancia.sh | 1131 ++++++++++++ kit/it/cantiere-client | 535 ++++++ kit/it/cassaforte-client | 625 +++++++ kit/it/consumi-client | 477 +++++ kit/it/copia-client | 286 +++ kit/it/delminio-client | 3164 +++++++++++++++++++++++++++++++++ kit/it/eseguibili-client | 3884 +++++++++++++++++++++++++++++++++++++++++ kit/it/firme-client | 1357 ++++++++++++++ kit/it/ganci-git-client | 224 +++ kit/it/lanciatori-client | 230 +++ kit/it/opencode-client.js | 174 ++ kit/it/plugin-client | 474 +++++ kit/it/squadra-client | 753 ++++++++ kit/it/worktree-client | 71 + 47 files changed, 30266 insertions(+)
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..d8e1a1b
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,624 @@
+# Changelog
+
+What changes in each version of Delminio. The number has three parts: the
+first changes when an update asks for an extra step from the person who installs it,
+the second when a new feature arrives, the third for fixes. Delminio Cloud and
+your own installations share the same numbers. You find yours in
+[Settings](https://delminio.com/en/guide/settings), in the licence card.
+The versions of the same week sit under one heading.
+
+
+## Week of 23 November 2026
+
+### 2.0.1 — 26 November 2026
+
+- **Fixed**: a Claude Code chat sent to the background, or copied into a new one, keeps the name it had, instead of taking a new one and leaving the first without a handoff; and a background chat nobody uses no longer takes a name or greets the other sessions. The chat left behind stops receiving the messages of the one that carries on.
+- **Changed**: in the first steps the button says “Continue with these”; on this page the index lists only the weeks.
+
+### 2.0.0 — 26 November 2026
+
+- **New**: Delminio Enterprise is downloaded from our registry, `registry.delminio.com`, with the username and password we give you: `docker login` once, then the installation and every update take the version from there, like any other container software. Next to every version there is its signature, which the person installing checks with the key in the contract before running it (INSTALLA.en.md). The package delivered by hand is gone.
+- **Changed**: the image is called `registry.delminio.com/delminio`, instead of the label used before. The update asks for the extra step of `docker login`, which is why the first number becomes 2.
+
+### 1.40.3 — 26 November 2026
+
+- **Fixed**: a memory that cites a file the project keeps out of git (a log, data, a cache) is no longer flagged as citing a file that has disappeared.
+
+### 1.40.2 — 26 November 2026
+
+- **Fixed**: a member proposing a [team plugin](https://delminio.com/en/guide/plugins#the-teams-plugins) from the **Plugins** view got “admin only” instead of sending the proposal.
+
+### 1.40.1 — 26 November 2026
+
+- **Fixed**: on the phone the repository and exception cards no longer run off the right edge when an address is long.
+- **Fixed**: in the Decisions view, when a repository has changed address, the menu for saying which repository it has become starts empty: Link turns on only after you choose.
+
+### 1.40.0 — 26 November 2026
+
+- **New**: a member can propose a [team plugin](https://delminio.com/en/guide/plugins#the-teams-plugins), or removing one, from the **Plugins** view. The proposal reaches the admin with the marketplace, where it comes from and the CLIs, and only the admin decides, from the app.
+- **Fixed**: [sign-offs in the CI](https://delminio.com/en/guide/change-sign-off) on Forgejo and Gitea. The required check to ask for in the branch rule is named “delminio-firme / controlla (pull_request)”: with “controlla”, as `delminio signoffs ci` said, merging stayed blocked even with the sign-offs. The command and the guide also say to turn off direct push and to apply the rule to administrators.
+
+### 1.39.2 — 26 November 2026
+
+- **Fixed**: a repository that changes address no longer leaves its [protected decisions](https://delminio.com/en/guide/protected-decisions#a-decision-in-one-repository-only) behind: those that apply only there, and the sign-off zones, name the old address, and Delminio remembers it as an address of the same repository. Before, they stopped applying without saying so. If the move happened before this version, the Decisions view flags it at the top, and the admin picks which repository it has become.
+
+### 1.39.1 — 26 November 2026
+
+- **Improved**: of the project you mount read-only, Delminio looks only at file names, to tell you when a memory cites a file that is no longer there. If it finds the `.git` folder, it takes those names from git: mounting that is enough, and files that are not in git, such as those holding secrets, Delminio does not see. Without `.git` it looks at the folder as before.
+
+### 1.39.0 — 25 November 2026
+
+- **Changed**: requests for an exception to a [protected decision](https://delminio.com/en/guide/protected-decisions#exceptions) are at the top of the Decisions item, next to the decision that stopped them, and no longer in the Backlog, which now holds only the work. The phone notification opens there, and the Exceptions item of the menu has moved under Decisions. In the Dashboard they stay, with the same buttons.
+- **Fixed**: someone who signs in and belongs to more than one space chooses where to go by the space's name, no longer by its code.
+
+### 1.38.0 — 25 November 2026
+
+- **New**: the [change sign-off](https://delminio.com/en/guide/change-sign-off#the-trail-for-the-people-who-verify) report also comes out as a page to read and print to PDF, if the file ends in `.html`, or as a table for programs, if it ends in `.csv`: the page for your auditor, the table to upload to the compliance platform you use.
+- **Improved**: an OpenCode agent on your own model no longer calls outside your network: OpenCode uses the model list built into it instead of downloading it from models.opencode.ai at every start, and conversation sharing is off. With OpenCode's free models the list is still downloaded, because it changes every few days.
+
+### 1.37.0 — 25 November 2026
+
+- **New**: in [change sign-offs](https://delminio.com/en/guide/change-sign-off#urgent-changes), urgent changes: when a fix cannot wait for the sign-offs, the administrator lets it in from the app with the reason, the CI lets it through and calls it urgent, and the sign-offs are given afterwards. It stays visible under Sign-offs and in the report for the people who verify.
+
+### 1.36.0 — 25 November 2026
+
+- **New**: in [change sign-offs](https://delminio.com/en/guide/change-sign-off#in-a-ci), on GitHub `delminio signoffs ci` sets by itself the main-branch rule that stops a merge without the check, for administrators too, if it finds the GitHub CLI signed in to an admin of the repository. You paste the secret in the terminal yourselves: an agent never sees the key.
+- **New**: under Sign-offs every repository with sign-offs shows the last day a CI checked it, and warns if it never happened or more than two weeks have passed.
+- **Fixed**: with more than one space, under your name at the bottom of the menu you see the name you gave the space, not its code.
+- **Fixed**: in English, the default role is called “main” where the app shows it (Agents, Agent roles).
+
+### 1.35.5 — 25 November 2026
+
+- **Changed**: on this page the versions of the same week sit under one heading, and each keeps its own address.
+- **Fixed**: in the [first steps](https://delminio.com/en/guide/first-steps), “First install OpenCode” with the free models stopped right after installing the CLI: it now starts with the chosen model and the connection guide. And the CLI it installs stays on the version chosen in Delminio, without updating itself on first start.
+
+### 1.35.4 — 25 November 2026
+
+- **Changed**: the Terms for personal use (1.3) say that the repository receives the memories everyone in the space can see, not all content: personal memories and those reserved to the admin do not go there. If you had accepted them, you accept them again the next time you sign in.
+- **Changed**: the Privacy notice for people (0.8) states backups in one line, with their 60-day maximum.
+- **Changed**: for teams, the Terms (1.8) and the Processor agreement (1.6) say that the repository holds the copy of the shared memories, and that for the others the service is the record; the log keeps operations for 90 days and the client's automatic repeated reads for 30.
+- **Changed**: the conditions of [change sign-offs](https://delminio.com/en/guide/change-sign-off) state everything Delminio keeps and for how long: as long as the space exists. If you accepted them, you accept them again.
+- **Changed**: the [vault](https://delminio.com/en/guide/vault) and [sign-off](https://delminio.com/en/guide/change-sign-off) guides state, in their limits, that like any web app they depend on the server that serves them, and the remedy.
+
+### 1.35.3 — 25 November 2026
+
+- **Changed**: two English commands have clearer names: `domains` is now `focus`, and `vault windows` is now `vault access`. The old names still work.
+
+### 1.35.2 — 25 November 2026
+
+- **Fixed**: in [change sign-offs](https://delminio.com/en/guide/change-sign-off#in-a-ci), the check in the CI speaks your space's language: the file `delminio signoffs ci` writes downloads the client with the read-only key. Before it always spoke Italian. If you already have the file, rewrite it with `delminio signoffs ci`.
+- **Fixed**: in the check's count, a commit that touches a sign-off zone without sign-offs now appears under “no sign-offs recorded”.
+- **Fixed**: before adding a passkey, confirming who you are with the button in the email now works like entering the code. Before, it took you back to the Dashboard and the confirmation was lost.
+- **Fixed**: a review asked from a terminal outside a session says why it isn't recorded, instead of just the usage line.
+- **Fixed**: a decision with a check before the command runs it in the repository where the command really runs (`cd other-repo && …`), not in the one the agent is open in.
+
+### 1.35.1 — 25 November 2026
+
+- **Fixed**: when your agent reads a [decision](https://delminio.com/en/guide/protected-decisions#a-decision-in-one-repository-only) that applies only in some repositories, it now also sees which ones. The decision already fired only there: the list was missing from what the agent reads.
+- **Fixed**: the summary of a change to a decision, and the decision as the agent reads it, use the app's words: “Verified by” and “What the agent uses instead”.
+
+### 1.35.0 — 24 November 2026
+
+- **New**: a [decision](https://delminio.com/en/guide/protected-decisions#a-decision-in-one-repository-only) can apply only in some of the space's repositories, up to 20, and doesn't fire in the others. You choose them in the Decisions view, under “Applies only in these repositories”.
+
+### 1.34.1 — 24 November 2026
+
+- **Fixed**: at the end of a connection the terminal says the space's name and your name with your role; before it said the space's code, your login and the role as written in the code.
+- **Fixed**: in Agents, each computer shows the name the person has in the space, not their login.
+- **Fixed**: on a [decision](https://delminio.com/en/guide/protected-decisions) that stops you too, shortening the time allowed for the check before a command comes as a proposal to approve, even when your agent asks for it with your token. Before it applied at once, and a check slower than the new time was skipped.
+- **Fixed**: in the Decisions view, the time for the check left empty stays the default; before, saving any other change fixed it at 5 seconds.
+- **Fixed**: in [change sign-offs](https://delminio.com/en/guide/change-sign-off#in-a-ci), when git in the CI can't find the commits to check (after a force push to the main branch, or without the whole history) the check goes red and says which range it can't read. Before it said “no commits” and passed.
+- **Fixed**: the same passkey confirmation, sent a second time, no longer counts. With synced passkeys (iCloud, Google), which don't count signatures, it counted again for the request's five minutes.
+- **Fixed**: at closing, the lines `/closing` generates for “Where we are” count as generated even when the agent rewrites them or joins them into one: before, they became the agent's own lines, went over the limit and the handoff came back.
+
+### 1.34.0 — 24 November 2026
+
+- **Changed**: a blocking decision now stops the commit or the command when its check does not start; before, it let it through with a warning. Before a command, a slow check lets it through as before, but each decision can choose to block, and the time can be set up to 30 seconds.
+
+### 1.33.1 — 24 November 2026
+
+- **Fixed**: the notification for a new passkey opened [change sign-off](https://delminio.com/en/guide/change-sign-off) even in a space that only has the [vault](https://delminio.com/en/guide/vault#the-passkey), where the page said “Not Found”. Now it opens the Vault.
+
+### 1.33.0 — 24 November 2026
+
+- **New**: in the [Vocabulary](https://delminio.com/en/guide/vocabulary), a field for **the mark on messages between sessions**, the word in angle brackets with which agents receive messages from other sessions. By default it is `messages-from-other-sessions`, in Italian `messaggi-dalle-altre-sessioni`; if you want your own, write it there.
+- **Changed**: at the top of a linked memory the mark is `_Part of [[…]]_`, in Italian `_Parte di [[…]]_`. Delminio also recognises the earlier one, and memories already written stay as they are.
+- **Changed**: in [change sign-off](https://delminio.com/en/guide/change-sign-off#the-trail-for-the-people-who-verify) commits carry the lines in English, `Delminio-Request` and `Delminio-Chain`, because the people who verify read the commits; the earlier ones, `Delminio-Richiesta` and `Delminio-Catena`, still count. The CI downloads the client from `signoff-client` (the earlier name works too) and `delminio signoffs export` writes `delminio-signoff-<date>.json`.
+- **Improved**: in English, quotations use English quotation marks, in the app, the guide, the default rules and the messages to agents.
+- **Improved**: when the check for a protected decision has not been accepted yet or doesn't start, the warning says the decision is not enforced on that machine until that step is done.
+- **Fixed**: in [change sign-off](https://delminio.com/en/guide/change-sign-off#in-a-ci), if the git service gave the CI the repository under an address other than the one connected to Delminio (SSH under another name, for example), the check said green on everything and the merge never stopped. Now the file written by `delminio signoffs ci` carries the repository as it is connected, and on a repository Delminio doesn't know the check goes red. If you already have the file, remove it and run `delminio signoffs ci` again.
+- **Fixed**: with Codex, a Delminio command run from inside the sandbox said “I don't know who you are”, and the agent added a session number at random. Now it tells the agent to ask you to approve the command.
+- **Fixed**: an agent looking for a terminal command (such as `delminio focus`) among Delminio's tools got only “unknown operation”. Now it is told to run it from the terminal.
+
+### 1.32.0 — 23 November 2026
+
+- **Changed**: in [change sign-off](https://delminio.com/en/guide/change-sign-off#signing) the reviewer's review and signature are a single act. The reviewer reviews the change with their agent, with whatever model they prefer (the author's too: Delminio just writes it down), records the outcome from their computer with `delminio signoffs review` and then signs from the app. A review recorded by someone else, the author included, stays written but does not count for their signature; until theirs is there, the row shows them the command to give to their agent. Changes already signed stay signed.
+- **New**: `delminio signoffs ci` writes the CI file for GitHub or Forgejo (for GitLab it says what to add) and the steps to take on the git service: the key among the secrets and the rule on the main branch. It warns you when the CI can't reach your Delminio. All the steps in [In a CI](https://delminio.com/en/guide/change-sign-off#in-a-ci).
+- **New**: in the **Repositories with sign-off** card, a repository with sign-off and no zone says so, and **Sign-offs on the whole repo** proposes a zone on every one of its files.
+- **Changed**: the rules for agents say that sign-offs stop neither the commit nor the push: you push and open the pull request whenever you like, and the sign-offs are needed before the main branch.
+- **Fixed**: with Codex the agent's commits did not reach sign-offs, and did not count in the code review: the work the commit leaves for afterwards ended together with the command. Now it starts detached, as with the other CLIs.
+
+### 1.31.1 — 23 November 2026
+
+- **Fixed**: with the same account in two spaces, the passkey added in the second one replaced the first one's on the phone, and in the phone's list they had the same name. Now each space has its own, and the phone shows it with the space's name (for example “anna · Production”).
+
+### 1.31.0 — 23 November 2026
+
+- **Changed**: the app, the guide, the messages to agents and the default rules use clearer words: **follow-up** instead of “scheduled check”, **approval** instead of “yes”, **Kanban** instead of “board”, **messages** between sessions, a protected decision that **applies to** files and commands and the check that **verifies it**, Delminio's **built-in safeguards**. Command names stay as they were.
+- **New**: in the [vault](https://delminio.com/en/guide/vault#the-passkey) granting a secret, showing its value, handing the key to a delegate, making a new code, changing the key and accepting a deposited value ask for a confirmation with your **passkey** — fingerprint, face or PIN —, checked by Delminio: someone who finds the app open on your unlocked phone can no longer grant in your place. It's the same passkey as for sign-offs; if you don't have it yet, the **Your passkey** card at the top of the Vault adds it once. Until then the vault doesn't grant.
+
+### 1.30.3 — 23 November 2026
+
+- **Fixed**: wherever Delminio names a person — in the [Backlog](https://delminio.com/en/guide/backlog) who is doing a task and who gave it to them, the notes and the messages to sessions; in the [vault](https://delminio.com/en/guide/vault) who granted or refused; in exceptions and in phone notifications — it uses the name others see in that space, not the account name. Tasks assigned earlier show it too; notes already written stay as they are.
+- **Fixed**: the makers' reply to a report reaches the person who sent it and also the agent of every admin of the space, with who wrote it: before, it waited until the person who sent it came back.
+- **Fixed**: if you grant a secret while the agent is still waiting for it, the command runs and the agent no longer also gets the message asking it to run it again, which made it run twice. The message arrives only if the agent had stopped waiting.
+
+### 1.30.2 — 23 November 2026
+
+- **Fixed**: after **Add agent**, under the computers where the agent is ready, the card said “null”.
+
+### 1.30.1 — 23 November 2026
+
+- **Fixed**: in **Add agent** the panel closed by itself while you were choosing, when the view refreshed (a computer changing state), and the choices were lost. Now it stays until you press **Add** or **Cancel**.
+- **Improved**: in **Add agent** and in the [first steps](https://delminio.com/en/guide/first-steps) a model that needs a CLI version Delminio hasn't tested yet stays off and says from which version up it is waiting for, instead of refusing the click.
+
+### 1.30.0 — 23 November 2026
+
+- **New**: in [change sign-off](https://delminio.com/en/guide/change-sign-off) every sign-off is a confirmation with the **passkey** of your phone or computer — fingerprint, face or PIN —, rejections included: without a passkey you can't sign. You add it once from **Sign-offs → Your passkey**, after proving it's you (with Delminio Cloud a code to your email, with your own login your password); every passkey added arrives as a notification, and a lost device can be revoked.
+- **New**: the report for the people who verify checks again, without Delminio, the device signature of every sign-off, and says with which passkey it was given, when the person joined the space and who invited them. Who joins and leaves the space and who adds or revokes a passkey are in the trail, with who governs sign-off.
+
+### 1.29.1 — 23 November 2026
+
+- **Changed**: in [change sign-off](https://delminio.com/en/guide/change-sign-off) the review is done by an agent with whatever model you prefer, from another session: Delminio records the reviewer's model and says whether it is the author's. Before, only a different model counted.
+- **Fixed**: the check before a merge looks at the sign-off zones on the real files of each commit, read from the git where it runs: a change recorded with other files no longer passes as outside the zones, not even merged with a squash.
+- **Fixed**: only someone who could sign a change can reject it, the author or a person the zone names for the review.
+- **Fixed**: on macOS, after an update, the version of a CLI that an agent still open runs from is no longer deleted.
+
+### 1.29.0 — 23 November 2026
+
+- **New**: in **Add agent** and in the [first steps](https://delminio.com/en/guide/first-steps), under each agent switched on, the **role** it starts from and the **name** of the command. A model you already have can be added again with another role, for example `sonnet5.5-costruttore` ([Agents](https://delminio.com/en/guide/agents)).
+- **Improved**: after **Add agent** there is no command to type any more: on the computers with an open session the agent arrives by itself in a few seconds, and the view says **Ready on …** computer by computer.
+- **Fixed**: in a space without the base role, **Add agent** did not create the agent; now it proposes the role your other agents start from.
+- **Fixed**: at the last step of the [first steps](https://delminio.com/en/guide/first-steps), after a first connection, the **I don't have an agent** choice disappeared, and with it the command that installs the CLI.
+
+### 1.28.3 — 23 November 2026
+
+- **Improved**: in Italian too, Delminio's rules, the messages to agents, the guide and the kit now call the person the agent works with “the user”, as in English. It is also the default name in the [Vocabulary](https://delminio.com/en/guide/vocabulary), and anyone who had chosen a word of their own keeps it.
+
+### 1.28.2 — 23 November 2026
+
+- **Improved**: every computer deletes by itself the CLI versions no agent uses any more — Claude Code, Codex, Qwen Code and OpenCode —, after every successful alignment. One that is needed again is downloaded again when it is needed ([Agents](https://delminio.com/en/guide/agents)).
+
+### 1.28.1 — 23 November 2026
+
+- **Improved**: in the [vault](https://delminio.com/en/guide/vault), everyday secrets are given with **time-bound access**: with a single approval from your phone, for an hour commands with those secrets start without asking. The words change in the app, in the messages to agents and in the guide; secrets already marked stay as they were.
+- **Fixed**: the guide said the memory repository carries a copy of all memories. It carries the shared memories, the handoffs, the Backlog and decisions; personal and admin-only memories do not go there ([Memories on git](https://delminio.com/en/guide/memories-on-git)).
+- **Fixed**: the message of a command stopped by a [protected decision](https://delminio.com/en/guide/protected-decisions) could end with two full stops.
+- **Improved**: the [Dashboard](https://delminio.com/en/guide/dashboard) calls the agents a session launches subagents.
+- **Improved**: Delminio's image installs the system's security updates with every version.
+
+## Week of 16 November 2026
+
+### 1.28.0 — 22 November 2026
+
+- **Improved**: the history of change sign-offs can no longer be rewritten without it showing. Every commit in a repository with sign-off carries the chain's **anchor** (`Delminio-Catena`), and the people who hold Delminio's database cannot change it without the report saying so. The acts of the people who administer — turning sign-off on and off, for everyone or in a repository, creating, changing or withdrawing a zone, the CI keys — also enter the chain, and the report lists them. With a token they can't be turned off, not even from the settings ([Change sign-off](https://delminio.com/en/guide/change-sign-off)).
+- **New**: a sign-off zone states its **checks** — the command that runs after every commit on the commit's files, and until it exits 0 the change can't be signed — and always asks for a review by another model and at least two people, the author and the reviewer. The reviewer signs after the checks and the other model. `delminio signoffs checks` runs the checks again on the commit, and `delminio signoffs review` records the review of a whole branch in one go.
+- **Improved**: in a repository with sign-off every commit has someone who answers for it: one Delminio did not see being made does not pass the check, not even outside the zones. A zone applies from the moment it is created, on branches already open too.
+- **Improved**: the report reads the signatures from the chain and says if the database says otherwise; for a commit merged with a squash it carries the words of the branch's commits; for a commit Delminio did not see being made it says that the author git reports is not verified.
+- **Fixed**: the person's words are no longer lost when the computer has just been switched on or after a commit in a repository without sign-off; a commit redone after the network dropped finds its words again; the check says when the words were removed from the message; a commit thrown away no longer stays to sign forever, and it can be discarded from the app.
+
+### 1.27.1 — 22 November 2026
+
+- **Fixed**: on Android, Chrome sometimes replaced the notification of an exception waiting for you with its own warning, “Possible spam”, and anyone who tapped “Unsubscribe” stopped receiving anything from Delminio. Notifications from [protected decisions](https://delminio.com/en/guide/protected-decisions) and the [vault](https://delminio.com/en/guide/vault) now only say who is asking and what is waiting for you: the reason, the decision and the names of the secrets are read in the app, also because anyone near the phone can read them.
+
+### 1.27.0 — 22 November 2026
+
+- **New**: change sign-off per repository. Once on, it applies only in the repositories the admin chooses from **Sign-offs**, in the **Repositories with sign-off** card: there commits carry the person's words and changes in the zones are signed; in the others nothing is recorded — not even the words on the computer — and the CI check says so and exits with 0. A sign-off zone can say in which repositories it applies ([Change sign-off](https://delminio.com/en/guide/change-sign-off)).
+- **Fixed**: in a CI the repository address often carries a token: the sign-off client now removes it before sending it to Delminio or writing it in the report.
+
+### 1.26.0 — 22 November 2026
+
+- **New**: change sign-off. Every commit an agent makes carries the words the person wrote to it, and Delminio keeps their fingerprint; on the files of a **sign-off zone** the change is signed from the app, first by the author — the person who directed the agent and answers for it — then by the reviewers. Sign-off zones are created from **Sign-offs**, and the people who must sign get a notification; a branch is signed in one go, with one signature recorded per commit. `delminio signoffs check` tells a CI what is missing before a merge — even without the client, with a read-only key — and finds the signatures of a branch merged with a squash or a rebase; `delminio signoffs description` writes the pull request text with the person's words, and `delminio signoffs report` the report for the auditor. It is an on-request feature: it exists where the licence carries it, and the admin turns it on from the **Sign-offs** menu item ([Change sign-off](https://delminio.com/en/guide/change-sign-off)).
+- **Fixed**: with [protected decisions](https://delminio.com/en/guide/protected-decisions) off, asking for an exception or for the list of decisions answered with a Delminio error instead of saying the feature is off.
+- **Fixed**: in an English space the opening pointed the agent to the Italian command for reading the previous session's handoff, and the agent wrote it on screen. Now it uses the name in the space's language. The same for the handoff text, which in English now ends with `END`.
+- **Fixed**: when connecting a computer that doesn't have an agent yet, the final message only talked about Qwen Code, twice. Now it says how to install one, from [Agents](https://delminio.com/en/guide/agents) → “Connect another computer” → “I don't have an agent”.
+- **Fixed**: a member saw an empty box under their account in [Access](https://delminio.com/en/guide/access). And the [Dashboard](https://delminio.com/en/guide/dashboard) said “The last 1 handoffs”.
+
+### 1.25.2 — 22 November 2026
+
+- **Fixed**: when the connection installs the agent and starts it, it always told you to type the opening command in Italian. Now it says it in the space's language ([First steps](https://delminio.com/en/guide/first-steps)).
+- **Fixed**: in an English space Delminio's rules were filed under categories the catalogue doesn't have, and the [Dashboard](https://delminio.com/en/guide/dashboard) showed twenty-five memories to fix from the first day. Now they take the name the category has in the space's language, and when the language changes the memories follow it; spaces already affected are fixed by the update ([Categories](https://delminio.com/en/guide/categories)).
+- **Fixed**: an exception waiting for a decision in the [Backlog](https://delminio.com/en/guide/backlog) showed the stopped command with an Italian word in front of it. Now there's only the command.
+- **Fixed**: when you asked the agent to run `delminio accept` or `delminio disconnect`, the message only said it can't be done by an agent. Now it tells you to open a terminal outside the agent, in the project folder.
+
+### 1.25.1 — 22 November 2026
+
+- **Improved**: your account can be found from the app. Tapping your name at the bottom of the menu opens [Access](https://delminio.com/en/guide/access), and on Delminio Cloud the **Your account** card has the **Manage account** button, which opens the page where you change your email address and delete your account. Before, there was only a word inside a sentence, and the guide didn't say how to leave.
+- **Fixed**: the first steps and the Agents, Agent roles and Git views always wrote Delminio's commands (the one that prepares the agents, the opening one) in Italian, even for those using Delminio in English: now `delminio agents` and `/opening`, in the language you use Delminio in ([First steps](https://delminio.com/en/guide/first-steps)).
+- **Fixed**: the first time you connect a computer, the `delminio` command is created in a folder the open terminal doesn't yet look in for commands, and it answered “command not found”. Now the connection says so and gives you the command written in full ([First steps](https://delminio.com/en/guide/first-steps)).
+
+### 1.25.0 — 22 November 2026
+
+- **Improved**: in the vault, the members who grant their own agents' requests are called **delegates**, and a delegate's phone is activated by approving the device. A delegate's secrets are chosen from their side, all together, with a filter by name, **Select all** and, for someone joining a team already at work, the same secrets as another delegate. Before, each secret had to be opened and assigned one by one (The vault).
+- **Fixed**: in the **Delegates** card the member is chosen from a list. Before, on the phone the list didn't open and the name had to be typed by hand.
+- **Fixed**: on the Cloud the command that connects the computer, in the first steps, spoke Italian until it was approved, even in an English space. Now it speaks the language you use Delminio in ([First steps](https://delminio.com/en/guide/first-steps)).
+
+### 1.24.2 — 22 November 2026
+
+- **Fixed**: in an English space the first steps suggested an Italian name for the memory repository, `memorie-delminio`, and used it if you left the field empty. Now the default name is in the space's language ([First steps](https://delminio.com/en/guide/first-steps)).
+
+### 1.24.1 — 22 November 2026
+
+- **Fixed**: the first time you open Delminio it speaks your browser's language, if Delminio has it. Before, it spoke Italian: even someone arriving from an English invitation found the agreement and the first steps in Italian, and the agreement page has no language choice. The language stays yours, and you change it from [Access](https://delminio.com/en/guide/access).
+- **Fixed**: a new Cloud space is created in the language of its invitation, with the rules, the first-start tasks and the basic protected decisions in that language. Before, it was always created in Italian ([Spaces](https://delminio.com/en/guide/spaces)).
+- **Fixed**: when you change the language of a space that is still empty, the first-start tasks in the [Backlog](https://delminio.com/en/guide/backlog) and the basic protected decisions move to the new language too; the ones you had already changed stay as you wrote them. Before, they stayed in the old language, and the [Dashboard](https://delminio.com/en/guide/dashboard) showed them first ([Settings](https://delminio.com/en/guide/settings)).
+- **Fixed**: in [Access](https://delminio.com/en/guide/access), under “Invite a person”, the words “nullnull” appeared, and in [Settings](https://delminio.com/en/guide/settings) a brand-new space showed a git error about the memories in red, before it even had a repository: now it says the repository isn't connected yet.
+- **Fixed**: in English the guide ([Collaborators](https://delminio.com/en/guide/outside-collaborators)) and the Codex connection messages said `apertura`; they now say `opening`, like the English commands.
+- **Fixed**: a memory that cites a file of another repository of the space (for example “in Giano”) is no longer flagged as a missing path.
+
+### 1.24.0 — 21 November 2026
+
+- **Changed**: Delminio works only with OpenCode 2. Agents that were on OpenCode 1 move by themselves to the latest tested version 2, and a version 1 can no longer be chosen: OpenCode 1 does not load Delminio's plugin, and the agent started without memory or checks. Your own OpenCode 1 opened in a connected project tells you how to update ([Agents](https://delminio.com/en/guide/agents)).
+- **Improved**: agents on OpenCode 2 summarize the conversation like the ones on Qwen Code, at 300,000 tokens or at 85% of the context if that is smaller, and no longer prepare the summary in advance with extra calls on your key. If the model does not answer for a minute they try again, and after a few minutes they stop with an error instead of waiting forever. These are two new default values, which you can keep or update like the others ([Agents](https://delminio.com/en/guide/agents)).
+- **New**: an agent on OpenCode that makes the same call again and gets the same answer is stopped the third time, and told to take another route or to stop and tell you what is blocking it. OpenCode does not do this on its own, and a small model could go round in circles for hundreds of calls ([Agents](https://delminio.com/en/guide/agents)).
+- **Fixed**: agents on OpenCode also read the instructions you wrote for Claude in `~/.claude/CLAUDE.md`, next to the rules Delminio gives them. Not any more; the project's `AGENTS.md` and your skills stay ([Agents](https://delminio.com/en/guide/agents)).
+
+### 1.23.2 — 21 November 2026
+
+- **Improved**: in the [Dashboard](https://delminio.com/en/guide/dashboard) the latest finished sessions say who was working in them and the model's name, like the ones at work.
+
+### 1.23.1 — 21 November 2026
+
+- **Improved**: when a device's notifications switch off, the message no longer assumes it was the phone.
+- **Fixed**: on a request that touches your customers' data, **Deny** did not open the field for the reason and nothing happened: the request stayed pending. Now the field opens, as it does for **Grant**.
+- **Fixed**: `delminio errors` also hid file paths, so you couldn't tell which file had caused the error. Now it hides only what looks like a key or a password ([Commands](https://delminio.com/en/guide/commands)).
+- **Fixed**: an agent looking up an exception by its code (D7) got “no protected decision”: now it finds it, with who asked for it and what was decided.
+
+### 1.23.0 — 21 November 2026
+
+- **New**: `delminio errors` tells you, in short, which of the agents' calls failed on this computer: by kind, by program and the latest. Claude Code collects them while the agent works, and they stay on the computer even when the conversation is deleted; what isn't an error — an Esc, a search that finds nothing — stays hidden ([Commands](https://delminio.com/en/guide/commands)).
+- **Fixed**: a protected decision on a command also looked at the whole line, and two independent commands written one after the other were stopped as if they were one. Now each command is looked at on its own, together with what prepares it (a variable, a folder), and so it also recognises some that used to slip through ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **Fixed**: on a computer that had never connected to the git service of the memories, connecting sat still for a minute on the copy of the memories, saying nothing. Now it doesn't wait, and goes straight to the way that works.
+- **Fixed**: **Connect GitHub** open in two tabs used the same code twice: one tab ended in an error while the other created the repository. Now it uses it once, and both say it's done ([First steps](https://delminio.com/en/guide/first-steps)).
+- **Improved**: in [Access](https://delminio.com/en/guide/access) the name field says it's the name others see, even when it's already filled in.
+- **Improved**: [Memories on git](https://delminio.com/en/guide/memories-on-git) say what anyone reading the memories repository sees: reserved and personal memories are never there, but all the others are, including those their role in Delminio keeps closed.
+
+### 1.22.7 — 21 November 2026
+
+- **Improved**: [Protected decisions](https://delminio.com/en/guide/protected-decisions) say what happens when, after an exception granted from the app, your CLI asks for its own permission or stops the command, and how to leave that command to Delminio's judgement.
+
+### 1.22.6 — 21 November 2026
+
+- **Fixed**: an exception on third-party data granted from the app covers the command that was stopped, identical. The agent, though, ran again the one it had described in its why, sometimes slightly different, and was stopped again, with a new request for you. Now we tell it the exact command when it asks for the exception and when you grant it, and if it runs another one we remind it which one goes through ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **Improved**: the why of an exception on third-party data, when you grant or deny it, is written inside the card in **Waiting for you**, with its own button, and no longer in the browser's little window.
+- **Fixed**: the [Dashboard](https://delminio.com/en/guide/dashboard) and the Exceptions view show who is working or who is asking by the name others see, not by the account name.
+
+### 1.22.5 — 21 November 2026
+
+- **Improved**: a computer that can't read the memories repository — for example a collaborator who isn't in your GitHub — no longer needs a key added by hand. With Claude Code the memory index reaches it from Delminio in the opening, as already happened with Codex and Qwen Code, and the agent no longer reports it as a fault. The connection says so without alarm; the local copy stays for anyone who has access to the repository ([A session with Delminio](https://delminio.com/en/guide/a-session)).
+
+### 1.22.4 — 20 November 2026
+
+- **Fixed**: the [Dashboard](https://delminio.com/en/guide/dashboard) opens right away again, and while it loads it says so instead of staying blank. With agents following the latest version of their CLI, Delminio asked the provider for that version's number for every agent every time it opened, and the Dashboard stayed empty for up to ten seconds: now only installing asks for that number, and it is remembered. The Dashboard carries only what it shows, and the “To clean up” list arrives when you open it.
+- **New**: the name others see you by can be changed whenever you like, in [Access](https://delminio.com/en/guide/access), with **Change name**. Before, it was given only at the first sign-in, and anyone who signed in without giving it kept their account name instead.
+- **New**: in the [first steps](https://delminio.com/en/guide/first-steps) Delminio creates the memories repository on GitHub itself: press **Connect GitHub**, type on GitHub the code it shows you, and Delminio creates the private repository, adds its deploy key and sends the first copy. The permission you give is used only for that, and Delminio doesn't keep it. Before, you had to create the repository, paste its SSH address and add the key with write access by hand; with another git host that is still the way, under **I already have a repository**.
+- **Fixed**: when a new model arrives for your agents, **Update** also works with agents that follow the latest version of their CLI: before it gave an error. And if you had already added the new model's agent, the update no longer tries to rename the previous one on top of it, which failed and left the card there for good: it offers **Remove the previous one** or **Keep both** ([Agents](https://delminio.com/en/guide/agents)).
+- **Improved**: for Codex the recommended model is GPT-6.2 Sol, with the same context window as 6.1. Anyone with an agent on GPT-6.1 Sol finds it among the update's news, and decides whether to switch.
+- **Fixed**: when two sessions updated the agents at the same moment, an agent's command could look changed by hand and stop updating. Now the second one reads again before writing. It comes with the connection: there is nothing to do.
+
+### 1.22.3 — 20 November 2026
+
+- **Fixed**: in the [Backlog](https://delminio.com/en/guide/backlog) search, a code with B (`B42`) opens that item at the top, like the number alone. Before only the old F opened it, and B searched among the words.
+- **Improved**: the Delminio client in the project is now in several files: the CLI launchers, the git hooks, a session's worktree and the token count each have their own, next to `.claude/delminio.sh`, and the safety copy is made by a file the connection downloads and does not leave in the project ([What Delminio installs](https://delminio.com/en/guide/what-delminio-installs)). They come with the connection: there is nothing to do.
+
+### 1.22.2 — 20 November 2026
+
+- **Improved**: [Backlog](https://delminio.com/en/guide/backlog) items have the code **B**, for Backlog: `B42` instead of `F42`. The number stays the same, and F, the old letter, always works: written to the agent, searched in the Backlog or in the memories, where searching for a code also finds the texts that still carry the F. The letter used to come from a name the Backlog no longer has.
+- **Fixed**: phone notifications are switched on once and arrive from every space you're in; the card in [Settings](https://delminio.com/en/guide/settings) says which ones. Before, each space had its own key and the phone kept only one: switching them on in one space silently switched them off in the others, and an exception request from that space didn't arrive. With more than one space the notification says which one it comes from, and tapping it takes you into that space. A phone that already had them on redoes them by itself the next time the app opens; on iPhone a notice appears to switch them back on with a tap ([The app on your phone](https://delminio.com/en/guide/phone-app)).
+
+### 1.22.1 — 20 November 2026
+
+- **Fixed**: when an agent reads a decision about third-party data, approved or refused change proposals no longer count among its exceptions: they are in the Decisions view ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+
+### 1.22.0 — 20 November 2026
+
+- **New**: the vault has delegates. The admin adds a member as a delegate and assigns them some secrets; the delegate receives the key on their phone, and from then on their agents' requests for their secrets reach them and they grant them. When a secret is added, or a deposit accepted, the app asks who it goes to (The vault).
+- **New**: a repository of the space that isn't on a computer is suggested by the agent as soon as it starts there, saying what it's for; with the person's yes it clones it next to the project and connects it. When the admin adds a repository to the space, the agents at work hear about it straight away. Before, the person working had to clone and connect it themselves, and without knowing it the agent was left without the code to work on ([Git](https://delminio.com/en/guide/git)).
+- **New**: a decision that stops the admin too, or that protects third-party data, is not withdrawn or loosened by your agent on its own. If you ask it, the change becomes a **proposal** that reaches you as a single notification, in **Waiting for you** and on the decision's card, with how it was and how it will be: tap **Approve** and Delminio applies it. Before, the change from the agent was refused and had to be redone by hand from the card; and on a decision about third-party data the agent could withdraw it with your token ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **Fixed**: in the [Git](https://delminio.com/en/guide/git) view on the phone, the "connected on N computers" pill wraps inside the card instead of spilling out, and a repository shared by another space shows its name above and its address and space below, separated. Before they ran together on one line.
+- **Fixed**: in an installation with several spaces, the Backlog command the agent reads in messages is its own space's. Before, every space received the main space's one, and an agent could read another space's Backlog on the same machine without noticing ([The Backlog](https://delminio.com/en/guide/backlog)).
+
+### 1.21.1 — 19 November 2026
+
+- **Fixed**: inside a worktree of the repository, the checks of decisions and the Backlog probes accepted from the clone now run. Before, the worktree looked for a list of acceptances of its own, empty: there the check did not run, and the agent was told nobody had accepted it ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+
+### 1.21.0 — 19 November 2026
+
+- **New**: a decision that blocks can stop the admin too, with the **Stop the admin too** switch on its card. Usually the admin goes past it with a warning, and so does their agent, which works with their access; this way it stops you too, you grant the exception only from the app, and withdrawing or loosening it is done only from there ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+
+### 1.20.0 — 19 November 2026
+
+- **New**: a decision on a command can carry its **check before the command**, a project script that Delminio runs before every command the decision lives on, with the command and the folder it is about to run in. So the decision speaks only when the command really undoes it: “compose only from the main clone” stays quiet from the main clone and fires from another folder. On each computer it runs after the person's yes from a terminal of theirs (`delminio accept`), like the commit check ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **New**: in **Decisions** each decision says when it fires — before its files are changed, before its commands, at the commit — and the admin, opening its card, changes its files, its commands and whether it warns or blocks, in their own words. Before, from there you could only withdraw it ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **New**: a decision can live on the agent's **tools**, not only on files and commands: “no agents without my yes” on `Agent` and `spawn_agent`, “the CRM is read, not exported” on its MCP server's tools. It warns, blocks or lets its check decide, as on commands ([Protected decisions](https://delminio.com/en/guide/protected-decisions)).
+- **New**: opening a decision with a check, **Where the check runs** says computer by computer where a person accepted it and where it waits for `delminio accept`. Before, only each computer knew.
+- **New**: at the bottom of **Decisions**, **The project's hooks** (the `.delminio` scripts, with where they run and where they are stopped) and **Delminio's built-in safeguards**, with how many times they stopped an agent.
+- **Improved**: a decision with its check counts as met only when the check says the command undoes it: before, every command that resembled it counted.
+- **Fixed**: `.delminio/lascito.sh`, which runs when the CLI shuts down, coming from another person's commit no longer runs until you accept it (`delminio accept`), like the other project scripts. Before, it always ran ([What Delminio installs](https://delminio.com/en/guide/what-delminio-installs)).
+- **Fixed**: a decision that blocks a command or a tool, or that has a check, is no longer said to have “nobody noticing”: Delminio notices.
+- **Fixed**: in the **Plugins** and **Decisions** views, a computer with no skills of its own shows its name instead of a code.
+- **Fixed**: on decisions that are not about third-party data, the road the agent takes instead is no longer called “instead of the data”.
+
+### 1.19.0 — 19 November 2026
+
+- **New**: handoffs can be searched. When an agent searches the memory, next to the memories it gets the handoffs of past sessions closest to what it is looking for, with the passage that answers; looking for exact words, the lines that contain them. So it finds the day something was said or decided even when it is only in a handoff. It sees only the handoffs it can read ([A session with Delminio](https://delminio.com/en/guide/a-session)).
+- **New**: the [Plugins](https://delminio.com/en/guide/plugins) view in the menu shows the plugins that the CLIs of the connected computers have installed, with their version, whether they are on and the marketplace they come from, and the marketplaces each computer knows. The computer reports them each time an agent starts, never with the plugins' files.
+- **New**: the [team's plugins](https://delminio.com/en/guide/plugins): the admin chooses the plugins from a marketplace that every agent in the space receives, or only those of a role, on Claude Code, Codex and Qwen Code. On each computer they are installed after the person's yes from their own terminal (`delminio accept`), and uninstalled only where Delminio put them.
+- **Improved**: the person who accepts the contracts for a team, in the Cloud, gives only the Customer's company name and country. Before, a VAT number or tax code and the full registered address were also required, and the form mentioned the SDI code and certified email, which only concern Italian invoices: invoicing details are asked when you move to a paid plan ([Access](https://delminio.com/en/guide/access)).
+- **Fixed**: in the same form every field says it is required and, while it is empty, what it is missing. Before, the button stayed off without saying why. An invisible character pasted along with the text no longer gets the field rejected.
+- **Fixed**: a Qwen Code agent installed with **First install** finds by itself the key you gave it at its first start: before, its command said the key was missing, and you had to put it in the terminal again.
+- **Fixed**: the agent guiding you through the [first steps](https://delminio.com/en/guide/first-steps) runs the connection giving it time to wait for your approval: with Claude Code and Qwen Code the command stopped after two minutes, and the code to approve was no longer valid.
+
+### 1.18.0 — 19 November 2026
+
+- **New**: in the [first steps](https://delminio.com/en/guide/first-steps) the first step is **Your agents**: you say what you already have — a Claude or ChatGPT subscription, a provider's key, nothing — and switch on only the agents you'll use. Before, a new space started with eight Claude and Codex agents, and none for anyone starting from OpenCode or Qwen Code.
+- **New**: in the [Agents](https://delminio.com/en/guide/agents) view, **Add agent**: the same switches, and the computers where the missing CLI should be installed. Someone who uses Claude and wants to try OpenCode for free switches it on, ticks their computer, and Delminio installs it for them.
+- **Improved**: the agent with OpenCode's free models no longer has a fixed model: at launch it picks one that answers at that moment. Before, you wrote the name of a free model, and it stopped working when OpenCode withdrew it.
+- **Improved**: the agents' proposals suggest only the model that replaces one you use. The other new models show up in **Add agent**, marked “new”.
+- **Fixed**: the Qwen Code versions tested with this Delminio start from 0.26.9: with the earlier ones an agent on the Anthropic provider got an error at its first answer. In the [Agents](https://delminio.com/en/guide/agents) view those versions now show as not tested.
+
+### 1.17.8 — 18 November 2026
+
+- **New**: the [team](https://delminio.com/en/guide/skills) is changed by the admin and the members they choose, in the **Who can change the team** card of the Skills view. The other members, and their agents, propose: the proposal appears in the **Proposals for the team** card, anyone who can change the team accepts or declines it with the reason, and the person who made it gets a notification. Before, a member could not even propose. MCP servers stay the admin's ([The team](https://delminio.com/en/guide/team)).
+- **Fixed**: in the [Backlog](https://delminio.com/en/guide/backlog), the card of a follow-up that is already closed shows only its date: before, it still said how many days it had been due, as if nobody had looked at it.
+
+### 1.17.7 — 18 November 2026
+
+- **Improved**: the [team](https://delminio.com/en/guide/skills) now reaches the OpenCode agents Delminio starts too: skills, commands, agents and accepted MCP servers, for everyone or for their role. A team skill or agent is called `team-name`, and one of yours with the same name stays yours.
+- **Improved**: the Codex and OpenCode versions tested with this Delminio include the latest ones: Codex 0.169.0 and 0.170.0, OpenCode 1.19.6 and 2.3.2 ([Agents](https://delminio.com/en/guide/agents)).
+- **Fixed**: an OpenCode agent created from the [Agents](https://delminio.com/en/guide/agents) view, on a computer that had no OpenCode when it was connected, started without Delminio's memory: now it has it from its first start.
+- **Fixed**: an OpenCode agent with a key chosen in the [Agents](https://delminio.com/en/guide/agents) view would not start, saying the key was missing; the keys card did not count it among those using the key.
+- **Fixed**: if a space's acceptance records cannot be read, its deletion stops and says why, instead of going on as if there were none.
+- **Fixed**: someone entering a space without having accepted their personal terms of use no longer gets access or connects a computer: they accept them from the app first.
+
+### 1.17.6 — 18 November 2026
+
+- **Improved**: in the [first steps](https://delminio.com/en/guide/first-steps), someone without an agent has a single path for all four CLIs: the “First install” command is there for Qwen Code too, at every step before the last one, and running it again reopens the agent with the sentence without downloading anything. At the first start Qwen Code asks which model to connect to, a Qwen account or a provider's key. The connection then is the one of someone who already had the agent, and the last step no longer says the agent has already started when that isn't true.
+- **Improved**: Delminio's server in the CLIs is called “memoria”, and its two tools have a full name without “delminio” repeated: on Claude Code `mcp__plugin_delminio_memoria__delminio` instead of `mcp__plugin_delminio_delminio__delminio`, which agents kept getting wrong. Permissions already given move to the new name by themselves, at the first start of an agent after the update. The names for each CLI: [What Delminio installs](https://delminio.com/en/guide/what-delminio-installs). An OpenCode 2 session open during the update sees the server change name once (OpenCode reloads the plugin by itself), and the agent may get a few calls wrong: reopen it.
+- **Improved**: OpenCode agents have the **Conversations on disk** choice, like the other CLIs: Delminio deletes only its agents' conversations, not the ones you have with OpenCode on your own ([Agents](https://delminio.com/en/guide/agents)).
+- **Improved**: in the [Agents](https://delminio.com/en/guide/agents) view the keys card is called “Provider keys” (it was “Qwen Code keys”): the same keys serve OpenCode agents too.
+- **Fixed**: on a computer where both OpenCode lines had worked, the tokens of OpenCode 2 sessions did not reach the count.
+- **Fixed**: disconnecting the last project left on the computer the OpenCode versions Delminio had downloaded ([What Delminio installs](https://delminio.com/en/guide/what-delminio-installs)).
+- **Fixed**: an MCP server of the [team](https://delminio.com/en/guide/skills) can no longer be called like Delminio's: in Codex and Qwen Code it took its place, and the agent was left without memory. Connecting also tells you when one of your servers in the project's settings has that name.
+
+### 1.17.5 — 18 November 2026
+
+- **Improved**: in the [first steps](https://delminio.com/en/guide/first-steps), someone without an agent can also choose OpenCode: it installs with the first command, and asks for a provider's key or to try OpenCode's free models, picked among those answering at that moment.
+- **Improved**: in the [Dashboard](https://delminio.com/en/guide/dashboard) Delminio's weight on a session reads only in its tokens; the line under the session says what it received from Delminio (memories, messages, wake-ups).
+- **Improved**: in the [Skills](https://delminio.com/en/guide/skills) view the “All” tile is gone, as it repeated the total already written above; a chosen tile, pressed again, goes back to showing everything.
+- **Fixed**: tokens, hook cost and loaded skills are written only on the sessions of the person who sends them, or of the admin: before, a person could write them on the name of someone else's session.
+- **Fixed**: a variable starting with `DELMINIO_` can no longer be written into an agent's environment, in the [Agents](https://delminio.com/en/guide/agents) view: they belong to each computer's connection, and the agent's command doesn't take them even from a changed registry.
+- **Fixed**: an MCP server with a variable in its address (for example `http://localhost:${PORT}/mcp`) stopped the reading of skills, commands and agents on the whole computer.
+- **Fixed**: the Agents view said nothing updates by itself, even where you chose a version that updates itself; in the Spaces view a repo's name and “this space only” read stuck together.
+
+### 1.17.4 — 18 November 2026
+
+- **Fixed**: the box's “First install” command installed the agent but then said it had not, and did not start it.
+
+### 1.17.3 — 18 November 2026
+
+- **Improved**: someone without an agent who chooses Claude Code or Codex, in the [first steps](https://delminio.com/en/guide/first-steps), installs only the agent as the first move, and it starts already with the sentence to follow. From there it takes them through everything: the GitHub account if they have none, the SSH key, the project, the memory repository with its deploy key, the connection. Anyone who already knows how to do a step tells the agent and skips it.
+
+### 1.17.2 — 18 November 2026
+
+- **Improved**: `delminio` on its own, or `delminio help`, shows the commands you run from the terminal, with what each one does, in the space's language; a mistyped command also answers with that list. Before it also showed the names the agent uses, and in English they stayed in Italian. The same list is on the [Commands](https://delminio.com/en/guide/commands) page.
+
+### 1.17.1 — 18 November 2026
+
+- **Improved**: on a Delminio you installed, the invitation takes **the address the person will come in from**, and the link starts there: someone arriving through a VPN or an IP no longer gets a link that does not open. Delminio remembers it for the next invitation ([Access](https://delminio.com/en/guide/access)).
+- **Fixed**: a collaborator who clones the project's repo from another address of the same server (an IP, another name, an SSH alias) connects to the same repo, instead of being told it is a new repo to ask the admin for. Delminio recognises it from the path; on GitHub, GitLab and the other public hosts the same path stays another repo.
+- **Improved**: [Bringing someone in from outside](https://delminio.com/en/guide/outside-collaborators) has the part to hand to the collaborator, and the text for the agent knows when the person came in with an invitation.
+
+### 1.17.0 — 18 November 2026
+
+- **New**: in an installation with several spaces, **Rename** in the [Spaces](https://delminio.com/en/guide/spaces) view: every space, the main one too, can have a name people read, with capitals and spaces, in the label at the top, on the cards and to the agents. The technical name stays as it was, and connected computers need do nothing.
+- **Improved**: on Delminio Cloud the name of the first space is chosen by the person who signs in first, and it is required; a new space is called what you type, no longer with the first space's name in front. Inside Delminio every new space has a technical name that says nothing about you. The spaces you already have stay as they are.
+- **Improved**: closing or deleting a space is confirmed by typing the name you read.
+- **Fixed**: in a space, a collaborator who starts an agent whose role takes memories from the main space starts from the space's default role, instead of stopping with a message that a memory of the role is missing ([Bringing someone in from outside](https://delminio.com/en/guide/outside-collaborators)).
+
+### 1.16.2 — 17 November 2026
+
+- **Improved**: an agent's fixed options and environment variables, in the [Agents](https://delminio.com/en/guide/agents) view, reach a computer only after the person has accepted them from their own terminal with `delminio accept`: they run with their permissions, and an option can start a server or a hook. If they change they are asked again, and meanwhile the previous command stays. Agents already running on a computer at the time of the update stay as they were.
+
+### 1.16.1 — 17 November 2026
+
+- **Improved**: the connection on your computers updates itself only with signed files. With every version Delminio signs the connection's files with the release key, the same as the packages, which is not on the server; the computer installs them only if the signature checks out. A file changed on the server, Delminio Cloud included, does not reach your computers: the previous connection stays, and the agent tells you ([What gets installed](https://delminio.com/en/guide/what-delminio-installs)).
+
+### 1.16.0 — 17 November 2026
+
+- **New**: OpenCode is the fourth agent CLI, in the [Agents](https://delminio.com/en/guide/agents) view next to Claude Code, Codex and Qwen Code. It talks to the same providers as Qwen Code, plus OpenCode's free models, which need no key: a new OpenCode agent is created with those. Delminio installs the chosen version on the computer, also when you ask for it from the view, and the agent starts with its role instead of OpenCode's default instructions; your own OpenCode settings stay as they are.
+- **New**: an agent can update itself. In the version choice, at the bottom, **Updates itself: always the stable** (or **the latest**): the agent follows that channel, including versions we have not tested yet, and the view says so next to today's number. By default it stays on a precise version, which changes when you choose it.
+- **Improved**: in the [Dashboard](https://delminio.com/en/guide/dashboard), sessions on OpenCode have their own token count, launched agents included; before they stayed at zero.
+
+### 1.15.0 — 17 November 2026
+
+- **New**: in the [Skills](https://delminio.com/en/guide/skills) view, next to the skills, the commands, agents and MCP servers the computers already have, the project's or personal ones, on Claude Code, Codex and Qwen Code, with a filter by type. Of a server only the names of its variables and headers arrive, never their values. **Bring to the team** works for them too: a command or an agent is sent by its computer, a server opens the form with its fields and you save it.
+- **Fixed**: a session closed after a few minutes, before it started working, no longer reaches the sessions that open afterwards as a notice.
+
+### 1.14.11 — 17 November 2026
+
+- **Improved**: in the [Dashboard](https://delminio.com/en/guide/dashboard), the lines under a session's tokens say it more simply: how many went to the agents launched by the session, and how many the CLI spent outside the conversation, for example on the auto mode permission check.
+- **Fixed**: the Privacy notice for people also covers the usage counts of the workspace, what they are for and how long they are kept: anyone who signs in sees it again.
+
+### 1.14.10 — 17 November 2026
+
+- **Improved**: in the [Dashboard](https://delminio.com/en/guide/dashboard), a session's tokens include the agents it launches, on Claude Code, Codex and Qwen Code: they have their own conversations, and before they were left out of the count even when they spent as much as the session. A line under the total says how many are theirs and with which model. On Qwen Code, at the end of the session, what the CLI spends on its own comes in too, like the auto mode classifier: the total matches the CLI's.
+- **Fixed**: on Qwen Code, with **Conversations on disk** set to **When the session ends**, the conversations of the agents launched by the session stayed on the computer. Now they go with it, and so do those left by earlier sessions.
+- **Fixed**: on Codex, a notice about the time of Delminio's end-of-session steps always showed at the bottom. Now it is gone; at the first start after the update Codex asks once to approve those two steps.
+
+### 1.14.9 — 16 November 2026
+
+- **Improved**: new spaces start with an agent on Claude Fable 5.2, and no longer one on Fable 5.1 as well. If you already have an agent on Fable 5.1, Fable 5.2 appears among the update's news and you decide whether to move to it; Fable 5.1 can still be chosen in the [Agents](https://delminio.com/en/guide/agents) view.
+- **Fixed**: “to decide”, in the [Backlog](https://delminio.com/en/guide/backlog), the [Dashboard](https://delminio.com/en/guide/dashboard) and the agent's opening, also counted the things on hold, waiting for something to happen, which cannot be decided now. Now it counts only the ones waiting for a decision; the others stay in the list, marked ⏸.
+- **Improved**: if you work for several spaces from the same computer, even of different Delminios (your Delminio Cloud and a client's Enterprise), you can have the same agent name in all of them: the folder you start it from decides the space ([Spaces](https://delminio.com/en/guide/spaces), “The folder decides the space”). Before, the second space stopped and asked to rename one, and agents on Codex, which have settings of their own for each space, could not share a name.
+
+### 1.14.8 — 16 November 2026
+
+- **Improved**: an agent asking for a long memory without saying which piece it needs gets its head and the list of its sections, and opens the one it needs; whole only when it asks for it on purpose, to rewrite or review it. In the app you always see it whole.
+- **Improved**: the memories to clean up now include those with a section so long it only opens whole, and the limit of a memory that does not arrive at startup asks whether it holds one subject: the rules “The shape of a memory” and “How to write a memory” and the [Categories](https://delminio.com/en/guide/categories) and [Memories](https://delminio.com/en/guide/memories) pages say so.
+- **Fixed**: the [memory review](https://delminio.com/en/guide/memory-review) counted twice the lines of a commit redone with a rebase or an amend: both the old commit and the new one stayed. Now the old one leaves the count.
+
+### 1.14.7 — 16 November 2026
+
+- **Fixed**: on the phone, the [Backlog](https://delminio.com/en/guide/backlog) with “Questions for you” open spilled to the side and the view scrolled right. Now it fits the screen.
+- **Fixed**: the [memory review](https://delminio.com/en/guide/memory-review) also counted the lines of files deleted entirely, so deleting old code made a review look due. Now a deleted file does not count.
+- **Fixed**: when an agent resumed a vault request that had already expired, nothing reached the phone. Now a new request starts.
+- **Fixed**: the outcome of a vault request reaches only the session that made it.
+
+### 1.14.6 — 16 November 2026
+
+- **Fixed**: on the [Dashboard](https://delminio.com/en/guide/dashboard), a session already at work when Delminio updated showed almost everything its answers had re-read as “startup”. Now the sources are counted again from the start of the conversation.
+
+### 1.14.5 — 16 November 2026
+
+- **New**: on the [Dashboard](https://delminio.com/en/guide/dashboard), under each session's tokens, what the model's answers have re-read is made of — startup, Delminio, work, model, person, CLI —, how big the context is now, who asked for the answers and the heaviest sources. Delminio reads only the numbers and the names of the tools, never the text of the conversation.
+- **Improved**: the rule “The shape of a memory” has a new point, every section reads on its own; when an agent saves a memory with a section that can only be read whole, Delminio tells it and asks it to split it.
+- **Improved**: an agent that asks for a memory with a question in words gets the section that answers it, with its lines and the list of the others, instead of the whole memory or a refusal.
+
+### 1.14.4 — 16 November 2026
+
+- **Improved**: a [memory review](https://delminio.com/en/guide/memory-review) that counts lines of code can leave out a folder further down too (“app -src/old”), with everything inside it.
+- **Fixed**: the Privacy notice for people also covers the session usage that the [Dashboard](https://delminio.com/en/guide/dashboard) shows since 1.14.2: anyone who signs in sees it again.
+
+## Week of 9 November 2026
+
+### 1.14.3 — 15 November 2026
+
+- **Improved**: on the [Dashboard](https://delminio.com/en/guide/dashboard) a session's tokens read in the order of a turn, first what the model reads and then what it writes: input, cache read, cache written, output.
+
+### 1.14.2 — 15 November 2026
+
+- **New**: on the [Dashboard](https://delminio.com/en/guide/dashboard), under each session at work, the tokens it has used so far, taken from its CLI (Claude Code, Codex and Qwen Code): the total and its parts, updating by themselves; below, the latest finished sessions. An agent can read them too, for the sessions in progress.
+- **New**: in English the commands are `/opening` and `/closing` (with Codex, `opening` and `closing`, without the slash); `/start`, `/handoff` and the Italian ones keep working.
+- **Fixed**: corrected versions of handoffs reached a member's computer even for sessions that member cannot read. Now that computer receives only the ones the member can open in [Git](https://delminio.com/en/guide/git): their own handoffs, the ones they inherit, and all of them for the admin.
+- **Fixed**: if a corrected handoff is later changed in its commit, or removed, the earlier corrected version is no longer shown in its place.
+- **Fixed**: on an Enterprise installation with several spaces, creating a person or giving them a role in a space is done only from the app, in [Spaces](https://delminio.com/en/guide/spaces), as in Access: an agent with the admin's token can no longer do it.
+
+### 1.14.1 — 15 November 2026
+
+- **Improved**: on the website, in English, also What Delminio is, A session, Your data, First steps and the FAQ.
+- **Fixed**: an agent with a role that writes to the session that called it now wakes that session, even when it is idle.
+- **Fixed**: on the [Dashboard](https://delminio.com/en/guide/dashboard) a member saw in the log the titles of other people's reserved and personal memories, and who had signed in. Now everyone sees only the titles of the memories they can open, and sign-ins are for the admin.
+- **Fixed**: with two agents writing the same memory at the same moment, the copy in the repository and the search stay aligned with the latest version, and a memory just made reserved stays reserved.
+- **Fixed**: a rebuild from the repository no longer sends to the bin a memory whose file cannot be read.
+- **Fixed**: on your own installation, the machine token file can be read only by the owner of the memories folder.
+
+### 1.14.0 — 15 November 2026
+
+- **New**: a space's first start has ten tasks instead of seven. The new ones are the project's other folders, what needs a look now and then and, if you want, why the project exists. The map, the opening scripts and the security questions come back at every memory review. All ten, one by one: [First steps](https://delminio.com/en/guide/first-steps).
+- **Improved**: the search in this guide shows more pages, at most two
+ paragraphs per page, and the same goes for what agents find.
+- **Improved**: in [Agents](https://delminio.com/en/guide/agents) a section says how your own Codex and
+ Qwen Code settings apply; the [Spaces](https://delminio.com/en/guide/spaces) page says at the start that
+ spaces keep clients and projects apart.
+- **Improved**: the English guide names the screens and buttons as the
+ English app shows them, and says the same things as the Italian guide.
+- **Fixed**: on Codex and Qwen Code, Delminio's rules described some built-in skills as off when they are on.
+- **Fixed**: a file just uploaded from [Files](https://delminio.com/en/guide/files) can no longer vanish
+ if Delminio removes the expired ones at the same moment.
+- **Fixed**: the notice that notifications are off takes you straight to the
+ notifications card in Settings.
+- **Fixed**: in your own Codex or Qwen Code settings, a key that overlaps Delminio's and is written in another form (for example `mcpServers` as a list) no longer cuts the agent off from Delminio: that part is ignored, and the agent says so at launch.
+- **Fixed**: in English spaces, raising a memory's size limit now works.
+
+### 1.13.0 — 14 November 2026
+
+- **New**: the version number in Settings, and this page with what is new in
+ each version.
+- **Improved**: agents know this guide exists and read it before explaining how
+ to do something in the app.
+- **Fixed**: in Delminio Cloud the Dashboard no longer suggests asking for a new
+ version. We update the Cloud ourselves.
+- **Fixed**: with several active sessions, [Files](https://delminio.com/en/guide/files) asks which session to
+ send a file to instead of picking one by itself.
+
+### 1.12.0 — 14 November 2026
+
+- **New**: [files](https://delminio.com/en/guide/files) between you and the agents, from the phone to the
+ session and back.
+- **New**: personal CLI settings, above the defaults and below those of a single
+ agent ([Agents](https://delminio.com/en/guide/agents)).
+- **New**: an update no longer changes the agents' defaults by itself. The changes appear among the news on the [Dashboard](https://delminio.com/en/guide/dashboard), with **Update** or **Keep the previous one**.
+
+### 1.11.0 — 12 November 2026
+
+- **New**: in the vault, the secrets you use often open with a single approval from your phone, for an hour, instead of one approval per command.
+- **Improved**: “Change the key” renews every key of the vault.
+
+### 1.10.0 — 9 November 2026
+
+- **New**: the team's [skills](https://delminio.com/en/guide/skills) reach every agent in the space, and the
+ ones a computer already has enter Delminio when it connects.
+
+## Week of 2 November 2026
+
+### 1.9.0 — 8 November 2026
+
+- **New**: Delminio on several [processes](https://delminio.com/en/guide/processes), chosen in Settings.
+- **Improved**: Delminio handles more agents at once: with three processes, 1,200 concurrent sessions get answers in under a second.
+
+### 1.8.0 — 3 November 2026
+
+- **New**: the connection installs as a plugin of Claude Code, Codex and Qwen
+ Code, and updates itself.
+- **New**: with every message the agent receives the memories on the subject
+ you are talking about.
+
+## Week of 26 October 2026
+
+### 1.7.0 — 29 October 2026
+
+- **New**: the vault. The secrets agents ask for stay encrypted on
+ the admin's device, and reach the agent only with their approval.
+
+### 1.6.0 — 28 October 2026
+
+- **New**: Qwen Code, the third CLI. With it, agents can use models that have no CLI of their own, including models you run yourselves.
+
+### 1.5.0 — 26 October 2026
+
+- **New**: the [Git](https://delminio.com/en/guide/git) view, with readable handoffs and the space's
+ repositories.
+- **New**: a Delminio installed from scratch on a memory repository that is
+ already full restores memories and Backlog.
+
+## Week of 19 October 2026
+
+### 1.4.0 — 22 October 2026
+
+- **New**: [sign-in](https://delminio.com/en/guide/access) with Delminio's own page, and invitations from the
+ admin.
+- **New**: after an update, changes to the defaults are approved or rejected
+ from a single list, on the Dashboard.
+
+### 1.3.0 — 20 October 2026
+
+- **New**: Delminio in Italian and English. The app and the messages to agents
+ speak the space's language.
+
+## Week of 12 October 2026
+
+### 1.2.0 — 16 October 2026
+
+- **New**: Codex next to Claude Code, on the same memories.
+
+### 1.1.0 — 15 October 2026
+
+- **New**: the guide inside the app, which agents read too. Searching the guide
+ is semantic, not just by words.
+
+## Week of 5 October 2026
+
+### 1.0.0 — 11 October 2026
+
+- The first version: memories, Backlog, protected decisions and verified handoffs for Claude Code agents, on Delminio Cloud and on your own installation.
diff --git a/FIRMA b/FIRMA
new file mode 100644
index 0000000..a959cbd
--- /dev/null
+++ b/FIRMA
@@ -0,0 +1,23 @@
+delminio-kit 2026.11.26-7fac9ff
+997be552538573e286591d9eb00f11db3318354ccc548c938c47c87418efdd4c aggancia.sh
+d7b142a6804306d8b8e313fbb032e4b386d300400bf9d9622f06e434e4f0d295 aggancia.sh
+babc6135db88393634d411906b60886028e628afbde33bbc3d799eb20b99bc56 delminio-client
+6e454a0bbe177a5e26dac24b894a00bda691072e891a8503cbd8892bdcc266d2 delminio-client
+4eb2bfaaa6c57bb0b1fc24dfa5fdc2a619ec70560d892dd9b07a66c8c5a3559b cantiere-client
+826cc4610678c3a333d63d110368e6ad2202e5ea2c87e338ce6f5baf5a883782 cantiere-client
+beca8d3e02accb659f87899d4b50ec2095fc4132df9c45a66d748d819034ef7d cassaforte-client
+df9cef2ad5ccbcda20b5323b1cc073ead312fe4057bc227f20af78436f2df5d3 cassaforte-client
+1e2b0f003bf2b2a57a1dae32803bc10a1244df2a91632c4f62904afa8516647d plugin-client
+9a15cac86995b19e3c572afab1fbec4ada8469f8d4f0db377683cdd32291503a plugin-client
+e7ed2a82d77601b312d67121e3f937b8ce3393b0984aded45452b6a941fedafe squadra-client
+76c3246172e797e82fe1d59888a4054e3c8f360c835361e2ef64349e5e8e8228 squadra-client
+479babf8be0f58185bffe1c228ba583d6ad39bf2e1f32bd9e21483a1e9fdb1b4 firme-client
+f94d8995f7651d6b04b39541d800e4f6ad9650be470347fc7358418f728c4f45 firme-client
+32602f03955c8b26b5f84cea8020c679fd40d47371393361a06d8184db63bd28 eseguibili-client
+e767941ac408b38b4733262c676174a18b8d5a09fc2f710b7597ec2879725ddb eseguibili-client
+66728cb83e25223c2c79e85a559f3be1220b2cb76268b16c85c9b90c2b706f34 opencode-client.js
+faeca00edb0ed26d8068d804fdd1644f2dafb324aa12f72fea2ee8a39b7058d2 lanciatori-client
+a975d1939b05a17daa5575c08183403806d25d705e9cc3113bbb6877852cfc93 ganci-git-client
+211002b2567ae3925df54f4ac3db5df15f6876bd94664db7199f101fec589d04 worktree-client
+2442b96d429e0451751c05a9ac3eb1492d72db477fe7cc6a8819cccb726531c7 consumi-client
+a8b1be601cf629e050fbfd51200cf1c3f16bcdd115a106b1809680e30e63b284 copia-client
diff --git a/FIRMA.sig b/FIRMA.sig
new file mode 100644
index 0000000..fe849eb
--- /dev/null
+++ b/FIRMA.sig
@@ -0,0 +1,6 @@
+-----BEGIN SSH SIGNATURE-----
+U1NIU0lHAAAAAQAAADMAAAALc3NoLWVkMjU1MTkAAAAg6kmkA/qj0BOmu4jxK1/zltAzCC
+atWWyZjclK+QMPCXQAAAAMZGVsbWluaW8ta2l0AAAAAAAAAAZzaGE1MTIAAABTAAAAC3Nz
+aC1lZDI1NTE5AAAAQILo50kh1d9vitPrcrG0XmrQ4PLiOSHzuogLdCnKZ+0GcmDTe/yW01
+ZNc8/tfYmyqO84BGHxrF1LwhOCR34GKws=
+-----END SSH SIGNATURE-----
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d1139f5
--- /dev/null
+++ b/README.md
@@ -0,0 +1,88 @@
+# Delminio — the client
+
+Shared memory for your AI coding agents: Claude Code, Codex, Qwen Code and OpenCode. This repository holds everything Delminio runs on your computer, so you can read it before you connect. The service itself runs on Delminio Cloud, in the EU, or on your own server with Delminio Enterprise. Its code is not here.
+
+## Read before you connect
+
+Connecting a project means asking your agent to follow [`agent/aggancia.en.md`](agent/aggancia.en.md). That file is here: read it first. It lists every command the agent will run. Nothing in your project's code is changed, and nothing needs administrator rights. `delminio disconnect` puts your settings back as they were.
+
+File names are in Italian, as the service serves them: `aggancia` means connect, and `FIRMA` is the signed manifest.
+
+## Every file is signed
+
+The client installs a file only if it is listed in the release manifest, signed with Delminio's release key. That key is not on the server: a file changed on the server, Delminio Cloud included, never reaches your computer. When a new version comes out, the client checks the signature again before installing anything.
+
+The release key:
+
+```
+rilasci@delminio.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0
+```
+
+The same key is printed on [delminio.com/en/security](https://delminio.com/en/security). Compare the two.
+
+## Verify a release yourself
+
+```
+curl -fsSO https://<your-delminio>/static/kit/FIRMA
+curl -fsSO https://<your-delminio>/static/kit/FIRMA.sig
+printf 'rilasci@delminio.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0\n' > allowed_signers
+ssh-keygen -Y verify -f allowed_signers -I rilasci@delminio.com -n delminio-kit -s FIRMA.sig < FIRMA
+sha256sum aggancia.sh # the result must appear in FIRMA
+```
+
+`<your-delminio>` is `app.delminio.com` on Delminio Cloud, or your own server.
+
+## What it installs
+
+In the project, kept out of git through `.git/info/exclude`:
+
+| File | What it does |
+|---|---|
+| `.claude/delminio.sh` | The Delminio client: it talks to Delminio when the agent starts and while it works, and carries commands such as `delminio disconnect`. It holds Delminio's address and the path of the token, not the token |
+| `.claude/lanciatori.sh`, `.claude/ganci-git.sh`, `.claude/worktree.sh`, `.claude/consumi.py` | Pieces of the Delminio client, which it reads when they are needed: how each CLI starts, the git hooks, a session's worktree and the token count of a conversation |
+| `.claude/cantiere.py`, `.claude/backlog.py` | The Backlog client (`delminio backlog`) |
+| `.claude/eseguibili.py` | The client that writes the agents' commands on the computer |
+| `.claude/cassaforte.py` | The safe's client, which hands a command the secrets requested from the administrator |
+| `.claude/firme.py` | The change sign-off client: the person's words in the commit message, and the `delminio signoffs` commands |
+| `.claude/plugin.py` | The client that installs the Delminio plugin in the CLIs |
+| `.claude/squadra.py` | The team client: its skills, commands, agents, MCP servers and plugins, and the approval they ask for on this computer |
+| `.claude/settings.local.json` | Claude Code's local settings: Delminio's hooks next to yours, the plugin switched on in this project, the CLI's notes folder moved to Delminio's copy of the memories, which of Claude Code's built-in skills the model sees and the confirmation before another agent or a workflow (only what you have not already chosen yourselves) |
+| `.claude/rules/delminio.md` | A rule for the agent: what to tell you if Delminio does not answer |
+| `.claude/commands/`, `.codex/hooks.json`, `.qwen/settings.json`, `.qwen/commands/` | The hooks and the `/opening` and `/closing` commands for Claude Code, Codex and Qwen Code, when a CLI does not take them from the plugin |
+| `.opencode/plugins/delminio.js` | Only where OpenCode is: Delminio's plugin for OpenCode, with the memory, the messages and the `/opening` and `/closing` commands. Outside git |
+| The git hooks `commit-msg`, `post-commit` and `post-rewrite` | They send a session's handoff to Delminio to be checked, and add the line `Delminio-Sessione: S<N>` to each commit (not in public repositories). When a commit is redone (a rebase, an amend) they tell Delminio which one, so the [review](https://delminio.com/en/guide/memory-review) does not count the same lines twice. A hook of yours that was already there is not replaced: the connection tells you the line to add |
+| A few marks inside `.git/` | Where the safety copy is, whether the repository is public, the checks you have accepted |
+
+On your computer, in your home folder:
+
+| Where | What |
+|---|---|
+| `~/.config/delminio/<project>.token` | This computer's **token**: the key the client uses to talk to Delminio. Only you can read the file (600, in a 700 folder) |
+| `~/.config/delminio/eseguibili.json`, `~/.config/delminio/ruoli/` | Which agent commands Delminio wrote here, and the channels of a role's agents |
+| `~/.local/bin/` | The agents' commands (for example `opus5.5`, `sol6.2`) and the `delminio` command |
+| `~/.local/share/claude/versions`, `~/.local/share/codex/versions`, `~/.local/share/qwen-code/versions` | The CLI versions chosen in the Agents view, downloaded from the official address and checked against their checksum, next to yours: your `claude` does not move |
+| `~/.local/share/delminio/<fingerprint>/memoria` | The copy of the memories repository, which Claude Code reads as its index. Only if the computer can read the repository: without it, the index comes from Delminio in the opening |
+| `~/.local/share/delminio/backup/` | The safety copy of what was there before the connection (only you can read it) |
+| `~/.local/share/delminio/plugin` | The Delminio plugin for the CLIs |
+| `~/.local/share/delminio/codex/<agent>` | The folder of each Codex agent: your login is linked there, not copied |
+| `~/.local/share/delminio/opencode/` | The OpenCode versions chosen in the Agents view, checked against the npm registry's integrity, and the mark on the conversations to delete, if you chose it. Your OpenCode and its data (`~/.local/share/opencode`) are not touched |
+| `~/.codex/config.toml` | Only if you use the Codex app and said yes to `delminio app-codex`: Delminio's plugin, its marketplace and the permission for its two tools. The rest of the file does not change ([The desktop apps](https://delminio.com/en/guide/desktop-apps)) |
+| `~/.claude.json` | Only if Claude Code does not take the plugin: the line of Delminio's server for this project, with the token |
+| `~/.cache/delminio-*` | Temporary work: the state of the sessions, the commands waiting |
+
+The token in `~/.config/delminio/` is readable only by you: treat it like a password.
+
+## What leaves your computer
+
+- **To Delminio, with every message you send the agent:** the message and the end of the agent's previous answer, to find the relevant memories. Not kept.
+- **To Delminio, while a session works:** the model name and the token counts, kept for 90 days.
+- **To Delminio, at the end of a session:** the handoff, to be checked, and the commit references (hash and repository). Never your code.
+- **To your git:** the shared memories, with the deploy key you gave it.
+
+Nothing else is read from your conversations. The full list, server side included: [Your data](https://delminio.com/en/guide/your-data).
+
+## Report a security issue
+
+Email [security@delminio.com, DESIDERATO]. See [`SECURITY.md`](SECURITY.md).
+
+Docs: https://delminio.com/en/guide · Changes: [`CHANGELOG.md`](CHANGELOG.md) · Licence: [`LICENCE`](LICENCE): you may read and verify this code, not reuse it ⚖️
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 0000000..849909d
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,24 @@
+# Security
+
+## Reporting a vulnerability
+
+Email [security@delminio.com, DESIDERATO]. Please do not open a public issue. We acknowledge every report within [2 working days, DESIDERATO] and tell you what we are doing about it within [7 days, DESIDERATO]. If you want, we credit you in the changelog once it is fixed.
+
+## In scope
+
+- The client in this repository and the files it writes on your computer.
+- Delminio Cloud (`app.delminio.com`) and a Delminio Enterprise installation.
+- The release signature: any way to make the client install a file that is not in the signed manifest.
+
+Please do not test against other customers' spaces, and do not run load tests against Delminio Cloud.
+
+## How the client is protected
+
+- Every file the client installs is listed, with its sha256, in a manifest signed with the release key. The key is not on the server.
+- The machine token is readable only by its owner (600, in a 700 folder).
+- Scripts a project adds to run at the start or end of a session run only if you wrote them, or after you accept them with `delminio accept`. A change by someone else asks again.
+- The agent cannot sign a change or open a secret: both need a person's passkey.
+
+## Supported versions
+
+The latest release. Delminio Cloud is always on it; on Enterprise, you install updates when you decide.
diff --git a/agent/aggancia.en.md b/agent/aggancia.en.md
new file mode 100644
index 0000000..ab7b1ca
--- /dev/null
+++ b/agent/aggancia.en.md
@@ -0,0 +1,191 @@
+# Connecting a project to Delminio — the text for the agent
+
+_You're the agent — Claude Code, Codex, Qwen Code or OpenCode — that the user has asked to connect their project to Delminio. Delminio is the project's memory: once it's connected, any agent that starts in that folder finds the rules, the memories and the work left by the sessions before it. Right now you can't see Delminio yet: this text takes you to the point where the agent starts again with Delminio inside. Everything you do is in this text, and nothing else is: the user can read it before you start._
+
+_⚠️ Follow this text **word for word**. If it reached you summarised (a tool that reads web pages and returns an extract), stop: download it in full with `curl -fsSL __DELMINIO_URL__/aggancia.en.md` and start again from there._
+
+## The three rules of the process
+
+1. **Say it first, then do it.** Show every command and say in one line what it does before you run it. Run only the commands written here; if you need another one (a missing package, a permission), suggest it and wait for approval.
+2. **What happens in the interface, the user does.** Delminio is already open in their browser, at `__DELMINIO_URL__`, on the “First steps” card: tell them what to press and wait for them to say it's done. Don't try to open it yourself.
+3. **No secret goes through the chat.** Keys, tokens and passwords don't get pasted here: Delminio doesn't ask you for any (the deploy key it shows is public: that one yes, step 2). If the user pastes one, tell them to change it afterwards: it has ended up in the conversation.
+
+When a step fails: read the message (the scripts say why and what to do), explain it to the user in plain words, fix it together and run it again. Running it again does no harm: what's already there isn't touched.
+
+⚠️ **If you're Codex**: before step 0, read the last section, “If you're Codex”. It says what to explain to the user about the sandbox, and the test to run before connecting.
+
+⚠️ **If the user came in with an invitation**, into a space the admin has already set up: the “First steps” card is not there for them, and they copied the sentence from the Agents view (“Connect another computer”). The licence and the memory copy are not theirs: don't mention them, and in the map of step 0 only “Connect the computer” and “Start the agent” remain. Do steps 1 and 1b, then check that the clone is the space's repo: ask them the path the admin gave them (for example `team/project`) and compare it with `git remote get-url origin`. The address can differ — an IP, another name of the same server, an alias in `~/.ssh/config` —, the path cannot: Delminio recognises the repo from it. In step 3, no `DELMINIO_STESSA_STORIA`: only the admin adds a new repo, and if the script refuses it the clone is of another repo. The user approves the code themselves, in the app. Then steps 4 and 5.
+
+## 0. The map, for the user
+
+In their browser, the “First steps” card shows the same steps as this text, with “you are here” on the current one: use the same words. Before touching anything, tell them in a few lines:
+
+1. **Your agents** — in the card they switch on the agents they want to work with: only those are created. If they haven't switched any on yet, tell them to do it first, and to switch on the one for the CLI you are.
+2. **The licence** — only on a Delminio you installed yourselves: they paste it into the card.
+3. **The copy of the memories** — the repository where Delminio keeps the memories (step 2).
+4. **Connect the computer** — you run the command in the project folder, they approve the code in the browser (step 3), then you write the agents' commands on this machine (step 4).
+5. **Start the agent** — they close this session and open the agent again from the new command (step 5). It's the last step and it isn't skipped: only then does the card tick it off.
+
+Before the steps come the checks: what's needed and what's already there (steps 1 and 1b), and for someone starting from zero git and the project (1c). As you go, tell them which step you're on. Ask them **which project** they'll work on with Delminio: the folder of the clone, on this machine.
+
+**If an agent before you stopped halfway**, or the card is already past the first step, don't start again from the beginning and don't rely only on “you are here”. Delminio measures the steps before “Connect the computer”, so they hold, but “Connect the computer” counts as done as soon as *any* computer is connected. Do the checks in step 1, then look at this computer:
+
+ test -f <the project>/.claude/delminio.sh && echo connected || echo not connected
+
+“not connected”: step 3 gets done, even if the card shows “Start the agent”. “connected”: pick up from step 4. Tell the user where you're picking up from, and why.
+
+## 1. What's needed
+
+Check, and report one line per item:
+
+ git --version && python3 -c 'import json, ssl' && curl --version | head -1
+ command -v claude codex qwen opencode
+ git config user.name && git config user.email
+ git -C <the project> rev-parse --show-toplevel
+ git -C <the project> remote get-url origin
+
+- `git`, `curl`, `python3`, and at least one CLI: **Claude Code** (`claude`), **Codex** (`codex`), **Qwen Code** (`qwen`) or **OpenCode** (`opencode`). Someone who had none installed it with the “First install” command of the first-steps box, and its CLI is usually you. That CLI lives in Delminio's folder, outside the PATH: `command -v` does not find it, and that is fine — it needs no link and no PATH, the agent commands of step 4 find it on their own. Delminio can also install Qwen Code later, from its agent in the Agents view. Linux or macOS; on Windows this CLI has to run in WSL, with the clone in the home folder and not in `/mnt/c`.
+- git and python3 are tested **by running them**, not with `command -v`: on a Mac without Apple's command line tools `/usr/bin/git` and `/usr/bin/python3` exist, but when launched they open an install window and fail. If that happens, the human presses “Install” in that window (about 1 GB) or runs `xcode-select --install`, and you retry once the installation is over.
+- **git knows who they are** (`user.name`, `user.email`): if not, have them set it.
+- **The project is a git clone.** Without a remote you can carry on anyway — the handoff and the merge will stay on this machine — and you tell them so.
+
+## 1b. What's already there, before you touch anything
+
+People often arrive with things of their own: instructions written for the agent, another tool's memories, MCP servers, their own commands and hooks, notes files the agent used to reread. The connection mustn't break any of it. Before running it, look, and tell them:
+
+ ls -la <the project> <the project>/.claude <the project>/.codex <the project>/.qwen
+ ls -la ~/.claude ~/.codex ~/.qwen
+ git -C <the project> status --short --ignored
+
+Look above all for:
+- instructions for agents: `CLAUDE.md`, `AGENTS.md`, `QWEN.md`, `GEMINI.md`, the rules for Cursor, Copilot, Windsurf or Cline;
+- another tool's memories (`memory-bank/`, `.serena/`, Claude Code's notes);
+- their MCP servers, hooks, commands and agents, in `.claude/`, `.codex/`, `.qwen/` and in the same folders in their home folder;
+- **notes or context files with any name at all** — a `NOTES.md`, a `CONTEXT.md`, a folder of notes for the agent. The connection doesn't know them; only you can recognise them, by reading how they start.
+
+Then tell them in a few lines, with the real names:
+- what you found;
+- what the connection will do: **first a backup outside the repository**, in their home folder (`~/.local/share/delminio/backup/`), of everything it touches and of all the instructions, memories and settings it sees, each file checked against the original; then it installs Delminio as a **plugin of the CLI** (the hooks, `/opening` and `/closing`, the memory server). On Claude Code it's switched on only in this project; on Codex and Qwen Code, in the folder Delminio keeps for each of its agents, never in `~/.codex` or `~/.qwen`. Their own hooks stay where they are; a project `/apertura` or `/chiusura` of theirs goes into the backup and comes back when they disconnect; nothing of theirs is deleted;
+- which of the notes files you found you'd put in the backup too.
+
+Wait for their approval, and ask which files to add to the backup. Don't open or show credentials files in the chat (`.env`, keys, the CLIs' logins): the backup doesn't take them, and the connection doesn't touch them.
+
+## 1c. Git and the project — for someone starting from zero
+
+If the project is already a clone with a remote (step 1) and the user handles their git host on their own, skip to step 2. If not, do these steps together. At each step ask whether they already know how to do it: what they know, you skip.
+
+**Where the code lives.** Ask whether they have an account on a git host (GitHub, GitLab, their company's git).
+- **They don't**: suggest **GitHub** — free, with private repositories, reachable from Delminio Cloud. They create the account themselves in the browser, at `https://github.com/signup`; you wait until they say done.
+- **They have GitHub**: go on with `gh`, below.
+- **They have another git** (GitLab, a Forgejo, their company's — on a Delminio installed by a company, ask before suggesting GitHub): no `gh`. Make the SSH key together (`ssh-keygen -t ed25519`, then they put the content of `~/.ssh/id_ed25519.pub` among the SSH keys **of their profile**), and they create the repositories in their git's interface: you tell them where to press.
+
+**`gh`, GitHub's command.** Try `gh --version`. If it's missing:
+- Ubuntu and WSL: `sudo apt install gh` (it asks for the Linux password);
+- macOS with Homebrew: `brew install gh`; without it, the macOS archive from `https://github.com/cli/cli/releases/latest`, unpacked with `gh` in `~/.local/bin`.
+
+Then the sign-in, which they do in the browser:
+
+ gh auth login --hostname github.com --git-protocol ssh --web
+
+To the question about the SSH key they answer yes: `gh` creates it and puts it in their account. Check with `gh auth status` and `ssh -T git@github.com`: it answers with their name (the first time it asks whether to trust github.com: yes).
+
+**The project.** Ask where their work is. Projects live in a folder of theirs, for example `~/projects` — on Windows inside Ubuntu, never in `/mnt/c`:
+- **it's already on GitHub or on their git**: `git clone <the SSH address> ~/projects/<name>`;
+- **it's only on their computer**: copy the folder to `~/projects/<name>` (Windows files are under `/mnt/c/Users/…`); inside, `git init`, `git add -A`, `git commit -m "The project as it was"`, then `gh repo create <name> --private --source . --push`;
+- **it doesn't exist yet**: `mkdir -p ~/projects/<name>`, inside `git init`, a `README.md` with one line, the first commit, then `gh repo create <name> --private --source . --push`.
+
+From here “the project” is that folder: `git -C <the project> remote get-url origin` must give the repository's address.
+
+## 2. The memory repository
+
+Delminio keeps a plain copy of all the memories in **a repository of the user's**, which belongs to them. If the “The copy of the memories” step on the “First steps” card already has its ✅, skip to step 3.
+
+**With GitHub and `gh`** (step 1c) you create the memory repository yourself, empty:
+
+ gh repo create <name>-memories --private
+
+The SSH address is `git@github.com:<user>/<name>-memories.git` (`gh api user -q .login` gives the user): tell them, they paste it in the “The copy of the memories” step and save. Delminio shows them a key: it's the **public** deploy key, not a secret, and they can paste it here. You add it, with write access:
+
+ printf '%s\n' '<the key>' > /tmp/delminio-deploy.pub
+ gh repo deploy-key add /tmp/delminio-deploy.pub --allow-write --title Delminio -R <user>/<name>-memories
+
+Then they press **“Done, check”** (step 4 below). Without `gh`, they do the steps below in their git's interface.
+
+1. On their git host (GitHub, GitLab, Codeberg, a Forgejo reachable from the internet), the user creates a **private, empty** repository: no README, no licence, no .gitignore. ⚠️ GitLab offers the README **already ticked**: leave it empty. Delminio makes the first push, and it refuses a repository that already has a commit.
+2. In the “The copy of the memories” step, they paste the repository's **SSH** address (`git@github.com:name/memories.git`) and save. Delminio shows them a **key**: it's Delminio's deploy key, and it's valid for that repository only.
+3. They add it to the repository, **with write access**:
+ - GitHub: repository → Settings → Deploy keys → Add deploy key, tick “Allow write access”;
+ - GitLab: repository → Settings → Repository → Deploy keys → Add new key, tick “Grant write permissions to this key”. If GitLab answers that the key already exists (“Fingerprint has already been taken”), it's in the “Privately accessible” keys tab: **Enable** it there, then edit it and tick write access;
+ - Forgejo and Codeberg: repository → Settings → Deploy keys → Add, with write access.
+
+ ⚠️ Not in their profile (the account's “SSH Keys”): that's something else, and it's where the git host's banner sends them.
+4. They press **“Done, check”**. If Delminio gives a reason, read it together: the repository isn't empty, the key has no write access, the address is wrong (it's fixed with **“Change address”**, also later, from Settings → Memories on git).
+
+**Without Claude Code (Codex or Qwen Code only), the computer doesn't need to read that repository.** Delminio keeps publishing the memories with its deploy key; Codex and Qwen Code read the index and the memories from the Delminio tool, without a local clone and without a second Git key. Skip the check below: don't ask the user for any other credentials.
+
+**With Claude Code**, the local copy is what feeds the CLI's automatic index. It's cloned with the user's own git credentials, separate from Delminio's key. You can carry on without it too: the agent gets the index from the Delminio tool. To have the local copy as well, try:
+
+ git ls-remote <the repository's SSH address>
+
+If it answers with a permissions error, the user doesn't have an SSH key of their own on this computer, or doesn't have it on their git host account: help them create one (`ssh-keygen -t ed25519`, then the public key in the “SSH Keys” of **their profile** — this time, yes) or sign in with their git host's CLI (`gh auth login`, `glab auth login`). If it can't be done straight away, carry on: the connection says so, and the agent starts without the index until it's sorted out.
+
+## 3. The connection — step “Connect the computer”
+
+Inside the project folder (if you started outside it, as when Delminio installed you: `cd <the project>` first, in the same command):
+
+ bash <(curl -fsS __DELMINIO_URL__/aggancia.en.sh)
+
+If in step 1b the user chose some files to add to the backup, pass them in front, separated by colons and with paths relative to the project:
+
+ DELMINIO_COPIA_ANCHE="NOTES.md:docs/notes" bash <(curl -fsS __DELMINIO_URL__/aggancia.en.sh)
+
+**With Codex**: the sandbox test (section “If you're Codex”) has to be done before this command. **Use an interactive terminal**: `exec_command` with `tty=true`. After the approval in the browser, the script may ask whether the repository is the same project as the ones already connected, or for a confirmation about the previous settings. Without a terminal it would stop after having already created the key. Pass the question on to the user and wait for their answer before replying.
+
+**The command waits for the approval up to 10 minutes.** If your CLI stops a command after a while — Claude Code and Qwen Code by default after 2 minutes — run it with the longest time, 10 minutes (`timeout` 600000), or in the background with its output in a file you read back. Stopped halfway, the code it showed is no longer valid: run it again, and the user approves the new one.
+
+**Before running it, one question for the user** (with any CLI): are other repositories already connected to their Delminio? They can see them in the app, in the Git view. If there are and this one is **the same project** (the same work, the same team), run it with the answer already given, so the script doesn't stop after the approval and they don't have to approve twice:
+
+ DELMINIO_STESSA_STORIA=si bash <(curl -fsS __DELMINIO_URL__/aggancia.en.sh)
+
+If it's **another project**, don't run anything: it goes in another space (in the app, “Spaces”), and gets connected there. If they don't know, run the normal command: if the script asks, pass the question on to the user and run it again with their answer.
+
+⚠️ Exactly like this, from a file: never `curl … | bash`, which swallows the rest of the script and ends silently.
+
+The script prints an **address to open**: give it to the user, who opens it in the browser where they're already signed in to Delminio and presses **Approve**. Then wait: the script receives the permission on its own and carries on. At the end it prints what it did and the warnings: pass them on to the user in plain words, one per line — and where the backup is: the `LEGGIMI.md` inside it says what it contains, and what it didn't copy and why.
+
+⛔ **The work doesn't end here.** The computer is connected, but no agent with Delminio has started yet, and the first-steps card stays open on the last step, “Start the agent”. Steps 4 and 5 are always done, even if the user is in a hurry: without them, they're left with a card that won't go away and no idea why.
+
+## 4. The agent's command — still “Connect the computer”
+
+Delminio has in its register the agents the user switched on in the “Your agents” step, all with Delminio's rules at the top: for example `opus5.5` on Claude Code, `sol6.1` on Codex, `zen` on OpenCode with the free models (the full list is the Agents view). Ask the user for approval, then:
+
+ delminio agents
+
+`delminio` is the command the connection has just put next to the agents' commands (in `~/.local/bin`). It works from any folder in the project, and from here on it's the name Delminio's commands are written with. If the terminal can't find it, that folder isn't on the PATH: help them add it to their shell profile, and meanwhile run `~/.local/bin/delminio agents`.
+
+It writes on this machine the command for every agent whose CLI is installed; it doesn't download a CLI that isn't. If it says the commands folder isn't on the PATH, help them add it. Then ask them which one they want to use among those written.
+
+If none of the agents switched on is for the CLI you are, `delminio agents` writes none for it. Whoever runs the space (on Cloud, alone, it is often the user themselves) adds it in the Agents view → **“Add agent”**: there they switch on the model, choose the role and the name, for OpenCode the free ones too, for Qwen Code the provider's model. With this session open the command arrives by itself in a few seconds: the view says “Ready on …”. If it doesn't, run `delminio agents` again. With Qwen Code the provider's key lives in the person's environment, never in the chat.
+
+## 5. Starting again with Delminio — step “Start the agent”
+
+You started before the connection: you can't see Delminio, and you won't in this session. Tell the user:
+
+1. to close this session;
+2. to open a terminal in the project folder and run the command for the model they chose (for example `sol6.1` or `opus5.5`: step 4 printed the names);
+3. **with Codex**: on the first start they answer yes to “Trust this folder?”, and then with `/hooks` they trust the hooks of Delminio's plugin (“Trust all”). Only once: Delminio's updates don't ask again. Without it, Codex starts but doesn't hear Delminio;
+4. to type **`/opening`** (with Claude Code and Qwen Code) or **`opening`** (with Codex, without the slash).
+
+From there the new agent starts with Delminio, and it explains the rest. The last of the first steps, “Start the agent”, ticks itself off as soon as it starts.
+
+## If you're Codex
+
+⚠️ **If you're Codex**: first explain, in a few lines, that the sandbox limits what commands can do with files and the network, while confirmations decide when you ask for permission. Don't infer the active mode from the defaults: `/permissions` shows it and lets the user choose it, full access included. Without a sandbox doesn't mean without confirmations. Don't suggest `--yolo` as a shortcut, and don't change the protections yourself. A personal choice doesn't change the shared line in the Agents view. For a necessary command outside the limits, ask for approval of that command.
+
+**Codex on Linux, before connecting**: test the mechanism, not just whether a package is there: `codex sandbox -c 'sandbox_mode="read-only"' -- true`. If it fails before running `true`, it's the sandbox environment that doesn't start, not a ban on the work requested. On Ubuntu you need `bubblewrap`; on Ubuntu 24.04 you may also need the AppArmor profile from the `apparmor-profiles` package, and `apparmor-utils`. Suggest the fix, wait for approval, and run the same command again. Don't disable the user-namespace restriction for the whole machine. The instructions for the user, if that profile is missing, are:
+
+ sudo apt install bubblewrap apparmor-profiles apparmor-utils
+ sudo install -m 0644 /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/
+ sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict
+
+`sudo` commands change the system: don't run them out of habit, or outside the approval given for this fix. From the Delminio command the test runs at every launch, not at every hook: protections at system level can change even after a pass.
diff --git a/agent/aggancia.md b/agent/aggancia.md
new file mode 100644
index 0000000..ad6ab2b
--- /dev/null
+++ b/agent/aggancia.md
@@ -0,0 +1,374 @@
+# Collegare un progetto a Delminio — il testo per l'agente
+
+_Sei l'agente — Claude Code, Codex, Qwen Code o OpenCode — a cui l'utente ha chiesto di collegare il
+suo progetto a Delminio. Delminio è la memoria del progetto: dopo il collegamento,
+chi si avvia in quella cartella trova le regole, le memorie e il lavoro lasciato da
+chi c'era prima. Adesso tu Delminio non lo vedi ancora: questo testo ti porta
+fino al punto in cui l'agente riparte con Delminio dentro. L'utente lo può
+leggere prima di te, e niente di quello che fai sta altrove._
+
+_⚠️ Questo testo si segue **parola per parola**. Se ti è arrivato riassunto
+(uno strumento che legge le pagine web e ne restituisce un estratto), fermati:
+scaricalo intero con `curl -fsSL __DELMINIO_URL__/aggancia.md` e riparti da lì._
+
+## Le tre regole del giro
+
+1. **Prima dici, poi fai.** Ogni comando lo mostri e dici in una riga cosa fa,
+ prima di lanciarlo. Lanci solo i comandi scritti qui; se ne serve un altro
+ (un pacchetto mancante, un permesso) lo proponi e aspetti il sì.
+2. **Ciò che si fa nell'interfaccia lo fa l'utente.** Delminio è già aperto nel
+ suo browser, in `__DELMINIO_URL__`, sulla carta «I primi passi»: tu gli dici
+ cosa premere e aspetti che ti dica fatto. Non provare ad aprirla tu.
+3. **Nessun segreto passa dalla chat.** Chiavi, token, password non si
+ incollano qui: Delminio non te ne chiede nessuno (la chiave di deploy che mostra
+ è pubblica: quella sì, punto 2). Se l'utente te ne incolla
+ uno, digli di cambiarlo dopo: è finito nella conversazione.
+
+Quando un passo fallisce: leggi il messaggio (gli script dicono il perché e
+cosa fare), spiegalo all'utente in parole sue, sistemate insieme e rilancia. Si
+rilancia senza danni: ciò che c'è già non si tocca.
+
+⚠️ **Se sei Codex**: prima del punto 0 leggi l'ultima sezione, «Se sei Codex»: dice
+cosa spiegare all'utente sulla sandbox e la prova da fare prima del collegamento.
+
+⚠️ **Se l'utente è entrato con un invito**, in uno spazio che l'amministratore ha già
+preparato: la carta «I primi passi» per lui non c'è, e la frase l'ha copiata dalla
+vista Agenti («Collega un altro computer»). La licenza e la copia delle memorie non
+lo riguardano: non nominarle, e nella mappa del punto 0 restano solo «Collega il
+computer» e «Avvia l'agente». Fai i punti 1 e 1b, poi controlla che il clone sia
+il repo dello spazio: chiedigli il percorso che gli ha dato l'amministratore (per
+esempio `squadra/progetto`) e confrontalo con `git remote get-url origin`.
+L'indirizzo può essere diverso — un IP, un altro nome dello stesso server, un
+alias in `~/.ssh/config` —, il percorso no: Delminio riconosce il repo da lì. Al
+punto 3 niente `DELMINIO_STESSA_STORIA`: un repo nuovo lo aggiunge solo
+l'amministratore, e se lo script lo rifiuta il clone è di un altro repo. Il codice
+lo approva l'utente stesso, nell'app. Poi i punti 4 e 5.
+
+## 0. La mappa, all'utente
+
+Nel suo browser il riquadro «I primi passi» mostra le stesse tappe di questo
+testo, con «sei qui» su quella di adesso: usate le stesse parole. Prima di toccare
+niente, diglielo in poche righe:
+
+1. **I tuoi agenti** — nel riquadro accende gli agenti con cui vuole lavorare:
+ si creano solo quelli. Se non ne ha ancora acceso nessuno, digli di farlo per
+ primo, e di accendere anche quello della CLI che sei tu.
+2. **La licenza** — solo su un Delminio installato da voi: la incolla lui nel riquadro.
+3. **La copia delle memorie** — il repo dove Delminio tiene le memorie (punto 2).
+4. **Collega il computer** — lanci il comando nella cartella del progetto, lui
+ approva il codice nel browser (punto 3), poi scrivi i comandi degli agenti
+ su questa macchina (punto 4).
+5. **Avvia l'agente** — lui chiude questa sessione e riapre l'agente dal comando
+ nuovo (punto 5). È l'ultima tappa e non si salta: solo lì il riquadro si spunta.
+
+Prima delle tappe, i controlli: cosa serve e cosa c'è già (punti 1 e 1b), e per chi comincia da zero il git e il progetto (1c). Man mano,
+digli a che tappa siete. Chiedigli **su quale progetto** lavorerà con Delminio: la
+cartella del clone, su questa macchina.
+
+**Se un agente prima di te si è fermato a metà**, o il riquadro è già più avanti
+della prima tappa, non ripartire dall'inizio e non fidarti solo del «sei qui»: le
+tappe prima di «Collega il computer» le misura Delminio e valgono, ma «Collega il computer» risulta fatta
+appena *un computer qualunque* è collegato. Fai i controlli del punto 1, poi
+guarda questo computer:
+
+ test -f <il progetto>/.claude/delminio.sh && echo collegato || echo da collegare
+
+«da collegare»: il punto 3 si fa, anche se il riquadro mostra «Avvia l'agente».
+«collegato»: si riparte dal punto 4. Di' all'utente da dove riprendete e perché.
+
+## 1. Cosa serve
+
+Controlla e riporta in una riga per voce:
+
+ git --version && python3 -c 'import json, ssl' && curl --version | head -1
+ command -v claude codex qwen opencode
+ git config user.name && git config user.email
+ git -C <il progetto> rev-parse --show-toplevel
+ git -C <il progetto> remote get-url origin
+
+- `git`, `curl`, `python3`, e almeno una CLI: **Claude Code** (`claude`), **Codex**
+ (`codex`), **Qwen Code** (`qwen`) o **OpenCode** (`opencode`). Chi non ne aveva
+ nessuna l'ha installata col comando «Prima installa» del riquadro dei primi passi,
+ e la sua CLI di solito sei tu. Quella CLI sta nella cartella di Delminio, fuori dal
+ PATH: `command -v` non la trova, ed è giusto così — non serve un collegamento né un
+ PATH per lei, i comandi degli agenti del punto 4 la ritrovano da soli. Qwen Code
+ Delminio lo installa anche dopo, dal suo agente nella vista Agenti. Linux o macOS; su Windows questa CLI deve
+ girare in WSL, con il clone nella home e non in `/mnt/c`.
+- git e python3 si provano **facendoli girare**, non con `command -v`: su un Mac
+ senza gli strumenti da riga di comando di Apple `/usr/bin/git` e `/usr/bin/python3`
+ ci sono, ma lanciati aprono una finestra d'installazione e cadono. Se succede,
+ l'utente preme «Installa» in quella finestra (circa 1 GB) o lancia
+ `xcode-select --install`, e si riprova a installazione finita.
+- **git sa chi è** (`user.name`, `user.email`): se no, glielo fai impostare.
+- **Il progetto è un clone git.** Senza un remoto si va avanti lo stesso — la
+ consegna e il merge resteranno su questa macchina — e glielo dici.
+
+## 1b. Cosa c'è già, prima di toccare
+
+Chi arriva spesso ha già della roba sua: istruzioni scritte per l'agente,
+memorie di un altro strumento, server MCP, comandi e ganci suoi, file di note
+che l'agente si rileggeva. Il collegamento non deve rompere niente di questo.
+Prima di lanciarlo, guarda e diglielo:
+
+ ls -la <il progetto> <il progetto>/.claude <il progetto>/.codex <il progetto>/.qwen
+ ls -la ~/.claude ~/.codex ~/.qwen
+ git -C <il progetto> status --short --ignored
+
+Cerca soprattutto:
+- le istruzioni per gli agenti: `CLAUDE.md`, `AGENTS.md`, `QWEN.md`, `GEMINI.md`,
+ le regole di Cursor, Copilot, Windsurf o Cline;
+- le memorie di un altro strumento (`memory-bank/`, `.serena/`, le note di Claude Code);
+- i server MCP, i ganci, i comandi e gli agenti suoi, in `.claude/`, `.codex/`, `.qwen/`
+ e nelle stesse cartelle della sua cartella personale;
+- **i file di note o di contesto con un nome qualsiasi** — un `NOTE.md`, un
+ `CONTESTO.md`, una cartella di appunti per l'agente —: il collegamento non li
+ conosce, li riconosci solo tu leggendone l'inizio.
+
+Poi diglielo in poche righe, coi nomi veri:
+- cosa hai trovato;
+- cosa farà il collegamento: **prima una copia di sicurezza fuori dal repo**,
+ nella sua cartella personale (`~/.local/share/delminio/backup/`), di tutto ciò
+ che tocca e di tutte le istruzioni, le memorie e le impostazioni che vede, ogni
+ file confrontato con l'originale; poi installa Delminio come **plugin della
+ CLI** (i ganci, `/apertura` e `/chiusura`, il server della memoria): su Claude
+ Code acceso solo in questo progetto, su Codex e Qwen Code nella cartella che
+ Delminio tiene per ogni suo agente, mai in `~/.codex` o `~/.qwen`; i ganci suoi
+ restano dove sono; un suo `/apertura` o `/chiusura` del progetto va nella copia
+ e torna quando si stacca; non elimina niente di suo;
+- quali dei file di note che hai trovato metteresti anche tu nella copia.
+
+Aspetta il suo sì, e chiedigli quali file aggiungere alla copia. Non aprire e non
+mostrare in chat file di credenziali (`.env`, chiavi, il login delle CLI): la
+copia non li prende e il collegamento non li tocca.
+
+## 1c. Il git e il progetto — per chi comincia da zero
+
+Se il progetto è già un clone con un remoto (punto 1) e l'utente usa da sé il suo
+git host, salta al punto 2. Se no, fate questi passi insieme. A ogni passo
+chiedigli se lo sa già fare: quello che sa, lo salti.
+
+**Dove sta il codice.** Chiedigli se ha un account su un git host (GitHub,
+GitLab, il git della sua azienda).
+- **Non ce l'ha**: proponi **GitHub** — gratis, coi repo privati, raggiungibile
+ da Delminio Cloud. L'account lo crea lui nel browser, su
+ `https://github.com/signup`; tu aspetti che ti dica fatto.
+- **Ha GitHub**: avanti con `gh`, qui sotto.
+- **Ha un altro git** (GitLab, un Forgejo, quello dell'azienda — su un Delminio
+ installato da un'azienda chiedilo prima di proporre GitHub): niente `gh`. La
+ chiave SSH la fate insieme (`ssh-keygen -t ed25519`, poi il contenuto di
+ `~/.ssh/id_ed25519.pub` lo mette lui nelle chiavi SSH **del suo profilo**), e i
+ repo li crea lui nell'interfaccia del suo git: tu gli dici dove premere.
+
+**`gh`, il comando di GitHub.** Prova `gh --version`. Se manca:
+- Ubuntu e WSL: `sudo apt install gh` (chiede la password di Linux);
+- macOS con Homebrew: `brew install gh`; senza, l'archivio per macOS di
+ `https://github.com/cli/cli/releases/latest`, scompattato con `gh` in `~/.local/bin`.
+
+Poi l'accesso, che fa lui nel browser:
+
+ gh auth login --hostname github.com --git-protocol ssh --web
+
+Alla domanda sulla chiave SSH risponde sì: `gh` la crea e la mette nel suo
+account. Controlla con `gh auth status` e `ssh -T git@github.com`: risponde col
+suo nome (la prima volta chiede se fidarsi di github.com: sì).
+
+**Il progetto.** Chiedigli dov'è il suo lavoro. I progetti stanno in una
+cartella sua, per esempio `~/progetti` — su Windows dentro Ubuntu, mai in `/mnt/c`:
+- **è già su GitHub o sul suo git**: `git clone <l'indirizzo SSH> ~/progetti/<nome>`;
+- **è solo sul suo computer**: copia la cartella in `~/progetti/<nome>` (i file
+ di Windows stanno sotto `/mnt/c/Users/…`); dentro, `git init`, `git add -A`,
+ `git commit -m "Il progetto com'era"`, poi `gh repo create <nome> --private
+ --source . --push`;
+- **non c'è ancora**: `mkdir -p ~/progetti/<nome>`, dentro `git init`, un
+ `README.md` con una riga, il primo commit, poi `gh repo create <nome> --private
+ --source . --push`.
+
+Da qui «il progetto» è quella cartella: `git -C <il progetto> remote get-url
+origin` deve dare l'indirizzo del repo.
+
+## 2. Il repo delle memorie
+
+Delminio tiene una copia in chiaro di tutte le memorie in **un repository
+dell'utente**, che è suo. Se nella carta «I primi passi» il passo «La copia
+delle memorie» ha già la spunta ✅, salta al punto 3.
+
+**Con GitHub e `gh`** (punto 1c) il repo delle memorie lo crei tu, vuoto:
+
+ gh repo create <nome>-memorie --private
+
+L'indirizzo SSH è `git@github.com:<utente>/<nome>-memorie.git` (l'utente lo dà
+`gh api user -q .login`): diglielo, lo incolla nel passo «La copia delle
+memorie» e salva. Delminio gli mostra una chiave: è la chiave **pubblica** di
+deploy, non un segreto, e te la può incollare qui. La aggiungi tu, con la scrittura:
+
+ printf '%s\n' '<la chiave>' > /tmp/delminio-deploy.pub
+ gh repo deploy-key add /tmp/delminio-deploy.pub --allow-write --title Delminio -R <utente>/<nome>-memorie
+
+Poi lui preme **«Fatto, controlla»** (punto 4 qui sotto). Senza `gh`, i passi
+qui sotto li fa lui nell'interfaccia del suo git.
+
+1. Sul suo git host (GitHub, GitLab, Codeberg, un Forgejo raggiungibile da
+ internet) l'utente crea un repository **privato e vuoto**: niente README,
+ niente licenza, niente .gitignore. ⚠️ GitLab propone il README **già
+ spuntato**: va lasciato vuoto. Il primo invio lo fa Delminio, e un repo che
+ ha già un commit lo rifiuta.
+2. Nel passo «La copia delle memorie» incolla l'indirizzo **SSH** del repo
+ (`git@github.com:nome/memorie.git`) e salva. Delminio gli mostra una
+ **chiave**: è la chiave di deploy di Delminio, vale per quel solo repo.
+3. La aggiunge al repo, **col permesso di scrittura**:
+ - GitHub: repo → Settings → Deploy keys → Add deploy key, spunta «Allow write access»;
+ - GitLab: repo → Settings → Repository → Deploy keys → Add new key, spunta
+ «Grant write permissions to this key». Se GitLab risponde che la chiave
+ c'è già («Fingerprint has already been taken»), è nella scheda delle
+ chiavi «Privately accessible»: lì **Enable**, poi la modifica e spunta la
+ scrittura;
+ - Forgejo e Codeberg: repo → Impostazioni → Chiavi di deploy → Aggiungi, con la scrittura.
+
+ ⚠️ Non nel suo profilo (le «SSH Keys» dell'account): quella è un'altra cosa,
+ ed è il posto dove il banner del git host lo porta.
+4. Preme **«Fatto, controlla»**. Se Delminio dice un motivo, leggetelo
+ insieme: il repo non vuoto, la chiave senza scrittura, l'indirizzo sbagliato
+ (si corregge con **«Cambia indirizzo»**, anche dopo, da Impostazioni → Le
+ memorie su git).
+
+**Senza Claude Code (solo Codex o Qwen Code), il PC non deve leggere quel repo.**
+Delminio continua a pubblicare le memorie con la sua chiave di deploy; Codex e
+Qwen Code leggono l'indice e le memorie dal tool Delminio, senza un clone locale e senza una seconda chiave Git.
+Salta la verifica qui sotto: non chiedere all'utente altre credenziali.
+
+**Con Claude Code**, la copia locale serve all'indice automatico della CLI.
+Si clona con le credenziali git dell'utente, distinte dalla chiave di Delminio.
+Anche senza, si può proseguire: l'agente prende l'indice dal tool Delminio.
+Per avere anche la copia locale, prova:
+
+ git ls-remote <l'indirizzo SSH del repo>
+
+Se risponde con un errore di permessi, l'utente non ha una chiave SSH sua su
+questo computer, o non l'ha nel suo account del git host: aiutalo a farla
+(`ssh-keygen -t ed25519`, poi la pubblica nelle «SSH Keys» del **suo
+profilo** — questa sì) o ad accedere con la CLI del suo git host (`gh auth
+login`, `glab auth login`). Se non si riesce subito si va avanti: il collegamento lo dice, e l'agente si avvia senza l'indice finché non si sistema.
+
+## 3. Il collegamento — tappa «Collega il computer»
+
+Dentro la cartella del progetto (se sei partito fuori, come quando ti ha
+installato Delminio: `cd <il progetto>` prima, nello stesso comando):
+
+ bash <(curl -fsS __DELMINIO_URL__/aggancia.sh)
+
+Se al punto 1b l'utente ha scelto dei file da aggiungere alla copia, li passi
+davanti, separati da due punti e coi percorsi dal progetto:
+
+ DELMINIO_COPIA_ANCHE="NOTE.md:docs/appunti" bash <(curl -fsS __DELMINIO_URL__/aggancia.sh)
+
+**Con Codex**: la prova della sandbox (sezione «Se sei Codex») va fatta prima di
+questo comando. **Usa un terminale interattivo**: `exec_command` con `tty=true`.
+Dopo l'approvazione nel browser lo script può chiedere se il repo
+è lo stesso progetto di quelli già collegati, o una conferma sulle impostazioni
+di prima. Senza terminale si fermerebbe dopo aver già creato la chiave.
+Riporta la domanda all'utente e aspetta la sua risposta prima di rispondere.
+
+**Il comando aspetta l'approvazione fino a 10 minuti.** Se la tua CLI ferma un
+comando dopo un tempo — Claude Code e Qwen Code di serie dopo 2 minuti — lancialo
+col tempo massimo, 10 minuti (`timeout` 600000), o in background con l'uscita in un
+file che rileggi. Fermato a metà, il codice che mostrava non vale più: si rilancia, e
+l'utente approva quello nuovo.
+
+**Prima di lanciarlo, una domanda all'utente** (con ogni CLI): nel suo Delminio ci
+sono già altri repo collegati? Li vede nell'app, nella vista Git. Se ci sono e
+questo è **lo stesso progetto** (lo stesso lavoro, la stessa squadra), lancia con
+la risposta già data, così lo script non si ferma dopo l'approvazione e non serve
+approvare due volte:
+
+ DELMINIO_STESSA_STORIA=si bash <(curl -fsS __DELMINIO_URL__/aggancia.sh)
+
+Se è **un altro progetto**, non lanciare niente: va in un altro spazio (nell'app,
+«Spazi»), e si collega lì. Se non lo sa, lancia il comando normale: se lo script
+lo chiede, riporti la domanda all'utente e rilanci con la sua risposta.
+
+⚠️ Così, da un file: mai `curl … | bash`, che si mangia il resto dello script
+e finisce muto.
+
+Lo script stampa un **indirizzo da aprire**: dallo all'utente, che lo apre nel
+browser dove è già dentro Delminio e preme **Approva**. Poi aspetti: lo script
+riceve il permesso da solo e va avanti. Alla fine stampa cosa ha fatto e gli
+avvisi: riportali all'utente in parole sue, uno per riga — e dov'è la copia di
+sicurezza: il `LEGGIMI.md` lì dentro dice cosa contiene, e cosa non ha copiato e
+perché.
+
+⛔ **Il lavoro non finisce qui**: il computer è collegato, ma nessun agente con
+Delminio è ancora partito, e il riquadro dei primi passi resta aperto sull'ultima
+tappa, «Avvia l'agente». I punti 4 e 5 si fanno sempre, anche se l'utente ha fretta:
+senza, resta con un riquadro che non va via e non sa perché.
+
+## 4. Il comando dell'agente — ancora «Collega il computer»
+
+Delminio ha nel suo registro gli agenti che l'utente ha acceso nella tappa «I tuoi
+agenti», tutti con le regole di Delminio in cima: per esempio `opus5.5` su Claude
+Code, `sol6.1` su Codex, `zen` su OpenCode coi modelli gratuiti (l'elenco intero è la
+vista Agenti). Chiedi il sì all'utente, poi:
+
+ delminio eseguibili
+
+`delminio` è il comando che il collegamento ha appena messo accanto a quelli degli
+agenti (in `~/.local/bin`): funziona da qualunque cartella del progetto, ed è il nome
+con cui da qui in avanti si scrivono i comandi di Delminio. Se il terminale non lo
+trova, quella cartella non è nel PATH: aiutalo ad aggiungerla al profilo della sua
+shell, e intanto lancia `~/.local/bin/delminio eseguibili`.
+
+Scrive su questa macchina il comando di ogni agente la cui CLI c'è; quella che
+non c'è non la scarica. Se dice che la cartella dei comandi non è nel PATH,
+aiutalo ad aggiungerla. Poi chiedigli quale vuole usare fra quelli scritti.
+
+Se fra gli agenti accesi non ce n'è uno della CLI che sei tu, `delminio eseguibili`
+non ne scrive per lei. Chi amministra lo spazio (nel Cloud, da solo, è spesso l'utente
+stesso) lo aggiunge nella vista Agenti → **«Aggiungi agente»**: lì accende il modello,
+sceglie il ruolo e il nome, per OpenCode anche i gratuiti, per Qwen Code il modello
+del fornitore. Con questa sessione aperta il comando arriva da solo in pochi secondi:
+la vista dice «Pronto su …». Se non arriva, rilanci `delminio eseguibili`. Con Qwen Code la chiave del fornitore sta nell'ambiente della
+persona, mai in chat.
+
+## 5. Ripartire con Delminio — tappa «Avvia l'agente»
+
+Tu ti sei avviato prima del collegamento: Delminio non lo vedi, e non lo vedrai in
+questa sessione. Di' all'utente:
+
+1. di chiudere questa sessione;
+2. di aprire un terminale nella cartella del progetto e lanciare il comando del
+ modello che ha scelto (per esempio `sol6.1` o `opus5.5`: i nomi li ha
+ stampati il punto 4);
+3. **con Codex**: al primo avvio risponde sì a «Trust this folder?», e poi con
+ `/hooks` dà la fiducia ai ganci del plugin di Delminio («Trust all»): una volta
+ sola, gli aggiornamenti di Delminio non la chiedono di nuovo. Senza, Codex
+ parte ma non sente Delminio;
+4. di scrivere **`/apertura`** (con Claude Code e Qwen Code) o **`apertura`** (con
+ Codex, senza la barra).
+
+Da lì l'agente nuovo si avvia con Delminio, e il resto glielo spiega lui. L'ultima tappa dei primi passi, «Avvia l'agente», si spunta da sola appena si avvia.
+
+## Se sei Codex
+
+⚠️ **Se sei Codex**: spiega prima, in poche righe, che la sandbox limita file e
+rete dei comandi, mentre le conferme decidono quando chiedi il permesso. Non
+dedurre la modalità attiva dai default: `/permissions` la mostra e permette
+all'utente di sceglierla, incluso accesso completo. Senza sandbox non significa
+senza conferme; non proporre `--yolo` come scorciatoia e non cambiare tu le
+protezioni. Una scelta personale non cambia la riga condivisa nella vista Agenti.
+Per un comando necessario fuori dai limiti, chiedi l'approvazione di quel comando.
+
+**Codex su Linux, prima del collegamento**: prova il meccanismo, non soltanto la
+presenza di un pacchetto: `codex sandbox -c 'sandbox_mode="read-only"' -- true`.
+Se cade prima di eseguire `true`, è l'ambiente della sandbox che non parte,
+non un divieto sul lavoro chiesto. Su Ubuntu serve `bubblewrap`; su Ubuntu
+24.04 possono servire anche il profilo AppArmor del pacchetto `apparmor-profiles`
+e `apparmor-utils`. Proponi la cura, aspetta il sì, e riprova lo stesso comando.
+Non disabilitare la restrizione degli user namespace per tutta la macchina.
+Le istruzioni per l'utente, se quel profilo manca, sono:
+
+ sudo apt install bubblewrap apparmor-profiles apparmor-utils
+ sudo install -m 0644 /usr/share/apparmor/extra-profiles/bwrap-userns-restrict /etc/apparmor.d/
+ sudo apparmor_parser -r /etc/apparmor.d/bwrap-userns-restrict
+
+I comandi `sudo` cambiano il sistema: non eseguirli per abitudine né fuori dal
+sì dato per questa cura. Dall'eseguibile Delminio la prova si fa a ogni lancio,
+non a ogni gancio: anche dopo un verde possono cambiare le protezioni di sistema.
diff --git a/agent/stacca.en.md b/agent/stacca.en.md
new file mode 100644
index 0000000..355a01c
--- /dev/null
+++ b/agent/stacca.en.md
@@ -0,0 +1,76 @@
+# Disconnecting a project from Delminio — the text for the agent
+
+_You're the agent — Claude Code, Codex, Qwen Code or OpenCode — that the user has asked to disconnect their project from Delminio. After disconnecting, the project on this machine goes back to how it was before the connection: the CLI's settings, its commands, its MCP servers. The project's memories aren't lost: they're in the memory repository, which belongs to the user. Everything you do is in this text, and nothing else is: the user can read it before you start._
+
+_⚠️ Follow this text **word for word**. If it reached you summarised (a tool that reads web pages and returns an extract), stop: download it in full with `curl -fsSL __DELMINIO_URL__/stacca.en.md` and start again from there._
+
+## The three rules of the process
+
+1. **The user runs the disconnection, not you.** The command needs a terminal of their own and refuses to start from an agent's chat: disconnecting is a person's decision. You prepare, explain, and check afterwards.
+2. **Say it first, then do it.** Show every command and say in one line what it does before you run it. Run only the commands written here, and only the ones that read; anything that deletes is the user's decision, one thing at a time.
+3. **No secret goes through the chat.** Delminio's token doesn't need pasting anywhere: the disconnection finds it on its own.
+
+## 0. The plan, for the user
+
+In a few lines, before touching anything: you check that the work is safe, they run the disconnection from their own terminal, you look at what's left and tell them, and it's repeated on every machine where an agent works on this project. The space in Delminio isn't closed from here: see step 5.
+
+⚠️ It has to be done **while Delminio is running**: Delminio is what hands over the personal memories and revokes the key. If it isn't responding, the disconnection goes ahead anyway, but the personal memories stay in Delminio and the key has to be revoked from the interface.
+
+## 1. The work is safe
+
+Inside the project folder (the main clone, not a worktree):
+
+ git status --short
+ git worktree list
+ git log --oneline @{u}..HEAD 2>/dev/null
+
+- **Uncommitted work** or **unpushed commits**: tell them, and they decide whether to commit and push them first.
+- **Session worktrees** (`sessione/…` branches): the disconnection doesn't touch them. If their work has already been merged, they can be deleted afterwards (`git worktree remove <folder>`); if not, they get merged first.
+
+## 2. The disconnection
+
+Tell the user to open a terminal **of their own** in the project folder and run:
+
+ delminio disconnect
+
+It asks for confirmation, then, in this order:
+
+1. it saves the **personal memories** of the person running it next to the backup, in `~/.local/share/delminio/backup/<repo>-<fingerprint>/personali-<when>/`, outside the repository;
+2. on Claude Code it switches Delminio's plugin off in this project (it stays installed for the other connected projects on the machine), and puts the CLI's settings back as they were (`.claude/settings.local.json`, and for Codex and Qwen Code `.codex/hooks.json` and `.qwen/settings.json`). It removes only Delminio's parts: anything the user added after the connection stays. With OpenCode, it removes Delminio's plugin file from the project and the folder Delminio kept for OpenCode; it doesn't touch the user's own configuration;
+3. it removes Delminio's `/opening` and `/closing` commands (and their other names: the Italian `/apertura` and `/chiusura`, and the earlier `/start` and `/handoff`), and puts the previous ones back if there were any;
+4. it removes the “delminio” MCP server from the CLI, and puts the previous one back if there was one;
+5. it deletes Delminio's git hooks (`commit-msg`, `post-commit`, `post-rewrite`); if a hook belongs to the user and calls Delminio, it says so and leaves it to them;
+6. it removes Delminio's lines from `.git/info/exclude`;
+7. it **revokes the access key** of this machine, if no other project connected here uses it;
+8. it deletes the commands for this space's agents (names like `opus5.5`, `sol6.1`), if no other project here uses them;
+9. it deletes the clone of the memories that Delminio kept on this machine;
+10. last of all it deletes `.claude/delminio.sh`, itself.
+
+At the end it prints what it did and the warnings: have them read them out or paste them (there's nothing secret in them), and pass them on in your own words, one per line.
+
+## 3. What's left, on purpose
+
+Check, and report one line per item:
+
+ ls -a .claude
+ claude mcp list 2>/dev/null | grep -i delminio
+ git config core.hooksPath || git rev-parse --git-path hooks
+
+These stay on purpose, and the user decides about them:
+
+- **The backup**, in `~/.local/share/delminio/backup/<repo>-<fingerprint>/` (the disconnection prints the path; an older connection made it inside the repository, in `.claude/delminio-prima/`): settings, commands, instructions and memories of Claude Code, Codex and Qwen Code as they were before the connection. It's useful if they want to reconnect or compare; if they don't need it, it can be deleted.
+- **Their personal memories**, in Markdown, in the same folder under `personali-<when>/` (an older connection left them in `.claude/delminio-personali/`). They're theirs: they don't go into git, and they keep them wherever they like.
+- **The handoff commits** the agents left in the code repository (“Handoff S…”, or “Chiusura S…” in an Italian space): they're part of the project's history, and they stay.
+- **The session worktrees**, if there were any (step 1).
+
+If `claude mcp list` still shows “delminio”, or `.claude` still has `delminio.sh`, the disconnection isn't finished: go over the warnings again with the user and run it again.
+
+## 4. The other machines and the memory repository
+
+- **Every machine** where an agent works on this project has its own connection: the disconnection is repeated on each one, always from the user's terminal.
+- **The memory repository** stays theirs, complete, and readable without Delminio. Once no machine is connected any more, Delminio's **deploy key** is removed from the repository on their git host: Settings → Deploy keys. While it's there, Delminio can still write to it.
+- If a key wasn't revoked (the disconnection said so), the user revokes it from Delminio's interface, in the “Access” view.
+
+## 5. The space in Delminio
+
+Disconnecting is about machines, not the space: what was created in Delminio stays in Delminio for as long as the space exists. How a space is closed is in the guide, on the “Your data” page, § Leaving. It isn't something for you to do: tell them, and stop here.
diff --git a/agent/stacca.md b/agent/stacca.md
new file mode 100644
index 0000000..2067573
--- /dev/null
+++ b/agent/stacca.md
@@ -0,0 +1,126 @@
+# Staccare un progetto da Delminio — il testo per l'agente
+
+_Sei l'agente — Claude Code, Codex, Qwen Code o OpenCode — a cui l'utente ha chiesto di
+staccare il suo progetto da Delminio. Dopo lo stacco, su questa macchina il
+progetto torna com'era prima del collegamento: le impostazioni della CLI, i suoi
+comandi, i suoi server MCP. Le memorie del progetto non si perdono: stanno nel
+repository delle memorie, che è dell'utente. L'utente può leggere questo testo
+prima di te, e niente di quello che fai sta altrove._
+
+_⚠️ Questo testo si segue **parola per parola**. Se ti è arrivato riassunto
+(uno strumento che legge le pagine web e ne restituisce un estratto), fermati:
+scaricalo intero con `curl -fsSL __DELMINIO_URL__/stacca.md` e riparti da lì._
+
+## Le tre regole del giro
+
+1. **Lo stacco lo lancia l'utente, non tu.** Il comando vuole un terminale suo
+ e si rifiuta di partire dalla chat di un agente: staccarsi è una decisione
+ di una persona. Tu prepari, spieghi, e dopo controlli.
+2. **Prima dici, poi fai.** Ogni comando lo mostri e dici in una riga cosa fa,
+ prima di lanciarlo. Lanci solo i comandi scritti qui, e solo quelli che
+ leggono; ciò che cancella lo decide l'utente, una cosa per volta.
+3. **Nessun segreto passa dalla chat.** Il token di Delminio non serve
+ incollarlo da nessuna parte: lo stacco lo trova da sé.
+
+## 0. Il piano, all'utente
+
+In poche righe, prima di toccare niente: controlli che il lavoro sia al sicuro,
+lui lancia lo stacco dal suo terminale, tu guardi cosa è rimasto e glielo dici,
+e si ripete su ogni macchina dove lavora un agente su questo progetto. Lo
+spazio in Delminio non si chiude da qui: vedi il punto 5.
+
+⚠️ Va fatto **con Delminio acceso**: è lui che consegna le memorie personali e
+revoca la chiave. Se non risponde, lo stacco va avanti lo stesso, ma le
+personali restano in Delminio e la chiave va revocata dall'interfaccia.
+
+## 1. Il lavoro al sicuro
+
+Dentro la cartella del progetto (il clone principale, non un worktree):
+
+ git status --short
+ git worktree list
+ git log --oneline @{u}..HEAD 2>/dev/null
+
+- **Lavoro non committato** o **commit non spinti**: diglielo, e decide lui se
+ committarli e spingerli prima.
+- **Worktree delle sessioni** (rami `sessione/…`): lo stacco non li tocca. Se
+ il loro lavoro è già unito si possono eliminare dopo
+ (`git worktree remove <cartella>`); se no, prima si uniscono.
+
+## 2. Lo stacco
+
+Di' all'utente di aprire un terminale **suo** nella cartella del progetto e di
+lanciare:
+
+ delminio stacca
+
+Chiede conferma, poi, nell'ordine:
+
+1. salva le **memorie personali** di chi lo lancia accanto alla copia di
+ sicurezza, in `~/.local/share/delminio/backup/<repo>-<impronta>/personali-<quando>/`,
+ fuori dal repo;
+2. su Claude Code spegne in questo progetto il plugin di Delminio (resta
+ installato per gli altri progetti collegati della macchina), e rimette le
+ impostazioni della CLI com'erano (`.claude/settings.local.json`, e per Codex e
+ Qwen Code `.codex/hooks.json` e `.qwen/settings.json`): rimuove solo i pezzi di
+ Delminio, e ciò che l'utente ha aggiunto dopo il collegamento resta.
+ Con OpenCode rimuove dal progetto il file del plugin di Delminio e la cartella che
+ Delminio teneva per OpenCode; la configurazione della persona non la tocca;
+3. rimuove i comandi `/apertura` e `/chiusura` di Delminio, e rimette quelli
+ di prima se c'erano;
+4. rimuove il server MCP «delminio» dalla CLI, e rimette quello di prima se
+ c'era;
+5. elimina i ganci git di Delminio (`commit-msg`, `post-commit`, `post-rewrite`); se un gancio
+ è dell'utente e chiama Delminio, lo dice e lo lascia a lui;
+6. rimuove da `.git/info/exclude` le righe di Delminio;
+7. **revoca la chiave d'accesso** di questa macchina, se nessun altro progetto
+ collegato qui la usa;
+8. elimina i comandi degli agenti di questo spazio (i nomi come `opus5.5`,
+ `sol6.1`), se nessun altro progetto di qui li usa;
+9. elimina il clone delle memorie che Delminio teneva su questa macchina;
+10. per ultimo elimina `.claude/delminio.sh`, sé stesso.
+
+Alla fine stampa cosa ha fatto e gli avvisi: fatteli dire o incollare (non c'è
+niente di segreto) e riportali in parole tue, uno per riga.
+
+## 3. Cosa è rimasto, apposta
+
+Controlla e riporta in una riga per voce:
+
+ ls -a .claude
+ claude mcp list 2>/dev/null | grep -i delminio
+ git config core.hooksPath || git rev-parse --git-path hooks
+
+Restano di proposito, e li decide l'utente:
+
+- **La copia di sicurezza**, in `~/.local/share/delminio/backup/<repo>-<impronta>/`
+ (lo stacco stampa il percorso; un collegamento più vecchio la faceva dentro il
+ repo, in `.claude/delminio-prima/`): com'erano, prima del collegamento,
+ impostazioni, comandi, istruzioni e memorie di Claude Code, Codex e Qwen Code.
+ Serve se vuole ricollegare o confrontare; se non gli serve si cancella.
+- **Le sue memorie personali**, in Markdown, nella stessa cartella in
+ `personali-<quando>/` (un collegamento più vecchio le lasciava in
+ `.claude/delminio-personali/`). Sono sue: non entrano in git, e le tiene dove vuole.
+- **I commit delle consegne** che gli agenti hanno lasciato nel repository del codice («Chiusura S…»): sono storia del progetto, e restano.
+- **I worktree delle sessioni**, se ce n'erano (punto 1).
+
+Se `claude mcp list` mostra ancora «delminio», o in `.claude` c'è ancora
+`delminio.sh`, lo stacco non è finito: rileggi gli avvisi con l'utente e
+rilancialo.
+
+## 4. Le altre macchine e il repository delle memorie
+
+- **Ogni macchina** dove un agente lavora su questo progetto ha il suo
+ collegamento: lo stacco si ripete su ognuna, sempre dal terminale dell'utente.
+- **Il repository delle memorie** resta suo, completo, leggibile anche senza
+ Delminio. Quando nessuna macchina è più collegata, la **chiave di deploy**
+ di Delminio si rimuove dal repository, nel suo git host: Impostazioni → Chiavi
+ di deploy. Finché c'è, Delminio può ancora scriverci.
+- Se una chiave non si è revocata (lo stacco l'ha detto), l'utente la revoca
+ dall'interfaccia di Delminio, nella carta «Accesso».
+
+## 5. Lo spazio in Delminio
+
+Lo stacco riguarda le macchine, non lo spazio: ciò che è stato creato in Delminio resta in Delminio finché lo spazio vive. Come si chiude uno spazio lo dice la guida,
+alla pagina «I vostri dati», § Andarsene. Non è una cosa da fare tu: diglielo, e ti
+fermi qui.
diff --git a/enterprise/INFORMATIVA.md b/enterprise/INFORMATIVA.md
new file mode 100644
index 0000000..fd86613
--- /dev/null
+++ b/enterprise/INFORMATIVA.md
@@ -0,0 +1,100 @@
+# Delminio — Informativa sul contatto giornaliero e sulle segnalazioni
+
+_Ai sensi degli artt. 13 e 14 del Regolamento (UE) 2016/679 («GDPR»). Versione
+1.7 del 9 novembre 2026._
+
+## Che cosa riguarda
+
+Delminio funziona sui sistemi del Licenziatario e **non invia mai al Licenziante
+le memorie, i messaggi, gli account né alcun altro contenuto scritto dagli
+utenti**, salvo le segnalazioni che un utente decide di mandarci. Questa
+informativa riguarda il controllo della licenza — una volta al giorno
+l'installazione chiama il servizio di licenze del Licenziante per sapere se la
+chiave è ancora valida — e le segnalazioni (in fondo).
+
+## Titolare del trattamento
+
+Luigi Casini, Località Tregozzano 45, 52100 Arezzo (AR), P. IVA 02356410510,
+e-mail privacy@delminio.com, PEC casini.luigi@pec.it.
+
+## Quali dati
+
+Ad ogni contatto il servizio riceve:
+- la chiave di licenza, che il Licenziante stesso ha emesso (contiene
+ il suo identificativo, il cliente indicato nell'Ordine, i posti e la
+ scadenza): prova che l'installazione è di chi la tiene;
+- un identificativo casuale dell'installazione, generato al primo avvio;
+- la versione del Software;
+- il numero di account attivi nell'installazione (un numero, non i nomi);
+- l'indirizzo IP da cui arriva la chiamata, come per ogni connessione di rete.
+
+Nient'altro: né i nomi degli account, né le memorie, né i loro titoli.
+
+Questi dati, di norma, riguardano un'azienda e non una persona. Possono
+diventare dati personali quando il Licenziatario è una persona fisica (per
+esempio un professionista) o quando l'indirizzo IP è riconducibile a una
+persona.
+
+## Perché, e su quale base
+
+| Finalità | Base giuridica |
+|---|---|
+| verificare che la licenza sia valida e non revocata, e far passare il Software in sola lettura quando non lo è | esecuzione del contratto di licenza (art. 6.1.b GDPR) |
+| contare i posti in uso rispetto a quelli acquistati | esecuzione del contratto (art. 6.1.b) |
+| sapere quali versioni sono in uso, per gli aggiornamenti e l'assistenza | legittimo interesse a mantenere il Software (art. 6.1.f) |
+| accertare l'uso oltre i posti o la durata acquistati, o con una chiave revocata | legittimo interesse a tutelare i propri diritti (art. 6.1.f) |
+| limitare le chiamate eccessive al servizio (l'indirizzo IP, tenuto in memoria per non più di dieci minuti) | legittimo interesse alla sicurezza del servizio (art. 6.1.f) |
+
+Il conferimento è necessario: senza il contatto, dopo quindici giorni il
+Software passa in sola lettura.
+
+## Per quanto tempo
+
+- i dati dell'installazione (identificativi, versione, numero di account, date
+ del primo e dell'ultimo contatto): per la durata del contratto e per 12 mesi
+ dopo la sua cessazione, poi vengono cancellati;
+- gli indirizzi IP: in memoria per non più di dieci minuti per il limite alle chiamate; nei
+ registri tecnici del servizio solo quando una richiesta va in errore, per un mese,
+ poi si cancellano da soli.
+
+## Chi li vede
+
+Il Licenziante, che ospita il servizio di licenze su un server di Hetzner
+Online GmbH in Germania, nominata responsabile del trattamento. I dati non sono
+diffusi e non sono trasferiti fuori dallo Spazio economico europeo.
+
+## I diritti dell'interessato
+
+Chi è interessato può chiedere al titolare l'accesso ai dati, la rettifica, la
+cancellazione, la limitazione, e può opporsi ai trattamenti basati sul
+legittimo interesse (artt. 15-22 GDPR), scrivendo a privacy@delminio.com. Ha
+diritto di proporre reclamo al Garante per la protezione dei dati personali
+(www.garanteprivacy.it).
+
+## Le segnalazioni
+
+Quando un utente lo chiede, o lo approva, il suo agente ci manda una
+segnalazione: un testo scritto apposta per chiedere una funzione o descrivere
+un difetto. Riceviamo il testo, l'identificativo della chiave e
+dell'installazione, la versione e il nome dell'account che l'ha mandata. Il
+Software maschera le credenziali che riconosce, e l'agente ha la regola di non
+riportarvi memorie né dati di persone; se ve ne finiscono, li trattiamo solo
+per rispondere.
+
+| Finalità | Base giuridica |
+|---|---|
+| rispondere alla segnalazione e correggere o migliorare il Software | esecuzione del contratto (art. 6.1.b) e legittimo interesse a mantenere il Software (art. 6.1.f) |
+
+Le conserviamo per la durata del contratto e per 12 mesi dopo. L'amministratore
+del Licenziatario può spegnere le segnalazioni dal pannello: da quel momento non
+parte più niente.
+
+## I dati che restano al Licenziatario
+
+Per i dati che il Licenziatario e i suoi utenti scrivono in Delminio, titolare è
+il Licenziatario stesso: il Licenziante non vi accede (art. 6 del contratto di
+licenza) e per essi non è responsabile del trattamento. La copia delle memorie
+che Delminio tiene in un repository git va dai sistemi del Licenziatario al
+repository che il Licenziatario sceglie, mai al Licenziante (art. 9 del
+contratto); se quel repository sta presso un fornitore esterno, il rapporto con
+il fornitore è del Licenziatario.
diff --git a/enterprise/INSTALLA.en.md b/enterprise/INSTALLA.en.md
new file mode 100644
index 0000000..92fcfe1
--- /dev/null
+++ b/enterprise/INSTALLA.en.md
@@ -0,0 +1,177 @@
+# Installing Delminio — the prompt for the agent
+
+_You're the agent the user has asked to install Delminio. Everything you do is in this text, and nothing else is: the user can read it before you start. The scripts Delminio brings with it do the checks; you explain, ask, run and verify._
+
+_⚠️ Follow this text **word for word**. If it reached you summarised (a tool that reads web pages and returns an extract), stop: download it in full with `curl -fsSL <the address>` and start again from there._
+
+## The three rules of the process
+
+1. **Say it first, then do it.** Show every command and say in one line what it does before you run it. Run only the commands written here; if you need another one (a missing package, a permission), suggest it and wait for approval.
+2. **The user's decisions are theirs.** They accept the licence themselves, in their own words: you don't answer “yes” on their behalf, not even if they ask you to in a hurry — tell them where to read it and wait.
+3. **No secret goes through the chat.** The admin's password, the licence, the embedder's key are typed into Delminio's interface, not here. If the user pastes one, tell them to change it afterwards: it has ended up in the conversation.
+
+When a step fails: read the message (the scripts say why and what to do), explain it to the user in plain words, fix it together and run it again. Running it again does no harm: what's already there isn't touched.
+
+## 0. The plan, for the user
+
+In a few lines, before touching anything: you check what the machine needs, you get Delminio (a Docker image, with its installation kit inside), you have them read the licence, you ask them for the memory repository, you install and start it, they create their account and set up the embedder from the interface, you connect their project, and you check everything. Then ask them two things: **which project** they'll work on with Delminio (the folder of the clone, on this machine) and **where** to install it — suggest `~/delminio`.
+
+## 1. What's needed
+
+Check, and report one line per item:
+
+ uname -s && docker compose version && docker info --format '{{.ServerVersion}}'
+ command -v git curl python3
+ git config user.name && git config user.email
+ git -C <the project> remote get-url origin
+
+- **Linux**, **Docker** usable by this user, `git`, `curl` and `python3`, and git configured with their name and email: without these, stop and tell them how to fix it. Delminio runs on this machine: if the user is on Windows, this CLI has to run in WSL or in an SSH session of the desktop app on a Linux machine — `LEGGIMI.en.md` § What you need.
+- **The project** with a remote they push to: if it's missing, carry on anyway — the handoff and the merge will stay on this machine — and tell them so.
+- **The embedder, on their network**: for Delminio Enterprise it's a requirement, so that the text of the memories doesn't leave the client's network. Our recommendation is `bge-m3` with Ollama, which runs even on CPU only (the model is 1.2 GB), on this machine or another one on the network. An outside service (for example `bge-m3` on Cloudflare Workers AI) only if the admin knowingly chooses to let the text leave: tell them in those words. Without an embedder, the memories are searched by words and not by meaning: you can start and set it up later.
+
+## 2. Getting Delminio
+
+Delminio is a Docker image, and its installation kit — the compose file, the installer, the licence, this very text — travels inside it. The installation folder goes **outside any repository**: a `.env` with the secret and the memory folder will be created there.
+
+ mkdir -p ~/delminio && cd ~/delminio
+ git rev-parse --show-toplevel
+
+The second command **must fail** (“not a git repository”). If it answers with a path, the folder is inside a repository: choose another one with the user. If the folder already has a `.env`, there's already a Delminio there: stop and ask them — if they want to update it, that's § *Updating*, below.
+
+Delminio is downloaded from **our registry**, `registry.delminio.com`, with the username and password the user received from us. Ask them also for the **release key** written in the annex of their contract (a line starting with `ssh-ed25519`). They give the access themselves, once per machine, from a terminal of theirs: the password doesn't go through you.
+
+ docker login registry.delminio.com
+
+Then the latest version and its signature — `latest`, or a precise number (`1.40.3`) if the user asks for one, in every command below. Before running it, the signature:
+
+ docker pull -q registry.delminio.com/delminio:latest
+ docker pull -q registry.delminio.com/delminio:latest.firma
+ c=$(docker create registry.delminio.com/delminio:latest.firma x)
+ docker cp -q "$c:/firma.txt" /tmp/ && docker cp -q "$c:/firma.txt.sig" /tmp/ && docker rm "$c"
+ printf 'rilasci@delminio.com %s\n' '<the key from the contract>' > /tmp/firmatari
+ ssh-keygen -Y verify -f /tmp/firmatari -I rilasci@delminio.com -n delminio-rilascio -s /tmp/firma.txt.sig < /tmp/firma.txt
+ cat /tmp/firma.txt
+ docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' registry.delminio.com/delminio:latest
+
+It must answer “Good "delminio-rilascio" signature”, and the last word of `firma.txt` (`registry.delminio.com/delminio@sha256:…`) must be among the lines of the last command. Otherwise stop: the image doesn't come from us, or it has been tampered with; remove it (`docker image rm`) and tell them. Then the kit:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ rm -f /tmp/firma.txt /tmp/firma.txt.sig /tmp/firmatari
+ cat VERSIONE
+
+The installer downloads by itself the version written in `VERSIONE` (the same content as the one just verified), and the compose file never downloads another: an update is your decision.
+
+Report the version and the files that appeared in the folder to the user.
+
+## 3. The licence
+
+Tell them to open and read `LICENZA.md` (what they can do with Delminio) and `INFORMATIVA.md` (what's sent to us: the licence check once a day, and the reports they send themselves), in the installation folder. If a translation of either one is in the folder (`LICENZA.en.md`, `INFORMATIVA.en.md`), the installer shows that one. If they ask you for a summary, give it, but a summary isn't reading it: tell them so. Then **wait for them to write that they've read them and accept them**. Without those words, nothing gets installed.
+
+Then the clauses the law requires to be approved separately, listed at the end of `LICENZA.md` (“Approvazione specifica”, the specific approval): show them, and ask them to write **their full name and on whose behalf they approve them** (for example “Jane Smith for Acme Ltd”). They write that name, never you: without it, nothing gets installed.
+
+## 4. The memory repository
+
+The memories live in Delminio and, as files, in a git repository **of theirs**, empty, on GitHub, Forgejo or Gitea: it's the copy outside this machine, and it also carries the Backlog, the protected decisions and the texts of the agent roles. **If the repository belongs to an earlier Delminio** (a lost server, a move), it can be full: at the first start Delminio sees an empty database and a full repository, and restores memories, Backlog, protected decisions and agent roles automatically. Personal memories and those reserved for the admin don't go there: the computer of the person who owns them keeps a copy, and brings them back to a Delminio rebuilt from this repository. The rest — accounts and settings — is only in Delminio's data folder, which is backed up every night into `copie/`: tell them to put that folder in their backup routine. Ask them for the address (ssh or https) and check that it can be reached:
+
+ git ls-remote <address>
+
+If it answers with a permissions error, the git credentials on this machine aren't enough: help them sort them out (an SSH key registered on their git host, or a token) before going on.
+
+## 5. Installing
+
+With their words on the licence, their name for the clauses and the repository's address, from the installation folder:
+
+ DELMINIO_LINGUA=en DELMINIO_ACCETTO=yes DELMINIO_APPROVO="<name> for <whom>" DELMINIO_MEMORIA_REMOTO=<address> bash installa.sh
+
+It writes the `.env`, clones the memories into `memoria/`, tests the push, starts Delminio and waits for it to respond. `DELMINIO_LINGUA=en` makes the installer speak English and records the language with their acceptance; the space's language is chosen in the interface (step 6). At the end it prints the address and the **code for the first sign-in**. Report both to the user. If they want Delminio as an app on their phone, they switch it on themselves from Settings → “The app on your phone”, which tells them the rest.
+
+## 6. From the interface, the user does it
+
+Give them the address and wait for them to say “done” at each point:
+
+1. **The first sign-in**: they open the address and create their account, which will be the **admin**, with the code from step 5. They choose the password and type it themselves, nobody else.
+2. **Settings → “The space's language”**: they choose English, before anything else. It's the language of Delminio's rules and of what Delminio tells the agents, and it can only be changed while the space is empty: from the first memory on, it stays.
+3. **Settings → “The licence”**: they paste the licence they received.
+4. **Settings → “The embedder”**: they choose theirs, paste the key, and press Test. It must say it responds.
+5. **Settings → “Memories on git”**: they copy the key Delminio shows and add it, on their git host, to the memory repository as a **deploy key with write access** (GitHub: Settings → Deploy keys, “Allow write access”; Forgejo and Gitea: Settings → Deploy keys). Then they press Test: it must say the push goes through. That's how Delminio saves the memories to their repository at the end of every session, without any agent touching the folder.
+6. **Settings → “Features”**: for now they leave them all switched on; the first session in the project will help them switch off what they don't need.
+7. **Access** (the button at the top) **→ “Connect a repository”**: the command is there. **They** run it, in their own terminal, inside the project's clone. It shows an eight-letter code; they type it in Access, see the name of their machine and approve. The key reaches the script from Delminio and doesn't pass through any screen — nor through here: ⛔ a token is never asked for in the chat, and if they paste one, the check stops it before you read it. If they paste you the output, read it: a ⚠️ says what's missing and why, a ❌ gets fixed and run again.
+
+## 7. The test
+
+Check it yourself, and report one line per item:
+
+ docker compose ps
+ git -C memoria log --oneline -3
+ cd <the project> && test -x .claude/delminio.sh && DELMINIO_PROVA=1 delminio apertura
+
+- Delminio is up (`running`), and the memory repository has the seeding commit.
+- The project has the client, and the opening answers **“the first session”**: it means Delminio sees it and that it doesn't have any memories of its own yet.
+
+The tool test happens after step 8, with the command for the CLI the user chose. Don't install Claude Code to test a project that only uses Codex.
+
+If an item doesn't check out, don't wrap up: look at it together.
+
+## 8. Delminio's agent, on this machine
+
+An agent starts better with Delminio's rules **at the top**, in the system prompt, instead of read afterwards: a command on this machine puts them there, written from Delminio's register (the Agents view: Delminio starts with one agent for each model it supports in its newest version, for example `opus5.5` and `fable5.2` on Claude Code and `sol6.1` on Codex, all with Delminio's rules at the top; on this machine, only those whose CLI is installed get written). Ask them whether they want it, and what to call it. If they do, inside the project — and only if they want another name, first the `rename`:
+
+ delminio agents rename <current name> <name>
+ delminio agents
+
+It downloads the CLI at the version set in the register (alongside the others, only if the checksum matches) and writes the command. Pass on what it prints; if it says the folder isn't on the PATH, help them add the line it shows to their shell profile. The command follows the register on its own — a new version chosen in the view arrives at the first opening —; if they change it, it stays theirs. If they don't want it: `delminio agents no`, and nobody suggests it again.
+
+Now, inside the project, test the tool with **that command**, not with another CLI: on Codex, Delminio's launch is also what gives it the MCP server. Replace `<name>` with the command you've just written. With Claude Code:
+
+ <name> -p "Call the delminio tool with operation=health. Reply with one line only: DELMINIO OK and the number of memories, or DELMINIO KO and why." --allowedTools=mcp__plugin_delminio_memoria__delminio
+
+With Codex:
+
+ <name> exec "Call the delminio tool with operation=health. Reply with one line only: DELMINIO OK and the number of memories, or DELMINIO KO and why."
+
+If they chose a Qwen Code agent, the same prompt with `<name> -p`. If they use Claude Code without Delminio's command, the first command uses `claude`. It must answer **“DELMINIO OK”**: that's the proof their CLI really sees the tool. The first interactive session, on the other hand, is theirs: you don't launch it, and the memories there are created with their approval. If an item doesn't check out, look at it together before saying goodbye.
+
+Their **profile** (how they want to work, which every agent will carry at the top) and the rules delivered in full are suggested to them by the first session: here, the Delminio tool isn't available yet to write them.
+
+## 9. Saying goodbye
+
+Tell them like this: “Delminio is up and the project is connected. Close this CLI, open `<the command's name>` (or `claude`, if they didn't want it) inside the project and type `/opening`. The first session maps the codebase: it reads the repository, asks you who you are and how you want to work, suggests the first memories one at a time for your approval, and which features you need.” If the connection said that what was there before is safe (the backup in `~/.local/share/delminio/backup/`), add: “and it starts with what you had before: nothing is lost, you'll go over it together”.
+
+And one line about afterwards: the installation folder stays Delminio's home (the `.env`, `memoria/`, the kit). When the interface says there's a new version, just ask an agent to update Delminio: how is in `INSTALLA.en.md` in there, § *Updating*.
+
+## Updating
+
+If the user asks you to update a Delminio that's already there:
+
+1. **With all sessions closed.** Ask them whether any agents are at work on the connected projects: a file just written and not yet committed would end up in the update's commit. Wait for them to finish.
+2. The update arrives like the installation: from the registry, with the signature verified before running it. From the installation folder (the one with the `.env`), with the commands of § *Getting Delminio* up to the “Good … signature” and the matching digest, then:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ rm -f /tmp/firma.txt /tmp/firma.txt.sig /tmp/firmatari
+ bash installa.sh
+
+ If the `.env` has `DELMINIO_IMMAGINE` (a registry of yours that mirrors ours), use that instead of `registry.delminio.com/delminio`.
+
+ The new kit is written over the old one; the `.env`, `memoria/` and the database stay where they are. The installer says “update: <old> → <new>”, restarts Delminio (which copies its database before changing its structure) and commits Delminio's realigned rules to the memory repository.
+3. Report the update line. The connected projects reconnect on their own at the first opening: there's nothing else to do.
+
+## Leaving
+
+If the user wants to uninstall Delminio from this machine:
+
+1. **First, on every machine where an agent works**, inside the connected repository and from a terminal of their own: `delminio disconnect`. With Delminio still running: it leaves them their personal memories (they aren't in git), revokes the token, and puts the CLI back as it was.
+2. From the installation folder: `bash installa.sh via`. It copies the database next to the `.env`, stops and removes the container and the image. `memoria/` and the volume stay.
+3. Tell them clearly: **nothing is deleted**. The memories are in their memory repository; deleting the rest (`docker volume rm`, the folder) is their own action, and you don't do it.
+
+## Going back
+
+If after an update something isn't right and the user wants the previous version:
+
+1. **With all sessions closed**, as for updating.
+2. From the installation folder, with the **current** kit (the old one doesn't know this command):
+
+ bash installa.sh indietro
+
+ It puts back the previous image and the **database as it was before the update** (the copy Delminio makes on its own before migrating); the current one stays among the copies. If the previous image is no longer on the machine, it downloads it again from the registry; if the registry doesn't give it, it says so.
+3. Tell them clearly: **whatever was written after the update isn't in the previous database**. The memories from that period aren't lost — their `.md` files stay in `memoria/`, uncommitted (`git -C memoria status`) — and you decide with them which ones to save again. The previous Delminio also rewrites `MEMORY.md` and Delminio's rules as they were.
+4. To update again, later: `bash installa.sh`.
diff --git a/enterprise/INSTALLA.md b/enterprise/INSTALLA.md
new file mode 100644
index 0000000..5790ea2
--- /dev/null
+++ b/enterprise/INSTALLA.md
@@ -0,0 +1,320 @@
+# Installare Delminio — il prompt per l'agente
+
+_Sei l'agente a cui l'utente ha chiesto di installare Delminio. Questo testo è
+tutto ciò che fai: l'utente lo può leggere prima di te, e niente di quello che
+fai sta altrove. Gli script che Delminio porta con sé fanno i controlli; tu
+spieghi, chiedi, lanci e verifichi._
+
+_⚠️ Questo testo si segue **parola per parola**. Se ti è arrivato riassunto
+(uno strumento che legge le pagine web e ne restituisce un estratto), fermati:
+scaricalo intero con `curl -fsSL <l'indirizzo>` e riparti da lì._
+
+## Le tre regole del giro
+
+1. **Prima dici, poi fai.** Ogni comando lo mostri e dici in una riga cosa fa,
+ prima di lanciarlo. Lanci solo i comandi scritti qui; se ne serve un altro
+ (un pacchetto mancante, un permesso) lo proponi e aspetti il sì.
+2. **Ciò che decide l'utente lo decide lui.** La licenza la accetta lui, con
+ parole sue: tu non rispondi «sì» al suo posto, nemmeno se te lo chiede di
+ fretta — gli dici dove leggerla e aspetti.
+3. **Nessun segreto passa dalla chat.** La password dell'amministratore, la licenza, la
+ chiave dell'embedder si scrivono nell'interfaccia di Delminio, non qui. Se
+ l'utente te ne incolla una, digli di cambiarla dopo: è finita nella
+ conversazione.
+
+Quando un passo fallisce: leggi il messaggio (gli script dicono il perché e
+cosa fare), spiegalo all'utente in parole sue, sistemate insieme e rilancia. Si
+rilancia senza danni: ciò che c'è già non si tocca.
+
+## 0. Il piano, all'utente
+
+In poche righe, prima di toccare niente: controlli cosa serve sulla macchina,
+prendi Delminio (un'immagine Docker, e dentro il suo kit d'installazione), gli fai leggere la
+licenza, gli chiedi il repo delle memorie, installi e avvii, lui crea il suo
+accesso e imposta l'embedder dall'interfaccia, agganci il suo progetto,
+verifichi tutto. Poi chiedigli due cose: **su quale progetto** lavorerà con
+Delminio (la cartella del clone, su questa macchina) e **dove** installarla —
+proponi `~/delminio`.
+
+## 1. Cosa serve
+
+Controlla e riporta in una riga per voce:
+
+ uname -s && docker compose version && docker info --format '{{.ServerVersion}}'
+ command -v git curl python3
+ git config user.name && git config user.email
+ git -C <il progetto> remote get-url origin
+
+- **Linux**, **Docker** che risponde a questo utente, `git`, `curl`
+ e `python3`, e git che sa chi è: senza, ci si ferma e gli dici come si
+ sistema. Delminio gira su questa macchina: se l'utente sta su Windows, questa
+ CLI deve girare in WSL o in una sessione SSH dell'app desktop su una
+ macchina Linux — `LEGGIMI.md` § Cosa serve.
+- **Il progetto** con un remoto su cui pusha: se manca, si va avanti lo
+ stesso — la chiusura e il merge resteranno su questa macchina — e glielo dici.
+- **L'embedder, nella sua rete**: per Delminio Enterprise è un requisito, perché
+ il testo delle memorie non esca dalla rete del cliente. Il consiglio è
+ `bge-m3` con Ollama, che gira anche solo su CPU (il modello pesa 1,2 GB), su
+ questa macchina o su un'altra della rete. Un servizio fuori (per esempio
+ `bge-m3` su Cloudflare Workers AI) solo se l'amministratore sceglie, sapendolo,
+ di far uscire il testo: diglielo con queste parole. Senza embedder le memorie
+ si cercano per parole e non per senso: si può partire e impostarlo dopo.
+
+## 2. Prendere Delminio
+
+Delminio è un'immagine Docker, e il suo kit d'installazione — il compose, l'installatore, la
+licenza, questo stesso testo — viaggia dentro di lei. La cartella
+d'installazione va **fuori da ogni repo**: lì nasceranno un `.env` col
+segreto e la cartella delle memorie.
+
+ mkdir -p ~/delminio && cd ~/delminio
+ git rev-parse --show-toplevel
+
+Il secondo comando **deve fallire** («not a git repository»). Se risponde con
+un percorso, la cartella sta dentro un repo: scegline un'altra con l'utente.
+Se nella cartella c'è già un `.env`, lì c'è già un Delminio: fermati e
+chiediglielo — se vuole aggiornarla è il § *Aggiornare*, qui sotto.
+
+Delminio si scarica dal **nostro registro**, `registry.delminio.com`, con
+l'utente e la password che l'utente ha ricevuto da noi. Chiedigli anche la
+**chiave dei rilasci** scritta nell'allegato del suo contratto (una riga che
+comincia con `ssh-ed25519`). L'accesso lo dà lui, una volta per macchina, da un
+suo terminale: la password non passa da te.
+
+ docker login registry.delminio.com
+
+Poi l'ultima versione e la sua firma — `latest`, o un numero preciso (`1.40.3`)
+se l'utente lo chiede, in tutti i comandi qui sotto. Prima di farla girare, la
+firma:
+
+ docker pull -q registry.delminio.com/delminio:latest
+ docker pull -q registry.delminio.com/delminio:latest.firma
+ c=$(docker create registry.delminio.com/delminio:latest.firma x)
+ docker cp -q "$c:/firma.txt" /tmp/ && docker cp -q "$c:/firma.txt.sig" /tmp/ && docker rm "$c"
+ printf 'rilasci@delminio.com %s\n' '<la chiave del contratto>' > /tmp/firmatari
+ ssh-keygen -Y verify -f /tmp/firmatari -I rilasci@delminio.com -n delminio-rilascio -s /tmp/firma.txt.sig < /tmp/firma.txt
+ cat /tmp/firma.txt
+ docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' registry.delminio.com/delminio:latest
+
+Deve rispondere «Good "delminio-rilascio" signature», e l'ultima parola di
+`firma.txt` (`registry.delminio.com/delminio@sha256:…`) deve stare fra le righe
+dell'ultimo comando. Altrimenti fermati: l'immagine non viene da noi, o è stata
+toccata; toglila (`docker image rm`) e diglielo. Poi il kit:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ rm -f /tmp/firma.txt /tmp/firma.txt.sig /tmp/firmatari
+ cat VERSIONE
+
+L'installatore scarica da sé la versione scritta in `VERSIONE` (lo stesso
+contenuto di quella appena verificata), e il compose non ne scarica mai
+un'altra: un aggiornamento lo decidete voi.
+
+Riporta all'utente la versione e i file comparsi nella cartella.
+
+## 3. La licenza
+
+Digli di aprire e leggere `LICENZA.md` (cosa può fare con Delminio) e
+`INFORMATIVA.md` (cosa parte verso di noi: il controllo della licenza una volta
+al giorno, e le segnalazioni che manda lui), nella cartella d'installazione. Se ti chiede un riassunto, faglielo, ma
+un riassunto non è la lettura: diglielo. Poi **aspetta che scriva lui che li ha
+letti e li accetta**. Senza quelle parole non si installa.
+
+Poi le clausole che la legge vuole approvate a parte, elencate in fondo a
+`LICENZA.md` («Approvazione specifica»): mostragliele, e chiedigli di
+scriverti **il suo nome e cognome e per chi le approva** (per esempio «Mario
+Rossi per Acme srl»). Quel nome lo scrive lui, mai tu: senza, non si installa.
+
+## 4. Il repo delle memorie
+
+Le memorie vivono in Delminio e, come file, in un repo git **suo**, vuoto, su
+GitHub, Forgejo o Gitea: è la copia fuori da questa macchina, e porta anche il
+Backlog, le decisioni protette e i testi dei ruoli. **Se il repo è quello di un
+Delminio di prima** (un server perso, un trasloco), va bene pieno: al primo avvio
+Delminio vede il suo database nuovo e la cartella piena, e si riprende da sé
+memorie, Backlog, decisioni protette e ruoli. Le personali e quelle riservate
+all'amministratore lì non ci vanno: le tiene in copia il PC di chi le possiede, e
+le riporta a un Delminio rifatto da questo repo. Il resto — account e impostazioni
+— sta solo nella cartella dei dati di Delminio, che ogni notte si copia da sé in
+`copie/`: digli di mettere quella cartella nel suo giro di backup. Chiedigli
+l'indirizzo (ssh o https) e prova che si raggiunge:
+
+ git ls-remote <indirizzo>
+
+Se risponde con un errore di permessi, le credenziali di git su questa
+macchina non bastano: aiutalo a sistemarle (una chiave SSH registrata sul suo
+git host, o un token) prima di andare avanti.
+
+## 5. L'installazione
+
+Con le sue parole sulla licenza, il suo nome per le clausole e l'indirizzo
+del repo, dalla cartella d'installazione:
+
+ DELMINIO_ACCETTO=si DELMINIO_APPROVO="<nome> per <chi>" DELMINIO_MEMORIA_REMOTO=<indirizzo> bash installa.sh
+
+Scrive il `.env`, clona le memorie in `memoria/`, prova il push, avvia Delminio e
+aspetta che risponda. Alla fine stampa l'indirizzo e il **codice del primo
+accesso**. Riporta all'utente entrambi. Se vuole Delminio come app sul telefono,
+la accende lui da Impostazioni → «L'app sul telefono», che gli dice il resto.
+
+## 6. Dall'interfaccia, lo fa l'utente
+
+Dagli l'indirizzo e aspetta che ti dica «fatto» a ogni punto:
+
+1. **Il primo accesso**: apre l'indirizzo e crea il suo account, che sarà
+ l'**amministratore**, col codice del passo 5. La password la sceglie e la scrive solo
+ lui.
+2. **Impostazioni → «La licenza»**: incolla la licenza che ha ricevuto.
+3. **Impostazioni → «L'embedder»**: sceglie il suo, incolla la chiave, preme
+ Prova. Deve dire che risponde.
+4. **Impostazioni → «Le memorie su git»**: copia la chiave che Delminio mostra
+ e la aggiunge, sul suo git host, al repo delle memorie come **chiave di
+ deploy con scrittura** (GitHub: Settings → Deploy keys, «Allow write
+ access»; Forgejo e Gitea: Impostazioni → Chiavi di deploy). Poi preme
+ Prova: deve dire che il push passa. È così che Delminio salva le memorie nel
+ suo repo alla chiusura di ogni sessione, senza che nessun agente tocchi la
+ cartella.
+5. **Impostazioni → «Le funzioni»**: per ora le lascia tutte accese; la prima
+ sessione nel progetto lo aiuterà a spegnere ciò che non gli serve.
+6. **Accesso** (il bottone in alto) **→ «Agganciare un progetto»**: c'è il
+ comando. Lo lancia **lui**, nel suo terminale, dentro il clone del progetto:
+ mostra un codice di otto lettere, lui lo
+ scrive in Accesso, vede il nome della sua macchina e approva. La chiave
+ arriva allo script da Delminio e non passa da nessuno schermo — né da qui:
+ ⛔ un token non si chiede mai in chat, e se te ne incolla uno la guardia lo
+ ferma prima che tu lo legga. Se ti incolla l'uscita, leggila: un ⚠️ dice
+ cosa manca e perché, un ❌ si sistema e si rilancia.
+
+## 7. La prova
+
+Verifica tu, e riporta in una riga per voce:
+
+ docker compose ps
+ git -C memoria log --oneline -3
+ cd <il progetto> && test -x .claude/delminio.sh && DELMINIO_PROVA=1 delminio apertura
+
+- Delminio è su (`running`), e nel repo delle memorie c'è il commit della semina.
+- Nel progetto c'è il client, e l'apertura risponde **«la prima sessione»**:
+ vuol dire che Delminio lo vede e che non ha ancora memorie sue.
+
+La prova del tool si fa dopo il passo 8, col comando della CLI scelta dall'utente.
+Non si installa Claude Code per provare un progetto che usa solo Codex.
+
+Se una voce non torna, non si chiude: si guarda insieme.
+
+## 8. L'agente di Delminio, su questa macchina
+
+Un agente nasce meglio con le regole di Delminio **in cima**, nel system prompt,
+invece che lette dopo: le porta lì un comando di questa macchina, scritto dal
+registro di Delminio (la vista Agenti: Delminio nasce con un agente per ogni modello che
+regge nella sua versione più nuova, per esempio `opus5.5` e `fable5.2` su Claude Code e `sol6.1` su
+Codex, tutti con le regole di Delminio in cima; su questa macchina si scrivono quelli
+la cui CLI c'è).
+Chiedigli se lo vuole, e come chiamarlo. Se sì, dentro il progetto — e solo se
+vuole un altro nome, prima la `rinomina`:
+
+ delminio eseguibili rinomina <il nome di adesso> <il nome>
+ delminio eseguibili
+
+Scarica la CLI alla versione della riga (accanto alle altre, solo se il checksum
+torna) e scrive il comando. Riportagli ciò che stampa; se dice che la cartella
+non è nel PATH, aiutalo ad aggiungere la riga che mostra al profilo della sua
+shell. Il comando segue il registro da solo — una versione nuova scelta nella
+vista arriva alla prima apertura —; se lo cambia, resta suo. Se non lo vuole:
+`delminio eseguibili no`, e nessuno glielo ripropone.
+
+Ora, dentro il progetto, verifica il tool con **quel comando**, non con un'altra
+CLI: su Codex il lancio di Delminio è anche ciò che gli dà il server MCP.
+Sostituisci `<il nome>` col comando appena scritto. Con Claude Code:
+
+ <il nome> -p "Chiama il tool delminio con operation=health. Rispondi con una riga sola: DELMINIO OK e il numero di memorie, oppure DELMINIO KO e il perché." --allowedTools=mcp__plugin_delminio_memoria__delminio
+
+Con Codex:
+
+ <il nome> exec "Chiama il tool delminio con operation=health. Rispondi con una riga sola: DELMINIO OK e il numero di memorie, oppure DELMINIO KO e il perché."
+
+Se ha scelto un agente Qwen Code, lo stesso prompt con `<il nome> -p`. Se usa
+Claude Code senza l'eseguibile di Delminio, il primo comando usa `claude`.
+Deve rispondere **«DELMINIO OK»**: è la prova che la sua CLI vede davvero il tool.
+La prima sessione interattiva invece è sua: non la lanci tu, e le memorie lì
+nascono col suo sì. Se una voce non torna, si guarda insieme prima del commiato.
+
+Il suo **profilo** (come vuole lavorare, che ogni agente porterà in cima) e le
+regole che nascono intere glieli propone la prima sessione: qui non c'è ancora
+il tool di Delminio per scriverli.
+
+## 9. Il commiato
+
+Diglielo così: «Delminio è su e il progetto è agganciato. Chiudi questa CLI,
+apri `<il nome dell'eseguibile>` (o `claude`, se non l'ha voluto) dentro il
+progetto e scrivi `/apertura`. La prima sessione è la ricognizione: legge il
+repo, ti chiede chi sei e come vuoi lavorare, ti propone le prime memorie una
+alla volta col tuo sì, e quali funzioni ti servono.» Se l'aggancio ha detto che ciò
+che c'era prima è al sicuro (la copia di sicurezza in `~/.local/share/delminio/backup/`), aggiungi: «e comincia
+dalla tua roba di prima: niente è perso, la ripassate insieme».
+
+E una riga sul dopo: la cartella d'installazione resta la casa di Delminio (il
+`.env`, `memoria/`, il kit). Quando l'interfaccia dirà che c'è una versione
+nuova, basta chiedere a un agente di aggiornare Delminio: il come sta in
+`INSTALLA.md` lì dentro, § *Aggiornare*.
+
+## Aggiornare
+
+Se l'utente ti chiede di aggiornare un Delminio che c'è già:
+
+1. **A sessioni chiuse.** Chiedigli se ci sono agenti al lavoro sui progetti
+ agganciati: un file appena scritto e non ancora committato finirebbe nel
+ commit dell'aggiornamento. Si aspetta che finiscano.
+2. L'aggiornamento arriva come l'installazione: dal registro, con la firma
+ verificata prima di farlo girare. Dalla cartella d'installazione (quella col
+ `.env`), coi comandi del § *Prendere Delminio* fino al «Good … signature» e al
+ digest che torna, poi:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ rm -f /tmp/firma.txt /tmp/firma.txt.sig /tmp/firmatari
+ bash installa.sh
+
+ Se nel `.env` c'è `DELMINIO_IMMAGINE` (un registro vostro che rispecchia il
+ nostro), al posto di `registry.delminio.com/delminio` va quello.
+
+ Il kit nuovo si scrive sopra quello vecchio; il `.env`, `memoria/` e il
+ database restano dove sono. L'installatore dice «aggiornamento: <vecchia> →
+ <nuova>», riavvia Delminio (che copia il suo database prima di cambiarne la
+ struttura) e committa nel repo delle memorie le regole di Delminio riallineate.
+3. Riporta la riga dell'aggiornamento. I progetti agganciati si riagganciano da
+ soli alla prima apertura: non c'è altro da fare.
+
+## Andarsene
+
+Se l'utente vuole disinstallare Delminio da questa macchina:
+
+1. **Prima, su ogni macchina dove lavora un agente**, dentro il repo agganciato
+ e da un suo terminale: `delminio stacca`. Con Delminio ancora
+ accesa: gli lascia le sue memorie personali (non stanno in git), revoca il
+ token, rimette la CLI com'era.
+2. Dalla cartella d'installazione: `bash installa.sh via`. Copia il database
+ accanto al `.env`, ferma e rimuove container e immagine. `memoria/` e il volume
+ restano.
+3. Diglielo chiaro: **niente è cancellato**. Le memorie stanno nel suo repo delle
+ memorie; cancellare il resto (`docker volume rm`, la cartella) è un suo gesto,
+ e non lo fai tu.
+
+## Tornare indietro
+
+Se dopo un aggiornamento qualcosa non va e l'utente vuole la versione di prima:
+
+1. **A sessioni chiuse**, come per aggiornare.
+2. Dalla cartella d'installazione, col kit **di adesso** (quello vecchio questo
+ gesto non lo conosce):
+
+ bash installa.sh indietro
+
+ Rimette l'immagine di prima e il **database com'era prima
+ dell'aggiornamento** (la copia che Delminio fa da sé prima di migrare); quello
+ di adesso resta fra le copie. Se l'immagine di prima non c'è più sulla
+ macchina, la riscarica dal registro; se il registro non la dà, lo dice.
+3. Diglielo chiaro: **ciò che si è scritto dopo l'aggiornamento non è nel
+ database di prima**. Le memorie di quel periodo non sono perse — i loro `.md`
+ restano in `memoria/`, non committati (`git -C memoria status`) — e con lui
+ decidi quali risalvare. Delminio di prima riscrive anche `MEMORY.md` e le regole
+ di Delminio com'erano.
+4. Per riaggiornare, più avanti: `bash installa.sh`.
diff --git a/enterprise/LEGGIMI.en.md b/enterprise/LEGGIMI.en.md
new file mode 100644
index 0000000..c7da9cb
--- /dev/null
+++ b/enterprise/LEGGIMI.en.md
@@ -0,0 +1,88 @@
+# Delminio — installing, updating, uninstalling
+
+Delminio runs on your own server in a container: the memories stay yours, in a database and in a folder of text files under git. First of all, read `LICENZA.md` (the licence) and `INFORMATIVA.md` (the privacy notice).
+
+## What you need
+
+To get started you need:
+
+- **A Linux machine** — a PC, a server or a VM, at home or in the office — with Docker and the `docker compose` plugin, `git`, `curl` and `python3`. Delminio runs here. Delminio isn't exposed to the internet: from outside, you reach it through your own network's VPN.
+- **The agents, on the computer of each person who works**: Linux, macOS or Windows with WSL, with `git`, `curl` and `python3`. Delminio saves the memories in their repository: an agent doesn't need its disk, only to reach it.
+- **Claude Code, Codex or Qwen Code**, with your own account: the `claude` CLI (or the Code tab of the desktop app, which is the same engine and reads the same files), OpenAI's `codex` CLI, or Qwen Code with the model you choose. They can be mixed in the same team: the memories are the same.
+- **An empty repository for the memories** on a git host — GitHub, Forgejo or Gitea — that you can push to: it's the copy of the memories outside this machine (one from an earlier Delminio is fine full: Delminio takes it back). Your git credentials (an SSH key, or a token) already on this machine, and `git config user.name` / `user.email` set.
+
+**From Windows**: inside **WSL** (Ubuntu), as on Linux. Windows without WSL isn't supported: Delminio's client is made of bash scripts. Keep the project's clone in the WSL home folder, not in `/mnt/c`: there git and the scripts are slow, and the token's permissions only hold with the `metadata` option.
+
+**A machine shared over SSH** (the desktop app or the CLI connected to a Linux machine on the network) is still possible, and it's a choice: each agent takes a few hundred MB plus the work it launches, multiplied by everyone's agents — and each person logs in **with their own Linux user**, never a shared one.
+
+**Recommended: `tmux`** for anyone working with the CLI over SSH (from a phone too): the agent's session survives a dropped connection, and you get back in where you were.
+
+**Several people**: one person = the user account on their machine = one Delminio account = their token, generated by the admin in **Access** (`~/.config/delminio/`, 600). That's all the recognition there is: two people on the same Linux user are a single person to Delminio, and their personal memories get mixed. Someone who works from several devices has **one token per device**, with its own label: if the laptop is lost, the admin revokes that one. Everyone has their own clone of the project and their own git credentials. Delminio commits and pushes the memories at the end of every session, or shortly after each write if the verified handoff is switched off (Settings → “Memories on git”). No agent touches their folder, so everyone can have their own Linux account, or work from another machine on the network that can reach Delminio. ⚠️ Anyone in the `docker` group on Delminio's machine is effectively root there, and can read the `.env` with the secret. People who need containers for their work use **rootless docker**: a docker of their own, running as their own user, without touching the system one or Delminio. **Delminio itself** can also be installed with rootless docker: the installer notices and runs it as your user. ⚠️ On Ubuntu 24.04 the `docker.io` package doesn't include the rootless scripts (`dockerd-rootless-setuptool.sh`): you need `docker-ce-rootless-extras` from Docker's own repository.
+
+And these are needed to work well, but you can start without them, and the connection tells you what's missing:
+
+- **the project on a git host you push to** (cloned from there, or a fork of yours): without it, the handoff and the merge stay on this machine;
+- **an embedder on your network**, set up by the admin in Settings → Embedder. For Delminio Enterprise it's a requirement, so that the text of the memories doesn't leave your network. Our recommendation is `bge-m3` with Ollama, even on CPU only (the model is 1.2 GB). An outside service, such as `bge-m3` on Cloudflare Workers AI, only if you choose to let the text leave. Without an embedder you can start anyway, and the memories are searched by words, without semantic search.
+
+## One installation, several spaces
+
+An installation holds one or more spaces, as many as the licence allows. Each space has its own repositories, memories, Backlog and people, and none of them can read another's. A repository belongs to one space only: work that's unrelated goes in a new space (**Spaces** view). The licence seats are counted per person, across all spaces. When you connect a new repository to a space that already holds others, the connection asks whether it's the same project.
+
+## Features, and what's yours
+
+Delminio starts with a set of features. In Settings → **Features**, the admin switches off what the project doesn't need — the verified handoff, multiple agents, the memory review, protected decisions, the Backlog. Switched off, a feature goes quiet, and its rule no longer reaches the agents.
+
+The memories Delminio brings come in two kinds. **Delminio's rules** describe a feature: they aren't edited, and every new version updates them. Whatever applies only to you goes in their **project addendum** (“<title> — project addendum”), which the agents receive right after the rule. The **default** memories — the map, why the project exists, when to split code, the model's traps — are yours from the first day: you change them and delete them, and Delminio doesn't touch them again.
+
+## Installing
+
+Open the CLI you use (Claude Code, Codex or Qwen Code) in any folder and tell it: “install Delminio: read the installation text with curl and follow it”, with the address we gave you. That text is `INSTALLA.en.md`, the same one you find here: you can read it before the agent does. The agent guides you: it explains each step before doing it, takes the image and extracts this installation kit from it, asks you what's yours to decide (you accept the licence yourself, and you type the password only in the interface), runs the installer, and at the end checks that everything responds.
+
+Delminio is downloaded from our **registry**, `registry.delminio.com`, with the username and password we gave you. If you prefer to do it by hand, sign in once (`docker login registry.delminio.com`), download the image and verify its signature with the key from your contract (`INSTALLA.en.md` § Getting Delminio), then, in a folder outside any repository:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ bash installa.sh
+
+The installer asks you to accept the licence, checks the image, writes the `.env` (version, a new secret, your user), clones the memory repository into `memoria/` (it asks you for the address, or pass it in `DELMINIO_MEMORIA_REMOTO`) and checks that you can push to it, creates `progetto/` and starts Delminio. At the end it gives you the address and the code for the first sign-in. In the web interface, the **Dashboard** guides you through the **first steps**:
+1. **The licence**: paste the one you received;
+2. **The copy of the memories**: the key Delminio uses to publish the memories to their repository;
+3. **Connect the computer**: the command to run inside the clone of your repository. It checks that git knows who you are, that you can push, and that the embedder responds.
+
+ If the project already had things of yours — the notes the CLI had written for itself, instructions for Claude Code, Codex or Qwen Code (`CLAUDE.md`, `AGENTS.md`, `QWEN.md`), settings, and `/apertura` and `/chiusura` commands — then before touching anything the connection makes a backup of it outside the repository, in `~/.local/share/delminio/backup/`, and the agent goes over it with you in the first session: the notes become memories once you approve them, and you either keep the `CLAUDE.md` files or move them to Delminio. If your CLI kept its notes in a folder you chose, the connection stops and asks you. It doesn't touch your other commands, agents or `.claude/settings.json`, so it doesn't copy them. To go back to how it was, from a terminal of your own: `delminio disconnect`.
+
+And in **Settings → Embedder**, choose yours and press Test.
+
+Names, port and folders are in the `.env`: change them before the first start if they clash with yours.
+
+Delminio can also answer over **HTTPS**, on a second port (`DELMINIO_HTTPS_PORTA`, usually 8402), with a certificate it makes for itself: you need it to install Delminio on your phone as an app. The admin switches it on from Settings → “The app on your phone”, where you download the certificate and read how to install it. `DELMINIO_HTTPS_NOMI=no` switches it off for good.
+
+## How the work goes
+
+**Opening.** Start your agent inside the connected repository (or one of its subfolders: from the folder above, the one with all your repositories, Delminio doesn't reach it) and type `/opening`: your agent role's opening runs (you write it in **Agent roles**). With **Codex** you start from the agent the admin created in the **Agents** view (Codex CLI): on the first start Codex asks whether to trust the folder and, with `/hooks`, Delminio's checks — say yes to both, or it starts without memory. Codex doesn't have the `/opening` and `/closing` commands: type **`opening`** (or **`closing`**) on its own, as the only message. The agent reads the rules, the last handoff (from the session before) and the Backlog, tells you in a few lines where things pick up, and waits: you say what the day's work is.
+
+**Working.** The pace is yours, the technical choices are its. It writes the memories with the `delminio` tool, never as files (a check blocks that), and a new memory is created only once you approve it. Work left for another day goes in the **Backlog**: a task, or a follow-up if it needs looking at on a specific day. It opens one only in your words, so the register doesn't fill up with “tomorrow”.
+
+**Closing.** Whenever you want — it won't suggest it — type `/closing`, followed by anything else you want done. The agent commits and pushes the work, tells you where it is and asks you a single question; after your answer it writes the handoff, which Delminio checks: if something's missing it refuses it and says why, and if it holds up, Delminio commits and pushes the memories and adds their hash. That's what the person who opens tomorrow will read.
+
+**Several sessions at once** on the same computer: each in its own worktree, and they talk on Delminio's channel; the opening tells each one who's there and what they're touching.
+
+**From the interface**: the **Dashboard** (what's waiting for you, who's working right now, the health of the memory), **Memories** (read, search, review), **Backlog** (tasks, follow-ups and the decisions waiting for you as admin), **Git** (each session's handoff, and the space's repositories), **Agents** (the commands, models and CLI versions, machine by machine), **Agent roles** (who an agent is when it starts), **Usage** (what the agents ask for, and what they can't find), **Settings** (licence, embedder, features), **Access** (people, tokens, invitations).
+
+## Updating
+
+Ask an agent (“update Delminio”): the process is in `INSTALLA.en.md` § Updating. By hand, download and verify the latest version as for the first installation, then from the folder where you installed:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ bash installa.sh
+
+The `.env`, `memoria/` and the database stay where they are: the installer recognises the new version, downloads it if missing and restarts Delminio, which makes a copy of its own database before changing its structure. Delminio's rules realign themselves to the new version — your project addenda (“… — project addendum”) stay as they are, and the default memories are yours and aren't touched — and the installer commits them to the memory repository. **Update with all sessions closed**: an agent at work would have files half-written. The connected projects update themselves: at the first opening after the update, the client sees the new version and reconnects, with its own token.
+
+**Leaving**: on every machine, inside the repository and from a terminal of your own, `delminio disconnect`. It leaves you your personal memories next to the backup, in `~/.local/share/delminio/backup/`, revokes the token and puts the CLI back as it was (do it while Delminio is running). Then, from the installation folder, `bash installa.sh via`: it stops Delminio, leaves a copy of the database next to the `.env`, and deletes nothing. The project's memories are already yours, in the memory repository.
+
+**Going back**: if the new version gives you a problem, from the same folder and with the current kit, `bash installa.sh indietro` puts back the previous image and the main space's database as it was before the update (the current one stays among the copies). The databases of the other spaces aren't restored by this command. Whatever you wrote in the meantime isn't in that database: the `.md` files stay in `memoria/`, to be saved again if you need them. `bash installa.sh` updates again.
+
+## Uninstalling
+
+ docker compose down
+
+stops Delminio and leaves everything else. `memoria/` holds every memory as a text file: it's yours even without Delminio. To delete the database too: `docker compose down -v` (there's no going back).
diff --git a/enterprise/LEGGIMI.md b/enterprise/LEGGIMI.md
new file mode 100644
index 0000000..22fa3db
--- /dev/null
+++ b/enterprise/LEGGIMI.md
@@ -0,0 +1,218 @@
+# Delminio — installare, aggiornare, disinstallare
+
+Delminio gira sul tuo server in un container: le memorie restano tue, in un
+database e in una cartella di file di testo sotto git. Prima di tutto leggi
+`LICENZA.md` e `INFORMATIVA.md`.
+
+## Cosa serve
+
+Per partire servono:
+
+- **Una macchina Linux** — un PC, un server o una VM, in casa o in ufficio —
+ con Docker e il plugin `docker compose`, `git`, `curl`, `python3`. Delminio
+ gira qui. Delminio non si espone su internet: da fuori ci si entra con la VPN
+ della propria rete.
+- **Gli agenti, sul PC di chi lavora**: Linux, macOS o Windows con WSL, con
+ `git`, `curl` e `python3`. Le memorie le salva Delminio nel loro repo: un
+ agente non ha bisogno del suo disco, solo di raggiungerlo.
+- **Claude Code, Codex o Qwen Code**, col tuo account: la CLI `claude` (o la scheda Code
+ dell'app desktop, che è lo stesso motore e legge gli stessi file), la CLI `codex` di OpenAI, o Qwen Code col modello che scegli. Anche insieme nella stessa squadra: le memorie sono le stesse.
+- **Un repo vuoto per le memorie** su un git host — GitHub, Forgejo o Gitea —
+ su cui puoi pushare: è la copia delle memorie fuori da questa macchina (quello
+ di un Delminio di prima va bene pieno: Delminio se lo riprende). Le
+ credenziali di git (una chiave SSH, o un token) già su questa macchina, e
+ `git config user.name` / `user.email` impostati.
+
+**Da Windows**: dentro **WSL** (Ubuntu), come su un Linux. Windows senza WSL
+non è supportato: il client di Delminio è fatto di script bash. Tieni il clone del
+progetto nella home di WSL, non in `/mnt/c`: lì git e gli script vanno lenti,
+e i permessi del token si reggono solo con l'opzione `metadata`.
+
+**Una macchina condivisa in SSH** (l'app desktop o la CLI collegate a una
+macchina Linux della rete) resta possibile, ed è una scelta: ogni agente pesa
+qualche centinaio di MB più il lavoro che lancia, moltiplicato per gli agenti
+di tutti — e ognuno ci entra **col suo utente Linux**, mai con uno in comune.
+
+**Consigliato: `tmux`** per chi lavora con la CLI in SSH (anche dal telefono):
+la sessione dell'agente sopravvive a una connessione che cade, e ci si
+rientra dove si era.
+
+**Più persone**: una persona = l'utente della sua macchina = un account di
+Delminio = il suo token, generato dall'amministratore in **Accesso** (`~/.config/delminio/`,
+600). È tutto il riconoscimento: due persone sullo stesso utente Linux sono una
+persona sola per Delminio, e le loro memorie personali si mescolano. Chi lavora da
+più dispositivi ha **un token per dispositivo**, con la sua etichetta: perso il
+portatile, l'amministratore revoca quello. Ognuno ha il suo clone del progetto e le sue
+credenziali di git. Le memorie le committa e
+le pusha Delminio alla chiusura di ogni sessione, o poco dopo ogni scrittura se
+la consegna verificata è spenta (Impostazioni → «Le memorie su git»): nessun agente tocca la loro cartella, quindi ognuno può avere il suo
+account Linux, o lavorare da un'altra macchina della rete che raggiunge Delminio.
+⚠️ Chi è nel gruppo `docker` della macchina di Delminio è di fatto root lì e
+legge il `.env` col segreto. Chi ha bisogno di container per il suo lavoro usa
+**docker rootless**: un docker suo, che gira col suo utente, senza toccare
+quello di sistema né Delminio. Anche **Delminio stesso** si installa con un docker
+rootless: l'installatore se ne accorge e la fa girare come il tuo utente.
+⚠️ Su Ubuntu 24.04 il pacchetto `docker.io` non porta gli script del rootless
+(`dockerd-rootless-setuptool.sh`): servono i `docker-ce-rootless-extras` del
+repository di Docker.
+
+E questo serve per lavorare bene, ma senza si parte lo stesso, e il collegamento dice cosa manca:
+
+- **il progetto su un git host su cui pushi** (clonato da lì, o un tuo fork):
+ senza, la consegna e il merge restano su questa macchina;
+- **un embedder nella vostra rete**, configurato dall'amministratore in
+ Impostazioni → Embedder: per Delminio Enterprise è un requisito, perché il testo delle memorie non esca dalla vostra rete. Il consiglio è `bge-m3` con Ollama,
+ anche solo su CPU (il modello pesa 1,2 GB). Un servizio fuori, come `bge-m3`
+ su Cloudflare Workers AI, solo se scegliete di far uscire il testo. Senza
+ embedder si parte lo stesso, e le memorie si cercano per parole, senza la ricerca semantica.
+
+## Un'installazione, più spazi
+
+Un'installazione tiene uno o più spazi, quanti ne permette la licenza. Ogni
+spazio ha i suoi repo, le sue memorie, il suo Backlog e le sue persone, e
+nessuno legge quelli di un altro. Un repo è di uno spazio solo: un lavoro che
+non c'entra va in uno spazio nuovo (vista **Spazi**). I posti della licenza si
+contano per persona, su tutti gli spazi. Il collegamento di un repo nuovo, se lo
+spazio ne tiene già altri, chiede se è lo stesso progetto.
+
+## Le funzioni, e cosa è vostro
+
+Delminio parte con una base di funzioni. In Impostazioni → **Le funzioni** l'amministratore spegne ciò che al
+progetto non serve — la consegna verificata, più agenti insieme, la revisione
+della memoria, le decisioni protette, il Backlog: spenta, una funzione tace, e la sua regola non arriva più
+agli agenti.
+
+Le memorie che Delminio porta sono di due specie. Le **regole di Delminio**
+descrivono una funzione: non si modificano, e ogni versione nuova le
+aggiorna. Ciò che vale solo per voi va nella loro **aggiunta** («<titolo> — da
+noi»), che gli agenti ricevono subito dopo la regola. Le memorie **predefinite** — la mappa, il perché del progetto, quando si spezza il codice, le trappole del modello — sono vostre dal
+primo giorno: si cambiano e si cancellano, e Delminio non le tocca più.
+
+## Installare
+
+Apri la CLI che usi (Claude Code, Codex o Qwen Code) in una cartella qualunque e scrivile: «installa Delminio: leggi
+con curl il testo d'installazione e seguilo», con l'indirizzo che ti abbiamo
+dato. Quel testo è `INSTALLA.md`, lo stesso che trovi qui: lo puoi leggere
+prima di lui. L'agente ti guida: spiega ogni passo prima di farlo, prende
+l'immagine e ne estrae questo kit d'installazione, ti chiede ciò che decidi tu (la licenza la
+accetti tu, la password la scrivi solo nell'interfaccia), lancia
+l'installatore e alla fine verifica che tutto risponda.
+
+Delminio si scarica dal nostro **registro**, `registry.delminio.com`, con
+l'utente e la password che vi abbiamo dato. Chi preferisce a mano entra una
+volta (`docker login registry.delminio.com`), scarica l'immagine e ne verifica la
+firma con la chiave del proprio contratto (`INSTALLA.md` § Prendere Delminio),
+poi, in una cartella fuori da ogni repo:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ bash installa.sh
+
+L'installatore ti chiede di accettare la licenza, controlla l'immagine, scrive il
+`.env` (versione, un segreto nuovo, il tuo utente), clona in `memoria/` il
+repo delle memorie (ti chiede l'indirizzo, o passalo in
+`DELMINIO_MEMORIA_REMOTO`) e prova che ci puoi pushare, crea `progetto/` e avvia
+Delminio. Alla fine ti dà l'indirizzo e il
+codice del primo accesso. Dall'interfaccia web, il **Cruscotto** ti guida coi **primi passi**:
+1. **La licenza**: incolla quella che hai ricevuto;
+2. **La copia delle memorie**: la chiave con cui Delminio pubblica le memorie
+ nel loro repo;
+3. **Collega il tuo repo**: il comando da lanciare dentro il clone del tuo
+ repo. Controlla che git sappia chi sei, che tu possa pushare, e che
+ l'embedder risponda.
+
+ Se il progetto aveva già roba tua — le note che la CLI si era scritta, le
+ istruzioni per Claude Code, Codex o Qwen Code (`CLAUDE.md`, `AGENTS.md`,
+ `QWEN.md`), le impostazioni e i comandi `/apertura` e `/chiusura` —, prima di
+ toccare qualunque cosa il collegamento ne fa una copia di sicurezza fuori dal
+ repo, in `~/.local/share/delminio/backup/`, e l'agente la ripassa
+ con te alla prima sessione: le note diventano memorie col tuo sì, e i
+ `CLAUDE.md` li tieni o li passi a Delminio. Se la tua CLI teneva le note in una
+ cartella scelta da te, il collegamento si ferma e te lo chiede.
+ Gli altri tuoi comandi, agenti e il `.claude/settings.json` non li tocca, e
+ quindi non li copia.
+ Tornare com'era, da un tuo terminale: `delminio stacca`.
+
+E in **Impostazioni → Embedder** scegli il tuo e premi Prova.
+
+Nomi, porta e cartelle stanno nel `.env`: cambiali prima del primo avvio se si
+scontrano con i tuoi.
+
+Delminio sa rispondere anche in **HTTPS**, su una seconda porta
+(`DELMINIO_HTTPS_PORTA`, di solito 8402), col certificato che si fa da sé: serve
+per installarlo sul telefono come un'app. La accende l'amministratore da
+Impostazioni → «L'app sul telefono», dove si scarica il certificato e si legge
+come installarla. `DELMINIO_HTTPS_NOMI=no` la spegne per sempre.
+
+## Come si lavora
+
+**Si apre.** Lancia il tuo agente dentro il repo collegato (o una sua sottocartella:
+dalla cartella sopra, quella con tutti i tuoi repo, Delminio non arriva) e scrivi `/apertura`:
+parte l'apertura del tuo ruolo (la scrivi tu in **Ruoli**).
+Con **Codex** si parte dall'agente che l'amministratore ha creato nella vista **Agenti**
+(CLI Codex): al primo avvio Codex chiede se fidarsi della cartella e, con `/hooks`, dei
+controlli di Delminio — rispondi sì a tutti e due, o parte senza memoria. Codex non ha
+i comandi `/apertura` e `/chiusura`: scrivi **`apertura`** (o **`chiusura`**) da sola,
+come unico messaggio.
+L'agente legge le regole, l'ultima consegna (quella di chi c'era prima) e
+il Backlog, ti dice in poche righe da dove si riparte e aspetta: il lavoro
+del giorno lo dici tu.
+
+**Si lavora.** Il ritmo è tuo, le scelte tecniche sono sue. Le memorie le
+scrive col tool `delminio`, mai come file (un controllo lo blocca), e una memoria nuova si crea solo col tuo sì. Il lavoro che resta per un altro giorno va nel
+**Backlog**: un'attività, o un controllo a data se va guardato in un giorno preciso. Lo apre solo
+con le tue parole, così il registro non si riempie di «domani».
+
+**Si chiude.** Quando vuoi tu — lui non te lo propone — scrivi `/chiusura`,
+e dopo il comando ciò che vuoi ancora. L'agente committa e pusha il lavoro,
+ti dice dov'è e ti fa una domanda sola; alla tua risposta scrive la consegna, che Delminio verifica: se manca qualcosa lo rifiuta col perché, se
+regge committa e pusha le memorie e ci aggiunge il loro hash. È quello che leggerà chi apre domani.
+
+**Più sessioni insieme** sullo stesso PC: ognuna nel suo worktree, si parlano
+sul canale di Delminio; l'apertura dice a ognuna chi c'è e cosa tocca.
+
+**Dalla UI**: il **Cruscotto** (cosa aspetta te, chi lavora adesso, la salute
+della memoria), **Memorie** (leggere, cercare, rivedere), **Backlog** (attività,
+controlli a data e le decisioni che aspettano te come amministratore), **Git**
+(la consegna di ogni sessione, e i repo dello spazio), **Agenti** (i comandi, i
+modelli e le versioni della CLI, macchina per macchina), **Ruoli** (chi è un
+agente quando si avvia), **Utilizzo** (cosa chiedono gli agenti, e cosa non
+trovano), **Impostazioni** (licenza, embedder, funzioni), **Accesso** (persone,
+token, inviti).
+
+## Aggiornare
+
+Chiedilo a un agente («aggiorna Delminio»): il giro è in `INSTALLA.md` §
+Aggiornare. A mano, scarica e verifica l'ultima versione come per la prima
+installazione, poi dalla cartella dove hai installato:
+
+ docker run --rm registry.delminio.com/delminio:latest kit | tar -x
+ bash installa.sh
+
+Il `.env`, `memoria/` e il database restano dove sono: l'installatore riconosce
+la versione nuova, la scarica se manca e riavvia Delminio, che fa una copia del proprio
+database prima di cambiarne la struttura. Le regole di Delminio si riallineano da sole
+alla versione nuova — le vostre aggiunte («… — da noi») restano come sono, e le
+memorie predefinite sono vostre e non si toccano — e l'installatore le committa nel repo delle
+memorie.
+**Aggiorna a sessioni chiuse**: un agente al lavoro avrebbe file a metà. I progetti collegati si aggiornano da soli: alla prima apertura dopo l'aggiornamento il client vede la versione nuova e si ricollega, col suo token.
+
+**Andarsene**: su ogni macchina, dentro il repo e da un tuo terminale, `delminio stacca` — ti lascia le tue memorie personali accanto
+alla copia di sicurezza, in `~/.local/share/delminio/backup/`, revoca il token e rimette la CLI com'era (va fatto con
+Delminio acceso). Poi, dalla cartella d'installazione, `bash installa.sh via`: ferma
+Delminio, lascia una copia del database accanto al `.env`, e non cancella niente. Le
+memorie del progetto sono già vostre, nel repo delle memorie.
+
+**Tornare indietro**: se la versione nuova vi dà un problema, dalla stessa
+cartella e col kit di adesso, `bash installa.sh indietro` rimette l'immagine di
+prima e il database dello spazio principale com'era prima dell'aggiornamento
+(quello di adesso resta fra le copie). I database degli altri spazi non vengono
+ripristinati da questo comando. Ciò che avete scritto nel frattempo non è in quel database: i `.md`
+restano in `memoria/`, da risalvare se servono. `bash installa.sh` riaggiorna.
+
+## Disinstallare
+
+ docker compose down
+
+ferma Delminio e lascia tutto il resto. `memoria/` contiene ogni memoria come file
+di testo: è tua anche senza Delminio. Per cancellare anche il database:
+`docker compose down -v` (non si torna indietro).
diff --git a/enterprise/LICENZA.md b/enterprise/LICENZA.md
new file mode 100644
index 0000000..e02fec7
--- /dev/null
+++ b/enterprise/LICENZA.md
@@ -0,0 +1,284 @@
+# Delminio — Contratto di licenza d'uso
+
+_Versione 1.5 del 15 novembre 2026._
+
+**Fra** Luigi Casini, con sede in Località Tregozzano 45, 52100 Arezzo (AR),
+P. IVA 02356410510, PEC casini.luigi@pec.it (il «**Licenziante**»)
+**e** il soggetto indicato nell'Ordine o, durante la Prova, nell'accettazione
+data nell'installatore (il «**Licenziatario**»).
+
+## 1. Definizioni
+
+- **Software**: il programma «Delminio» in forma eseguibile (l'immagine container
+ e i moduli compilati che contiene), la sua interfaccia web, gli script di
+ installazione e di aggancio, e gli aggiornamenti che il Licenziante rende
+ disponibili durante la Durata.
+- **Contenuti di Delminio**: i testi che il Software installa al primo avvio
+ (le regole di Delminio, i semi, la porta d'apertura e il system prompt degli
+ agenti) e la documentazione.
+- **Dati del Licenziatario**: tutto ciò che il Licenziatario e i suoi utenti
+ scrivono nel Software (memorie, registro del lavoro, messaggi fra sessioni,
+ account), e i file che il Software ne ricava sui suoi sistemi.
+- **Ordine**: il documento, accettato da entrambe le parti, che indica
+ Licenziatario, numero di Posti, Durata, corrispettivo e condizioni
+ particolari. In caso di contrasto, l'Ordine prevale su questo contratto.
+- **Prova**: l'uso gratuito del Software senza Ordine, con una Chiave di
+ licenza di prova (art. 2.5).
+- **Posto**: un account utente attivo nel Software.
+- **Chiave di licenza**: il codice firmato che il Licenziante consegna e che
+ abilita la scrittura nel Software per i Posti e la Durata dell'Ordine.
+- **Cassaforte**: la funzione del Software che conserva in forma cifrata i
+ segreti usati dagli agenti (password, token) e li consegna, su autorizzazione
+ dell'amministratore, al solo comando che li richiede. È inclusa solo se
+ l'Ordine la indica.
+
+## 2. Oggetto e ambito professionale
+
+2.1 Il Licenziante concede al Licenziatario una licenza **non esclusiva, non
+trasferibile e non sublicenziabile** di installare e usare il Software, sui
+sistemi che il Licenziatario controlla, per il numero di Posti e per la Durata
+indicati nell'Ordine, per le esigenze interne della propria attività.
+
+2.2 Il Licenziatario dichiara di agire nell'esercizio della propria attività
+imprenditoriale o professionale. Il Software non è offerto a consumatori.
+
+2.3 Questo contratto riguarda il Software installato e funzionante presso il
+Licenziatario («self-hosted», offerta Enterprise). Il Licenziante non ospita
+il Software e non ha accesso ai sistemi del Licenziatario. Il servizio che il
+Licenziante ospita sui propri sistemi è regolato da termini propri, non da
+questo contratto.
+
+2.4 Il Software non fornisce modelli di intelligenza artificiale. Gli agenti
+del Licenziatario usano i modelli con i propri account presso i rispettivi
+fornitori (per esempio Anthropic, per Claude Code), alle condizioni che il
+Licenziatario ha con loro: il Licenziante non paga, non rivende e non
+intermedia quell'uso, e non riceve né conserva le credenziali del
+Licenziatario presso quei fornitori.
+
+2.5 Il Software si può provare gratuitamente, senza impegno di acquisto, con
+una Chiave di licenza di prova. Durante la Prova i Posti e la Durata sono
+quelli scritti nella Chiave, e dove questo contratto rimanda all'Ordine vale
+la Chiave. Alla fine della Prova, se non è stato concluso un Ordine, il
+Software passa in sola lettura (art. 7) e il Licenziatario conserva pieno
+accesso ai propri Dati.
+
+## 3. Cosa il Licenziatario può fare
+
+Oltre all'uso previsto, il Licenziatario può:
+a) fare le copie di sicurezza del Software e dei propri Dati necessarie
+all'uso;
+b) osservare, studiare e sottoporre a prova il funzionamento del Software,
+durante le operazioni che ha diritto di eseguire, per determinarne le idee e i
+principi, nei limiti dell'art. 64-ter, comma 3, della legge 22 aprile 1941,
+n. 633;
+c) decompilare il Software solo nei casi e nei limiti dell'art. 64-quater
+della stessa legge (interoperabilità con un programma creato
+autonomamente), dopo averne chiesto per iscritto al Licenziante le
+informazioni necessarie e se il Licenziante non le ha fornite entro trenta
+giorni.
+
+Nessuna clausola di questo contratto limita i diritti che la legge riconosce
+all'utente legittimo di un programma e che non possono essere esclusi per
+contratto.
+
+## 4. Cosa il Licenziatario non può fare
+
+Salvo quanto previsto all'art. 3 e dalla legge, il Licenziatario non può:
+a) copiare, modificare, tradurre, decompilare, disassemblare o in altro modo
+ricostruire il codice sorgente del Software, né estrarne i moduli per usarli
+fuori dal Software;
+b) eludere, disattivare o alterare la verifica della Chiave di licenza, il
+conteggio dei Posti o il passaggio in sola lettura alla scadenza, né aiutare
+altri a farlo;
+c) cedere, prestare, noleggiare, rivendere o mettere a disposizione di terzi
+il Software o la Chiave di licenza, anche come servizio ospitato per altri;
+d) usare il Software oltre il numero di Posti o la Durata dell'Ordine;
+e) rimuovere o alterare le indicazioni di titolarità, di licenza o di marchio;
+f) riprodurre o distribuire i Contenuti di Delminio fuori dall'installazione
+licenziata. Il Licenziatario può invece modificarli liberamente al suo
+interno: le versioni modificate e i testi nuovi che scrive sono suoi;
+g) usare il Software o i Contenuti di Delminio per sviluppare o offrire un
+prodotto concorrente, fermo quanto previsto all'art. 3.
+
+Le stesse regole valgono per gli strumenti automatici — compresi gli agenti di
+intelligenza artificiale — che il Licenziatario usa sui propri sistemi: ciò
+che il Licenziatario non può fare, non può farlo fare.
+
+## 5. Titolarità
+
+5.1 Il Software, i Contenuti di Delminio, il nome e i segni «Delminio» restano del
+Licenziante o dei suoi danti causa. Questo contratto non trasferisce alcun
+diritto oltre la licenza dell'art. 2.
+
+5.2 Il Software contiene componenti di terze parti distribuiti con licenze
+proprie, elencati nel file `TERZE-PARTI.md` consegnato con il Software; per
+quei componenti valgono le rispettive licenze.
+
+## 6. I Dati del Licenziatario
+
+6.1 **I Dati del Licenziatario sono e restano suoi.** Il Software li conserva
+sui sistemi del Licenziatario; il Licenziante non vi accede, non li riceve e
+non li tratta, salvo il Licenziatario glieli consegni volontariamente (per
+esempio in una richiesta di assistenza).
+
+6.2 Il Licenziatario è titolare del trattamento dei dati personali che
+eventualmente inserisce nel Software e ne risponde secondo il Regolamento (UE)
+2016/679. Poiché il Licenziante non accede a quei dati, per essi non agisce
+come responsabile del trattamento.
+
+6.3 Il Software scrive le memorie anche come file di testo in una cartella del
+Licenziatario e ne consente l'esportazione: i Dati restano leggibili e
+portabili anche senza il Software. La copia che fa fede è quella nel
+repository del Licenziatario (art. 9).
+
+6.4 La chiave che apre la Cassaforte è generata e conservata soltanto nei
+dispositivi iscritti dal Licenziatario. Il Licenziante non può leggere i
+segreti né recuperarli: se il Licenziatario perde tutti i dispositivi iscritti
+e il codice di recupero, i segreti non sono più recuperabili.
+
+## 7. Chiave di licenza, scadenza e sola lettura
+
+7.1 La scrittura nel Software richiede una Chiave di licenza valida. Senza
+Chiave valida — mancante, scaduta, revocata o non verificabile — il Software
+**passa in sola lettura**: i Dati restano consultabili ed esportabili, e gli
+agenti continuano a riceverli; non se ne possono scrivere di nuovi.
+
+7.2 Il passaggio in sola lettura è una misura tecnica di protezione del
+Software e non costituisce inadempimento del Licenziante.
+
+## 8. Il contatto giornaliero
+
+8.1 Una volta al giorno il Software comunica al servizio di licenze del
+Licenziante: la Chiave di licenza, un identificativo
+casuale dell'installazione, la versione del Software e il numero di account
+attivi. **Non comunica mai i Dati del Licenziatario**, salvo le segnalazioni
+dell'art. 8.4. La risposta del
+servizio è firmata, e dice se la Chiave è stata revocata e qual è l'ultima
+versione del Software disponibile, che il pannello mostra quando è più nuova
+di quella installata.
+
+8.2 Se il servizio non è raggiungibile, il Software continua a funzionare
+normalmente per quindici giorni dall'ultimo contatto riuscito, poi passa in
+sola lettura fino al contatto successivo.
+
+8.3 Il trattamento dei dati del contatto e delle segnalazioni è descritto nel
+file `INFORMATIVA.md`.
+
+8.4 Su richiesta di un utente, o con il suo consenso, gli agenti possono inviare
+al Licenziante una **segnalazione**: un testo scritto apposta per chiedere una
+funzione o descrivere un difetto del Software, con l'identificativo della
+Chiave e dell'installazione, la versione e il nome dell'account. Il Software
+maschera le credenziali che riconosce prima dell'invio. Il Licenziante la usa
+solo per rispondere e per migliorare il Software, e la risposta torna agli
+agenti attraverso il contatto dell'art. 8.1. L'amministratore del Licenziatario
+può spegnere le segnalazioni dal pannello.
+
+## 9. Le memorie nel repository del Licenziatario
+
+9.1 Il Software conserva una copia delle memorie in un repository git che il
+Licenziatario indica e controlla (sul proprio server o presso un fornitore di
+sua scelta). Il Software vi registra e trasmette le modifiche con una chiave
+d'accesso generata sui sistemi del Licenziatario, che il Licenziatario
+autorizza e può revocare in ogni momento.
+
+9.2 Quella copia va dai sistemi del Licenziatario al repository del
+Licenziatario: **il Licenziante non la riceve e non vi accede**. Il fornitore
+del repository, se esterno, è scelto dal Licenziatario e opera per suo conto.
+
+9.3 Il Software tiene inoltre, sui sistemi del Licenziatario, un registro
+delle sessioni di lavoro degli agenti (numero, account, repository e
+riferimento del commit di chiusura), che serve a ritrovare il lavoro fatto in
+un altro repository dello stesso progetto. Il registro non contiene il testo
+delle chiusure, che resta nei repository.
+
+## 10. Aggiornamenti e assistenza
+
+Durante la Durata il Licenziante rende disponibili gli aggiornamenti del
+Software. Assistenza, tempi di risposta e canali sono quelli indicati
+nell'Ordine; se l'Ordine non dice nulla, l'assistenza è prestata via e-mail
+senza tempi garantiti. Prima di ogni aggiornamento che modifica la struttura
+dei dati il Software esegue una copia del proprio database.
+
+## 11. Corrispettivo
+
+Il corrispettivo, le modalità e i termini di pagamento sono indicati
+nell'Ordine. In caso di mancato pagamento oltre 30 giorni dalla scadenza il
+Licenziante può revocare la Chiave di licenza, previa comunicazione scritta.
+
+## 12. Garanzie
+
+12.1 Il Licenziante garantisce di avere il diritto di concedere la licenza e
+che il Software, usato come previsto, funziona in modo sostanzialmente
+conforme alla sua documentazione. Se il Licenziatario segnala per iscritto una
+difformità riproducibile entro la Durata, il Licenziante la corregge o, se non
+è possibile entro un tempo ragionevole, restituisce la parte di corrispettivo
+riferita al periodo residuo.
+
+12.2 Fuori da quanto previsto al punto 12.1, e nei limiti consentiti dalla
+legge, il Software è fornito come è. Il Software organizza e conserva ciò che
+gli utenti e i loro agenti vi scrivono: il Licenziante non garantisce la
+correttezza dei contenuti scritti dagli utenti o dagli agenti, né l'esito del
+lavoro che gli agenti svolgono usandoli, né l'uso che gli agenti fanno dei
+segreti che il Licenziatario concede loro attraverso la Cassaforte.
+
+## 13. Responsabilità
+
+13.1 Ciascuna parte risponde dei danni causati dal proprio inadempimento. La
+responsabilità complessiva del Licenziante derivante da questo contratto è
+limitata all'importo pagato dal Licenziatario nei dodici mesi precedenti
+l'evento (durante la Prova, che è gratuita: 100 euro), ed è esclusa per i
+danni indiretti, il mancato guadagno e la perdita di dati che una copia di
+sicurezza ragionevole avrebbe evitato.
+
+13.2 Le limitazioni del punto 13.1 non si applicano in caso di dolo o colpa
+grave, né agli altri casi in cui la legge non le consente (art. 1229 c.c.).
+
+## 14. Durata, cessazione e risoluzione
+
+14.1 Il contratto ha la Durata indicata nell'Ordine e si rinnova solo se
+l'Ordine lo prevede.
+
+14.2 Il Licenziante può risolvere il contratto ai sensi dell'art. 1456 c.c.,
+con comunicazione scritta, in caso di violazione dell'art. 4.
+
+14.3 Alla cessazione, per qualunque causa, il Software passa in sola lettura
+(art. 7) e il Licenziatario conserva pieno accesso ai propri Dati, che può
+esportare. Le clausole degli artt. 5, 6, 13 e 15 restano valide.
+
+## 15. Legge e foro
+
+Il contratto è regolato dalla legge italiana. Per ogni controversia è
+competente in via esclusiva il Foro di Firenze.
+
+## 16. Disposizioni finali
+
+Il contratto, con l'Ordine, è l'intero accordo fra le parti sul suo oggetto.
+Le modifiche valgono solo se scritte e accettate da entrambe. Se una clausola
+risulta invalida, le altre restano efficaci.
+
+---
+
+**Approvazione specifica.** Ai sensi degli artt. 1341 e 1342 c.c. il
+Licenziatario dichiara di approvare specificamente le clausole: 4 (divieti),
+7 (sola lettura), 12.2 (limiti di garanzia), 13
+(limitazione di responsabilità), 14.2 (clausola risolutiva espressa), 15
+(foro esclusivo).
+
+L'approvazione specifica si dà con la sottoscrizione dell'Ordine. Durante
+la Prova si dà nell'installatore, con un consenso separato dall'accettazione
+di questo contratto, che registra chi lo dà e per quale soggetto.
+
+---
+
+## Allegato — La chiave dei rilasci
+
+Ogni rilascio del Software è consegnato con la sua firma
+(`delminio-<versione>.tar.sig`), fatta con la chiave del Licenziante qui
+sotto. Il Licenziatario verifica ogni pacco con questa chiave prima di
+installarlo (INSTALLA.md § Prendere Delminio): un pacco la cui firma non si
+verifica non viene dal Licenziante, e non va installato. Fa fede la chiave
+scritta nella copia del contratto sottoscritta dalle parti.
+
+ ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0
+
+Identità: `rilasci@delminio.com` · ambito della firma: `delminio-rilascio`.
diff --git a/enterprise/TERZE-PARTI.md b/enterprise/TERZE-PARTI.md
new file mode 100644
index 0000000..0274ab4
--- /dev/null
+++ b/enterprise/TERZE-PARTI.md
@@ -0,0 +1,92 @@
+# Delminio — componenti di terze parti
+
+Il Software contiene i componenti qui sotto, ognuno distribuito con la sua
+licenza (LICENZA.md, art. 5.2). I testi completi stanno nei metadati dei
+pacchetti dentro l'immagine e nei siti dei progetti.
+
+- Python 3.14.10 — PSF-2.0
+- Nuitka (runtime dei moduli compilati) — Apache-2.0
+
+| Pacchetto | Versione | Licenza |
+|---|---|---|
+| aiofile | 3.12.3 | Apache-2.0 |
+| aiosqlite | 0.22.1 | MIT License |
+| annotated-types | 0.8.0 | MIT |
+| anyio | 4.15.1 | MIT |
+| attrs | 26.1.0 | MIT |
+| authlib | 1.8.0 | BSD-3-Clause |
+| beartype | 0.22.9 | MIT License |
+| cachetools | 7.2.1 | MIT |
+| caio | 0.12.9 | Apache-2.0 |
+| cbor2 | 6.3.0 | MIT |
+| certifi | 2026.7.22 | MPL-2.0 |
+| cffi | 2.1.1 | MIT-0 |
+| click | 8.5.0 | BSD-3-Clause |
+| cryptography | 50.0.2 | Apache-2.0 OR BSD-3-Clause |
+| cyclopts | 5.2.0 | Apache-2.0 |
+| dnspython | 2.8.0 | ISC |
+| docstring_parser | 0.18.0 | MIT |
+| email-validator | 2.3.0 | Unlicense |
+| exceptiongroup | 1.3.1 | MIT License |
+| fastmcp | 4.0.11 | Apache-2.0 |
+| fastmcp-slim | 4.0.11 | Apache-2.0 |
+| griffelib | 2.3.2 | ISC |
+| h11 | 0.16.0 | MIT |
+| httpcore | 1.0.9 | BSD-3-Clause |
+| httpcore2 | 2.13.1 | BSD-3-Clause |
+| httpx | 0.28.1 | BSD-3-Clause |
+| httpx2 | 2.13.1 | BSD-3-Clause |
+| idna | 3.20 | BSD-3-Clause |
+| jaraco.classes | 3.4.0 | MIT License |
+| jaraco.context | 6.1.2 | MIT |
+| jaraco.functools | 4.6.0 | MIT |
+| jeepney | 0.9.0 | MIT |
+| joserfc | 1.7.5 | BSD-3-Clause |
+| jsonref | 1.1.0 | MIT |
+| jsonschema | 4.26.0 | MIT |
+| jsonschema-path | 0.5.0 | Apache-2.0 |
+| jsonschema-specifications | 2025.9.1 | MIT |
+| keyring | 25.7.0 | MIT |
+| markdown-it-py | 4.2.0 | MIT License |
+| mcp | 2.3.0 | MIT |
+| mcp-types | 2.3.0 | MIT |
+| mdurl | 0.1.2 | MIT License |
+| more-itertools | 11.1.0 | MIT |
+| numpy | 2.5.3 | BSD-3-Clause AND 0BSD AND MIT AND Zlib AND CC0-1.0 |
+| openapi-pydantic | 0.6.0 | MIT |
+| opentelemetry-api | 1.45.1 | Apache-2.0 |
+| packaging | 26.3 | Apache-2.0 OR BSD-2-Clause |
+| pathable | 0.6.0 | Apache-2.0 |
+| pip | 26.2.2 | MIT |
+| platformdirs | 4.12.4 | MIT |
+| py-key-value-aio | 0.4.6 | Apache-2.0 |
+| pyasn1 | 0.6.5 | BSD-2-Clause |
+| pyasn1_modules | 0.4.2 | BSD |
+| pycparser | 3.0 | BSD-3-Clause |
+| pydantic | 2.13.5 | MIT |
+| pydantic-settings | 2.15.0 | MIT |
+| pydantic_core | 2.46.5 | MIT |
+| pygments | 2.21.0 | BSD-2-Clause |
+| pyjwt | 2.15.1 | MIT |
+| pyopenssl | 26.4.0 | Apache License, Version 2.0 |
+| pyperclip | 1.11.0 | BSD |
+| python-dotenv | 1.2.4 | BSD-3-Clause |
+| python-multipart | 0.0.32 | Apache-2.0 |
+| pyyaml | 6.0.3 | MIT |
+| referencing | 0.37.0 | MIT |
+| regex | 2026.11.9 | Apache-2.0 AND CNRI-Python |
+| rich | 15.0.0 | MIT |
+| rich-rst | 2.2.0 | MIT |
+| rpds-py | 2026.9.1 | MIT |
+| secretstorage | 3.5.0 | BSD-3-Clause |
+| sqlalchemy | 2.1.4 | MIT |
+| sse-starlette | 3.5.0 | BSD-3-Clause |
+| starlette | 1.7.0 | BSD-3-Clause |
+| truststore | 0.10.4 | MIT |
+| typing-inspection | 0.4.4 | MIT |
+| typing_extensions | 4.16.0 | PSF-2.0 |
+| uncalled-for | 0.4.0 | MIT License |
+| uvicorn | 0.54.0 | BSD-3-Clause |
+| watchfiles | 1.3.0 | MIT |
+| webauthn | 3.0.1 | BSD-3-Clause |
+| websockets | 17.2 | BSD-3-Clause |
diff --git a/enterprise/docker-compose.yml b/enterprise/docker-compose.yml
new file mode 100644
index 0000000..5929a58
--- /dev/null
+++ b/enterprise/docker-compose.yml
@@ -0,0 +1,78 @@
+# Delminio — il compose del kit. Tutto ciò che è un nome o un posto sta nel .env
+# accanto (copia .env.esempio): chi i container li monta a mano legge qui e fa
+# da sé, chi preferisce lancia installa.sh, che non fa niente di più.
+#
+# ⚠️ Le due cartelle vanno create PRIMA del primo `up`: se non ci sono, Docker
+# le crea come root e tu non ci scrivi più (installa.sh lo fa per te).
+services:
+ delminio:
+ # L'immagine dal nostro registro, con l'accesso dato a docker (docker login
+ # registry.delminio.com), o da un registro vostro che la rispecchia
+ # (DELMINIO_IMMAGINE). La versione la scrive installa.sh dal kit: si scarica
+ # solo se manca, e una versione già scaricata non cambia mai.
+ image: ${DELMINIO_IMMAGINE:-registry.delminio.com/delminio}:${DELMINIO_VERSIONE:?manca DELMINIO_VERSIONE nel .env}
+ pull_policy: missing
+ container_name: ${DELMINIO_CONTAINER:-delminio}
+ restart: unless-stopped
+ # Il tuo utente: ciò che Delminio scrive nella cartella delle memorie nasce tuo,
+ # e lo committi o lo togli senza sudo. installa.sh lo scrive nel .env.
+ # ⚠️ Senza, gira come root: un volume nato così resta di root, e passarlo a un
+ # altro utente dopo ferma Delminio (il database non è più suo).
+ user: "${DELMINIO_UID:-0}:${DELMINIO_GID:-0}"
+ # Nessun potere oltre il suo utente (F553): Delminio non ha bisogno di
+ # nessuna capability (porta alta, /etc/passwd scrivibile nell'immagine), e
+ # niente dentro può guadagnarne con un setuid.
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ ports:
+ - "${DELMINIO_ASCOLTA:-0.0.0.0}:${DELMINIO_PORTA:-8002}:8002"
+ # L'HTTPS col certificato locale, per l'app sul telefono (F573): risponde
+ # quando l'amministratore la accende dalle Impostazioni. Una porta poco
+ # comune, accanto alla sua: installa.sh ne sceglie una libera se è occupata.
+ - "${DELMINIO_ASCOLTA:-0.0.0.0}:${DELMINIO_HTTPS_PORTA:-8402}:8443"
+ volumes:
+ - delminio-dati:/data
+ # I .md delle memorie e MEMORY.md: il backup leggibile, da tenere sotto git.
+ - ${DELMINIO_MEMORIA:-./memoria}:/data/memory:rw
+ # Il clone del tuo progetto, in sola lettura: l'audit ci cerca i file che
+ # le memorie citano. Può restare vuoto.
+ - ${DELMINIO_PROGETTO:-./progetto}:/repo:ro
+ environment:
+ DATA_DIR: /data
+ DB_PATH: /data/delminio.db
+ MEMORY_DIR: /data/memory
+ # Gli spazi in più (F660): ognuno con le sue memorie, il suo Backlog e i suoi
+ # account, nello stesso volume; il primo è questo, il «principale».
+ DELMINIO_SPAZI_DIR: /data/spazi
+ # La stessa cartella vista dall'host: la guardia del client ci ferma i
+ # gesti che aggirano Delminio.
+ MEMORIA_SUL_DISCO: ${DELMINIO_MEMORIA_SUL_DISCO:-}
+ # Le memorie le committa e le pusha Delminio alla chiusura di ogni sessione,
+ # con una chiave di deploy sua (Impostazioni → «Le memorie su git»): gli
+ # agenti non toccano la cartella, e lavorano da qualunque macchina.
+ DELMINIO_MEMORIE_GIT: "si"
+ # Il comando che i messaggi del Cantiere nominano: il client del kit.
+ CANTIERE_CMD: delminio backlog
+ REPO_DIR: /repo
+ HOST: 0.0.0.0
+ PORT: "8002"
+ HTTPS_PORT: "8443"
+ DELMINIO_HTTPS_NOMI: ${DELMINIO_HTTPS_NOMI:-}
+ DELMINIO_HTTPS_PORTA: ${DELMINIO_HTTPS_PORTA:-8402}
+ JWT_SECRET: ${DELMINIO_JWT_SECRET:?manca DELMINIO_JWT_SECRET nel .env}
+ DELMINIO_PROXY_FIDATI: ${DELMINIO_PROXY_FIDATI:-}
+ DELMINIO_ORIGINI: ${DELMINIO_ORIGINI:-}
+ # Solo il primo valore: dopo vince ciò che scrivi nel pannello Impostazioni.
+ EMBEDDER_URL: ${DELMINIO_EMBEDDER_URL:-}
+ EMBEDDER_MODELLO: ${DELMINIO_EMBEDDER_MODELLO:-}
+ EMBEDDER_CHIAVE: ${DELMINIO_EMBEDDER_CHIAVE:-}
+ networks:
+ - delminio
+
+volumes:
+ delminio-dati:
+ name: ${DELMINIO_VOLUME:-delminio-dati}
+
+networks:
+ delminio:
+ name: ${DELMINIO_RETE:-delminio}
diff --git a/enterprise/frasi.en.sh b/enterprise/frasi.en.sh
new file mode 100644
index 0000000..5556c8d
--- /dev/null
+++ b/enterprise/frasi.en.sh
@@ -0,0 +1,107 @@
+M_dentro_un_repo='this folder is inside the repository {repo}: Delminio is installed outside any repository (a .env with the secret and memoria/ are created here). Move it, for example to ~/delminio, and run it again from there.'
+M_tolto_claude_md='removed the CLAUDE.md of the previous kit'
+M_manca='{cosa} is missing'
+M_manca_compose='docker compose is missing (the v2 plugin: “docker compose”, not “docker-compose”)'
+M_docker_muto='docker doesn'"'"'t respond to this user (docker group, or sudo)'
+M_passo_licenza='The licence'
+M_kit_incompleto='{file} is missing: the installation kit isn'"'"'t complete, extract it again from the image (INSTALLA.md § Getting Delminio)'
+M_leggi_licenza='Before installing, read {licenza} (what you can do with Delminio) and
+ {informativa} (what goes out to us: the licence check, and the reports you send).'
+M_li_accetti='Have you read them and do you accept them? [y/N]'
+M_senza_licenza='without accepting the licence nothing is installed (or pass DELMINIO_ACCETTO=si)'
+M_clausole='{licenza}, at the end (“Specific approval”), lists the clauses that are
+ approved separately: restrictions, read-only, limits of warranty and liability,
+ termination, jurisdiction.'
+M_approva_chi='To approve them write your first and last name and on whose behalf (e.g. “John Smith for Acme Ltd”):'
+M_senza_approvazione='without the specific approval of the clauses nothing is installed: the first and last name of the person approving, and on whose behalf, are needed (DELMINIO_APPROVO="John Smith for Acme Ltd")'
+M_indietro_senza_env='there'"'"'s no installation here (.env is missing): “indietro” is run from Delminio'"'"'s folder'
+M_indietro_senza_versione='there'"'"'s no installation here to roll back (DELMINIO_VERSIONE is missing from the .env)'
+M_copie_illeggibili='I can'"'"'t read the copies in the volume {volume} with the image {immagine}'
+M_nessun_prima='in the volume {volume} there'"'"'s no copy of the DB made when leaving another version: there'"'"'s no “before” to go back to'
+M_manca_immagine_prima='the image {immagine} is missing and the registry doesn'"'"'t give it: sign in to the registry (docker login, INSTALLA.en.md § Getting Delminio) and run again'
+M_passo_indietro='Back: {da} → {a}'
+M_db_torna='the DB goes back to the copy {copia}; the current one stays among the copies'
+M_db_non_tornato='the DB didn'"'"'t go back: Delminio is stopped, the copies are in /data/copie of the volume {volume}'
+M_non_risponde_indietro='Delminio isn'"'"'t responding on port {porta} after 40 seconds: docker logs {container}'
+M_tornato='✅ Delminio is back to {prima}, with the DB from before the update. The installation kit here is still the one from {ora}: “bash installa.sh” updates again.'
+M_via_senza_env='there'"'"'s no installation here (.env is missing): “via” is run from Delminio'"'"'s folder'
+M_passo_via='Delminio is leaving this machine'
+M_via_spiega='Before this, on every machine where an agent works: delminio disconnect
+ (inside the connected repository): everyone gets their personal memories and their token is switched off.
+ These stay yours: memoria/ (the clone of the memory repository), the volume {volume}, and a
+ copy of the database I'"'"'m making right now next to it. The container and the image are stopped.'
+M_procedo='Go ahead? [y/N]'
+M_niente_di_fatto='Nothing done.'
+M_copia_fallita='the database copy didn'"'"'t succeed: I haven'"'"'t stopped anything'
+M_database_in='the database is in {percorso}'
+M_spento_db_volume='Delminio isn'"'"'t running: the database stays in the volume {volume} (no copy next to it)'
+M_memoria_sporca='there are uncommitted files in memoria/: git -C memoria status, and commit them yourselves if needed'
+M_tolta_immagine='deleted the image {immagine}'
+M_immagine_resta='the image {immagine} stays: docker image rm didn'"'"'t go through (docker image ls to see it)'
+M_immagine_in_uso='the image {immagine} stays: another container on this machine uses it'
+M_via_fatto='✅ Delminio is stopped and removed from this machine. Your data is still here:
+ memoria/ and the memory repository on your git host, {copia}the volume {volume}.
+ To really delete them, whenever you want: docker volume rm {volume}, then this folder.
+ To come back: “bash installa.sh” (with access to the registry) restarts from the volume.'
+M_passo_immagine='The image'
+M_env_creato='.env created from .env.esempio'
+M_kit_senza_versione='the installation kit doesn'"'"'t state its version (VERSIONE is missing): extract it again from the image (INSTALLA.md § Getting Delminio)'
+M_aggiornamento='update: {da} → {a} (the database copies itself before changing schema)'
+M_manca_immagine='the image {immagine} is missing and the registry doesn'"'"'t give it: sign in to the registry (docker login, INSTALLA.en.md § Getting Delminio) and run again'
+M_immagine_ce='{immagine} is there'
+M_passo_env='The .env'
+M_segreto='secret generated (DELMINIO_JWT_SECRET): don'"'"'t change it, or the agents need reconnecting'
+M_https_per='HTTPS for the phone app, for: {nomi}'
+M_porta_https_occupata='the HTTPS port {occupata} is taken: using {libera}'
+M_altrui_container='the container “{container}” (installed from {dove})'
+M_altrui_progetto='the container “{container}” (same compose project “{progetto}”, installed from {dove})'
+M_senza_padrone='{cosa} “{nome}” already exists and doesn'"'"'t say whose it is: if it doesn'"'"'t belong to this installation, change the name in the .env'
+M_il_volume='the volume'
+M_la_rete='the network'
+M_altrui_tipo='{cosa} “{nome}” (of the compose project “{progetto}”)'
+M_altrui_porta='the port {porta} (used by the container “{container}”)'
+M_altra_installazione='There'"'"'s another installation on this machine, and this one would use its things:'
+M_altra_spiega='The other one isn'"'"'t touched. If it'"'"'s yours and you want to update it: LEGGIMI.md § Updating, from its folder.
+ If this is a separate installation: in this .env change DELMINIO_CONTAINER, DELMINIO_VOLUME,
+ DELMINIO_RETE, DELMINIO_PORTA and COMPOSE_PROJECT_NAME (for example delminio-2, delminio-2-dati, delminio-2,
+ 8003, delminio-2) and run again.'
+M_volume_root='the volume {volume} already exists: Delminio stays as you started it (root), the .md files are created as root'
+M_rootless='rootless docker: Delminio runs as the container'"'"'s 0, which here is you ({utente}): the memories are created with your user'
+M_gira_come='Delminio will run as {utente} (uid {uid}): the memories are created with your user'
+M_da_root='you'"'"'re installing as root: Delminio will run as root in the container. Better a user of yours in the docker group (or rootless docker): run again from there on a new folder'
+M_riepilogo='version {versione} · container {container} · port {porta}'
+M_passo_cartelle='The folders'
+M_non_scrivibile='{cartella} exists but isn'"'"'t writable by {utente}: maybe Docker created it as root'
+M_creata='created {cartella}'
+M_memoria_non_vuota='{cartella} isn'"'"'t empty and isn'"'"'t a git repository: move it, or clone the memory repository into it'
+M_repo_tuo='Memories live in a repository of yours: create it empty on your GitHub, Forgejo or Gitea.'
+M_indirizzo_clone='The address to clone it (ssh or https):'
+M_serve_repo='the memory repository is needed: pass DELMINIO_MEMORIA_REMOTO=<address of a repository of yours, empty>'
+M_clone_fallito='I can'"'"'t clone {remoto}: check the address and git'"'"'s credentials on this machine'
+M_clone_di='{cartella} is the clone of {remoto}'
+M_chmod_fallito='I can'"'"'t close {cartella} to the machine'"'"'s other users'
+M_senza_remoto='{cartella} is a repository without a remote: git -C {cartella} remote add origin <your memory repository>'
+M_gitignore_token='The machine'"'"'s token: a credential, not a memory.'
+M_commit_cartella='Delminio: the memory folder'
+M_chi_sei='git doesn'"'"'t know who you are: git config --global user.name "Name" && git config --global user.email you@example.com'
+M_push_negato='you can'"'"'t push to {remoto}: a repository of yours and git credentials are needed'
+M_push_ok='memories: {remoto}, pushing works'
+M_progetto_vuoto='{cartella} is empty: clone your repository into it (read-only for Delminio) whenever you want'
+M_passo_avvio=Startup
+M_non_risponde='Delminio isn'"'"'t responding on port {porta} after 40 seconds (its log is above)'
+M_non_scrive='Delminio responds but doesn'"'"'t write in {cartella} (its log is above): usually it'"'"'s the container'"'"'s user (DELMINIO_UID in the .env) that can'"'"'t write in the folder'
+M_cosa_semina='the defaults of the first startup'
+M_cosa_regole='Delminio'"'"'s rules for version {versione}'
+M_commit_cosa='Delminio: {cosa}'
+M_cosa_pushate='memories: {cosa}, committed and pushed'
+M_cosa_non_entrate='{cosa} didn'"'"'t get into the memory repository: commit them yourself (git -C {cartella} status)'
+M_su='✅ Delminio is up: {indirizzo}'
+M_app_telefono='the phone app is switched on from Settings → “The app on your phone”'
+M_codice='The first sign-in creates the admin and needs this code: {codice}'
+M_codice_perso='(it disappears afterwards; if you lose it: docker exec {container} cat /data/codice_installazione)'
+M_si_ricollegano='Connected projects reconnect by themselves at the first opening: there'"'"'s nothing else to do.'
+M_poi_dalla_app='Then, from the app:
+ 1. Settings → The licence: paste the licence we gave you.
+ 2. Settings → Embedder: choose yours and press Test.
+ 3. Access → Connect a repository: it gives you the command to run inside the
+ clone of your repository, on this machine.'
diff --git a/enterprise/installa.sh b/enterprise/installa.sh
new file mode 100755
index 0000000..d9cf618
--- /dev/null
+++ b/enterprise/installa.sh
@@ -0,0 +1,500 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+set -euo pipefail
+cd "$(dirname "$0")"
+
+: '⟦frasi: installa⟧'
+M_dentro_un_repo='questa cartella sta dentro il repo {repo}: Delminio si installa fuori da ogni repo (qui si creano un .env col segreto e memoria/). Spostala, per esempio in ~/delminio, e rilancia da lì.'
+M_tolto_claude_md='rimosso il CLAUDE.md del kit di prima'
+M_manca='manca {cosa}'
+M_manca_compose='manca docker compose (il plugin v2: «docker compose», non «docker-compose»)'
+M_docker_muto='docker non risponde a questo utente (gruppo docker, o sudo)'
+M_passo_licenza='La licenza'
+M_kit_incompleto='manca {file}: il kit d'"'"'installazione non è completo, riestrailo dall'"'"'immagine (INSTALLA.md § Prendere Delminio)'
+M_leggi_licenza='Prima di installare, leggi {licenza} (cosa puoi fare con Delminio) e
+ {informativa} (cosa parte verso di noi: il controllo della licenza, e le segnalazioni che mandate voi).'
+M_li_accetti='Li hai letti e li accetti? [s/N]'
+M_senza_licenza='senza l'"'"'accettazione della licenza non si installa (o passa DELMINIO_ACCETTO=si)'
+M_clausole='{licenza}, in fondo («Approvazione specifica»), elenca le clausole che si
+ approvano a parte: divieti, sola lettura, limiti di garanzia e di responsabilità,
+ risoluzione, foro.'
+M_approva_chi='Per approvarle scrivi nome e cognome e per chi (es. «Mario Rossi per Acme srl»):'
+M_senza_approvazione='senza l'"'"'approvazione specifica delle clausole non si installa: serve nome e cognome di chi approva e per chi (DELMINIO_APPROVO="Mario Rossi per Acme srl")'
+M_indietro_senza_env='qui non c'"'"'è un'"'"'installazione (manca .env): «indietro» si lancia dalla cartella di Delminio'
+M_indietro_senza_versione='qui non c'"'"'è un'"'"'installazione da riportare indietro (nel .env manca DELMINIO_VERSIONE)'
+M_copie_illeggibili='non riesco a leggere le copie nel volume {volume} con l'"'"'immagine {immagine}'
+M_nessun_prima='nel volume {volume} non c'"'"'è una copia del DB fatta lasciando un'"'"'altra versione: non c'"'"'è un «prima» a cui tornare'
+M_manca_immagine_prima='manca l'"'"'immagine {immagine} e il registro non la dà: accedi al registro (docker login, INSTALLA.md § Prendere Delminio) e rilancia'
+M_passo_indietro='Indietro: {da} → {a}'
+M_db_torna='il DB torna quello della copia {copia}; quello di adesso resta fra le copie'
+M_db_non_tornato='il DB non è tornato indietro: Delminio è fermo, le copie sono in /data/copie del volume {volume}'
+M_non_risponde_indietro='Delminio non risponde sulla porta {porta} dopo 40 secondi: docker logs {container}'
+M_tornato='✅ Delminio è tornato a {prima}, col DB di prima dell'"'"'aggiornamento. Il kit d'"'"'installazione qui è ancora quello di {ora}: «bash installa.sh» riaggiorna.'
+M_via_senza_env='qui non c'"'"'è un'"'"'installazione (manca .env): «via» si lancia dalla cartella di Delminio'
+M_passo_via='Delminio se ne va da questa macchina'
+M_via_spiega='Prima di questo, su ogni macchina dove lavora un agente: delminio stacca
+ (dentro il repo collegato): ognuno riceve le sue memorie personali e il suo token si spegne.
+ Restano vostri: memoria/ (il clone del repo delle memorie), il volume {volume}, e una
+ copia del database che faccio adesso qui accanto. Si fermano il container e l'"'"'immagine.'
+M_procedo='Procedo? [s/N]'
+M_niente_di_fatto='Niente di fatto.'
+M_copia_fallita='la copia del database non è riuscita: non ho fermato niente'
+M_database_in='il database è in {percorso}'
+M_spento_db_volume='Delminio non è acceso: il database resta nel volume {volume} (nessuna copia qui accanto)'
+M_memoria_sporca='in memoria/ ci sono file non committati: git -C memoria status, e committali voi se servono'
+M_tolta_immagine='eliminata l'"'"'immagine {immagine}'
+M_immagine_resta='l'"'"'immagine {immagine} resta: docker image rm non è passato (docker image ls per vederla)'
+M_immagine_in_uso='l'"'"'immagine {immagine} resta: la usa un altro container su questa macchina'
+M_via_fatto='✅ Delminio è fermo ed eliminato da questa macchina. I vostri dati sono ancora qui:
+ memoria/ e il repo delle memorie sul vostro git host, {copia}il volume {volume}.
+ Cancellarli davvero, quando volete: docker volume rm {volume}, poi questa cartella.
+ Tornare: «bash installa.sh» (con l'"'"'accesso al registro) riparte dal volume.'
+M_passo_immagine='L'"'"'immagine'
+M_env_creato='.env creato da .env.esempio'
+M_kit_senza_versione='il kit d'"'"'installazione non dice la sua versione (manca VERSIONE): riestrailo dall'"'"'immagine (INSTALLA.md § Prendere Delminio)'
+M_aggiornamento='aggiornamento: {da} → {a} (il database si copia da sé prima di cambiare schema)'
+M_manca_immagine='manca l'"'"'immagine {immagine} e il registro non la dà: accedi al registro (docker login, INSTALLA.md § Prendere Delminio) e rilancia'
+M_immagine_ce='{immagine} c'"'"'è'
+M_passo_env='Il .env'
+M_segreto='segreto generato (DELMINIO_JWT_SECRET): non cambiarlo, o gli agenti vanno ricollegati'
+M_https_per='HTTPS per l'"'"'app sul telefono, per: {nomi}'
+M_porta_https_occupata='la porta HTTPS {occupata} è occupata: uso la {libera}'
+M_altrui_container='il container «{container}» (installato da {dove})'
+M_altrui_progetto='il container «{container}» (stesso progetto compose «{progetto}», installato da {dove})'
+M_senza_padrone='{cosa} «{nome}» c'"'"'è già e non dice di chi è: se non è di questa installazione, cambia il nome nel .env'
+M_il_volume='il volume'
+M_la_rete='la rete'
+M_altrui_tipo='{cosa} «{nome}» (del progetto compose «{progetto}»)'
+M_altrui_porta='la porta {porta} (la usa il container «{container}»)'
+M_altra_installazione='Su questa macchina c'"'"'è un'"'"'altra installazione, e questa userebbe le sue cose:'
+M_altra_spiega='L'"'"'altra non si tocca. Se è la tua e vuoi aggiornarla: LEGGIMI.md § Aggiornare, dalla sua cartella.
+ Se questa è un'"'"'installazione separata: nel .env di qui cambia DELMINIO_CONTAINER, DELMINIO_VOLUME,
+ DELMINIO_RETE, DELMINIO_PORTA e COMPOSE_PROJECT_NAME (per esempio delminio-2, delminio-2-dati, delminio-2,
+ 8003, delminio-2) e rilancia.'
+M_volume_root='il volume {volume} c'"'"'è già: Delminio resta come l'"'"'hai avviato (root), i .md si creano di root'
+M_rootless='docker rootless: Delminio gira come lo 0 del container, che qui sei tu ({utente}): le memorie si creano col tuo utente'
+M_gira_come='Delminio girerà come {utente} (uid {uid}): le memorie si creano col tuo utente'
+M_da_root='stai installando da root: Delminio girerà da root nel container. Meglio un utente tuo nel gruppo docker (o docker rootless): rilancia da lì su una cartella nuova'
+M_riepilogo='versione {versione} · container {container} · porta {porta}'
+M_passo_cartelle='Le cartelle'
+M_non_scrivibile='{cartella} esiste ma non è scrivibile da {utente}: forse l'"'"'ha creata Docker come root'
+M_creata='creata {cartella}'
+M_memoria_non_vuota='{cartella} non è vuota e non è un repo git: spostala, o clonaci dentro il repo delle memorie'
+M_repo_tuo='Le memorie stanno in un repo tuo: crealo vuoto sul tuo GitHub, Forgejo o Gitea.'
+M_indirizzo_clone='L'"'"'indirizzo per clonarlo (ssh o https):'
+M_serve_repo='serve il repo delle memorie: passa DELMINIO_MEMORIA_REMOTO=<indirizzo di un repo tuo, vuoto>'
+M_clone_fallito='non riesco a clonare {remoto}: controlla l'"'"'indirizzo e le credenziali di git su questa macchina'
+M_clone_di='{cartella} è il clone di {remoto}'
+M_chmod_fallito='non riesco a chiudere {cartella} agli altri utenti della macchina'
+M_senza_remoto='{cartella} è un repo senza remoto: git -C {cartella} remote add origin <il tuo repo delle memorie>'
+M_gitignore_token='Il token della macchina: una credenziale, non una memoria.'
+M_commit_cartella='Delminio: la cartella delle memorie'
+M_chi_sei='git non sa chi sei: git config --global user.name "Nome" && git config --global user.email tu@esempio.it'
+M_push_negato='non puoi pushare su {remoto}: serve un repo tuo e le credenziali di git'
+M_push_ok='memorie: {remoto}, il push funziona'
+M_progetto_vuoto='{cartella} è vuota: clonaci il tuo repo (sola lettura per Delminio) quando vuoi'
+M_passo_avvio=Avvio
+M_non_risponde='Delminio non risponde sulla porta {porta} dopo 40 secondi (sopra, il suo log)'
+M_non_scrive='Delminio risponde ma non scrive in {cartella} (qui sopra il suo log): di solito è l'"'"'utente del container (DELMINIO_UID nel .env) che non può scrivere nella cartella'
+M_cosa_semina='la semina del primo avvio'
+M_cosa_regole='le regole di Delminio della versione {versione}'
+M_commit_cosa='Delminio: {cosa}'
+M_cosa_pushate='memorie: {cosa}, committate e pushate'
+M_cosa_non_entrate='{cosa} non sono entrate nel repo delle memorie: committale tu (git -C {cartella} status)'
+M_su='✅ Delminio è su: {indirizzo}'
+M_app_telefono='l'"'"'app sul telefono si accende da Impostazioni → «L'"'"'app sul telefono»'
+M_codice='Il primo accesso crea l'"'"'amministratore e vuole questo codice: {codice}'
+M_codice_perso='(sparisce dopo; se lo perdi: docker exec {container} cat /data/codice_installazione)'
+M_si_ricollegano='I progetti collegati si ricollegano da soli alla prima apertura: non c'"'"'è altro da fare.'
+M_poi_dalla_app='Poi, dall'"'"'app:
+ 1. Impostazioni → La licenza: incolla la licenza che ti abbiamo dato.
+ 2. Impostazioni → Embedder: scegli il tuo e premi Prova.
+ 3. Accesso → Collegare un repo: ti dà il comando da lanciare dentro il
+ clone del tuo repo, su questa macchina.'
+: '⟦fine frasi⟧'
+LINGUA=""
+_l=${DELMINIO_LINGUA:-${LC_ALL:-${LC_MESSAGES:-${LANG:-}}}}; _l=${_l%%[.@]*}; _l=${_l/_/-}
+for _c in "$_l" "${_l%%-*}"; do
+ if [ -n "$_c" ] && [ -f "frasi.$_c.sh" ]; then . "./frasi.$_c.sh"; LINGUA=$_c; break; fi
+done
+_f() { # _f "$M_<chiave>" [segnaposto valore]... → la frase coi {segnaposto} riempiti
+ local t=$1 k v fuori
+ shift
+ while [ $# -ge 2 ]; do
+ k="{$1}"; v=$2; fuori=""
+ while [ "${t#*"$k"}" != "$t" ]; do fuori=$fuori${t%%"$k"*}$v; t=${t#*"$k"}; done
+ t=$fuori$t; shift 2
+ done
+ printf '%s\n' "$t"
+}
+
+passo() { printf '\n▸ %s\n' "$*"; }
+muori() { printf '❌ %s\n' "$*" >&2; exit 1; }
+ha_tty() { { : </dev/tty; } 2>/dev/null; }
+
+if dentro=$(git rev-parse --show-toplevel 2>/dev/null); then
+ muori "$(_f "$M_dentro_un_repo" repo "$dentro")"
+fi
+
+if [ -f CLAUDE.md ] && [ "$(head -1 CLAUDE.md)" = "# Delminio — la cartella dell'installazione" ]; then
+ rm CLAUDE.md && echo " $M_tolto_claude_md"
+fi
+
+command -v docker >/dev/null || muori "$(_f "$M_manca" cosa docker)"
+docker compose version >/dev/null 2>&1 || muori "$M_manca_compose"
+docker info >/dev/null 2>&1 || muori "$M_docker_muto"
+
+if [ "${1:-}" != indietro ] && [ "${1:-}" != via ] && ! grep -q '^DELMINIO_LICENZA_ACCETTATA=.' .env 2>/dev/null; then
+ passo "$M_passo_licenza"
+ for f in LICENZA.md INFORMATIVA.md; do [ -f "$f" ] || muori "$(_f "$M_kit_incompleto" file "$f")"; done
+ lic=LICENZA.md; inf=INFORMATIVA.md
+ if [ -n "$LINGUA" ]; then
+ [ -f "LICENZA.$LINGUA.md" ] && lic=LICENZA.$LINGUA.md
+ [ -f "INFORMATIVA.$LINGUA.md" ] && inf=INFORMATIVA.$LINGUA.md
+ fi
+ echo " $(_f "$M_leggi_licenza" licenza "$lic" informativa "$inf")"
+ risposta="${DELMINIO_ACCETTO:-}"
+ if [ -z "$risposta" ] && ha_tty; then
+ read -rp " $M_li_accetti " risposta </dev/tty || true
+ fi
+ case "$risposta" in
+ s|S|si|sì|SI|y|yes) accettata="$(date -u +%Y-%m-%dT%H:%M:%SZ) v$(grep -m1 -o 'Versione [0-9.]*' LICENZA.md | cut -d' ' -f2)${LINGUA:+ $LINGUA}" ;;
+ *) muori "$M_senza_licenza" ;;
+ esac
+ echo " $(_f "$M_clausole" licenza "$lic")"
+ approva="${DELMINIO_APPROVO:-}"
+ if [ -z "$approva" ] && ha_tty; then
+ read -rp " $M_approva_chi " approva </dev/tty || true
+ fi
+ case "${approva,,}" in
+ ""|s|si|sì|y|yes|no|n) muori "$M_senza_approvazione" ;;
+ esac
+ approvata="$(date -u +%Y-%m-%dT%H:%M:%SZ) $(printf '%s' "$approva" | tr -d '\n="' | cut -c1-120)"
+fi
+
+leggi_env() { grep -m1 "^$1=" .env | cut -d= -f2- || true; }
+scrivi_env() { # sostituisce la riga, o la aggiunge
+ if grep -q "^$1=" .env; then
+ python3 - "$1" "$2" <<'EOF' 2>/dev/null || sed -i "s|^$1=.*|$1=$2|" .env
+import sys, pathlib
+k, v = sys.argv[1], sys.argv[2]
+p = pathlib.Path(".env")
+p.write_text("".join(f"{k}={v}\n" if r.startswith(k + "=") else r
+ for r in p.read_text().splitlines(keepends=True)))
+EOF
+ else
+ printf '%s=%s\n' "$1" "$2" >> .env
+ fi
+}
+
+if [ "${1:-}" = indietro ]; then
+ [ -f .env ] || muori "$M_indietro_senza_env"
+ ora=$(leggi_env DELMINIO_VERSIONE)
+ [ -n "$ora" ] || muori "$M_indietro_senza_versione"
+ img=$(leggi_env DELMINIO_IMMAGINE); img=${img:-registry.delminio.com/delminio}
+ volume=$(leggi_env DELMINIO_VOLUME); volume=${volume:-delminio-dati}
+ utente="$(leggi_env DELMINIO_UID):$(leggi_env DELMINIO_GID)"; [ "$utente" = ":" ] && utente=0:0
+ dati() { docker run --rm --user "$utente" --entrypoint python -v "$volume:/data" "$img:$ora" -c "$@"; }
+ copia=$(dati 'import glob, os, sys
+c = [p for p in sorted(glob.glob("/data/copie/delminio-*-da-*.db") + glob.glob("/data/copie/delminio-*-da-*.db.gz"))
+ if not p.endswith(("-da-%s.db" % sys.argv[1], "-da-%s.db.gz" % sys.argv[1]))]
+print(os.path.basename(c[-1]) if c else "")' "$ora") \
+ || muori "$(_f "$M_copie_illeggibili" volume "$volume" immagine "$img:$ora")"
+ [ -n "$copia" ] || muori "$(_f "$M_nessun_prima" volume "$volume")"
+ prima=${copia##*-da-}; prima=${prima%.gz}; prima=${prima%.db}
+ if ! docker image inspect "$img:$prima" >/dev/null 2>&1; then
+ altra=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -m1 -E "(^|/)delminio:$prima\$" || true)
+ if [ -n "$altra" ]; then docker tag "$altra" "$img:$prima"
+ else docker pull -q "$img:$prima" >/dev/null 2>&1 \
+ || muori "$(_f "$M_manca_immagine_prima" immagine "$img:$prima")"; fi
+ fi
+ passo "$(_f "$M_passo_indietro" da "$ora" a "$prima")"
+ echo " $(_f "$M_db_torna" copia "$copia")"
+ docker compose down
+ dati 'import datetime, gzip, os, shutil, sqlite3, sys
+ora, copia, prima = sys.argv[1:4]
+db = "/data/delminio.db"
+def copia_db(da, a):
+ s, d = sqlite3.connect(da), sqlite3.connect(a)
+ with d:
+ s.backup(d)
+ s.close(); d.close()
+if os.path.exists(db):
+ copia_db(db, "/data/copie/delminio-%s-da-%s.db" % (datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), ora))
+for f in (db + "-wal", db + "-shm"):
+ if os.path.exists(f):
+ os.remove(f)
+if copia.endswith(".gz"):
+ with gzip.open("/data/copie/" + copia, "rb") as da, open(db + ".indietro", "wb") as a:
+ shutil.copyfileobj(da, a, 1 << 20)
+ os.replace(db + ".indietro", db)
+else:
+ copia_db("/data/copie/" + copia, db)
+open("/data/versione_ultimo_avvio", "w").write(prima)' "$ora" "$copia" "$prima" \
+ || muori "$(_f "$M_db_non_tornato" volume "$volume")"
+ scrivi_env DELMINIO_VERSIONE "$prima"
+ docker compose up -d
+ porta=$(leggi_env DELMINIO_PORTA); porta=${porta:-8002}
+ for _ in $(seq 1 40); do
+ [ "$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$porta/api/auth/check")" != 000 ] && break
+ sleep 1
+ done
+ [ "$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$porta/api/auth/check")" != 000 ] \
+ || muori "$(_f "$M_non_risponde_indietro" porta "$porta" container "$(leggi_env DELMINIO_CONTAINER)")"
+ echo "$(_f "$M_tornato" prima "$prima" ora "$ora")"
+ exit 0
+fi
+
+if [ "${1:-}" = via ]; then
+ [ -f .env ] || muori "$M_via_senza_env"
+ ora=$(leggi_env DELMINIO_VERSIONE)
+ img=$(leggi_env DELMINIO_IMMAGINE); img=${img:-registry.delminio.com/delminio}
+ volume=$(leggi_env DELMINIO_VOLUME); volume=${volume:-delminio-dati}
+ contenitore=$(leggi_env DELMINIO_CONTAINER); contenitore=${contenitore:-delminio}
+ passo "$M_passo_via"
+ echo " $(_f "$M_via_spiega" volume "$volume")"
+ risposta="${DELMINIO_VIA:-}"
+ if [ -z "$risposta" ] && ha_tty; then
+ read -rp " $M_procedo " risposta </dev/tty || true
+ fi
+ case "$risposta" in s|S|si|sì|y|yes) ;; *) echo "$M_niente_di_fatto"; exit 0 ;; esac
+ copia="delminio-finale-$(date +%Y%m%d-%H%M%S).db"
+ if docker ps --format '{{.Names}}' | grep -qxF "$contenitore"; then
+ docker exec "$contenitore" python -c 'import sqlite3, sys
+s, d = sqlite3.connect("/data/delminio.db"), sqlite3.connect("/data/" + sys.argv[1])
+with d:
+ s.backup(d)' "$copia" && docker cp "$contenitore:/data/$copia" "./$copia" \
+ && docker exec "$contenitore" rm -f "/data/$copia" \
+ || muori "$M_copia_fallita"
+ chmod 600 "./$copia"
+ echo " $(_f "$M_database_in" percorso "$(pwd)/$copia")"
+ else
+ copia=""
+ echo " ⚠️ $(_f "$M_spento_db_volume" volume "$volume")"
+ fi
+ if [ -d memoria/.git ] && [ -n "$(git -C memoria status --porcelain 2>/dev/null)" ]; then
+ echo " ⚠️ $M_memoria_sporca"
+ fi
+ docker compose down
+ if [ -n "$ora" ]; then
+ altri=$(docker ps -a -q --filter "ancestor=$img:$ora")
+ if [ -z "$altri" ]; then
+ if docker image rm "$img:$ora" >/dev/null 2>&1; then echo " $(_f "$M_tolta_immagine" immagine "$img:$ora")"
+ else echo " ⚠️ $(_f "$M_immagine_resta" immagine "$img:$ora")"; fi
+ else
+ echo " $(_f "$M_immagine_in_uso" immagine "$img:$ora")"
+ fi
+ fi
+ echo "$(_f "$M_via_fatto" copia "${copia:+$copia, }" volume "$volume")"
+ exit 0
+fi
+
+passo "$M_passo_immagine"
+[ -f .env ] || { cp .env.esempio .env; echo " $M_env_creato"; }
+v=$(leggi_env DELMINIO_VERSIONE)
+v_kit=$(cat VERSIONE 2>/dev/null || true)
+[ -n "$v_kit" ] || muori "$M_kit_senza_versione"
+if [ "$v" != "$v_kit" ]; then
+ [ -n "$v" ] && aggiornato=si && echo " $(_f "$M_aggiornamento" da "$v" a "$v_kit")"
+ v=$v_kit; scrivi_env DELMINIO_VERSIONE "$v"
+fi
+img=$(leggi_env DELMINIO_IMMAGINE); img=${img:-registry.delminio.com/delminio}
+docker image inspect "$img:$v" >/dev/null 2>&1 || docker pull -q "$img:$v" >/dev/null 2>&1 \
+ || muori "$(_f "$M_manca_immagine" immagine "$img:$v")"
+echo " $(_f "$M_immagine_ce" immagine "$img:$v")"
+
+passo "$M_passo_env"
+if [ -z "$(leggi_env DELMINIO_JWT_SECRET)" ]; then
+ segreto=$(openssl rand -hex 32 2>/dev/null || head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n')
+ scrivi_env DELMINIO_JWT_SECRET "$segreto"
+ echo " $M_segreto"
+fi
+if [ -z "$(leggi_env DELMINIO_HTTPS_NOMI)" ]; then
+ if [ "$(uname)" = Darwin ]; then
+ ips=$(ifconfig 2>/dev/null | awk '/inet /{print $2}')
+ else
+ ips=$(ip -4 -o addr show scope global 2>/dev/null | awk '$2 !~ /^(docker|br-|veth|virbr|lxc)/ {sub(/\/.*/, "", $4); print $4}')
+ fi
+ nomi=$(printf '%s\n' $ips | grep -E '^(10\.|192\.168\.|172\.(1[6-9]|2[0-9]|3[01])\.)' | paste -sd, - || true)
+ nome=$(hostname -s 2>/dev/null || hostname 2>/dev/null || true)
+ nome=$(printf '%s' "$nome" | tr 'A-Z' 'a-z')
+ if printf '%s' "$nome" | grep -qE '^[a-z0-9][a-z0-9-]*$' && [ "$nome" != localhost ]; then
+ nomi="${nomi:+$nomi,}$nome,$nome.local"
+ fi
+ if [ -n "$nomi" ]; then
+ scrivi_env DELMINIO_HTTPS_NOMI "$nomi"
+ echo " $(_f "$M_https_per" nomi "$nomi")"
+ fi
+fi
+ph=$(leggi_env DELMINIO_HTTPS_PORTA); ph=${ph:-8402}
+mio_c=$(leggi_env DELMINIO_CONTAINER); mio_c=${mio_c:-delminio}
+occupata() {
+ docker port "$mio_c" 2>/dev/null | grep -q ":$1\$" && return 1
+ docker ps --format '{{.Ports}}' | grep -qE ":$1->" && return 0
+ if command -v ss >/dev/null; then ss -Hltn "sport = :$1" 2>/dev/null | grep -q . && return 0
+ elif command -v lsof >/dev/null; then lsof -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1 && return 0; fi
+ return 1
+}
+p0=$ph
+while occupata "$ph"; do ph=$((ph + 1)); [ "$ph" -gt $((p0 + 50)) ] && break; done
+if [ "$ph" != "$(leggi_env DELMINIO_HTTPS_PORTA)" ]; then
+ scrivi_env DELMINIO_HTTPS_PORTA "$ph"
+ [ "$ph" != "$p0" ] && echo " $(_f "$M_porta_https_occupata" occupata "$p0" libera "$ph")"
+fi
+c=$(leggi_env DELMINIO_CONTAINER); c=${c:-delminio}
+dove=$(docker inspect "$c" --format '{{index .Config.Labels "com.docker.compose.project.working_dir"}}' 2>/dev/null || true)
+mio=$(leggi_env COMPOSE_PROJECT_NAME)
+if [ -z "$mio" ]; then
+ progetto_nuovo=si; mio=$c
+ if [ -n "$dove" ] && [ "$(readlink -f "$dove")" = "$(pwd -P)" ]; then
+ mio=$(docker inspect "$c" --format '{{index .Config.Labels "com.docker.compose.project"}}')
+ fi
+fi
+altrui=""
+[ -n "$dove" ] && [ "$(readlink -f "$dove")" != "$(pwd -P)" ] && altrui="$altrui\n · $(_f "$M_altrui_container" container "$c" dove "$dove")"
+while read -r nome wd; do
+ [ -n "$wd" ] && [ "$(readlink -f "$wd")" != "$(pwd -P)" ] \
+ && altrui="$altrui\n · $(_f "$M_altrui_progetto" container "$nome" progetto "$mio" dove "$wd")"
+done < <([ -n "$mio" ] && docker ps -a --filter "label=com.docker.compose.project=$mio" \
+ --format '{{.Names}} {{.Label "com.docker.compose.project.working_dir"}}' 2>/dev/null)
+for tipo in volume network; do
+ case $tipo in volume) n=$(leggi_env DELMINIO_VOLUME); n=${n:-delminio-dati} ;; network) n=$(leggi_env DELMINIO_RETE); n=${n:-delminio} ;; esac
+ docker $tipo inspect "$n" >/dev/null 2>&1 || continue
+ suo=$(docker $tipo inspect "$n" --format '{{index .Labels "com.docker.compose.project"}}' 2>/dev/null || true)
+ if [ $tipo = volume ]; then cosa_t=$M_il_volume; else cosa_t=$M_la_rete; fi
+ if [ -z "$suo" ]; then
+ echo " ⚠️ $(_f "$M_senza_padrone" cosa "$cosa_t" nome "$n")"
+ elif [ -n "$mio" ] && [ "$suo" != "$mio" ]; then
+ altrui="$altrui\n · $(_f "$M_altrui_tipo" cosa "$cosa_t" nome "$n" progetto "$suo")"
+ fi
+done
+p=$(leggi_env DELMINIO_PORTA); p=${p:-8002}
+occupa=$(docker ps --format '{{.Names}} {{.Ports}}' | grep -E ":$p->" | awk '{print $1}' | grep -vx "$c" | head -1 || true)
+[ -n "$occupa" ] && altrui="$altrui\n · $(_f "$M_altrui_porta" porta "$p" container "$occupa")"
+if [ -n "$altrui" ]; then
+ printf '❌ %s%b\n' "$M_altra_installazione" "$altrui" >&2
+ echo " $M_altra_spiega" >&2
+ exit 1
+fi
+[ -n "${progetto_nuovo:-}" ] && scrivi_env COMPOSE_PROJECT_NAME "$mio"
+
+if [ -z "$(leggi_env DELMINIO_UID)" ]; then
+ volume=$(leggi_env DELMINIO_VOLUME); volume=${volume:-delminio-dati}
+ if docker volume inspect "$volume" >/dev/null 2>&1; then
+ echo " ⚠️ $(_f "$M_volume_root" volume "$volume")"
+ elif docker info --format '{{.SecurityOptions}}' 2>/dev/null | grep -q 'name=rootless'; then
+ scrivi_env DELMINIO_UID 0; scrivi_env DELMINIO_GID 0
+ echo " $(_f "$M_rootless" utente "$(id -un)")"
+ else
+ scrivi_env DELMINIO_UID "$(id -u)"; scrivi_env DELMINIO_GID "$(id -g)"
+ echo " $(_f "$M_gira_come" utente "$(id -un)" uid "$(id -u)")"
+ if [ "$(id -u)" = 0 ]; then
+ echo " ⚠️ $M_da_root"
+ fi
+ fi
+fi
+[ -n "${accettata:-}" ] && scrivi_env DELMINIO_LICENZA_ACCETTATA "$accettata"
+[ -n "${approvata:-}" ] && scrivi_env DELMINIO_CLAUSOLE_APPROVATE "\"$approvata\""
+chmod 600 .env
+echo " $(_f "$M_riepilogo" versione "$v" container "$(leggi_env DELMINIO_CONTAINER)" porta "$(leggi_env DELMINIO_PORTA)")"
+
+passo "$M_passo_cartelle"
+memoria=$(leggi_env DELMINIO_MEMORIA); memoria=${memoria:-./memoria}
+progetto=$(leggi_env DELMINIO_PROGETTO); progetto=${progetto:-./progetto}
+command -v git >/dev/null || muori "$(_f "$M_manca" cosa git)"
+for d in "$memoria" "$progetto"; do
+ if [ -d "$d" ]; then
+ [ -w "$d" ] || muori "$(_f "$M_non_scrivibile" cartella "$d" utente "$(id -un)")"
+ else
+ mkdir -p "$d" && echo " $(_f "$M_creata" cartella "$d")"
+ fi
+done
+if [ ! -d "$memoria/.git" ]; then
+ [ -z "$(ls -A "$memoria" 2>/dev/null)" ] || muori "$(_f "$M_memoria_non_vuota" cartella "$memoria")"
+ remoto="${DELMINIO_MEMORIA_REMOTO:-}"
+ if [ -z "$remoto" ] && ha_tty; then
+ echo " $M_repo_tuo"
+ read -rp " $M_indirizzo_clone " remoto </dev/tty || true
+ fi
+ [ -n "$remoto" ] || muori "$M_serve_repo"
+ GIT_TERMINAL_PROMPT=0 git clone -q "$remoto" "$memoria" 2>/dev/null \
+ || muori "$(_f "$M_clone_fallito" remoto "$remoto")"
+ echo " $(_f "$M_clone_di" cartella "$memoria" remoto "$remoto")"
+fi
+chmod 700 "$memoria" || muori "$(_f "$M_chmod_fallito" cartella "$memoria")"
+git -C "$memoria" remote get-url origin >/dev/null 2>&1 \
+ || muori "$(_f "$M_senza_remoto" cartella "$memoria")"
+grep -qx '.hook_token' "$memoria/.gitignore" 2>/dev/null || {
+ printf '# %s\n.hook_token\n' "$M_gitignore_token" >> "$memoria/.gitignore"
+}
+if ! git -C "$memoria" rev-parse -q --verify HEAD >/dev/null; then
+ git -C "$memoria" add .gitignore && git -C "$memoria" commit -q -m "$M_commit_cartella" \
+ || muori "$M_chi_sei"
+ GIT_TERMINAL_PROMPT=0 git -C "$memoria" push -q -u origin HEAD 2>/dev/null \
+ || muori "$(_f "$M_push_negato" remoto "$(git -C "$memoria" remote get-url origin)")"
+else
+ GIT_TERMINAL_PROMPT=0 git -C "$memoria" push --dry-run -q origin HEAD >/dev/null 2>&1 \
+ || muori "$(_f "$M_push_negato" remoto "$(git -C "$memoria" remote get-url origin)")"
+fi
+echo " $(_f "$M_push_ok" remoto "$(git -C "$memoria" remote get-url origin)")"
+scrivi_env DELMINIO_MEMORIA_SUL_DISCO "$(cd "$memoria" && pwd)"
+[ -z "$(ls -A "$progetto" 2>/dev/null)" ] && \
+ echo " $(_f "$M_progetto_vuoto" cartella "$progetto")"
+
+passo "$M_passo_avvio"
+docker compose up -d
+contenitore=$(leggi_env DELMINIO_CONTAINER); contenitore=${contenitore:-delminio}
+porta=$(leggi_env DELMINIO_PORTA); porta=${porta:-8002}
+risponde() { [ "$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$porta/api/auth/check")" != 000 ]; }
+for _ in $(seq 1 40); do
+ risponde && break
+ sleep 1
+done
+risponde || {
+ docker logs "$contenitore" 2>&1 | tail -15
+ muori "$(_f "$M_non_risponde" porta "$porta")"
+}
+
+for _ in $(seq 1 20); do [ -f "$memoria/MEMORY.md" ] && break; sleep 1; done
+if [ ! -f "$memoria/MEMORY.md" ]; then
+ docker logs "$contenitore" 2>&1 | grep -m3 -iE 'denied|error' >&2 || true
+ muori "$(_f "$M_non_scrive" cartella "$memoria")"
+fi
+sleep 2
+if [ -n "$(git -C "$memoria" status --porcelain)" ]; then
+ if [ "$(git -C "$memoria" log -1 --format=%s 2>/dev/null)" = "$M_commit_cartella" ]; then
+ cosa=$M_cosa_semina
+ else
+ cosa=$(_f "$M_cosa_regole" versione "$v")
+ fi
+ git -C "$memoria" add -A && git -C "$memoria" commit -q -m "$(_f "$M_commit_cosa" cosa "$cosa")" \
+ && GIT_TERMINAL_PROMPT=0 git -C "$memoria" push -q origin HEAD 2>/dev/null \
+ && echo " $(_f "$M_cosa_pushate" cosa "$cosa")" \
+ || echo " ⚠️ $(_f "$M_cosa_non_entrate" cosa "$cosa" cartella "$memoria")"
+fi
+
+ascolta=$(leggi_env DELMINIO_ASCOLTA)
+case "${ascolta:-0.0.0.0}" in
+ 0.0.0.0) ip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1)
+ [ -n "$ip" ] || ip=$(hostname -I 2>/dev/null | awk '{print $1}') ;;
+ 127.*) ip=localhost ;;
+ *) ip=$ascolta ;;
+esac
+codice=$(docker exec "$contenitore" cat /data/codice_installazione 2>/dev/null || true)
+echo
+echo "$(_f "$M_su" indirizzo "http://${ip:-localhost}:$porta")"
+nh=$(leggi_env DELMINIO_HTTPS_NOMI)
+if [ -n "$nh" ] && [ "$nh" != no ]; then
+ echo " $M_app_telefono"
+fi
+if [ -n "$codice" ]; then
+ echo
+ echo " $(_f "$M_codice" codice "$codice")"
+ echo " $(_f "$M_codice_perso" container "$contenitore")"
+fi
+if [ "${aggiornato:-}" = si ]; then
+ echo
+ echo "$M_si_ricollegano"
+ exit 0
+fi
+printf '\n%s\n' "$M_poi_dalla_app"
diff --git a/kit/en/aggancia.sh b/kit/en/aggancia.sh
new file mode 100644
index 0000000..0a140c4
--- /dev/null
+++ b/kit/en/aggancia.sh
@@ -0,0 +1,1131 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+set -euo pipefail
+
+URL="${DELMINIO_URL:-__DELMINIO_URL__}"
+URL="${URL%/}"
+
+muori() { printf '❌ %s\n' "$*" >&2; exit 1; }
+_no_del_motore() {
+ local c=${1##*$'\n'} e
+ case "$c" in
+ 200) return 0 ;;
+ ''|000) [ -n "${2:-}" ] || return 0
+ e=$(_f "$M_non_risponde" url "$URL"); muori "$(_f "$M_rifiutato" motivo "$e")" ;;
+ *) e=$(printf '%s' "${1%$'\n'*}" | campo error); muori "$(_f "$M_rifiutato" motivo "HTTP $c${e:+: $e}")" ;;
+ esac
+}
+
+: '⟦frasi: aggancia⟧'
+M_agente_opencode_domanda='
+ OpenCode works with a provider'"'"'s models. Do you have its key? [c] I'"'"'ll add it now — or [g] I'"'"'ll try OpenCode'"'"'s free models, no key: '
+M_agente_opencode_gratuito=' The free model answering right now is {modello}: fine for trying; to work for real you need a provider'"'"'s key.'
+M_agente_opencode_nessuno='no free OpenCode model answers right now: run this command again and choose a provider'"'"'s key'
+M_agente_opencode_chiave_no='the key was not added: run this command again, or choose the free models'
+M_agente_opencode_senza_terminale=' OpenCode is installed. To start it needs a terminal: run this command again from there, and choose the key or the free models.'
+M_agente_non_installato='{cli} did not install (the reason is in the lines above): run this command again, and if it stops again show those lines to the person who gave you Delminio'
+M_agente_quale='“--agente” wants claude, codex, qwen or opencode and the version (you wrote “{cli} {versione}”)'
+M_agente_frase='Read {url}/aggancia.en.md with curl -fsSL and follow that text word for word.'
+M_agente_entra_account='the first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes.'
+M_agente_entra_qwen='the first time it asks which model to connect to: a Qwen account, or a provider with its key (pick it from the list and paste the key). Then, if it asks, say you trust this folder.'
+M_agente_entra_opencode='with the key or the free model you chose.'
+M_agente_parte='
+ Done: {cli} is on this computer. It starts now: {entra}
+ We already gave it the sentence: it reads Delminio'"'"'s guide and takes you through every step — git, the project, the memory copy, the connection. What you already know how to do, tell it and it skips it.
+ If it closes halfway, run the same command again: it downloads nothing new, and reopens it with the sentence.
+'
+M_manca='“{c}” is missing: install it and run this command again (on Ubuntu and Debian: sudo apt install {c})'
+M_non_parte='“{c}” is there ({dove}) but does not run: {perche}. Fix it and run this command again.'
+M_mac_strumenti='On this Mac git and python3 are Apple'"'"'s, and they only run with Apple'"'"'s command line tools (about 1 GB, one click).
+ I asked the Mac to install them: in Apple'"'"'s window press “Install”, wait for it to finish and run this command again.
+ If the window did not open, run: xcode-select --install'
+M_argomento_ignoto='I don'"'"'t know “{arg}”: the arguments are --installa claude, codex or qwen, and --agente claude, codex, qwen or opencode with the version'
+M_installa_quale='“--installa” wants claude, codex or qwen (you wrote “{cli}”)'
+M_chi_sei_nome='git does not know who you are yet. The name that will sign your work (for example Mary Smith): '
+M_chi_sei_mail='Your email: '
+M_installo_cli=' Installing {cli} on this machine, at the version chosen in Delminio: a few minutes the first time.'
+M_installa_non_riuscita='the computer is connected, but {cli} was not installed (the reason is in the lines above): run this command again, and if it stops again show those lines to your administrator'
+M_parto_codex=' With Codex, after the folder: type /hooks and choose “Trust all”, just once. Without it Codex starts but does not hear Delminio.
+'
+M_parto_qwen=' With Qwen Code the model and provider are those of the agent in the Agents view, and it reads the provider key from your environment.
+'
+M_fuori_dal_clone='run it inside the clone of the repository you want to connect'
+M_progetto_nome='There is no git project here ({dove}). I'"'"'ll create a new one, in a new folder inside this one, with a git on this computer only.
+What should I call it? [progetto] '
+M_progetto_nome_no='“{nome}” is not a good folder name: use letters without accents, digits, “-” and “_”, and do not start with a dot'
+M_progetto_esiste='{cartella} already exists and I won'"'"'t touch it: run again choosing another name, or go inside it and run again if it already is your project'
+M_progetto_creato=' The project is in the folder {cartella}, with a git on this computer only. When you want it on GitHub or another git host too, the agent explains how.'
+M_progetto_primo_commit='The project begins'
+M_parto='
+ Done. {nome} is starting. The first time it asks you to sign in with your account (the browser opens) and whether to trust this folder: say yes.
+ When it is ready type {apertura}: from there the agent guides you. Next time open the terminal in {cartella} and type {dopo}.
+'
+M_rito_apertura=/opening
+M_rito_apertura_codex=opening
+M_comando_occupato='{file} already exists and isn'"'"'t Delminio'"'"'s: I leave it alone. Without the “delminio” command, the commands are written in full, from the project folder: bash .claude/delminio.sh …'
+M_comando_fuori='delminio: there is no project connected to Delminio here. Go into the project folder, or one of its subfolders, and try again.'
+M_chi_sei='git doesn'"'"'t know who you are: git config --global user.name "Name" && git config --global user.email you@example.com'
+M_senza_origin='this repository has no “origin” remote: handoffs and merges stay on this machine, and anyone working from another one doesn'"'"'t see them'
+M_non_pusha='you can'"'"'t push to {origine} (git: {errore}): handoffs and merges will stay on this machine until you fix the credentials'
+M_codice_apri=' Open this address and press Approve:'
+M_codice_oppure=' (or: Delminio → Access, enter the code {codice} and press Approve)'
+M_codice_vale=' Valid for 10 minutes. This machine introduces itself as “{macchina}”.
+ Waiting for approval…'
+M_approvato=' ✅ approved'
+M_scaduto=' ❌ the code has expired: run the command again'
+M_senza_terminale='no terminal to ask for the token: pass it in DELMINIO_TOKEN'
+M_domanda_token='The Delminio token (app → Access → Connect a repository): '
+M_nessun_token='no token'
+M_non_risponde='Delminio is not responding at {url}'
+M_token_rifiutato='Delminio at {url} rejects this token (HTTP {codice})'
+M_rifiutato='not connected: {motivo}'
+M_tiene_gia='⚠️ Other repositories are already connected to this Delminio space: {altri}.
+ A space holds a single project: several repositories are fine if they belong to the same
+ work, with the same team. A different project goes in another space.'
+M_stessa_storia=' Is {repo} part of the same project? [y/N] '
+M_altra_storia='not connected: if it'"'"'s another project, create another space (in the app, “Spaces”) and connect it there; if it'"'"'s the same one, run the command again and answer yes'
+M_app_codex_domanda=' The Codex app is on this computer: shall I add Delminio to it too? I only add the Delminio plugin and the permission for its two tools to ~/.codex/config.toml. [y/N] '
+M_clone_fermo='the memory clone in {cartella} isn'"'"'t updating: it'"'"'s retried at every opening'
+M_clone_https=' memories: ssh to {remoto} doesn'"'"'t get through from here, cloned over https ({https})'
+M_clonate=' memories: cloned from {remoto} into {cartella} — the CLI finds the index there'
+M_memorie_vuote='the memory repository ({remoto}) is still empty: Delminio puts the base there as soon as its push goes through (Settings → “Memories on git”: the deploy key, with write access). The clone in {cartella} updates itself; while it'"'"'s empty the agent starts without the index, and is told so'
+M_clone_negato='the memory repository ({remoto}) can'"'"'t be read from this computer with your git credentials: that'"'"'s fine, the agent gets the memory index from Delminio when it starts. If you also want the local copy, ask the person who owns the repository for read access and run the connection again'
+M_codex_indice=' Codex and Qwen Code receive the memory index in Delminio'"'"'s opening: they need neither a local git clone nor an initial call to list.'
+M_senza_embedder='Delminio has no embedder: until the admin configures it (Settings → Embedder) memories are searched by words, without semantic search'
+M_embedder_muto='the embedder configured in Delminio is not responding ({risposta}): until it'"'"'s back, search is by words'
+M_note_sue='📦 Your CLI keeps its notes in {cartella} (says {fonte}).
+ From now on Delminio would keep them and that folder wouldn'"'"'t be read any more. First I make a backup
+ outside the repo, the agent proposes the notes to you as memories, and with
+ “delminio disconnect” everything goes back to how it was.'
+M_va_bene=' OK? [y/N] '
+M_memoria_sua_resta='not connected: your memory stays where it is. If it'"'"'s OK, run it again and answer yes (or DELMINIO_MEMORIA_SUA=si)'
+M_prima_non_salva='I can'"'"'t back up what was there before: I haven'"'"'t touched anything'
+M_prima_copia_diversa='the copy of {file} doesn'"'"'t match the original: I'"'"'m stopping before touching anything'
+M_mcp_fallito='claude mcp add failed'
+M_mcp_senza_claude='Claude Code is not in this shell'"'"'s PATH: the Delminio tool is not registered, and a Claude started here would have no memory. With Claude Code installed (and `claude` in the PATH), run this connection again: it only redoes what is missing.'
+M_senza_client='Delminio doesn'"'"'t provide the client ({indirizzo})'
+M_comando_tuo='{file} is a /{c} of yours, and it wins over Delminio'"'"'s in every project: here /{c} won'"'"'t be Delminio'"'"'s. If you want that one, rename yours (for example to /{c}-mine)'
+M_mcp_col_nome_nostro='{file} has an MCP server of its own called “memoria”, like Delminio'"'"'s: in {cli} it takes its place, and the agent is left without memory. Give it another name.'
+M_json_non_valido='{file} isn'"'"'t valid JSON: fix it and run again'
+M_codex_sotto_git='.codex/hooks.json is tracked by git: Codex here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again'
+M_qwen_sotto_git='.qwen/settings.json is tracked by git: Qwen Code here starts without Delminio'"'"'s hooks. Remove the file from git (it stays yours), or add the hooks from .claude/settings.local.json by hand, and run the connection again'
+M_senza_client_cantiere='Delminio doesn'"'"'t provide the Backlog client ({indirizzo})'
+M_senza_client_eseguibili='Delminio doesn'"'"'t provide the agents client ({indirizzo})'
+M_senza_client_cassaforte='Delminio doesn'"'"'t provide the vault client ({indirizzo})'
+M_apertura_muta='the opening hook gets no answer from Delminio: look at delminio apertura'
+M_nello_spazio=' in the space “{spazio}”'
+M_collegato='✅ {repo} is connected to Delminio ({url}){dove} as {chi}.'
+M_sempre_nello_spazio=' An agent opened in this folder always works{dove}: for another space, use another clone connected from there.'
+M_prima_al_sicuro='📦 What was there before is safe in {cartella}, outside the repo (the LEGGIMI.md in there says what).
+ The agent goes through it with you at the first session. To go back to how it was: delminio disconnect'
+M_apri_eseguibile=' Open the agent in here with your Delminio command, and type /opening.'
+M_scrivi_eseguibile=' The agent starts best from Delminio'"'"'s command, with the rules at the top:
+ delminio agents writes it on this machine (the name in the Agents view); then /opening.'
+M_path_nuovo=' ℹ️ The “delminio” command is in {cartella}, which isn'"'"'t in this terminal'"'"'s PATH: until it is, write it in full,
+ {comando}. On Linux a new terminal usually finds it by name.'
+M_con_codex=' With Codex: if it'"'"'s already open, close it and start it again from Delminio'"'"'s command (the one “eseguibili” writes):
+ a Codex opened before the connection doesn'"'"'t see Delminio. At the first start Codex asks whether to trust the
+ folder and the hooks (/hooks → Trust all): say yes, then type opening, without the slash.'
+M_senza_cli=' This machine doesn'"'"'t have an agent CLI yet (claude, codex, qwen or opencode). To install one, run the
+ connection again with the one you want: the right command is in Delminio → Agents →
+ “Connect another computer” → “I don'"'"'t have an agent”.'
+M_con_qwen=' With Qwen Code: start it from Delminio'"'"'s command (the one “delminio agents” writes), which gives it the model
+ chosen in the Agents view and its key from the environment; a Qwen opened before the connection doesn'"'"'t see
+ Delminio. Then type /opening.'
+M_con_opencode=' With OpenCode: open it in this folder (restart one that is already open): memory, /opening and /closing
+ come with Delminio'"'"'s plugin in .opencode/plugins. Then type /opening.'
+M_qwen_ripiego='Delminio'"'"'s extension did not link in Qwen Code ({agente}): the hooks and /opening and /closing stay in the project, as before the package.'
+M_solo_claude=' With plain claude, or from the desktop app, it starts with the standard prompt: /opening brings it the rules.'
+M_gancio_tuo='⚠️ {file} is already there and isn'"'"'t Delminio'"'"'s: add this line to it yourself {riga}'
+M_gancio_globale='⚠️ git hooks here come from {dir}, which isn'"'"'t this repository'"'"'s (global core.hooksPath): it applies to all your repositories, and Delminio doesn'"'"'t write there. Add to {file} yourself {riga}'
+M_prima_questo_progetto='this project'
+M_prima_claude_md='the project'"'"'s instructions for Claude'
+M_prima_claude_local='your personal instructions for this project'
+M_prima_settings='the CLI'"'"'s local settings for this project, as they were'
+M_prima_hook_codex='Codex'"'"'s hooks for this project, as they were'
+M_prima_qwen='Qwen Code'"'"'s settings for this project, as they were'
+M_prima_apertura='your /opening command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one'
+M_prima_chiusura='your /closing command: from now on it'"'"'s Delminio'"'"'s, and the agent proposes its steps to you inside the new one'
+M_prima_mcp='the “{nome}” MCP server you had before (it contains its token)'
+M_prima_note='- `memoria/` — the {n} notes the CLI had written for itself, from `{cartella}`'
+M_prima_configurazioni='- your CLI configurations (hooks, commands, agents, MCP servers, plugins): **not touched**, they stay where they are; the settings files are also in this backup, `fatti.json` has the list, and the agent tells you what works alongside Delminio and what doesn'"'"'t'
+M_prima_altri='- the instructions you wrote for other tools and the memories other tools keep ({elenco}): **copied here and not touched**, the originals stay where they are; `fatti.json` says what they are, and the agent proposes them to you along with the notes'
+M_prima_chiesti='- what you asked to back up before the connection ({elenco})'
+M_prima_tutti='- {n} files in all, each with its fingerprint in `fatti.json`: that'"'"'s how the copy is checked against the original'
+M_prima_non_copiato='- `{file}`: not copied ({perche})'
+M_prima_perche_credenziali='it holds credentials: it stays only where it is, and the connection doesn'"'"'t touch it'
+M_prima_perche_grande='too big for the backup: it stays where it is, and the connection doesn'"'"'t touch it'
+M_prima_perche_fuori='it'"'"'s outside the repo and your home folder'
+M_prima_perche_assente='it isn'"'"'t there'
+M_prima_niente_da_ripassare='nothing of yours to go through: the backup is there anyway'
+M_prima_leggimi_titolo='What was there before Delminio'
+M_prima_leggimi_testa='Before touching anything, the connection to Delminio copied here what this project had on this machine. Nothing was deleted: the originals are still in place.'
+M_prima_leggimi_note='From now on the CLI'"'"'s notes aren'"'"'t read any more: the CLI reads Delminio'"'"'s index. The agent proposes them to you as memories, one by one, and only what you approve is created; you can keep the CLAUDE.md files as they are, or move them to Delminio.'
+M_prima_leggimi_tornare='To go back to how it was: `delminio disconnect`. It restores the previous settings, commands and MCP server, and the CLI goes back to reading its notes; what was created in Delminio stays in Delminio.'
+M_qwen_comando_apertura='Delminio: open the session with your role'"'"'s briefing — what you write after the command goes as your message'
+M_qwen_comando_chiusura='Delminio: end the session — what you write after the command goes as your message'
+M_senza_client_plugin='Delminio doesn'"'"'t provide the package client for the CLIs ({indirizzo})'
+M_senza_client_squadra='Delminio does not serve the team client ({indirizzo})'
+M_kit_non_firmato='{file} from {url} doesn'"'"'t carry Delminio'"'"'s release signature, or isn'"'"'t the signed file: not installing it. If this Delminio is a development build and you know it, run again with DELMINIO_KIT_SENZA_FIRMA=1.'
+: '⟦fine frasi⟧'
+export ${!M_@} # anche ai python (F, fra gli aiutanti qui sotto)
+
+
+PORTABILI=$(cat <<'PORTABILI'
+ha_terminale() { { : </dev/tty; } 2>/dev/null; }
+_f() { # _f "$M_<chiave>" [segnaposto valore]... → la frase coi {segnaposto} riempiti
+ local t=$1 k v fuori
+ shift
+ while [ $# -ge 2 ]; do
+ k="{$1}"; v=$2; fuori=""
+ while [ "${t#*"$k"}" != "$t" ]; do fuori=$fuori${t%%"$k"*}$v; t=${t#*"$k"}; done
+ t=$fuori$t; shift 2
+ done
+ printf '%s\n' "$t"
+}
+export DELMINIO_F_PY='def F(chiave, **s):
+ t = __import__("os").environ.get("M_" + chiave, chiave)
+ for k, v in s.items():
+ t = t.replace("{" + k + "}", str(v))
+ return t'
+_sha16() { # stdin → i primi 16 dello sha256 (il nome del file del token: uguale ovunque)
+ if command -v sha256sum >/dev/null 2>&1; then sha256sum
+ elif command -v shasum >/dev/null 2>&1; then shasum -a 256
+ else python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())'
+ fi | cut -c1-16
+}
+_tempo() { # _tempo <secondi> <comando…> — come timeout: 124 se scade
+ if command -v timeout >/dev/null 2>&1; then timeout "$@"
+ elif command -v gtimeout >/dev/null 2>&1; then gtimeout "$@"
+ else python3 -c 'import subprocess, sys
+try: sys.exit(subprocess.run(sys.argv[2:], timeout=float(sys.argv[1])).returncode)
+except subprocess.TimeoutExpired: sys.exit(124)
+except OSError: sys.exit(127)' "$@"
+ fi
+}
+_staccato() { # _staccato <comando…> — in una sessione sua: la CLI che esce non se lo porta via
+ if command -v setsid >/dev/null 2>&1; then setsid nohup "$@"
+ else nohup python3 -c 'import os, sys
+try: os.setsid()
+except OSError: pass
+os.execvp(sys.argv[1], sys.argv[1:])' "$@"
+ fi
+}
+_mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; }
+_lucchetto() { # _lucchetto <secondi> — esclusivo sull'fd 9, come flock -w
+ if command -v flock >/dev/null 2>&1; then flock -w "$1" 9
+ else python3 -c 'import fcntl, sys, time
+fine = time.time() + float(sys.argv[1])
+while True:
+ try:
+ fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB); break
+ except BlockingIOError:
+ if time.time() > fine: sys.exit(1)
+ time.sleep(0.5)' "$1"
+ fi
+}
+_assoluto() { python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"; }
+_args() { # _args <pid> → gli argomenti del processo, uno per riga, coi loro confini
+ if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; return; fi
+ python3 -c 'import ctypes, ctypes.util, struct, sys
+pid = int(sys.argv[1]); libc = ctypes.CDLL(ctypes.util.find_library("c"))
+def leggi(mib):
+ m = (ctypes.c_int * len(mib))(*mib); n = ctypes.c_size_t(0)
+ if libc.sysctl(m, len(mib), None, ctypes.byref(n), None, 0): sys.exit(1)
+ b = ctypes.create_string_buffer(n.value)
+ if libc.sysctl(m, len(mib), b, ctypes.byref(n), None, 0): sys.exit(1)
+ return b.raw[:n.value]
+if sys.platform == "darwin":
+ r = leggi([1, 49, pid]) # KERN_PROCARGS2: argc, il percorso, NUL, gli argomenti
+ argc = struct.unpack("i", r[:4])[0]; r = r[4:]
+ args = r[r.index(b"\0"):].lstrip(b"\0").split(b"\0")[:argc]
+else:
+ args = leggi([1, 14, 7, pid]).rstrip(b"\0").split(b"\0") # KERN_PROC_ARGS
+print("\n".join(a.decode(errors="replace") for a in args))' "$1" 2>/dev/null \
+ || ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n'
+}
+_chiave() { printf 'header = "Authorization: Bearer %s"\n' "$1"; }
+KIT_FIRMA='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0'
+_firmato() { # _firmato <indirizzo> <nome servito> <file> → 0 se il file sta nella firma del kit
+ [ -n "${DELMINIO_KIT_SENZA_FIRMA:-}" ] && return 0
+ local d r=1
+ d=$(mktemp -d) || return 1
+ if curl -fsS -m 30 "$1/static/kit/FIRMA" -o "$d/f" 2>/dev/null \
+ && curl -fsS -m 30 "$1/static/kit/FIRMA.sig" -o "$d/f.sig" 2>/dev/null \
+ && printf 'rilasci@delminio.com %s\n' "$KIT_FIRMA" > "$d/chi" \
+ && ssh-keygen -Y verify -f "$d/chi" -I rilasci@delminio.com -n delminio-kit -s "$d/f.sig" < "$d/f" >/dev/null 2>&1 \
+ && python3 -c 'import hashlib, sys
+i = hashlib.sha256(open(sys.argv[3], "rb").read()).hexdigest()
+righe = open(sys.argv[1], encoding="utf-8").read().splitlines()
+sys.exit(0 if righe[:1] and righe[0].startswith("delminio-kit ") and i + " " + sys.argv[2] in righe[1:] else 1)' \
+ "$d/f" "$2" "$3"; then
+ r=0
+ fi
+ rm -rf "$d"
+ return $r
+}
+campo() { # campo <chiave> < json → il valore, o "" (anche su un corpo che non è JSON)
+ python3 -c 'import json,sys
+try: print(json.load(sys.stdin).get(sys.argv[1]) or "")
+except Exception: print("")' "$1"
+}
+json_stringa() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"; } # una stringa JSON
+export DELMINIO_GANCI_PY='def nostro(h, cosa=None):
+ c = h.get("command", "")
+ return ".claude/mneme.sh" in c or ("delminio.sh" in c and (cosa is None or c.endswith(" " + cosa)))
+def togli_ganci(s, cosa=None):
+ for evento, lista in list((s.get("hooks") or {}).items()):
+ for b in lista:
+ b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
+ lista[:] = [b for b in lista if b.get("hooks")]
+ if not lista:
+ del s["hooks"][evento]
+ if not s.get("hooks"):
+ s.pop("hooks", None)
+def metti_ganci(s, comando, gesti, matcher_sempre=False):
+ for evento, cosa, extra, matcher in gesti:
+ lista = s.setdefault("hooks", {}).setdefault(evento, [])
+ for b in lista:
+ b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
+ lista[:] = [b for b in lista if b.get("hooks")]
+ lista.append({**({"matcher": matcher} if matcher or matcher_sempre else {}),
+ "hooks": [{"type": "command", "command": comando + " " + cosa, **extra}]})'
+KIT_FILE=".claude/delminio.sh .claude/lanciatori.sh .claude/ganci-git.sh .claude/worktree.sh .claude/consumi.py .claude/cantiere.py .claude/backlog.py .claude/eseguibili.py .claude/cassaforte.py .claude/firme.py .claude/plugin.py .claude/squadra.py .claude/settings.local.json .claude/commands/apertura.md .claude/commands/chiusura.md .claude/commands/start.md .claude/commands/handoff.md .claude/commands/opening.md .claude/commands/closing.md .claude/rules/delminio.md .codex/hooks.json .qwen/settings.json .qwen/commands/apertura.md .qwen/commands/chiusura.md .qwen/commands/start.md .qwen/commands/handoff.md .qwen/commands/opening.md .qwen/commands/closing.md .claude/opencode.js .opencode/plugins/delminio.js"
+KIT_DI_PRIMA=".claude/guardia.py .claude/commands/risveglio.md"
+PORTABILI
+)
+eval "$PORTABILI"
+
+installa=""
+agente_cli=""; agente_versione=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --installa) installa=${2:-}; [ $# -ge 2 ] && shift; shift ;;
+ --agente) agente_cli=${2:-}; agente_versione=${3:-}; shift; [ $# -gt 0 ] && shift; [ $# -gt 0 ] && shift ;;
+ *) muori "$(_f "$M_argomento_ignoto" arg "$1")" ;;
+ esac
+done
+case "$installa" in ''|claude|codex|qwen) ;; *) muori "$(_f "$M_installa_quale" cli "$installa")" ;; esac
+if [ -n "$agente_cli" ]; then
+ case "$agente_cli" in claude|codex|qwen|opencode) ;; *) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
+ case "$agente_versione" in ''|*[!A-Za-z0-9.]*) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
+fi
+
+segnaposto_apple() {
+ local d
+ [ "$(uname -s)" = Darwin ] || return 1
+ case "$1" in git|python3) ;; *) return 1 ;; esac # curl di /usr/bin è vero
+ case "$(command -v "$1")" in /usr/bin/*) ;; *) return 1 ;; esac
+ d=$(xcode-select -p 2>/dev/null) && [ -d "$d" ] && return 1
+ return 0
+}
+for c in curl git python3; do
+ command -v "$c" >/dev/null || muori "$(_f "$M_manca" c "$c")"
+ if segnaposto_apple "$c"; then
+ xcode-select --install >/dev/null 2>&1 || true
+ muori "$M_mac_strumenti"
+ fi
+ case $c in
+ curl) perche=$(curl --version 2>&1 >/dev/null) ;;
+ git) perche=$(git --version 2>&1 >/dev/null) ;;
+ python3) perche=$(python3 -c 'import json, ssl, urllib.request' 2>&1) ;;
+ esac || {
+ dove_c=$(command -v "$c"); perche=$(printf '%s' "${perche:-?}" | tail -1)
+ muori "$(_f "$M_non_parte" c "$c" dove "$dove_c" perche "$perche")"
+ }
+done
+if [ -n "$agente_cli" ]; then
+ cartella_agente=$(mktemp -d) || muori "$(_f "$M_installa_non_riuscita" cli "$agente_cli")"
+ curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
+ || muori "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
+ _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
+ || muori "$(_f "$M_kit_non_firmato" file eseguibili-client url "$URL")"
+ case $agente_cli in claude) nome_cli="Claude Code" ;; codex) nome_cli=Codex ;; qwen) nome_cli="Qwen Code" ;; *) nome_cli=OpenCode ;; esac
+ _f "$M_installo_cli" cli "$nome_cli"
+ uscita=$(python3 "$cartella_agente/eseguibili.py" installa-agente "$agente_cli" "$agente_versione") \
+ && lancia=$(printf '%s\n' "$uscita" | tail -1) && [ -x "$lancia" ] \
+ || { rm -rf "$cartella_agente"; muori "$(_f "$M_agente_non_installato" cli "$nome_cli")"; }
+ rm -rf "$cartella_agente"
+ nodo=$(printf '%s\n' "$uscita" | sed -n 's/^DELMINIO_NODE=//p' | tail -1)
+ [ -n "$nodo" ] && PATH="$nodo:$PATH" && export PATH
+ case $0 in /dev/fd/*|/proc/self/fd/*) cat "$0" >/dev/null 2>&1 || true ;; esac
+ frase=$(_f "$M_agente_frase" url "$URL")
+ primo=("$frase"); entra=$M_agente_entra_account
+ [ "$agente_cli" = qwen ] && primo=(-i "$frase") && entra=$M_agente_entra_qwen
+ export QWEN_CODE_SKIP_UPDATE_CHECK_ONCE=true OPENCODE_DISABLE_AUTOUPDATE=1
+ if [ "$agente_cli" = opencode ]; then
+ primo=(--standalone)
+ entra=$M_agente_entra_opencode
+ ha_terminale || { echo "$M_agente_opencode_senza_terminale"; exit 0; }
+ risposta=""; read -rp "$M_agente_opencode_domanda" risposta </dev/tty || true
+ case "$risposta" in
+ g|G)
+ cartella_agente=$(mktemp -d)
+ curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
+ && _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
+ && modello=$(python3 "$cartella_agente/eseguibili.py" modello-gratuito "$lancia") || modello=""
+ rm -rf "$cartella_agente"
+ [ -n "$modello" ] || muori "$M_agente_opencode_nessuno"
+ _f "$M_agente_opencode_gratuito" modello "$modello"
+ OPENCODE_CONFIG_CONTENT=$(DELMINIO_M="$modello" python3 -c 'import json, os; print(json.dumps({"model": os.environ["DELMINIO_M"]}))')
+ export OPENCODE_CONFIG_CONTENT
+ primo+=(--prompt "$frase") ;;
+ *)
+ "$lancia" auth login </dev/tty || muori "$M_agente_opencode_chiave_no"
+ primo+=(--prompt "$frase") ;;
+ esac
+ fi
+ _f "$M_agente_parte" cli "$nome_cli" entra "$entra"
+ ha_terminale || exit 0
+ if [ -t 0 ]; then exec "$lancia" "${primo[@]}"; fi
+ exec "$lancia" "${primo[@]}" </dev/tty
+fi
+cli_presente() {
+ local d
+ case $1 in
+ claude) d=${DELMINIO_VERSIONI:-$HOME/.local/share/claude/versions} ;;
+ codex) d=${DELMINIO_VERSIONI_CODEX:-$HOME/.local/share/codex/versions} ;;
+ qwen) d=${DELMINIO_VERSIONI_QWEN:-$HOME/.local/share/qwen-code/versions} ;;
+ opencode) d=${DELMINIO_OPENCODE_BIN:-$HOME/.opencode/bin} ;;
+ esac
+ command -v "$1" >/dev/null || [ -n "$(ls -A "$d" 2>/dev/null)" ] \
+ || { [ "$1" = opencode ] && [ -n "$(ls -A "${DELMINIO_VERSIONI_OPENCODE:-$HOME/.local/share/delminio/opencode/versions}" 2>/dev/null)" ]; }
+}
+senza_cli=""
+cli_presente claude || cli_presente codex || cli_presente qwen || cli_presente opencode || senza_cli=1
+chiedi_una_riga() { # chiedi_una_riga <domanda> → la risposta, richiesta finché è vuota (tre volte)
+ local r="" giri=0
+ while [ -z "$r" ] && [ $giri -lt 3 ]; do read -rp "$1" r </dev/tty; giri=$((giri + 1)); done
+ printf '%s' "$r"
+}
+if [ -n "$installa" ] && ha_terminale && { [ -z "$(git config user.name)" ] || [ -z "$(git config user.email)" ]; }; then
+ chi_nome=$(git config user.name || true); [ -n "$chi_nome" ] || chi_nome=$(chiedi_una_riga "$M_chi_sei_nome")
+ chi_mail=$(git config user.email || true); [ -n "$chi_mail" ] || chi_mail=$(chiedi_una_riga "$M_chi_sei_mail")
+ [ -n "$chi_nome" ] && [ -n "$chi_mail" ] || muori "$M_chi_sei"
+ git config --global user.name "$chi_nome"
+ git config --global user.email "$chi_mail"
+fi
+progetto_nuovo=""
+if ! radice=$(git rev-parse --show-toplevel 2>/dev/null); then
+ [ -n "$installa" ] && ha_terminale || muori "$M_fuori_dal_clone"
+ domanda=$(_f "$M_progetto_nome" dove "$PWD")
+ read -rp "$domanda" nome_progetto </dev/tty
+ nome_progetto=${nome_progetto:-progetto}
+ case "$nome_progetto" in
+ .*|*[!A-Za-z0-9._-]*) muori "$(_f "$M_progetto_nome_no" nome "$nome_progetto")" ;;
+ esac
+ [ -e "$nome_progetto" ] && muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
+ mkdir "$nome_progetto" && git -C "$nome_progetto" init -q || muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
+ radice=$(cd "$nome_progetto" && pwd)
+ progetto_nuovo=1
+fi
+cd "$radice"
+
+avvisa() { printf '⚠️ %s\n' "$*" >&2; }
+senza_credenziali() { sed -E 's#([A-Za-z][A-Za-z0-9+.-]*://)[^/[:space:]]*@#\1#g'; }
+[ -n "$(git config user.name)" ] && [ -n "$(git config user.email)" ] || muori "$M_chi_sei"
+if [ -n "$progetto_nuovo" ]; then
+ git commit -q --allow-empty -m "$M_progetto_primo_commit"
+ _f "$M_progetto_creato" cartella "$radice"
+fi
+if ! git remote get-url origin >/dev/null 2>&1; then
+ avvisa "$M_senza_origin"
+elif ! perche=$(GIT_TERMINAL_PROMPT=0 git push --dry-run -q origin "HEAD:refs/heads/delminio-prova-del-push-$$" 2>&1); then
+ origine=$(git remote get-url origin | senza_credenziali)
+ errore_git=$(printf '%s' "$perche" | tail -1 | senza_credenziali)
+ avvisa "$(_f "$M_non_pusha" origine "$origine" errore "$errore_git")"
+fi
+
+aggancio_col_codice() {
+ local r codice disp c giri=0 macchina
+ macchina=$(hostname 2>/dev/null || echo "?")
+ r=$(python3 -c 'import json,sys; print(json.dumps({"macchina": sys.argv[1]}))' "$macchina" \
+ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
+ "$URL/api/aggancio/inizia" 2>/dev/null) || return 1
+ [ "${r##*$'\n'}" = 200 ] || return 1
+ r=${r%$'\n'*}
+ codice=$(printf '%s' "$r" | campo codice)
+ disp=$(printf '%s' "$r" | campo dispositivo)
+ [ -n "$codice" ] && [ -n "$disp" ] || return 1
+ {
+ echo
+ echo "$M_codice_apri"
+ echo
+ echo " $URL/?aggancio=$codice"
+ echo
+ _f "$M_codice_oppure" codice "$codice"
+ echo
+ _f "$M_codice_vale" macchina "$macchina"
+ } >&2
+ while [ $giri -lt 220 ]; do
+ sleep 3; giri=$((giri + 1))
+ r=$(python3 -c 'import json,sys; print(json.dumps({"dispositivo": sys.argv[1]}))' "$disp" \
+ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
+ "$URL/api/aggancio/ritira" 2>/dev/null) || continue
+ c=${r##*$'\n'}
+ case "$c" in
+ 200) printf '%s' "${r%$'\n'*}" | campo token
+ echo "$M_approvato" >&2; return 0 ;;
+ 410) echo "$M_scaduto" >&2; return 1 ;;
+ esac
+ done
+ return 1
+}
+
+token="${DELMINIO_TOKEN:-}"
+[ -n "$token" ] || token=$(aggancio_col_codice) || token=""
+if [ -z "$token" ]; then
+ ha_terminale || muori "$M_senza_terminale"
+ read -rsp "$M_domanda_token" token </dev/tty
+ echo
+fi
+[ -n "$token" ] || muori "$M_nessun_token"
+
+risposta=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/auth/check" 2>&1) \
+ || muori "$(_f "$M_non_risponde" url "$URL")"
+codice=${risposta##*$'\n'}
+[ "$codice" = 200 ] || muori "$(_f "$M_token_rifiutato" url "$URL" codice "$codice")"
+if frasi=$(curl -fsS -m 10 -K <(_chiave "$token") "$URL/aggancia.sh" 2>/dev/null | python3 -c '
+import re, shlex, sys
+m = re.search(r"^: .⟦frasi: aggancia⟧.\n(.*?)^: .⟦fine frasi⟧.\n", sys.stdin.read(), re.S | re.M)
+voci = shlex.split(m.group(1), comments=True) if m else []
+if voci and all(re.fullmatch(r"M_\w+=.*", v, re.S) for v in voci):
+ print("".join("%s=%s\n" % (k, shlex.quote(v)) for k, _, v in (x.partition("=") for x in voci)))
+') && [ -n "$frasi" ]; then
+ eval "$frasi"; export ${!M_@}
+fi
+chi=$(python3 -c 'import json,sys; u=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("utente") or {}; print((u.get("mostrato") or u.get("nome") or "?") + " (" + (u.get("ruolo_detto") or u.get("ruolo") or "?") + ")")' <<<"$risposta")
+etichetta=$(python3 -c 'import json,sys; print(json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("etichetta") or "")' <<<"$risposta" 2>/dev/null)
+remoto_repo=$(git remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#' || true)
+conferma=false
+{ [ -f .claude/delminio.sh ] || [ "${DELMINIO_STESSA_STORIA:-}" = si ]; } && conferma=true
+remoto_prima=$(sed -n 's/^REMOTO=//p' .claude/delminio.sh 2>/dev/null | head -1 | sed 's/\\\(.\)/\1/g' || true)
+corpo_repo=$(python3 -c 'import json,sys; print(json.dumps({"remoto": sys.argv[1], "nome": sys.argv[2], "conferma": sys.argv[3] == "true", "prima": sys.argv[4]}))' "$remoto_repo" "$(basename "$radice")" "$conferma" "$remoto_prima")
+repo=$(curl -sS -m 10 -w '\n%{http_code}' -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" 2>/dev/null) || repo=""
+_no_del_motore "$repo"; repo=${repo%$'\n'*}
+no=$(printf '%s' "$repo" | campo rifiuta)
+[ -z "$no" ] || muori "$(_f "$M_rifiutato" motivo "$no")"
+if [ -n "$repo" ] \
+ && altri=$(printf '%s' "$repo" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(", ".join(d.get("altri") or []) if d.get("chiede") else "")' 2>/dev/null) \
+ && [ -n "$altri" ]; then
+ _f "$M_tiene_gia" altri "$altri"
+ risposta_storia="${DELMINIO_STESSA_STORIA:-}"
+ if [ -z "$risposta_storia" ] && ha_terminale; then
+ nome_repo=$(basename "$radice")
+ read -rp "$(_f "$M_stessa_storia" repo "$nome_repo")" risposta_storia </dev/tty
+ fi
+ case "$risposta_storia" in
+ s|S|si|sì|y|yes) corpo_repo=$(python3 -c 'import json,sys; d=json.loads(sys.argv[1]); d["conferma"]=True; print(json.dumps(d))' "$corpo_repo")
+ curl -sS -m 10 -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" >/dev/null 2>&1 || true ;;
+ *) muori "$M_altra_storia" ;;
+ esac
+fi
+
+imp=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/impostazioni" 2>/dev/null || true)
+_no_del_motore "$imp" si; imp=${imp%$'\n'*}
+emb=$(printf '%s' "$imp" | python3 -c 'import json,sys
+try: e = json.load(sys.stdin).get("embedder") or {}
+except Exception: e = {}
+print(json.dumps({"url": e.get("url") or "", "modello": e.get("modello") or ""}) if not e.get("di_delminio") else "di_delminio")')
+memoria=$(printf '%s' "$imp" | campo memoria_sul_disco)
+kit=$(printf '%s' "$imp" | campo versione)
+[ -n "$memoria" ] && [ ! -d "$memoria" ] && memoria=""
+clone=""
+if [ -z "$memoria" ]; then
+ remoto_memorie=$(printf '%s' "$imp" | campo memorie_remoto)
+ dest="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$radice" | _sha16)/memoria"
+ ssh_muto=${GIT_SSH_COMMAND:-ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new}
+ if [ -d "$dest/.git" ]; then
+ GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 30 git -C "$dest" pull -q --ff-only >/dev/null 2>&1 \
+ || avvisa "$(_f "$M_clone_fermo" cartella "$dest")"
+ memoria=$dest; clone=si
+ elif [ -n "$remoto_memorie" ] && command -v claude >/dev/null; then
+ mkdir -p "$(dirname "$dest")"
+ in_https=$(python3 -c 'import sys
+r = sys.argv[1].strip()
+if r.startswith("ssh://"):
+ host, _, p = r[6:].split("@", 1)[-1].partition("/")
+ host = host.split(":", 1)[0]
+elif "://" not in r and "@" in r and ":" in r.split("@", 1)[1]:
+ host, _, p = r.split("@", 1)[1].partition(":")
+else:
+ sys.exit(1)
+print("https://" + host + "/" + p.lstrip("/"))' "$remoto_memorie" 2>/dev/null || true)
+ if GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$remoto_memorie" "$dest" 2>/dev/null \
+ || { [ -n "$in_https" ] && rm -rf "$dest" && GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$in_https" "$dest" 2>/dev/null \
+ && _f "$M_clone_https" remoto "$remoto_memorie" https "$in_https"; }; then
+ memoria=$dest; clone=si
+ if [ -f "$dest/MEMORY.md" ]; then
+ _f "$M_clonate" remoto "$remoto_memorie" cartella "$dest"
+ else
+ avvisa "$(_f "$M_memorie_vuote" remoto "$remoto_memorie" cartella "$dest")"
+ fi
+ else
+ _f "$M_clone_negato" remoto "$remoto_memorie"
+ fi
+ elif ! command -v claude >/dev/null && { cli_presente codex || cli_presente qwen; }; then
+ echo "$M_codex_indice"
+ fi
+fi
+if [ "$emb" != di_delminio ]; then
+ case "$emb" in *'"url": ""'*)
+ avvisa "$M_senza_embedder" ;;
+ esac
+ prova=$(curl -sS -m 30 -w '\n%{http_code}' -X POST -K <(_chiave "$token") \
+ -H "Content-Type: application/json" --data-binary "$emb" "$URL/api/impostazioni/embedder/prova" 2>/dev/null || true)
+ if [ "${prova##*$'\n'}" = 200 ] && ! printf '%s' "${prova%$'\n'*}" | grep -q '"ok": *true'; then
+ risposta_emb="${prova%$'\n'*}"
+ avvisa "$(_f "$M_embedder_muto" risposta "$risposta_emb")"
+ fi
+fi
+
+scarica_client() { # nome, destinazione, errore già composto nella lingua dello spazio
+ local nuovo indirizzo="$URL/static/kit/$1"
+ case $1 in *.*) ;; *) indirizzo+=-client ;; esac
+ nuovo=$(mktemp "$2.XXXXXX") || muori "$3"
+ if ! curl -fsS -K <(_chiave "$token") "$indirizzo" -o "$nuovo"; then
+ rm -f "$nuovo"
+ muori "$3"
+ fi
+ if ! _firmato "$URL" "${indirizzo##*/}" "$nuovo"; then
+ rm -f "$nuovo"
+ muori "$(_f "$M_kit_non_firmato" file "${indirizzo##*/}" url "$URL")"
+ fi
+ mv -f "$nuovo" "$2"
+}
+cartella_copia=$(mktemp -d) || muori "$M_prima_non_salva"
+scarica_client copia "$cartella_copia/copia.py" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/copia-client")"
+prima_volta=si; [ -f .claude/delminio.sh ] && prima_volta=""
+gitdir=$(_assoluto "$(git rev-parse --git-common-dir)")
+comune=$(dirname "$gitdir")
+if [ -n "$prima_volta" ]; then
+ sua=$(python3 "$cartella_copia/copia.py" controlla "$radice" "$memoria" "$comune" "$URL" "$gitdir")
+ if [ -n "$sua" ]; then
+ cartella_sua="${sua%%$'\t'*}"; chi_lo_dice="${sua#*$'\t'}"
+ _f "$M_note_sue" cartella "$cartella_sua" fonte "$chi_lo_dice"
+ risposta_sua="${DELMINIO_MEMORIA_SUA:-}"
+ if [ -z "$risposta_sua" ] && ha_terminale; then
+ read -rp "$M_va_bene" risposta_sua </dev/tty
+ fi
+ case "$risposta_sua" in
+ s|S|si|sì|y|yes) ;;
+ *) muori "$M_memoria_sua_resta" ;;
+ esac
+ fi
+fi
+salvato=$(umask 077; DELMINIO_PRIMA_VOLTA="${prima_volta:+si}" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" \
+ DELMINIO_GANCI="$(git config --local core.hooksPath || git rev-parse --git-path hooks)" \
+ python3 "$cartella_copia/copia.py" salva "$radice" "$memoria" "$comune" "$URL" "$gitdir") \
+ || muori "$M_prima_non_salva"
+rm -rf "$cartella_copia"
+
+
+mkdir -p .claude
+rm -f .claude/mneme.sh # il client di prima della rinomina (0cfdde7): i suoi hook li toglie il passo 2
+cartella_token="${XDG_CONFIG_HOME:-$HOME/.config}/delminio"
+mkdir -p "$cartella_token" && chmod 700 "$cartella_token"
+file_token="$cartella_token/$(printf '%s' "$radice" | _sha16).token"
+( umask 077; printf '%s' "$token" > "$file_token" )
+
+scarica_client plugin .claude/plugin.py "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/plugin-client")"
+scarica_client squadra .claude/squadra.py "$(_f "$M_senza_client_squadra" indirizzo "$URL/static/kit/squadra-client")"
+mcp_locali() { # mcp_locali togli|da-parte
+ python3 - "$1" "${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" "$radice" "$URL" \
+ "$(_assoluto "$(git rev-parse --git-common-dir)")/delminio-backup" <<'MCP_LOCALI' || true
+import glob, json, os, subprocess, sys
+gesto, cj, radice, url, segno = sys.argv[1:6]
+try:
+ server = json.load(open(cj, encoding="utf-8"))["projects"][radice]["mcpServers"] or {}
+except (OSError, ValueError, KeyError, TypeError):
+ server = {}
+for nome in ("memoria", "delminio"):
+ s = server.get(nome)
+ if not isinstance(s, dict):
+ continue
+ if str(s.get("url", "")).startswith(url):
+ if gesto == "togli":
+ subprocess.run(["claude", "mcp", "remove", nome, "-s", "local"], capture_output=True, timeout=60)
+ elif gesto == "da-parte" and nome == "memoria":
+ try:
+ prime = sorted(glob.glob(os.path.join(open(segno, encoding="utf-8").read().strip(), "*", "fatti.json")))
+ except OSError:
+ prime = []
+ dest = os.path.join(os.path.dirname(prime[-1]), "mcp-memoria.json") if prime else ""
+ if dest and not os.path.exists(dest):
+ os.umask(0o077)
+ with open(dest, "w", encoding="utf-8") as f:
+ json.dump(s, f, indent=2)
+MCP_LOCALI
+}
+con_plugin=""
+if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && command -v claude >/dev/null && python3 .claude/plugin.py claude "$radice"; then
+ con_plugin=si
+ mcp_locali togli
+else
+ python3 .claude/plugin.py rimuovi "$radice" >/dev/null 2>&1 || true
+fi
+scarica_client opencode-client.js .claude/opencode.js "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/opencode-client.js")"
+if cli_presente opencode || [ -f .opencode/plugins/delminio.js ]; then
+ python3 .claude/plugin.py opencode "$radice" || true
+fi
+ganci_claude_nel_progetto=""
+if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || { [ -z "$con_plugin" ] && command -v claude >/dev/null; }; then
+ ganci_claude_nel_progetto=si
+fi
+
+if [ -z "$con_plugin" ] && command -v claude >/dev/null; then
+ mcp_locali togli
+ mcp_locali da-parte
+ claude mcp remove memoria -s local >/dev/null 2>&1 || true
+ cj="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json"
+ conf=$(python3 -c 'import json,sys
+url, f, cj, radice = sys.argv[1:5]
+try:
+ fidato = json.load(open(cj, encoding="utf-8")).get("projects", {}).get(radice, {}).get("hasTrustDialogAccepted") is True
+except (OSError, ValueError, AttributeError):
+ fidato = False
+h = "printf %s \"$(cat %s)\"" % (chr(39) + "{\"Authorization\":\"Bearer %s\"}" + chr(39), chr(39) + f + chr(39))
+if not fidato or chr(39) in f or not all(32 <= ord(c) < 127 for c in h):
+ sys.exit(1)
+print(json.dumps({"type": "http", "url": url + "/mcp", "headersHelper": h}))' "$URL" "$file_token" "$cj" "$radice" 2>/dev/null || true)
+ if [ -z "$conf" ] || ! claude mcp add-json -s local memoria "$conf" >/dev/null 2>&1 \
+ || ! python3 -c 'import json,sys
+s = json.load(open(sys.argv[1], encoding="utf-8"))["projects"][sys.argv[2]]["mcpServers"]["memoria"]
+sys.exit(0 if s.get("headersHelper") else 1)' "$cj" "$radice" 2>/dev/null; then
+ claude mcp remove memoria -s local >/dev/null 2>&1 || true
+ claude mcp add -s local -t http memoria "$URL/mcp" -H "Authorization: Bearer $token" >/dev/null \
+ || muori "$M_mcp_fallito"
+ fi
+elif [ -z "$con_plugin" ] && [ -z "$installa" ] && ! cli_presente codex && ! cli_presente qwen; then
+ avvisa "$M_mcp_senza_claude"
+fi
+for parte in lanciatori:lanciatori.sh ganci-git:ganci-git.sh worktree:worktree.sh consumi:consumi.py firme:firme.py; do
+ scarica_client "${parte%%:*}" ".claude/${parte#*:}" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/${parte%%:*}-client")"
+done
+client_scaricato=$(mktemp) || muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"
+curl -fsS -K <(_chiave "$token") "$URL/static/kit/delminio-client" -o "$client_scaricato" \
+ || { rm -f "$client_scaricato"; muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"; }
+_firmato "$URL" delminio-client "$client_scaricato" \
+ || { rm -f "$client_scaricato"; muori "$(_f "$M_kit_non_firmato" file delminio-client url "$URL")"; }
+{
+ echo '#!/usr/bin/env bash'
+ echo "# Il client di Delminio per gli hook di Claude Code, scritto da aggancia.sh."
+ echo "# Il token sta fuori dal repo, nel file qui sotto (600). Per cambiarlo, rilancia l'aggancio."
+ printf 'URL=%q\nFILE_TOKEN=%q\nMEMORIA=%q\nCLONE=%q\nKIT=%q\nREMOTO=%q\n' "$URL" "$file_token" "$memoria" "$clone" "$kit" "$remoto_repo"
+ echo 'TOKEN=$(cat "$FILE_TOKEN" 2>/dev/null || true)'
+ printf '%s\n' "$PORTABILI"
+ cat "$client_scaricato"
+} > .claude/delminio.sh.nuovo
+rm -f "$client_scaricato"
+mv -f .claude/delminio.sh.nuovo .claude/delminio.sh
+chmod 700 .claude/delminio.sh
+comando_client=$(python3 -c 'import shlex,sys; print("bash " + shlex.quote(sys.argv[1]))' "$radice/.claude/delminio.sh")
+
+mkdir -p .claude/commands
+if [ -f .claude/commands/risveglio.md ] && grep -q 'delminio.sh' .claude/commands/risveglio.md; then
+ rm -f .claude/commands/risveglio.md
+fi
+if [ -z "$ganci_claude_nel_progetto" ]; then
+ for c in apertura chiusura opening closing start handoff; do
+ f=".claude/commands/$c.md"
+ [ -f "$f" ] || continue
+ if grep -q 'delminio.sh' "$f"; then rm -f "$f"
+ elif [ -n "$con_plugin" ] && { [ "$c" = apertura ] || [ "$c" = chiusura ]; }; then rm -f "$f"; fi
+ done
+ rmdir .claude/commands 2>/dev/null || true
+else
+cat > .claude/commands/apertura.md <<COMANDO
+---
+description: "${M_qwen_comando_apertura//\"/\'}"
+argument-hint: "[cosa vuoi dirgli subito]"
+allowed-tools: Bash(bash:*)
+---
+!\`$comando_client prompt\`
+
+\$ARGUMENTS
+COMANDO
+
+cat > .claude/commands/chiusura.md <<COMANDO
+---
+description: "${M_qwen_comando_chiusura//\"/\'}"
+argument-hint: "[cosa fare prima di chiudere]"
+allowed-tools: Bash(bash:*)
+---
+!\`$comando_client chiusura\`
+
+\$ARGUMENTS
+COMANDO
+for coppia in opening:apertura closing:chiusura start:apertura handoff:chiusura; do
+ f=".claude/commands/${coppia%%:*}.md"
+ [ -f "$f" ] && ! grep -q 'delminio.sh' "$f" && continue
+ cp ".claude/commands/${coppia#*:}.md" "$f"
+done
+fi
+while IFS=$'\t' read -r f cli; do
+ [ -n "$f" ] && avvisa "$(_f "$M_mcp_col_nome_nostro" file "$f" cli "$cli")"
+done < <(python3 - "$radice" "$URL" <<'NOME_NOSTRO' 2>/dev/null || true
+import json, os, re, sys
+radice, url = sys.argv[1:3]
+def suo(s):
+ return isinstance(s, dict) and not str(s.get("url") or s.get("httpUrl") or "").startswith(url) \
+ and "delminio" not in json.dumps([s.get("command"), s.get("args")])
+f = os.path.join(radice, ".qwen", "settings.json")
+try:
+ if suo((json.load(open(f, encoding="utf-8")).get("mcpServers") or {}).get("memoria")):
+ print(f"{f}\tQwen Code")
+except (OSError, ValueError, AttributeError):
+ pass
+for f, sempre in ((os.path.join(radice, ".codex", "config.toml"), True),
+ (os.path.expanduser("~/.codex/config.toml"), False)):
+ try:
+ testo = open(f, encoding="utf-8").read()
+ except OSError:
+ continue
+ if re.search(r"(?m)^\[mcp_servers\.memoria\]", testo) and (sempre or re.search(r"(?m)^\[marketplaces\.delminio\]", testo)):
+ print(f"{f}\tCodex")
+NOME_NOSTRO
+)
+for c in apertura chiusura opening closing start handoff; do
+ f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/commands/$c.md"
+ if [ -f "$f" ] && ! grep -q 'delminio.sh' "$f"; then
+ avvisa "$(_f "$M_comando_tuo" file "$f" c "$c")"
+ fi
+done
+
+python3 - "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "$radice" <<'GESTITE' || true
+import glob, json, os, runpy, sys
+config, radice = sys.argv[1], sys.argv[2]
+cartelle = os.environ.get("DELMINIO_GESTITE_DIRS",
+ "/etc/claude-code:/Library/Application Support/ClaudeCode:/mnt/c/Program Files/ClaudeCode").split(":")
+def leggi(f):
+ try:
+ with open(f, encoding="utf-8") as h:
+ return json.load(h)
+ except Exception:
+ return None
+def dice(testo):
+ print("⚠️ " + testo, file=sys.stderr)
+for d in cartelle:
+ for f in [os.path.join(d, "managed-settings.json")] + sorted(glob.glob(os.path.join(d, "managed-settings.d", "*.json"))):
+ s = leggi(f)
+ if not isinstance(s, dict):
+ continue
+ if s.get("disableAllHooks") is True:
+ dice(f"{f} (impostazioni gestite di questa macchina) spegne TUTTI gli hook: gli agenti nascono senza l'apertura di Delminio, senza la posta e senza i controlli. Chiedi a chi amministra la macchina di togliere disableAllHooks, o di mettere gli hook di Delminio fra quelli gestiti.")
+ if s.get("allowManagedHooksOnly") is True:
+ dice(f"{f} lascia partire solo gli hook gestiti (allowManagedHooksOnly): quelli di Delminio no. Chiedi a chi amministra la macchina di aggiungerli fra quelli gestiti.")
+ nomi = lambda lista: [str((x or {}).get("serverName") or (x or {}).get("serverUrl") or "") for x in (lista or []) if isinstance(x, dict)]
+ consentiti = s.get("allowedMcpServers")
+ di_delminio = lambda n: "delminio" in n.lower() or n.lower() == "memoria"
+ if (isinstance(consentiti, list) and not any(di_delminio(n) for n in nomi(consentiti))) \
+ or any(di_delminio(n) for n in nomi(s.get("deniedMcpServers"))):
+ dice(f"{f} non lascia collegare il server MCP «memoria» di Delminio: l'agente non raggiungerà la memoria. Chiedi di aggiungerlo fra i server consentiti.")
+ if s.get("allowManagedPermissionRulesOnly") is True:
+ try:
+ nomi_tool = " e ".join(runpy.run_path(".claude/plugin.py")["TOOLS_CLAUDE"])
+ except Exception:
+ nomi_tool = "mcp__plugin_delminio_memoria__delminio e mcp__plugin_delminio_memoria__delminio_write"
+ dice(f"{f} tiene solo i permessi gestiti: ogni chiamata a Delminio chiederà il permesso. Chiedi di consentire {nomi_tool} fra i permessi gestiti.")
+for f in (os.path.join(config, "settings.json"), os.path.join(radice, ".claude", "settings.json"),
+ os.path.join(radice, ".claude", "settings.local.json")):
+ s = leggi(f)
+ if isinstance(s, dict) and s.get("disableAllHooks") is True:
+ dice(f"{f} ha disableAllHooks: true — è tua e non la tocco, ma con quella gli hook di Delminio non partono.")
+for f in ("/etc/codex/requirements.toml", "/etc/codex/managed_config.toml"):
+ if os.path.isfile(f):
+ dice(f"{f}: ci sono regole gestite di Codex su questa macchina. Delminio non le legge: se Codex non fa partire i ganci o il server MCP di Delminio, guarda lì.")
+GESTITE
+
+python3 - "$comando_client" "$memoria" "$con_plugin" "$ganci_claude_nel_progetto" <<'IMPOSTA' || muori "$(_f "$M_json_non_valido" file .claude/settings.local.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, memoria, con_plugin, nel_progetto = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
+pacchetto = runpy.run_path(".claude/plugin.py")
+p = pathlib.Path(".claude/settings.local.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if nel_progetto:
+ metti_ganci(s, comando, pacchetto["GANCI_CLAUDE"])
+else:
+ togli_ganci(s)
+if memoria:
+ s["autoMemoryDirectory"] = memoria
+allow = s.setdefault("permissions", {}).setdefault("allow", [])
+progetto = pacchetto["TOOLS_CLAUDE_PROGETTO"]
+tools, vecchi = ((progetto, pacchetto["TOOLS_CLAUDE"]) if nel_progetto
+ else (pacchetto["TOOLS_CLAUDE"], progetto))
+vecchi = (*vecchi, *pacchetto["TOOLS_CLAUDE_DI_PRIMA"])
+allow[:] = [a for a in allow if a not in vecchi]
+allow.extend(t for t in tools if t not in allow)
+def scelte(f):
+ try:
+ v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("skillOverrides")
+ except (OSError, ValueError, AttributeError):
+ return {}
+ return v if isinstance(v, dict) else {}
+gia = {**scelte(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json"),
+ **scelte(".claude/settings.json")}
+mie = s.get("skillOverrides") if isinstance(s.get("skillOverrides"), dict) else {}
+import subprocess
+try:
+ comune = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
+ capture_output=True, text=True, timeout=10).stdout.strip()
+except (OSError, subprocess.SubprocessError):
+ comune = ""
+segno_f844 = pathlib.Path(comune) / "delminio-skill-f844" if comune else None
+if segno_f844 and not segno_f844.exists():
+ prima = pacchetto.get("SKILL_CLAUDE_F811") or {}
+ mie = {n: (pacchetto["SKILL_CLAUDE"].get(n, v) if prima.get(n) == v else v) for n, v in mie.items()}
+ if mie:
+ s["skillOverrides"] = mie
+else:
+ segno_f844 = None
+nuove = {n: v for n, v in pacchetto["SKILL_CLAUDE"].items() if n not in mie and n not in gia}
+if nuove:
+ s["skillOverrides"] = {**mie, **nuove}
+def regole(f):
+ try:
+ v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("permissions") or {}
+ except (OSError, ValueError, AttributeError):
+ return []
+ return [r for k in ("allow", "ask", "deny") for r in (v.get(k) or []) if isinstance(r, str)] if isinstance(v, dict) else []
+sue = regole(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json") \
+ + regole(".claude/settings.json") \
+ + [r for k in ("allow", "deny") for r in (s.get("permissions", {}).get(k) or []) if isinstance(r, str)]
+ask = s.setdefault("permissions", {}).setdefault("ask", [])
+for tool in pacchetto.get("CHIEDI_CLAUDE") or ():
+ if tool not in ask and not any(r == tool or r.startswith(tool + "(") for r in sue):
+ ask.append(tool)
+if not ask:
+ s["permissions"].pop("ask")
+p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+if segno_f844:
+ try:
+ segno_f844.touch()
+ except OSError:
+ pass
+IMPOSTA
+
+if git ls-files --error-unmatch .codex/hooks.json >/dev/null 2>&1; then
+ avvisa "$M_codex_sotto_git"
+else
+mkdir -p .codex
+python3 - "$comando_client" "${DELMINIO_SENZA_PLUGIN:-}" <<'CODEX' || muori "$(_f "$M_json_non_valido" file .codex/hooks.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, senza_plugin = sys.argv[1], sys.argv[2]
+p = pathlib.Path(".codex/hooks.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if senza_plugin:
+ metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_CODEX"])
+else:
+ togli_ganci(s)
+if s or p.exists():
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+CODEX
+rmdir .codex 2>/dev/null || true # vuota: non era dell'umano, e il plugin non la usa
+fi
+
+qwen_senza_plugin=${DELMINIO_SENZA_PLUGIN:-}
+if [ -z "$qwen_senza_plugin" ] && cli_presente qwen; then
+ for w in "${DELMINIO_BIN:-$HOME/.local/bin}"/*; do
+ [ -f "$w" ] && grep -q '^export DELMINIO_CLI_NOME=qwen' "$w" 2>/dev/null || continue
+ grep -q 'DELMINIO_NASCITA=porta' "$w" && continue
+ if ! ( eval "$(grep -E '^export (QWEN_HOME|PATH|DELMINIO_CLI)=' "$w")"
+ [ -n "${QWEN_HOME:-}" ] && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" \
+ python3 .claude/plugin.py qwen "$QWEN_HOME" >/dev/null 2>&1 ); then
+ avvisa "$(_f "$M_qwen_ripiego" agente "$(basename "$w")")"
+ qwen_senza_plugin=si
+ fi
+ done
+fi
+if git ls-files --error-unmatch .qwen/settings.json >/dev/null 2>&1; then
+ avvisa "$M_qwen_sotto_git"
+else
+mkdir -p .qwen
+python3 - "$comando_client" "$qwen_senza_plugin" <<'QWEN' || muori "$(_f "$M_json_non_valido" file .qwen/settings.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, senza_plugin = sys.argv[1], sys.argv[2]
+p = pathlib.Path(".qwen/settings.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if senza_plugin:
+ metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_QWEN"], matcher_sempre=True)
+else:
+ togli_ganci(s)
+if s or p.exists():
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+QWEN
+if [ -z "$qwen_senza_plugin" ]; then
+ for parola in apertura chiusura opening closing start handoff; do
+ f=".qwen/commands/$parola.md"
+ [ -f "$f" ] && grep -q 'Delminio' "$f" && rm -f "$f"
+ done
+ rmdir .qwen/commands .qwen 2>/dev/null || true
+else
+mkdir -p .qwen/commands
+for parola in apertura chiusura opening closing start handoff; do
+ f=".qwen/commands/$parola.md"
+ [ -f "$f" ] && ! grep -q 'Delminio' "$f" && continue
+ case $parola in
+ apertura|opening|start) descrizione=$M_qwen_comando_apertura ;;
+ *) descrizione=$M_qwen_comando_chiusura ;;
+ esac
+ printf -- '---\ndescription: "%s"\n---\n%s\n' "${descrizione//\"/\'}" "$parola" > "$f"
+done
+fi
+fi
+
+mkdir -p .claude/rules
+cat > .claude/rules/delminio.md <<REGOLA
+# Questo repo è agganciato a Delminio
+
+Se in questa sessione non ti è arrivato niente da Delminio — né l'apertura (il
+contesto che comincia con «# Delminio —») né l'avviso che Delminio non risponde —,
+la CLI è partita da fuori di questo repo, o prima dell'aggancio, o (Codex) senza
+il comando di Delminio: niente memoria, niente posta, niente consegna verificata, e
+il tool \`delminio\` non c'è. Prima di continuare dillo al tuo umano: chiudere e
+rilanciare l'agente dentro $radice (o una sua sottocartella), col comando che scrive
+\`delminio eseguibili\` — con Codex è l'unico modo, perché è il
+lancio a dargli Delminio.
+REGOLA
+
+scarica_client cantiere .claude/cantiere.py "$(_f "$M_senza_client_cantiere" indirizzo "$URL/static/kit/cantiere-client")"
+ln -sfn cantiere.py .claude/backlog.py
+scarica_client eseguibili .claude/eseguibili.py "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
+bin_delminio="${DELMINIO_BIN:-$HOME/.local/bin}"
+comando_delminio="$bin_delminio/delminio"
+if [ -e "$comando_delminio" ] && ! grep -q '^# delminio-comando$' "$comando_delminio" 2>/dev/null; then
+ avvisa "$(_f "$M_comando_occupato" file "$comando_delminio")"
+else
+ mkdir -p "$bin_delminio"
+ {
+ cat <<'COMANDO'
+#!/usr/bin/env bash
+# delminio-comando
+# Scritto da aggancia.sh: i gesti di Delminio da qualunque cartella di un progetto collegato.
+r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""
+if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
+ c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")
+fi
+if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
+COMANDO
+ printf ' echo %q >&2\n' "$M_comando_fuori"
+ cat <<'COMANDO'
+ exit 1
+fi
+# Tutto al client, anche il Backlog: i nomi dei comandi in ogni lingua li sa lui (F666).
+exec bash "$r/.claude/delminio.sh" "$@"
+COMANDO
+ } > "$comando_delminio.nuovo" && chmod 755 "$comando_delminio.nuovo" && mv -f "$comando_delminio.nuovo" "$comando_delminio"
+fi
+scarica_client cassaforte .claude/cassaforte.py "$(_f "$M_senza_client_cassaforte" indirizzo "$URL/static/kit/cassaforte-client")"
+rm -f .claude/guardia.py
+
+ganci_globali=""
+if ! git config --local core.hooksPath >/dev/null 2>&1 && git config core.hooksPath >/dev/null 2>&1; then
+ ganci_globali=$(git config core.hooksPath)
+fi
+ganci=$(git config --local core.hooksPath || git rev-parse --git-path hooks)
+mkdir -p "$ganci"
+for g in commit-msg post-commit post-rewrite; do
+ if [ -n "$ganci_globali" ]; then
+ _f "$M_gancio_globale" dir "$ganci_globali" file "$ganci_globali/$g" riga "$comando_client $g \"\$@\""
+ continue
+ fi
+ f="$ganci/$g"
+ if [ -e "$f" ] && ! sed -n 2p "$f" | grep -qE '^# (Delminio|Mneme) \(aggancia\.sh\)'; then
+ grep -q "delminio.sh" "$f" \
+ || { riga_gancio="$comando_client $g \"\$@\""; _f "$M_gancio_tuo" file "$f" riga "$riga_gancio"; }
+ continue
+ fi
+ printf '#!/bin/sh\n# Delminio (aggancia.sh): la chiusura giudicata dal motore. Gli altri commit passano.\nexec %s %s "$@"\n' "$comando_client" "$g" > "$f"
+ chmod +x "$f"
+done
+
+pubblico=$(printf '%s' "$repo" | python3 -c 'import json,sys
+try: d = json.load(sys.stdin)
+except Exception: sys.exit(0)
+d = d.get("repo", d) if isinstance(d, dict) else {}
+print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null || true)
+segno="$(git rev-parse --path-format=absolute --git-common-dir)/delminio-pubblico"
+case "$pubblico" in si) : > "$segno" ;; no) rm -f "$segno" ;; esac
+
+escludi=$(git rev-parse --git-path info/exclude)
+mkdir -p "$(dirname "$escludi")"
+for f in $KIT_FILE .claude/delminio-prima/ .claude/delminio-personali/; do
+ case "$f" in .codex/hooks.json|.qwen/settings.json) git ls-files --error-unmatch "$f" >/dev/null 2>&1 && continue ;; esac
+ grep -qxF "$f" "$escludi" 2>/dev/null || echo "$f" >> "$escludi"
+done
+
+DELMINIO_PROVA=1 bash .claude/delminio.sh apertura < /dev/null > /dev/null \
+ || muori "$M_apertura_muta"
+
+spazio=$(python3 .claude/eseguibili.py spazio --da .claude/delminio.sh 2>/dev/null || printf '%s' "${URL%/}")
+case "$spazio" in
+ *"#"*) nome_spazio="${etichetta:-${spazio##*#}}"; dove=$(_f "$M_nello_spazio" spazio "$nome_spazio") ;;
+ *) dove=""
+ python3 -c 'import json,sys; d=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]); sys.exit(0 if len(d.get("spazi") or []) > 1 else 1)' <<<"$risposta" 2>/dev/null \
+ && dove=$(_f "$M_nello_spazio" spazio principale) ;;
+esac
+nome_repo=$(basename "$radice")
+_f "$M_collegato" repo "$nome_repo" url "$URL" dove "$dove" chi "$chi"
+[ -n "$dove" ] && _f "$M_sempre_nello_spazio" dove "$dove"
+if [ -n "$salvato" ]; then
+ _f "$M_prima_al_sicuro" cartella "$salvato"
+fi
+if ha_terminale && [ -f .claude/plugin.py ] && [ "$(python3 .claude/plugin.py app-codex stato 2>/dev/null)" = manca ]; then
+ risposta_app=""; read -rp "$M_app_codex_domanda" risposta_app </dev/tty || true
+ case "$risposta_app" in
+ s|S|si|sì|y|yes) bash .claude/delminio.sh app-codex || true ;;
+ n|N|no) bash .claude/delminio.sh app-codex no || true ;;
+ esac
+fi
+if [ -n "$installa" ]; then
+ _f "$M_installo_cli" cli "$installa"
+ primo=$(mktemp)
+ bash .claude/delminio.sh eseguibili allinea --vuoi "$installa" --primo "$primo" || true
+ lancia=$(cat "$primo" 2>/dev/null || true); rm -f "$primo"
+ [ -n "$lancia" ] && [ -x "$lancia" ] || muori "$(_f "$M_installa_non_riuscita" cli "$installa")"
+ nome_agente=$(basename "$lancia")
+ apertura=$M_rito_apertura; [ "$installa" = codex ] && apertura=$M_rito_apertura_codex # Codex: senza la barra
+ case ":$PATH:" in *":$(dirname "$lancia"):"*) dopo=$nome_agente ;; *) dopo=$lancia ;; esac
+ _f "$M_parto" nome "$nome_agente" apertura "$apertura" cartella "$radice" dopo "$dopo"
+ case "$installa" in
+ codex) echo "$M_parto_codex" ;;
+ qwen) echo "$M_parto_qwen" ;;
+ esac
+ ha_terminale || exit 0
+ if [ -t 0 ]; then exec "$lancia"; fi
+ exec "$lancia" </dev/tty
+fi
+case ":$PATH:" in *":$bin_delminio:"*) ;; *) _f "$M_path_nuovo" cartella "$bin_delminio" comando "$comando_delminio" ;; esac
+if python3 -c 'import json,os,sys
+try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
+except Exception: r = {}
+u = sys.argv[1].rstrip("/")
+s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
+miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
+sys.exit(0 if not s.get("rifiutato") and any(os.path.isfile(p) for p in miei) else 1)' "$spazio"; then
+ bash .claude/delminio.sh eseguibili allinea || true
+ echo "$M_apri_eseguibile"
+else
+ echo "$M_scrivi_eseguibile"
+fi
+if cli_presente codex; then
+ echo "$M_con_codex"
+fi
+if [ -n "$senza_cli" ]; then
+ echo "$M_senza_cli"
+fi
+if cli_presente qwen; then
+ echo "$M_con_qwen"
+fi
+if [ -f .opencode/plugins/delminio.js ]; then
+ echo "$M_con_opencode"
+fi
+if command -v claude >/dev/null; then
+ echo "$M_solo_claude"
+fi
diff --git a/kit/en/cantiere-client b/kit/en/cantiere-client
new file mode 100644
index 0000000..63af766
--- /dev/null
+++ b/kit/en/cantiere-client
@@ -0,0 +1,535 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Il Cantiere da riga di comando — il client del registro che vive in Delminio."""
+from __future__ import annotations
+import json
+import os
+import subprocess
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+QUI = os.path.dirname(os.path.abspath(__file__))
+RADICE = os.path.dirname(QUI)
+CMD = 'python3 .claude/' + ('backlog.py' if os.path.basename(sys.argv[0]) == 'backlog.py' else 'cantiere.py')
+FRASI = {
+ "aiuto": " {cmd} the open tasks, by PRIORITY\n {cmd} list [domain] filtered by a domain\n {cmd} to-decide [domain] only the items to DECIDE\n {cmd} follow-ups [domain] the follow-ups, due ones first\n {cmd} mine the ones you have in progress now\n {cmd} assigned the ones the admin assigned to your user\n {cmd} questions the ones done with your user, and what they need to say or do\n {cmd} show <id> the full card\n {cmd} search \"<words>\" the closest semantically, done ones included (a number: that one)\n \u26d4 open needs --asked \"<the admin's words>\", or at the session end --half-done \"<what you were doing>\"\n {cmd} open --title \"...\" --risk \"...\" --done-when \"...\" --domain <d> \\\n [--priority 1-4] [--owner agent|together|admin] [--autocheck \"cmd\"] \\\n [--question \"what's needed from your user\" [--type decision|action]] \\\n [--hold \"what it waits for\"] [--memory \"<memory name>\"]\n [--wait-for B<n>] optional: created on hold until B<n> is done\n {cmd} open --decision --title \"...\" --risk \"...\" --to-decide \"which decision is missing\" --domain <d>\n {cmd} open --follow-up --title \"...\" --when <YYYY-MM-DD> \\\n --must-be-true \"what must be true that day\" --domain <d> [--autocheck \"cmd\"]\n \u26d4 an item that resembles one not yet done isn't created: update that one, or\n --different-from \"why it's something else\" (it names the close ones; it stays in the origin)\n {cmd} postpone <id> <YYYY-MM-DD> [\"why\"] looked at, not yet decidable\n {cmd} link <id> [--memory \"X\"] [--remove \"X\"] the memories to read before touching it\n {cmd} take <id> \xb7 release <id> \xb7 reopen <id>\n {cmd} answer <id> \"<their words>\" your user's answer to the question: the task\n becomes the agent's. \u26d4 Their words, said in chat, never yours\n {cmd} ask <id> \"why\" the admin's approval is needed: it's on hold until they decide\n (a member only on the tasks they opened)\n {cmd} assign <id> <login> the admin gives a task to a person (without a login it frees it)\n {cmd} note <id> \"<note>\" what you found out, without closing it (--replace to rewrite)\n {cmd} edit <id> [--title ..] [--risk ..] [--done-when ..] [--priority 1-4|none] [--autocheck \"cmd\"|none]\n [--owner ..] [--question \"..\"|none] [--type decision|action]\n {cmd} close <id> [\"how\"] it's done, and how \u2014 an item to decide: the decision and why\n {cmd} hold <id> \"<wait>\" not debt: it's waiting for something\n {cmd} wait <id> B<n> [B<m>] waits for other tasks: it goes on hold, and when the last one is done\n it reopens by itself \xb7 --remove B<n> removes the link\n {cmd} autochecks runs the auto-checks and closes what's true\n\nWith together the question is required: a decision in words, or an action only your user can take.\nPriority: P1 now \xb7 P2 next \xb7 P3 when there's time \xb7 P4 someday (--priority 1-4). The admin decides it.\nThe Italian names (apri, chiudi, --title\u2026) work too.",
+ "non_collegato": "\u274c this repository isn't connected to Delminio (.claude/delminio.sh): run the connection again.",
+ "non_risponde": "\u274c Delminio is not responding ({url}): {errore} \u2014 the Backlog is there.",
+ "chi_sei": "\u274c I don't know who you are: the Backlog signs every write with the session. Run it from a connected CLI, or CANTIERE_SESSIONE=S<N> {cmd} \u2026",
+ "sonda_dice_si": "\u274c this auto-check can't say NO: as soon as it's attached it already answers \u201cthe task is done\u201d (exit 0).\nThe comparison goes INSIDE it: test \"$(<measure>)\" -eq 0 \xb7 <measure> | grep -q '<expected>'\nWhat it answered:\n",
+ "argomento_sconosciuto": "\u274c unknown argument: {argomento}",
+ "vuole_valore": "\u274c {argomento} needs a value",
+ "uso_mostra": "usage: {cmd} show <id>",
+ "uso_cerca": "usage: {cmd} search \"<words or number>\"",
+ "chiusa": "\u2705 {sigla} done",
+ "memorie_chiusa": "\U0001f4d6 These memories tell its story: reread them, now that it's done \u2014 {memorie}",
+ "uso_aspetta": "usage: {cmd} wait <id> B<n> [B<m>] \xb7 --remove B<n>",
+ "uso_rinvia": "usage: {cmd} postpone <id> <YYYY-MM-DD> [\"why\"]",
+ "nessuna_sonda": "No live task has an auto-check.",
+ "chiusa_dalla_sonda": "\u2705 {sigla} closed by the auto-check",
+ "sonda_muta": "\u26a0\ufe0f {sigla} \u2014 the auto-check couldn't answer (rc={rc}): {uscita}",
+ "sonda_non_accettata": "\u23f8 {sigla} \u2014 the auto-check doesn't run: nobody has accepted it on this machine\n | {sonda}",
+ "sonde_da_accettare": "{n} auto-checks are waiting for a person to read and accept them, from a terminal: {cmd} autochecks accetta",
+ "sonda_accetta_domanda": "\n{sigla} \u2014 this auto-check will run on this machine, in this repository:\n {sonda}\nDo you accept it? [y/N] ",
+ "sonda_si": "y yes",
+ "sonde_accettate": "\u2705 {nuove} auto-checks accepted now \xb7 {tutte} in total \xb7 the list: {file}",
+ "accetta_da_terminale": "\u274c auto-checks are accepted by a person, from a real terminal: run \u201c{cmd} autochecks accetta\u201d yourself.",
+ "sonda_scaduta": "time's up (300 s)",
+ "comando_sconosciuto": "unknown command: {comando}\n\n{aiuto}",
+ "uso_rispondi": "usage: {cmd} answer <id> \"<your user's words>\"",
+ "priorita_numero": "\u274c priority: 1-4, not \u201c{priorita}\u201d"
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+AIUTO = F('aiuto', cmd=CMD)
+
+class Rifiuto(Exception):
+ pass
+
+def _ambiente() -> tuple[str, str, str]:
+ try:
+ out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines()
+ except (OSError, subprocess.TimeoutExpired):
+ out = []
+ url, file_token, sessione = (out + ['', '', ''])[:3]
+ try:
+ with open(file_token, encoding='utf-8') as f:
+ token = f.read().strip()
+ except OSError:
+ token = ''
+ if not url or not token:
+ raise Rifiuto(F('non_collegato'))
+ return (url.rstrip('/'), token, os.environ.get('CANTIERE_SESSIONE') or sessione)
+URL, TOKEN, SESSIONE = ('', '', '')
+
+def _http(metodo: str, percorso: str, corpo: dict | None=None, *, testo: bool=False, params: dict | None=None):
+ q = dict(params or {})
+ if testo:
+ q['formato'] = 'testo'
+ url = f'{URL}/api/cantiere{percorso}' + (f'?{urllib.parse.urlencode(q)}' if q else '')
+ dati = json.dumps(corpo).encode() if corpo is not None else None
+ req = urllib.request.Request(url, data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ raw = r.read().decode()
+ except urllib.error.HTTPError as e:
+ raw = e.read().decode()
+ if testo and (not raw.lstrip().startswith('{')):
+ raise Rifiuto(raw.strip())
+ try:
+ msg = json.loads(raw).get('error', raw)
+ except ValueError:
+ msg = raw
+ raise Rifiuto(f'❌ {msg}')
+ except (urllib.error.URLError, OSError) as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e))
+ return raw if testo else json.loads(raw)
+
+def _sessione() -> str:
+ if not SESSIONE:
+ raise Rifiuto(F('chi_sei', cmd=CMD))
+ return SESSIONE
+
+def _azione(id_: str, azione: str, corpo: dict) -> str:
+ return _http('POST', f'/{urllib.parse.quote(id_)}/{azione}', {'sessione': _sessione(), **corpo}, testo=True)
+
+def _esegui(cmd: str) -> tuple[int, str]:
+ try:
+ r = subprocess.run(cmd, shell=True, cwd=RADICE, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=300, executable='/bin/bash')
+ except subprocess.TimeoutExpired:
+ return (124, F('sonda_scaduta'))
+ return (r.returncode, r.stdout + r.stderr)
+
+def _file_accettate() -> str:
+
+ def git(*a):
+ return subprocess.run(['git', 'rev-parse', '--path-format=absolute', *a], cwd=RADICE, capture_output=True, text=True).stdout.strip()
+ comune = os.path.join(git('--git-common-dir') or os.path.join(RADICE, '.git'), 'delminio-sonde-accettate')
+ sua = git('--git-path', 'delminio-sonde-accettate')
+ if sua and sua != comune and os.path.isfile(sua):
+ try:
+ righe = set(open(sua, encoding='utf-8').read().split())
+ if os.path.isfile(comune):
+ righe |= set(open(comune, encoding='utf-8').read().split())
+ with open(comune, 'w', encoding='utf-8') as f:
+ f.write(''.join((x + '\n' for x in sorted(righe))))
+ os.remove(sua)
+ except OSError:
+ pass
+ return comune
+
+def _impronta(sonda: str) -> str:
+ import hashlib
+ return hashlib.sha256(sonda.encode()).hexdigest()
+
+def _accettate() -> set[str]:
+ try:
+ with open(_file_accettate(), encoding='utf-8') as f:
+ return set(f.read().split())
+ except OSError:
+ return set()
+
+def _scrivi_accettate(tutte: set[str]) -> None:
+ with open(_file_accettate(), 'w', encoding='utf-8') as f:
+ f.write(''.join((x + '\n' for x in sorted(tutte))))
+
+def sonda_sa_dire_no(cmd: str) -> None:
+ rc, out = _esegui(cmd)
+ if rc == 0:
+ raise Rifiuto(F('sonda_dice_si') + '\n'.join((' | ' + r for r in out.splitlines()[:8])))
+
+def _flag(args: list[str], spec: dict[str, str]) -> dict:
+ out: dict = {}
+ i = 0
+ while i < len(args):
+ a = args[i]
+ if not a.startswith('--') or a[2:] not in spec:
+ raise Rifiuto(F('argomento_sconosciuto', argomento=a))
+ tipo, _, dest = spec[a[2:]].partition(':')
+ dest = dest or a[2:]
+ if tipo == 'bool':
+ out[dest] = True
+ i += 1
+ continue
+ if i + 1 >= len(args):
+ raise Rifiuto(F('vuole_valore', argomento=a))
+ if tipo == 'lista':
+ out.setdefault(dest, []).append(args[i + 1])
+ else:
+ out[dest] = args[i + 1]
+ i += 2
+ return out
+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"
+ },
+ "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"
+ }
+}
+
+def in_italiano(argv: list[str]) -> list[str]:
+ if not argv:
+ return argv
+ verbi, opzioni = (COMANDI.get('backlog') or {}, COMANDI.get('backlog_opzioni') or {})
+ valori = {'--tipo': COMANDI.get('backlog_tipo') or {}, '--owner': COMANDI.get('backlog_owner') or {}}
+ out = [verbi.get(argv[0], argv[0])]
+ for a in argv[1:]:
+ if len(out) > 1 and out[-1] in valori:
+ out.append(valori[out[-1]].get(a, a))
+ elif a.startswith('--') and a[2:] in opzioni:
+ out.append('--' + opzioni[a[2:]])
+ else:
+ out.append(a)
+ return out
+
+def comando(argv: list[str]) -> int:
+ argv = in_italiano(argv)
+ cmd = argv[0] if argv else 'lista'
+ resto = argv[1:]
+ arg = resto[0] if resto else ''
+ if cmd in ('aiuto', '-h', '--help', 'help'):
+ print(AIUTO)
+ return 0
+ if cmd == 'assegnate':
+ print(_http('GET', '', testo=True, params={'vista': 'assegnate', 'a': arg}), end='')
+ return 0
+ if cmd == 'assegna':
+ print(_azione(arg, 'assegna', {'a': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'domande':
+ print(_http('GET', '', testo=True, params={'vista': 'domande'}), end='')
+ return 0
+ if cmd == 'rispondi':
+ if len(resto) < 2:
+ raise Rifiuto(F('uso_rispondi', cmd=CMD))
+ print(_azione(arg, 'rispondi', {'risposta': resto[1]}), end='')
+ return 0
+ if cmd in ('lista', 'concept', 'veglie', 'veglia', 'mie'):
+ vista = 'veglie' if cmd == 'veglia' else cmd
+ print(_http('GET', '', testo=True, params={'vista': vista, 'dominio': arg, 'sessione': SESSIONE}), end='')
+ return 0
+ if cmd in ('mostra', 'scheda', 'vedi'):
+ if not arg:
+ raise Rifiuto(F('uso_mostra', cmd=CMD))
+ print(_http('GET', f'/{urllib.parse.quote(arg)}', testo=True), end='')
+ return 0
+ if cmd in ('cerca', 'trova', 'search'):
+ q = ' '.join(resto).strip()
+ if not q:
+ raise Rifiuto(F('uso_cerca', cmd=CMD))
+ print(_http('GET', '/cerca', testo=True, params={'q': q}), end='')
+ return 0
+ if cmd == 'apri':
+ f = _flag(resto, {'titolo': 'val', 'danno': 'val', 'chiusura': 'val', 'verifica': 'val:chiusura', 'decide': 'val:chiusura', 'veglia': 'bool', 'concept': 'bool', 'quando': 'val', 'dominio': 'val', 'owner': 'val', 'priorita': 'val', 'sonda': 'val', 'memoria': 'lista:memorie', 'ferma': 'val', 'aspetta': 'lista:aspetta', 'chiesto': 'val', 'a-meta': 'val:a_meta', 'diversa-da': 'val:diversa_da', 'domanda': 'val', 'tipo': 'val:domanda_tipo'})
+ f['tipo'] = 'veglia' if f.pop('veglia', False) else 'concept' if f.pop('concept', False) else 'opera'
+ if 'priorita' in f:
+ try:
+ f['priorita'] = int(f['priorita'])
+ except ValueError:
+ raise Rifiuto(F('priorita_numero', priorita=f['priorita'])) from None
+ if f.get('sonda') and f['tipo'] != 'concept':
+ sonda_sa_dire_no(f['sonda'])
+ _scrivi_accettate(_accettate() | {_impronta(f['sonda'])})
+ f['sessione'] = _sessione()
+ print(_http('POST', '/apri', f, testo=True), end='')
+ return 0
+ if cmd == 'correggi':
+ f = _flag(resto[1:], {'titolo': 'val', 'danno': 'val', 'chiusura': 'val', 'decide': 'val:chiusura', 'owner': 'val', 'dominio': 'val', 'priorita': 'val', 'sonda': 'val', 'memoria': 'lista:memorie', 'domanda': 'val', 'tipo': 'val:domanda_tipo'})
+ if f.get('sonda') and f['sonda'] not in ('none', '-'):
+ sonda_sa_dire_no(f['sonda'])
+ _scrivi_accettate(_accettate() | {_impronta(f['sonda'])})
+ print(_azione(arg, 'correggi', f), end='')
+ return 0
+ if cmd == 'lega':
+ print(_azione(arg, 'lega', _flag(resto[1:], {'memoria': 'lista:aggiungi', 'togli': 'lista'})), end='')
+ return 0
+ if cmd in ('prendi', 'molla', 'riapri'):
+ print(_azione(arg, cmd, {}), end='')
+ return 0
+ if cmd == 'chiedi':
+ print(_azione(arg, 'chiedi', {'perche': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'tocca':
+ sost = len(resto) > 1 and resto[1] == '--sostituisci'
+ nota = resto[2] if sost and len(resto) > 2 else resto[1] if len(resto) > 1 else ''
+ print(_azione(arg, 'tocca', {'nota': nota, 'sostituisci': sost}), end='')
+ return 0
+ if cmd == 'chiudi':
+ r = _http('POST', f'/{urllib.parse.quote(arg)}/chiudi', {'sessione': _sessione(), 'come': resto[1] if len(resto) > 1 else ''})
+ print(F('chiusa', sigla=r['chiusa']))
+ for riga in r.get('sblocchi') or []:
+ print(f' {riga}')
+ if r.get('memorie'):
+ print(F('memorie_chiusa', memorie=' · '.join(r['memorie'])))
+ return 0
+ if cmd == 'ferma':
+ print(_azione(arg, 'ferma', {'attesa': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'aspetta':
+ togli = '--togli' in resto
+ sigle = [x for x in resto[1:] if x != '--togli']
+ if not sigle:
+ raise Rifiuto(F('uso_aspetta', cmd=CMD))
+ print(_azione(arg, 'aspetta', {'togli': sigle} if togli else {'su': sigle}), end='')
+ return 0
+ if cmd == 'rinvia':
+ if len(resto) < 2:
+ raise Rifiuto(F('uso_rinvia', cmd=CMD))
+ print(_azione(arg, 'rinvia', {'quando': resto[1], 'perche': resto[2] if len(resto) > 2 else ''}), end='')
+ return 0
+ if cmd == 'sonde':
+ sonde = _http('GET', '', params={'vista': 'sonde'})['sonde']
+ if not sonde:
+ print(F('nessuna_sonda'))
+ return 0
+ accettate = _accettate()
+ if arg == 'accetta':
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ raise Rifiuto(F('accetta_da_terminale', cmd=CMD))
+ nuove = 0
+ for s in sonde:
+ h = _impronta(s['sonda'])
+ if h in accettate:
+ continue
+ tty.write(F('sonda_accetta_domanda', sigla=s['sigla'], sonda=s['sonda']))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('sonda_si').split():
+ accettate.add(h)
+ nuove += 1
+ _scrivi_accettate(accettate)
+ print(F('sonde_accettate', nuove=nuove, tutte=len(accettate), file=_file_accettate()))
+ return 0
+ da_accettare = 0
+ for s in sonde:
+ if _impronta(s['sonda']) not in accettate:
+ da_accettare += 1
+ print(F('sonda_non_accettata', sigla=s['sigla'], sonda=s['sonda']))
+ continue
+ rc, out = _esegui(s['sonda'])
+ if rc == 0:
+ r = _http('POST', f"/{s['id']}/chiudi", {'sessione': SESSIONE or 'S0', 'da_sonda': True, 'misura': ' '.join(out.split())[:200]})
+ print(F('chiusa_dalla_sonda', sigla=s['sigla']))
+ for riga in r.get('sblocchi') or []:
+ print(f' {riga}')
+ elif rc > 125 or rc == 124:
+ print(F('sonda_muta', sigla=s['sigla'], rc=rc, uscita=out[:80]))
+ if da_accettare:
+ print(F('sonde_da_accettare', n=da_accettare, cmd=CMD))
+ return 0
+ print(F('comando_sconosciuto', comando=cmd, aiuto=AIUTO))
+ return 1
+if __name__ == '__main__':
+ try:
+ URL, TOKEN, SESSIONE = _ambiente()
+ sys.exit(comando(sys.argv[1:]))
+ except Rifiuto as e:
+ print(str(e).rstrip(), file=sys.stderr)
+ sys.exit(1)
diff --git a/kit/en/cassaforte-client b/kit/en/cassaforte-client
new file mode 100644
index 0000000..cac9694
--- /dev/null
+++ b/kit/en/cassaforte-client
@@ -0,0 +1,625 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La cassaforte da riga di comando (F747): un segreto arriva solo col sì della persona."""
+from __future__ import annotations
+import base64
+import hashlib
+import hmac
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+QUI = os.path.dirname(os.path.abspath(__file__))
+CMD = 'delminio cassaforte'
+ATTESA_S = int(os.environ.get('DELMINIO_CASSAFORTE_ATTESA', '100'))
+INFO = b'delminio-cassaforte-v1'
+FIRMA = b'delminio-cassaforte-firma-v1:'
+FIRMA_DEPOSITO = 'delminio-cassaforte-deposito-v1:'
+FIRMA_PASSAGGIO = 'delminio-cassaforte-passaggio-v1:'
+NOME_RE = re.compile('^[A-Z][A-Z0-9_]{0,63}$')
+NOMI_VIETATI = frozenset({'PATH', 'HOME', 'SHELL', 'IFS', 'ENV', 'BASH_ENV', 'CDPATH', 'PS4', 'PROMPT_COMMAND', 'SHELLOPTS', 'BASHOPTS', 'GLOBIGNORE', 'NODE_OPTIONS', 'NODE_PATH', 'PERL5OPT', 'PERL5LIB', 'PERLLIB', 'RUBYOPT', 'RUBYLIB', 'JAVA_TOOL_OPTIONS', '_JAVA_OPTIONS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_EXEC_PATH', 'GIT_ASKPASS', 'SSH_ASKPASS', 'EDITOR', 'VISUAL', 'PAGER', 'BROWSER', 'TMPDIR', 'GIT_PROXY_COMMAND', 'GIT_TEMPLATE_DIR', 'ZDOTDIR', 'GCONV_PATH', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'})
+PREFISSI_VIETATI = ('LD_', 'DYLD_', 'PYTHON', 'BASH_FUNC_', 'GIT_CONFIG', 'LUA_')
+FRASI = {
+ "aiuto": " {cmd} list the secrets you can request (names and notes, never values; \u201ctime-bound\u201d = opens with a single approval)\n {cmd} NAME[,NAME\u2026] \"<why>\" -- command [arguments\u2026]\n requests the secrets from the administrator, with the why: the request reaches their phone.\n Granted, the command starts with the secrets in its environment variables (NAME=value).\n If an open time-bound access covers them all, it starts at once, without asking.\n The command reads the variables: to use them in arguments, go through a shell \u2014\n -- bash -c 'curl -u \"admin:$NAME\" \u2026'\n {cmd} open NAME[,NAME\u2026]|--larghe \"<why>\"\n time-bound access: a single approval for the secrets marked \u201ctime-bound\u201d (--larghe: all of them), for the time the app says.\n {cmd} windows | close the time-bound access opened from here \xb7 close it all\n {cmd} propose NAME \"<what it is for>\"\n proposes a secret that is not there yet: the administrator approves it by entering the value.\n {cmd} deposit NAME[,NAME\u2026] \"<what it is for>\" [--larga] [--dal-file FILE]\n puts a value in the vault without showing it: from stdin (one name) or from a NAME=value file.\n It becomes a secret when the administrator accepts it in the app.",
+ "non_collegato": "\u274c this repository isn't connected to Delminio (.claude/delminio.sh): run the connection again.",
+ "non_risponde": "\u274c Delminio is not responding ({url}): {errore}",
+ "nessun_segreto": "This space's vault is empty: the admin adds secrets from the app (Vault). If you need one, propose it by name.",
+ "nessuna_cassaforte": "This space has no vault: the admin creates it from the app (Vault).",
+ "uso_chiedi": "usage: {cmd} NAME[,NAME\u2026] \"<why>\" -- command [arguments\u2026]",
+ "chiesta": "\U0001f511 Request sent to the admin: {nomi}. Tell them in the chat too: they grant it from the app, on their phone.",
+ "aspetto": " Waiting for approval (up to {secondi} s)\u2026",
+ "ancora_niente": "\u23f3 Not granted yet. When the admin decides, the decision reaches you on the channel: then run the same command again, identical, and it picks up this request.",
+ "negata": "\u270b Denied by {chi}{parole}. The command didn't start.",
+ "scaduta": "\u231b The request expired before anyone approved it: the command didn't start. If it's still needed, run it again and the request starts over.",
+ "consegna_rotta": "\u274c What arrived can't be opened (encrypted data altered, or it wasn't for this request): the command didn't start.",
+ "firma_falsa": "\u274c What arrived doesn't carry the vault's signature: it wasn't sent by an admin's device. The command didn't start; tell the admin.",
+ "firma_cambiata": "\u274c The vault's signing key isn't the one seen the first time ({file}): the command didn't start. If the admin really did recreate the vault, delete that file.",
+ "nomi_diversi": "\u274c Names different from the ones requested arrived: the command didn't start; tell the admin.",
+ "nome_vietato": "\u274c {nome} is a variable that changes what a command runs: it can't be requested from the vault.",
+ "impronta": " Request fingerprint: {impronta} \u2014 in the app the admin sees the same one.",
+ "concessa": "\u2705 Granted by {chi}: the command starts.",
+ "comando_mancante": "\u274c the command after \u201c--\u201d is missing",
+ "uso_proponi": "usage: {cmd} proponi NAME \"<what it is for>\"",
+ "proposta": "\U0001f4dd Proposed {nome}: the admin sees it in the app and, if they approve it, adds the value. Tell them in chat too.",
+ "segno_larga": " \xb7 time-bound",
+ "finestra_chiesta": "\U0001f511 Time-bound access requested from the administrator for {n} secrets ({minuti} minutes from approval). Tell them in chat too: they approve it in the app, on their phone.",
+ "finestra_aperta": "\u2705 Time-bound access opened by {chi} until {ora}: {nomi}. Commands with these secrets start without asking.",
+ "finestra_usata": "\U0001f511 From the open time-bound access (until {ora}): the command starts.",
+ "finestra_finita": "\u231b A time-bound access opened from here is gone (closed or ended).",
+ "finestre_nessuna": "No time-bound access opened from here.",
+ "finestra_riga": " until {ora} {nomi}",
+ "finestre_chiuse": "\U0001f512 Time-bound access closed: {n}.",
+ "nessuna_larga": "No secret is marked \u201ctime-bound\u201d: the administrator marks them in the app, one by one.",
+ "uso_apri": "usage: {cmd} open NAME[,NAME\u2026]|--larghe \"<why>\"",
+ "uso_deposita": "usage: {cmd} deposit NAME[,NAME\u2026] \"<what it is for>\" [--larga] [--dal-file FILE] (one name only: the value from stdin)",
+ "deposito_senza_chiave": "The vault has no deposit key yet: the app creates it when the administrator opens the vault from their device. Tell them, then run it again.",
+ "deposito_firma": "\u274c The deposit key does not carry the vault's signature: I encrypt nothing for it. Warn the administrator.",
+ "deposito_vuoto": "\u274c {nome}: no value (empty stdin, or not in the file). Nothing deposited.",
+ "deposito_stdin": "\u274c With several names the value does not come from stdin: use --dal-file FILE.",
+ "depositato": "\U0001f4e5 Deposited {nome}, encrypted for the vault: it becomes a secret when the administrator accepts it in the app. Tell them in chat too.",
+ "non_concessa": "\u274c The secrets did not arrive (denied, expired or not granted yet): nothing to do.",
+ "chiesta_tua": "\U0001f511 Request sent to the user's phone: {nomi}. It's their secret: they grant it from the app, on their phone. Tell them in the chat too.",
+ "finestra_chiesta_tua": "\U0001f511 Time-bound access requested from the user for {n} of their secrets ({minuti} minutes from approval): they approve it in the app, on their phone. Tell them in chat too.",
+ "impronta_tua": " Request fingerprint: {impronta} \u2014 in the app, on their phone, the user sees the same one."
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+class Rifiuto(Exception):
+
+ def __init__(self, messaggio: str, stato: int=0):
+ super().__init__(messaggio)
+ self.stato = stato
+_P = 2 ** 255 - 19
+_A24 = 121665
+
+def x25519(k: bytes, u: bytes) -> bytes:
+ kk = bytearray(k)
+ kk[0] &= 248
+ kk[31] &= 127
+ kk[31] |= 64
+ n = int.from_bytes(bytes(kk), 'little')
+ x1 = int.from_bytes(u, 'little') & (1 << 255) - 1
+ x2, z2, x3, z3 = (1, 0, x1, 1)
+ swap = 0
+ for t in reversed(range(255)):
+ kt = n >> t & 1
+ if swap ^ kt:
+ x2, x3, z2, z3 = (x3, x2, z3, z2)
+ swap = kt
+ a, b = ((x2 + z2) % _P, (x2 - z2) % _P)
+ aa, bb = (a * a % _P, b * b % _P)
+ e = (aa - bb) % _P
+ c, d = ((x3 + z3) % _P, (x3 - z3) % _P)
+ da, cb = (d * a % _P, c * b % _P)
+ x3, z3 = ((da + cb) ** 2 % _P, x1 * (da - cb) ** 2 % _P)
+ x2, z2 = (aa * bb % _P, e * (aa + _A24 * e) % _P)
+ if swap:
+ x2, z2 = (x3, z3)
+ return (x2 * pow(z2, _P - 2, _P) % _P).to_bytes(32, 'little')
+_Q = 115792089210356248762697446949407573530086143415290314195533631308867097853951
+_B = 41058363725152142129326129780047268409114441015993725554835256314039467401291
+_N = 115792089210356248762697446949407573529996955224135760342422259061068512044369
+_G = (48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109)
+
+def _somma(p1, p2):
+ if p1 is None:
+ return p2
+ if p2 is None:
+ return p1
+ if p1[0] == p2[0] and (p1[1] + p2[1]) % _Q == 0:
+ return None
+ if p1 == p2:
+ m = 3 * (p1[0] * p1[0] - 1) * pow(2 * p1[1], _Q - 2, _Q) % _Q
+ else:
+ m = (p2[1] - p1[1]) * pow(p2[0] - p1[0], _Q - 2, _Q) % _Q
+ x = (m * m - p1[0] - p2[0]) % _Q
+ return (x, (m * (p1[0] - x) - p1[1]) % _Q)
+
+def _per(k: int, p):
+ r = None
+ while k:
+ if k & 1:
+ r = _somma(r, p)
+ p = _somma(p, p)
+ k >>= 1
+ return r
+
+def verifica_firma(pub: bytes, messaggio: bytes, firma: bytes) -> bool:
+ if len(pub) != 65 or pub[0] != 4 or len(firma) != 64:
+ return False
+ x, y = (int.from_bytes(pub[1:33], 'big'), int.from_bytes(pub[33:], 'big'))
+ if not (x < _Q and y < _Q) or (y * y - x * x * x + 3 * x - _B) % _Q:
+ return False
+ r, s = (int.from_bytes(firma[:32], 'big'), int.from_bytes(firma[32:], 'big'))
+ if not (0 < r < _N and 0 < s < _N):
+ return False
+ z = int.from_bytes(hashlib.sha256(messaggio).digest(), 'big')
+ w = pow(s, _N - 2, _N)
+ punto = _somma(_per(z * w % _N, _G), _per(r * w % _N, (x, y)))
+ return punto is not None and punto[0] % _N == r
+
+def pubblica(privata: bytes) -> bytes:
+ return x25519(privata, 9 .to_bytes(32, 'little'))
+
+def hkdf(chiave: bytes, sale: bytes, info: bytes, lunghezza: int) -> bytes:
+ prk = hmac.new(sale, chiave, hashlib.sha256).digest()
+ out, blocco, i = (b'', b'', 1)
+ while len(out) < lunghezza:
+ blocco = hmac.new(prk, blocco + info + bytes([i]), hashlib.sha256).digest()
+ out += blocco
+ i += 1
+ return out[:lunghezza]
+
+def flusso(chiave: bytes, n: int) -> bytes:
+ out = b''
+ i = 0
+ while len(out) < n:
+ out += hmac.new(chiave, i.to_bytes(8, 'big'), hashlib.sha256).digest()
+ i += 1
+ return out[:n]
+
+def chiavi(condiviso: bytes, pub_client: bytes, eph: bytes, rid: str) -> tuple[bytes, bytes]:
+ k = hkdf(condiviso, pub_client + eph, INFO + b':' + rid.encode(), 64)
+ return (k[:32], k[32:])
+
+def apri(privata: bytes, pub_client: bytes, rid: str, consegna: dict, firma_pub: bytes, nomi: list[str]) -> dict:
+ eph, ct, tag, firma = (_b64d(consegna.get(x, '')) for x in ('eph', 'ct', 'tag', 'firma'))
+ if len(eph) != 32 or len(tag) != 32:
+ raise Rifiuto(F('consegna_rotta'))
+ if not verifica_firma(firma_pub, FIRMA + rid.encode() + pub_client + eph + ct + tag, firma):
+ raise Rifiuto(F('firma_falsa'))
+ condiviso = x25519(privata, eph)
+ if condiviso == bytes(32):
+ raise Rifiuto(F('consegna_rotta'))
+ k_cifra, k_tag = chiavi(condiviso, pub_client, eph, rid)
+ if not hmac.compare_digest(hmac.new(k_tag, eph + ct, hashlib.sha256).digest(), tag):
+ raise Rifiuto(F('consegna_rotta'))
+ chiaro = bytes((a ^ b for a, b in zip(ct, flusso(k_cifra, len(ct)))))
+ try:
+ valori = json.loads(chiaro.decode('utf-8'))
+ except (UnicodeDecodeError, ValueError):
+ raise Rifiuto(F('consegna_rotta')) from None
+ if not isinstance(valori, dict) or not all((isinstance(v, str) for v in valori.values())):
+ raise Rifiuto(F('consegna_rotta'))
+ if set(valori) != set(nomi):
+ raise Rifiuto(F('nomi_diversi'))
+ return valori
+
+def vietato(nome: str) -> bool:
+ return not NOME_RE.match(nome) or nome in NOMI_VIETATI or nome.startswith(PREFISSI_VIETATI)
+
+def _firme() -> tuple[str, dict]:
+ percorso = os.path.join(_sospese(), 'firme.json')
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ return (percorso, json.load(f))
+ except (OSError, ValueError):
+ return (percorso, {})
+
+def _di_chi() -> str:
+ return hashlib.sha256(TOKEN.encode()).hexdigest()[:16]
+
+def _spazio() -> str:
+ try:
+ pezzo = TOKEN.split('.')[1]
+ cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
+ except (IndexError, ValueError, AttributeError):
+ cli = ''
+ return URL if cli in ('', 'unico') else f'{URL}#{cli}'
+
+def _segue_la_catena(da: str, a: str, passaggi) -> bool:
+ passaggi = [x for x in passaggi or [] if isinstance(x, dict)]
+ adesso = da
+ for _ in range(len(passaggi)):
+ p = next((x for x in passaggi if x.get('da') == adesso), None)
+ try:
+ if p is None or not verifica_firma(_b64d(adesso), (FIRMA_PASSAGGIO + str(p.get('a'))).encode(), _b64d(str(p.get('firma') or ''))):
+ return False
+ except (ValueError, TypeError):
+ return False
+ adesso = str(p['a'])
+ if adesso == a:
+ return True
+ return False
+
+def firma_ricordata(pub_b64: str, passaggi=None) -> bytes:
+ percorso, note = _firme()
+ if not pub_b64:
+ raise Rifiuto(F('firma_falsa'))
+ vista = note.get(_spazio())
+ if vista and vista != pub_b64 and (not _segue_la_catena(vista, pub_b64, passaggi)):
+ raise Rifiuto(F('firma_cambiata', file=percorso))
+ return _b64d(pub_b64)
+
+def ricorda_firma(pub_b64: str) -> None:
+ percorso, note = _firme()
+ if note.get(_spazio()) == pub_b64:
+ return
+ note[_spazio()] = pub_b64
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump(note, f)
+
+def impronta_richiesta(pub: bytes) -> str:
+ h = hashlib.sha256(pub).hexdigest()[:8].upper()
+ return h[:4] + '-' + h[4:]
+
+def _b64(b: bytes) -> str:
+ return base64.b64encode(b).decode()
+
+def _b64d(s: str) -> bytes:
+ try:
+ return base64.b64decode(s.replace('-', '+').replace('_', '/') + '=' * (-len(s) % 4))
+ except (ValueError, TypeError):
+ return b''
+
+def _ambiente() -> tuple[str, str, str]:
+ try:
+ out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines()
+ except (OSError, subprocess.TimeoutExpired):
+ out = []
+ url, file_token, sessione = (out + ['', '', ''])[:3]
+ try:
+ with open(file_token, encoding='utf-8') as f:
+ token = f.read().strip()
+ except OSError:
+ token = ''
+ if not url or not token:
+ raise Rifiuto(F('non_collegato'))
+ return (url.rstrip('/'), token, sessione)
+URL, TOKEN, SESSIONE = ('', '', '')
+
+def _http(metodo: str, percorso: str, corpo: dict | None=None) -> dict:
+ dati = json.dumps(corpo).encode() if corpo is not None else None
+ req = urllib.request.Request(f'{URL}/api/cassaforte{percorso}', data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return json.loads(r.read().decode())
+ except urllib.error.HTTPError as e:
+ raw = e.read().decode()
+ try:
+ msg = json.loads(raw).get('error', raw)
+ except ValueError:
+ msg = raw
+ raise Rifiuto(f'❌ {msg}', e.code) from None
+ except (urllib.error.URLError, OSError) as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
+
+def _sospese() -> str:
+ d = os.path.join(os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache'), 'delminio-cassaforte')
+ os.makedirs(d, mode=448, exist_ok=True)
+ os.chmod(d, 448)
+ return d
+
+def _impronta(nomi: list[str], perche: str, comando: list[str]) -> str:
+ return hashlib.sha256(json.dumps([URL, nomi, perche, comando]).encode()).hexdigest()[:32]
+
+def _riprendi(chiave: str) -> dict | None:
+ try:
+ with open(os.path.join(_sospese(), chiave), encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return None
+
+def _metti_da_parte(chiave: str, dati: dict) -> None:
+ percorso = os.path.join(_sospese(), chiave)
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump(dati, f)
+
+def _dimentica(chiave: str) -> None:
+ try:
+ os.remove(os.path.join(_sospese(), chiave))
+ except OSError:
+ pass
+
+def _finestre_dir() -> str:
+ run = os.environ.get('XDG_RUNTIME_DIR') or ''
+ d = os.path.join(run, 'delminio-cassaforte') if run and os.path.isdir(run) else os.path.join(_sospese(), 'finestre')
+ os.makedirs(d, mode=448, exist_ok=True)
+ os.chmod(d, 448)
+ return d
+
+def _ora(iso: str) -> str:
+ try:
+ from datetime import datetime
+ return datetime.fromisoformat(iso).astimezone().strftime('%H:%M')
+ except (TypeError, ValueError):
+ return '?'
+
+def _finestre() -> list[dict]:
+ from datetime import datetime, timezone
+ adesso = datetime.now(timezone.utc)
+ vive = []
+ cartella = _finestre_dir()
+ for nome in sorted(os.listdir(cartella)):
+ percorso = os.path.join(cartella, nome)
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ w = json.load(f)
+ finita = datetime.fromisoformat(w['scade']) <= adesso
+ except (OSError, ValueError, KeyError, TypeError):
+ finita = True
+ w = {}
+ if finita:
+ try:
+ os.remove(percorso)
+ except OSError:
+ pass
+ elif w.get('spazio') == _spazio() and w.get('token') == _di_chi():
+ w['_file'] = percorso
+ vive.append(w)
+ return vive
+
+def _togli_finestra(w: dict) -> None:
+ try:
+ os.remove(w['_file'])
+ except (OSError, KeyError):
+ pass
+
+def _dalla_finestra(nomi: list[str], comando: str) -> dict | None:
+ for w in _finestre():
+ if not set(nomi) <= set(w['nomi']):
+ continue
+ try:
+ r = _http('GET', '/richiesta/' + urllib.parse.quote(w['id']) + '?comando=' + urllib.parse.quote(comando[:500]))
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ continue
+ if not r.get('consegna'):
+ _togli_finestra(w)
+ print(F('finestra_finita'), file=sys.stderr)
+ continue
+ firma_pub = r.get('firma_pub') or ''
+ valori = apri(_b64d(w['privata']), _b64d(w['pub']), w['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), w['nomi'])
+ print(F('finestra_usata', ora=_ora(w['scade'])), file=sys.stderr)
+ return {n: valori[n] for n in nomi}
+ return None
+
+def elenco() -> int:
+ d = _http('GET', '/elenco')
+ if not d.get('esiste'):
+ print(F('nessuna_cassaforte'))
+ return 0
+ if not d.get('segreti'):
+ print(F('nessun_segreto'))
+ return 0
+ for s in d['segreti']:
+ print(f" {s['nome']}" + (F('segno_larga') if s.get('larga') else '') + (f" — {s['nota']}" if s.get('nota') else ''))
+ return 0
+
+def proponi(argomenti: list[str]) -> int:
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_proponi', cmd=CMD))
+ nome = argomenti[0].strip()
+ if vietato(nome):
+ raise Rifiuto(F('nome_vietato', nome=nome))
+ _http('POST', '/proponi', {'nome': nome, 'nota': ' '.join(argomenti[1:]), 'sessione': SESSIONE})
+ print(F('proposta', nome=nome))
+ return 0
+
+def _nomi(testo: str) -> list[str]:
+ nomi = list(dict.fromkeys((n for n in testo.replace(' ', ',').split(',') if n)))
+ for n in nomi:
+ if vietato(n):
+ raise Rifiuto(F('nome_vietato', nome=n))
+ return nomi
+
+def _attendi(nomi: list[str], perche: str, comando: list[str], finestra: bool):
+ chiave = _impronta(nomi, perche, (['--finestra'] if finestra else []) + comando)
+ sospesa = _riprendi(chiave)
+ gia = None
+ if sospesa is not None:
+ try:
+ gia = _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ _dimentica(chiave)
+ sospesa = None
+ if sospesa is not None and (not gia.get('consegna')) and (gia.get('stato') in ('scaduta', 'ritirata', 'chiusa')):
+ _dimentica(chiave)
+ sospesa, gia = (None, None)
+ if sospesa is None:
+ privata = os.urandom(32)
+ pub = pubblica(privata)
+ r = _http('POST', '/chiedi', {'nomi': nomi, 'perche': perche, 'comando': shlex.join(comando), 'sessione': SESSIONE, 'pub': _b64(pub), 'finestra': finestra})
+ sospesa = {'id': r['id'], 'privata': _b64(privata), 'pub': _b64(pub), 'tua': r.get('decide') == 'tu'}
+ _metti_da_parte(chiave, sospesa)
+ tua = sospesa['tua']
+ minuti = (r.get('finestra_s') or 0) // 60
+ if finestra:
+ print(F('finestra_chiesta_tua', n=len(nomi), minuti=minuti) if tua else F('finestra_chiesta', n=len(nomi), minuti=minuti), file=sys.stderr)
+ else:
+ print(F('chiesta_tua', nomi=', '.join(nomi)) if tua else F('chiesta', nomi=', '.join(nomi)), file=sys.stderr)
+ imp = impronta_richiesta(_b64d(sospesa['pub']))
+ print(F('impronta_tua', impronta=imp) if sospesa.get('tua') else F('impronta', impronta=imp), file=sys.stderr)
+ print(F('aspetto', secondi=ATTESA_S), file=sys.stderr)
+ fine = time.monotonic() + ATTESA_S
+ while True:
+ r = gia if gia is not None else _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
+ gia = None
+ stato = r.get('stato')
+ if r.get('consegna'):
+ _dimentica(chiave)
+ firma_pub = r.get('firma_pub') or ''
+ valori = apri(_b64d(sospesa['privata']), _b64d(sospesa['pub']), sospesa['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), nomi)
+ ricorda_firma(firma_pub)
+ return (sospesa, r, valori)
+ if stato == 'negata':
+ _dimentica(chiave)
+ parole = r.get('parole') or ''
+ print(F('negata', chi=r.get('deciso_da') or '?', parole=f': «{parole}»' if parole else ''), file=sys.stderr)
+ return 3
+ if stato in ('scaduta', 'ritirata', 'chiusa'):
+ _dimentica(chiave)
+ print(F('scaduta'), file=sys.stderr)
+ return 3
+ if time.monotonic() > fine:
+ print(F('ancora_niente'), file=sys.stderr)
+ return 4
+ time.sleep(2)
+
+def valori(nomi: list[str], perche: str, comando: str) -> dict:
+ global URL, TOKEN, SESSIONE
+ if not URL:
+ URL, TOKEN, SESSIONE = _ambiente()
+ nomi = _nomi(','.join(nomi))
+ dalla = _dalla_finestra(nomi, comando)
+ if dalla is not None:
+ return dalla
+ esito = _attendi(nomi, perche, shlex.split(comando) or [comando], False)
+ if isinstance(esito, int):
+ raise Rifiuto(F('non_concessa'), esito)
+ print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
+ return esito[2]
+
+def chiedi(argomenti: list[str]) -> int:
+ if '--' not in argomenti or argomenti.index('--') < 2:
+ raise Rifiuto(F('uso_chiedi', cmd=CMD))
+ i = argomenti.index('--')
+ nomi = _nomi(argomenti[0])
+ perche = ' '.join(argomenti[1:i])
+ comando = argomenti[i + 1:]
+ if not comando:
+ raise Rifiuto(F('comando_mancante'))
+ dati = _dalla_finestra(nomi, shlex.join(comando))
+ if dati is None:
+ esito = _attendi(nomi, perche, comando, False)
+ if isinstance(esito, int):
+ return esito
+ print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
+ dati = esito[2]
+ sys.stderr.flush()
+ os.execvpe(comando[0], comando, dict(os.environ, **dati))
+
+def apri_finestra(argomenti: list[str]) -> int:
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_apri', cmd=CMD))
+ if argomenti[0] == '--larghe':
+ nomi = [s['nome'] for s in _http('GET', '/elenco').get('segreti', []) if s.get('larga')]
+ if not nomi:
+ raise Rifiuto(F('nessuna_larga'))
+ else:
+ nomi = _nomi(argomenti[0])
+ esito = _attendi(nomi, ' '.join(argomenti[1:]), [], True)
+ if isinstance(esito, int):
+ return esito
+ sospesa, r, _ = esito
+ scade = r.get('scade') or ''
+ percorso = os.path.join(_finestre_dir(), 'finestra-' + hashlib.sha256(_spazio().encode()).hexdigest()[:8] + '-' + re.sub('[^A-Za-z0-9_-]', '', sospesa['id']) + '.json')
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump({**sospesa, 'nomi': nomi, 'scade': scade, 'spazio': _spazio(), 'token': _di_chi()}, f)
+ print(F('finestra_aperta', chi=r.get('deciso_da') or '?', ora=_ora(scade), nomi=', '.join(nomi)), file=sys.stderr)
+ return 0
+
+def finestre() -> int:
+ vive = _finestre()
+ if not vive:
+ print(F('finestre_nessuna'))
+ for w in vive:
+ print(F('finestra_riga', ora=_ora(w['scade']), nomi=', '.join(w['nomi'])))
+ return 0
+
+def chiudi() -> int:
+ n = 0
+ for w in _finestre():
+ try:
+ _http('POST', '/richiesta/' + urllib.parse.quote(w['id']) + '/chiudi', {})
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ _togli_finestra(w)
+ n += 1
+ print(F('finestre_chiuse', n=n))
+ return 0
+
+def _da_file(percorso: str, nomi: list[str]) -> dict:
+ trovati = {}
+ with open(percorso, encoding='utf-8') as f:
+ for riga in f:
+ riga = riga.strip()
+ k, uguale, v = riga.partition('=')
+ if uguale and k.strip() in nomi:
+ trovati[k.strip()] = v.strip().strip('\'"')
+ return trovati
+
+def cifra_deposito(pub: bytes, nome: str, valore: str) -> dict:
+ privata = os.urandom(32)
+ eph = pubblica(privata)
+ condiviso = x25519(privata, pub)
+ if condiviso == bytes(32):
+ raise Rifiuto(F('deposito_firma'))
+ k = hkdf(condiviso, pub + eph, INFO + b':deposito:' + nome.encode(), 64)
+ dati = valore.encode('utf-8')
+ ct = bytes((a ^ b for a, b in zip(dati, flusso(k[:32], len(dati)))))
+ tag = hmac.new(k[32:], eph + ct, hashlib.sha256).digest()
+ return {'eph': _b64(eph), 'ct': _b64(ct), 'tag': _b64(tag)}
+
+def deposita(argomenti: list[str]) -> int:
+ larga = '--larga' in argomenti
+ argomenti = [a for a in argomenti if a != '--larga']
+ file = None
+ if '--dal-file' in argomenti:
+ i = argomenti.index('--dal-file')
+ if i + 1 >= len(argomenti):
+ raise Rifiuto(F('uso_deposita', cmd=CMD))
+ file = argomenti[i + 1]
+ argomenti = argomenti[:i] + argomenti[i + 2:]
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_deposita', cmd=CMD))
+ nomi, nota = (_nomi(argomenti[0]), ' '.join(argomenti[1:]))
+ d = _http('GET', '/elenco')
+ if not d.get('esiste'):
+ raise Rifiuto(F('nessuna_cassaforte'))
+ dep = d.get('deposito') or {}
+ if not dep.get('pub'):
+ raise Rifiuto(F('deposito_senza_chiave'))
+ fp = firma_ricordata(dep.get('firma_pub') or '', dep.get('passaggi'))
+ if not verifica_firma(fp, (FIRMA_DEPOSITO + dep['pub']).encode(), _b64d(dep.get('firma') or '')):
+ raise Rifiuto(F('deposito_firma'))
+ ricorda_firma(dep['firma_pub'])
+ if file:
+ trovati = _da_file(file, nomi)
+ elif len(nomi) == 1:
+ trovati = {nomi[0]: sys.stdin.read().rstrip('\n')}
+ else:
+ raise Rifiuto(F('deposito_stdin'))
+ for n in nomi:
+ if not trovati.get(n):
+ raise Rifiuto(F('deposito_vuoto', nome=n))
+ pub = _b64d(dep['pub'])
+ for n in nomi:
+ _http('POST', '/proponi', {'nome': n, 'nota': nota, 'sessione': SESSIONE, 'larga': larga, 'deposito': cifra_deposito(pub, n, trovati[n]), 'per': dep['pub']})
+ print(F('depositato', nome=n))
+ return 0
+
+def main(argv: list[str]) -> int:
+ global URL, TOKEN, SESSIONE
+ if not argv or argv[0] in ('aiuto', 'help', '-h', '--help'):
+ print(F('aiuto', cmd=CMD))
+ return 0
+ try:
+ URL, TOKEN, SESSIONE = _ambiente()
+ gesti = {'elenco': lambda: elenco(), 'proponi': lambda: proponi(argv[1:]), 'apri': lambda: apri_finestra(argv[1:]), 'finestre': lambda: finestre(), 'chiudi': lambda: chiudi(), 'deposita': lambda: deposita(argv[1:])}
+ if argv[0] in gesti:
+ return gesti[argv[0]]()
+ return chiedi(argv)
+ except Rifiuto as e:
+ print(str(e), file=sys.stderr)
+ return 1
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/en/consumi-client b/kit/en/consumi-client
new file mode 100644
index 0000000..061d4e7
--- /dev/null
+++ b/kit/en/consumi-client
@@ -0,0 +1,477 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""I token di una conversazione, letti dalla CLI e mai il testo (F868)."""
+import glob, json, os, re, sys
+POSTA = re.compile('^ \\S+ → \\S+ \\d\\d:\\d\\d UTC$', re.M)
+stato_f = sys.argv[1]
+try:
+ e = json.load(sys.stdin)
+ p = e.get('transcript_path') or ''
+ dim = os.path.getsize(p)
+except Exception:
+ sys.exit(0)
+try:
+ st = json.load(open(stato_f))
+except Exception:
+ st = {}
+oc = e.get('cli') == 'opencode'
+sid_oc = str(e.get('session_id') or '')
+chiave = p + '#' + sid_oc if oc else p
+if st.get('p') != chiave or (not oc and st.get('off', 0) > dim):
+ st = {'p': chiave, 'off': 0, 'cli': '', 'mod': '', 't': {}, 'id': '', 'u': {}, 'n': 0}
+t = st['t']
+
+def oc_testo(x):
+ if isinstance(x, str):
+ return x
+ if isinstance(x, list):
+ return ''.join((oc_testo(b) for b in x))
+ if isinstance(x, dict):
+ return str(x.get('text') or x.get('output') or '')
+ return ''
+
+def oc_risposta(mid, modello, tok, blocchi, risultati):
+ tok = tok or {}
+ cache = tok.get('cache') or {}
+ u = {'input_tokens': int(tok.get('input') or 0), 'cache_read_input_tokens': int(cache.get('read') or 0), 'cache_creation_input_tokens': int(cache.get('write') or 0), 'output_tokens': int(tok.get('output') or 0) + int(tok.get('reasoning') or 0)}
+ out = [{'type': 'assistant', 'message': {'id': mid, 'model': modello, 'usage': u, 'content': blocchi}}]
+ if risultati:
+ out.append({'type': 'user', 'message': {'content': risultati}})
+ return out
+
+def oc_umano(parti):
+ out = []
+ for x in parti:
+ if x.get('type') != 'text' or not x.get('text'):
+ continue
+ if x.get('synthetic'):
+ out.append({'type': 'attachment', 'attachment': {'type': 'hook_additional_context', 'hookEvent': 'opencode', 'content': x['text']}})
+ else:
+ out.append({'type': 'user', 'message': {'content': [{'type': 'text', 'text': x['text']}]}})
+ return out
+
+def oc_righe(db, sid, dopo):
+ import sqlite3
+ righe, fino = ([], list(dopo or [0, '']))
+ try:
+ c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
+ except sqlite3.Error:
+ return (righe, fino)
+ try:
+ tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
+ dove = 'session_id=? and (time_created>? or (time_created=? and id>?)) order by time_created, id'
+ arg = (sid, fino[0], fino[0], fino[1])
+ if 'session_message' in tabelle:
+ for mid, tc, tipo, d in c.execute('select id, time_created, type, data from session_message where ' + dove, arg).fetchall():
+ m = json.loads(d)
+ if tipo == 'assistant':
+ if not (m.get('time') or {}).get('completed'):
+ break
+ mod = m.get('model') or {}
+ modello = (str(mod.get('providerID') or '') + '/' + str(mod.get('id') or '')).strip('/')
+ blocchi, ris = ([], [])
+ for x in m.get('content') or []:
+ k = x.get('type')
+ if k == 'tool':
+ s = x.get('state') or {}
+ blocchi.append({'type': 'tool_use', 'id': x.get('id'), 'name': x.get('name'), 'input': s.get('input') or {}})
+ if s.get('status') in ('completed', 'error'):
+ ris.append({'type': 'tool_result', 'tool_use_id': x.get('id'), 'content': oc_testo(s.get('content') or s.get('error') or '')})
+ elif k == 'text':
+ blocchi.append({'type': 'text', 'text': x.get('text') or ''})
+ elif k == 'reasoning':
+ blocchi.append({'type': 'thinking', 'thinking': oc_testo(x.get('text') or x.get('content'))})
+ righe += oc_risposta(mid, modello, m.get('tokens'), blocchi, ris)
+ elif tipo == 'user':
+ righe += oc_umano([{'type': 'text', 'text': m.get('text') or ''}])
+ elif (tx := oc_testo(m.get('text') or m.get('content'))):
+ righe += oc_umano([{'type': 'text', 'text': tx, 'synthetic': True}])
+ fino = [tc, mid]
+ except (sqlite3.Error, ValueError):
+ pass
+ finally:
+ c.close()
+ return (righe, fino)
+
+def oc_figlie(db, sid):
+ import sqlite3
+ try:
+ c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
+ except sqlite3.Error:
+ return []
+ try:
+ tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
+ figli = {}
+ for tab in ('session', 'session_v2'):
+ if tab in tabelle:
+ for i, padre in c.execute('select id, parent_id from ' + tab + ' where parent_id is not null'):
+ figli.setdefault(padre, []).append(i)
+ except sqlite3.Error:
+ return []
+ finally:
+ c.close()
+ out, coda = ([], [sid])
+ while coda:
+ for i in figli.get(coda.pop(), []):
+ if i not in out:
+ out.append(i)
+ coda.append(i)
+ return out
+
+def somma(d):
+ for k, v in d.items():
+ t[k] = t.get(k, 0) + int(v or 0)
+import re
+_CAR_PER_TOKEN = 3.2
+_FONTI_MAX = 64
+_COMANDO_DELMINIO = re.compile('(?:^|[\\s;&|(\\"\\x27])delminio\\s+[a-z]|delminio\\.sh\\b')
+
+def _fonti_lungo(x):
+ if isinstance(x, str):
+ return len(x)
+ if isinstance(x, list):
+ return sum((6000 if isinstance(b, dict) and b.get('type') == 'image' else _fonti_lungo(b) for b in x))
+ if isinstance(x, dict) and x.get('type') == 'text':
+ return len(x.get('text') or '')
+ return len(json.dumps(x, ensure_ascii=False))
+
+def _fonti_tool(nome, argomenti):
+ nome = str(nome or '?')
+ if 'delminio' in nome.lower():
+ op = argomenti.get('operation') if isinstance(argomenti, dict) else None
+ return 'delminio:' + str(op or nome.rsplit('__', 1)[-1])[:30]
+ testo = argomenti if isinstance(argomenti, str) else json.dumps(argomenti, ensure_ascii=False)
+ if nome in ('Bash', 'bash', 'exec_command', 'shell', 'exec', 'run_shell_command') or 'shell' in nome.lower():
+ return 'delminio:comando' if _COMANDO_DELMINIO.search(testo or '') else 'comando'
+ if nome.startswith('mcp__'):
+ return 'mcp:' + nome.split('__')[1][:30]
+ return 'tool:' + nome[:30]
+
+def fonti_nuovo():
+ return {'E': {}, 'R': {}, 'G': {}, 'pend': [], 'dopo': [], 'tid': {}, 'prev': 0, 'n': 0, 'ultimo': None}
+
+def _fonti_pezzo(a, fonte, car):
+ if car > 0:
+ a['pend'].append([fonte, int(car)])
+
+def _fonti_risposta(a, ctx, pezzi):
+ E = a['E']
+ if a['n'] == 0:
+ stima = {}
+ for f, c in pezzi:
+ stima[f] = stima.get(f, 0) + c / _CAR_PER_TOKEN
+ tot = sum(stima.values())
+ scala = min(1.0, ctx / tot) if tot else 0
+ for f, v in stima.items():
+ E[f] = E.get(f, 0) + v * scala
+ E['sistema'] = E.get('sistema', 0) + max(0, ctx - tot * scala)
+ elif ctx < a['prev']:
+ scala = ctx / a['prev']
+ for f in E:
+ E[f] *= scala
+ else:
+ delta = ctx - a['prev']
+ car = sum((c for _, c in pezzi))
+ if not car:
+ E['altro'] = E.get('altro', 0) + delta
+ for f, c in pezzi:
+ E[f] = E.get(f, 0) + delta * c / car if car else E.get(f, 0)
+ for f, v in E.items():
+ a['R'][f] = a['R'].get(f, 0) + v
+ motori = sorted({f for f, _ in pezzi if f.split(':')[0] in ('delminio', 'comando', 'tool', 'mcp')})
+ if not motori:
+ motori = ['persona'] if any((f == 'persona' for f, _ in pezzi)) else ['altro']
+ for f in motori:
+ a['G'][f] = a['G'].get(f, 0) + ctx / len(motori)
+ a['prev'] = ctx
+ a['n'] += 1
+
+def fonti_riga(a, d):
+ t = d.get('type')
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if t == 'attachment' and isinstance(d.get('attachment'), dict):
+ at = d['attachment']
+ k = str(at.get('type') or '')
+ if k == 'hook_additional_context':
+ _fonti_pezzo(a, 'gancio:' + str(at.get('hookEvent') or '?')[:30], _fonti_lungo(at.get('content') or ''))
+ elif k not in ('hook_success', 'prompt_snapshot', ''):
+ _fonti_pezzo(a, 'cli:' + k[:40], _fonti_lungo({x: y for x, y in at.items() if x != 'type'}))
+ return
+ if t == 'user' and isinstance(d.get('message'), dict) and (not d.get('isSidechain')):
+ c = d['message'].get('content')
+ if isinstance(c, str):
+ _fonti_pezzo(a, 'cli:meta' if d.get('isMeta') else 'persona', len(c))
+ return
+ for b in c if isinstance(c, list) else []:
+ if not isinstance(b, dict):
+ continue
+ if b.get('type') == 'tool_result':
+ _fonti_pezzo(a, a['tid'].pop(b.get('tool_use_id'), 'tool:?'), _fonti_lungo(b.get('content') or ''))
+ elif b.get('type') == 'text':
+ x = b.get('text') or ''
+ f = 'gancio:posta' if POSTA.search(x) else 'cli:promemoria' if '<system-reminder>' in x or d.get('isMeta') else 'persona'
+ _fonti_pezzo(a, f, len(x))
+ elif b.get('type') == 'image':
+ _fonti_pezzo(a, 'persona', 6000)
+ return
+ if t == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict) and (not d.get('isSidechain')):
+ m = d['message']
+ if m.get('id') != a['ultimo']:
+ u = m['usage']
+ a['ultimo'] = m.get('id')
+ _fonti_risposta(a, int(u.get('input_tokens') or 0) + int(u.get('cache_read_input_tokens') or 0) + int(u.get('cache_creation_input_tokens') or 0), a['pend'])
+ a['pend'] = []
+ for b in m.get('content') or []:
+ if not isinstance(b, dict):
+ continue
+ if b.get('type') == 'tool_use':
+ a['tid'][b.get('id')] = _fonti_tool(b.get('name'), b.get('input') or {})
+ _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(b.get('input') or {}))
+ elif b.get('type') == 'thinking':
+ _fonti_pezzo(a, 'modello:pensiero', len(b.get('thinking') or '') or len(b.get('signature') or '') // 2)
+ elif b.get('type') == 'text':
+ _fonti_pezzo(a, 'modello:testo', len(b.get('text') or ''))
+ return
+ if t == 'assistant' and isinstance(d.get('usageMetadata'), dict):
+ _fonti_risposta(a, int(d['usageMetadata'].get('promptTokenCount') or 0), a['pend'])
+ a['pend'] = []
+ for p in (d.get('message') or {}).get('parts') or []:
+ if not isinstance(p, dict):
+ continue
+ if isinstance(p.get('functionCall'), dict):
+ fc = p['functionCall']
+ a['tid'][fc.get('id') or fc.get('name')] = _fonti_tool(fc.get('name'), fc.get('args') or {})
+ _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(fc.get('args') or {}))
+ elif p.get('text'):
+ _fonti_pezzo(a, 'modello:pensiero' if p.get('thought') else 'modello:testo', len(p['text']))
+ return
+ if t == 'tool_result':
+ for p in (d.get('message') or {}).get('parts') or []:
+ fr = p.get('functionResponse') if isinstance(p, dict) else None
+ if isinstance(fr, dict):
+ f = a['tid'].pop(fr.get('id'), None) or a['tid'].pop(fr.get('name'), None) or _fonti_tool(fr.get('name'), {})
+ _fonti_pezzo(a, f, _fonti_lungo(fr.get('response') or ''))
+ return
+ if t == 'user' and isinstance(d.get('message'), dict):
+ for p in d['message'].get('parts') or []:
+ if isinstance(p, dict) and p.get('text'):
+ _fonti_pezzo(a, 'cli:avviso' if d.get('subtype') else 'persona', len(p['text']))
+ return
+ if t == 'session_meta':
+ _fonti_pezzo(a, 'sistema', _fonti_lungo(pl.get('base_instructions') or ''))
+ elif t == 'response_item':
+ k = pl.get('type')
+ if k == 'message':
+ car = _fonti_lungo(pl.get('content') or [])
+ if pl.get('role') == 'assistant':
+ a['dopo'].append(['modello:testo', car])
+ else:
+ testo = json.dumps(pl.get('content') or [], ensure_ascii=False)
+ f = 'persona' if pl.get('role') == 'user' and '<environment_context>' not in testo and ('AGENTS.md' not in testo) else 'cli:istruzioni'
+ _fonti_pezzo(a, f, car)
+ elif k == 'reasoning':
+ a['dopo'].append(['modello:pensiero', len(pl.get('encrypted_content') or '') // 3 or _fonti_lungo(pl.get('summary') or [])])
+ elif k in ('function_call', 'custom_tool_call', 'local_shell_call'):
+ arg = pl.get('arguments') or pl.get('input') or pl.get('action') or {}
+ if isinstance(arg, str):
+ try:
+ arg = json.loads(arg)
+ except ValueError:
+ pass
+ a['tid'][pl.get('call_id')] = _fonti_tool(pl.get('name') or 'shell', arg)
+ a['dopo'].append(['modello:chiamate', _fonti_lungo(arg)])
+ elif k in ('function_call_output', 'custom_tool_call_output', 'local_shell_call_output'):
+ _fonti_pezzo(a, a['tid'].pop(pl.get('call_id'), 'tool:?'), _fonti_lungo(pl.get('output') or ''))
+ elif t == 'event_msg' and pl.get('type') == 'token_count':
+ u = (pl.get('info') or {}).get('last_token_usage') or {}
+ tot = ((pl.get('info') or {}).get('total_token_usage') or {}).get('total_tokens')
+ if u and tot != a.get('tot_codex'):
+ a['tot_codex'] = tot
+ _fonti_risposta(a, int(u.get('input_tokens') or 0), a.pop('prima', []) + a['pend'])
+ a['pend'] = []
+ a['prima'], a['dopo'] = (a['dopo'], [])
+
+def fonti_fuori(a):
+ tutte = sorted(set(a['E']) | set(a['R']) | set(a['G']), key=lambda f: -a['R'].get(f, 0))
+ out, resto = ({}, [0, 0, 0])
+ for i, f in enumerate(tutte):
+ v = [round(a['E'].get(f, 0)), round(a['R'].get(f, 0)), round(a['G'].get(f, 0))]
+ if i < _FONTI_MAX - 1:
+ out[f] = v
+ else:
+ resto = [x + y for x, y in zip(resto, v)]
+ if any(resto):
+ out['altro'] = [x + y for x, y in zip(out.get('altro', [0, 0, 0]), resto)]
+ return {'contesto': int(a['prev']), 'fonti': out}
+
+def righe_testo(testo):
+ for riga in testo.splitlines():
+ try:
+ d = json.loads(riga)
+ except ValueError:
+ continue
+ if isinstance(d, dict):
+ yield d
+a = st.get('a') or fonti_nuovo()
+st['a'] = a
+if oc:
+ nuove, st['oc'] = oc_righe(p, sid_oc, st.get('oc'))
+ fine = 0
+else:
+ with open(p, 'rb') as f:
+ f.seek(st['off'])
+ pezzo = f.read()
+ fine = pezzo.rfind(b'\n') + 1
+ nuove = righe_testo(pezzo[:fine].decode('utf-8', 'replace'))
+for d in nuove:
+ fonti_riga(a, d)
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if d.get('type') == 'turn_context' and pl.get('model'):
+ st['cli'], st['mod'] = ('codex', str(pl['model']))
+ elif pl.get('type') == 'token_count':
+ u = (pl.get('info') or {}).get('total_token_usage') or {}
+ if u:
+ st['cli'] = 'codex'
+ letta = int(u.get('cached_input_tokens') or 0)
+ st['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ st['n'] += 1
+ elif d.get('type') == 'assistant' and isinstance(d.get('usageMetadata'), dict):
+ u = d['usageMetadata']
+ st['cli'], st['mod'] = ('qwen', str(d.get('model') or st['mod']))
+ letta = int(u.get('cachedContentTokenCount') or 0)
+ somma({'input': max(0, int(u.get('promptTokenCount') or 0) - letta), 'cache_letta': letta, 'output': int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0)})
+ st['n'] += 1
+ elif d.get('type') == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict):
+ m = d['message']
+ if m.get('model') and (not str(m['model']).startswith('<')):
+ st['mod'] = str(m['model'])
+ st['cli'] = 'opencode' if oc else 'claude'
+ u = m['usage']
+ nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ if m.get('id') != st['id']:
+ if st['id']:
+ somma(st['u'])
+ st['id'] = m.get('id') or ''
+ st['n'] += 1
+ st['u'] = nuovo
+st['off'] += fine
+for k in list(a['tid'])[:-200]:
+ del a['tid'][k]
+tot = dict(t)
+if st['cli'] in ('claude', 'codex', 'opencode'):
+ for k, v in st['u'].items():
+ tot[k] = (tot.get(k, 0) if st['cli'] != 'codex' else 0) + v
+atteso = sum((tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta')))
+if atteso and abs(sum(a['R'].values()) - atteso) > max(1000, atteso // 100):
+ a = fonti_nuovo()
+ if oc:
+ tutte = oc_righe(p, sid_oc, [0, ''])[0]
+ else:
+ with open(p, 'rb') as f:
+ tutte = righe_testo(f.read(st['off']).decode('utf-8', 'replace'))
+ for d in tutte:
+ fonti_riga(a, d)
+ for k in list(a['tid'])[:-200]:
+ del a['tid'][k]
+ st['a'] = a
+sid = os.path.basename(p).rsplit('.', 1)[0]
+radice = {'claude': os.path.join(os.path.dirname(p), sid, 'subagents'), 'qwen': os.path.join(os.path.dirname(os.path.dirname(p)), 'subagents', sid)}.get(st['cli'])
+ag = st.setdefault('ag', {})
+file_agenti = sorted(glob.glob(os.path.join(radice, '**', 'agent-*.jsonl'), recursive=True)) if radice else []
+if st['cli'] == 'codex':
+ casa = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p))))
+ padri = st.setdefault('padri', {})
+ nato = st.setdefault('nato', os.path.getmtime(p) - 86400)
+ for f in glob.glob(os.path.join(casa, '*', '*', '*', 'rollout-*.jsonl')):
+ if f in padri or f == p:
+ continue
+ try:
+ if os.path.getmtime(f) < nato:
+ continue
+ with open(f, 'rb') as h:
+ m = json.loads(h.readline() or b'{}').get('payload') or {}
+ except (OSError, ValueError):
+ continue
+ sp = ((m.get('source') or {}).get('subagent') or {}).get('thread_spawn') if isinstance(m.get('source'), dict) else None
+ padri[f] = [str(m.get('id') or ''), str((sp or {}).get('parent_thread_id') or '')]
+ try:
+ with open(p, 'rb') as h:
+ mio = str((json.loads(h.readline() or b'{}').get('payload') or {}).get('id') or '')
+ except (OSError, ValueError):
+ mio = ''
+ famiglia, cresce = ({mio or str(e.get('session_id') or '')}, True)
+ while cresce:
+ cresce = False
+ for i, padre in padri.values():
+ if padre in famiglia and i and (i not in famiglia):
+ famiglia.add(i)
+ cresce = True
+ file_agenti = sorted((f for f, (i, padre) in padri.items() if padre in famiglia))
+if oc:
+ file_agenti = ['oc:' + i for i in oc_figlie(p, sid_oc)]
+for f in file_agenti:
+ if f.startswith('oc:'):
+ s = ag.get(f) or {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
+ ag[f] = s
+ righe_ag, s['oc'] = oc_righe(p, f[3:], s.get('oc'))
+ fn = 0
+ else:
+ try:
+ dimf = os.path.getsize(f)
+ except OSError:
+ continue
+ s = ag.get(f)
+ if not s or s['off'] > dimf:
+ s = ag[f] = {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
+ with open(f, 'rb') as h:
+ h.seek(s['off'])
+ pz = h.read()
+ fn = pz.rfind(b'\n') + 1
+ righe_ag = righe_testo(pz[:fn].decode('utf-8', 'replace'))
+ for d in righe_ag:
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if d.get('type') == 'turn_context' and pl.get('model'):
+ s['mod'] = str(pl['model'])
+ elif pl.get('type') == 'token_count' and (pl.get('info') or {}).get('total_token_usage'):
+ u = pl['info']['total_token_usage']
+ letta = int(u.get('cached_input_tokens') or 0)
+ s['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ s['n'] += 1
+ if d.get('type') != 'assistant':
+ continue
+ if isinstance(d.get('usageMetadata'), dict):
+ u = d['usageMetadata']
+ letta = int(u.get('cachedContentTokenCount') or 0)
+ for k, v in (('input', max(0, int(u.get('promptTokenCount') or 0) - letta)), ('cache_letta', letta), ('output', int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0))):
+ s['t'][k] = s['t'].get(k, 0) + v
+ s['n'] += 1
+ s['mod'] = str(d.get('model') or s['mod'])
+ elif isinstance((d.get('message') or {}).get('usage'), dict):
+ m = d['message']
+ u = m['usage']
+ if m.get('model') and (not str(m['model']).startswith('<')):
+ s['mod'] = str(m['model'])
+ nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ if m.get('id') != s['id']:
+ if s['id']:
+ for k, v in s['u'].items():
+ s['t'][k] = s['t'].get(k, 0) + v
+ s['id'] = m.get('id') or ''
+ s['n'] += 1
+ s['u'] = nuovo
+ s['off'] += fn
+agenti = {}
+for s in ag.values():
+ for k in ('input', 'cache_letta', 'cache_scritta', 'output'):
+ agenti[k] = agenti.get(k, 0) + s['t'].get(k, 0) + s['u'].get(k, 0)
+ agenti['risposte'] = agenti.get('risposte', 0) + s['n']
+ agenti['modello'] = s['mod'] or agenti.get('modello', '')
+tmp = stato_f + '.nuovo'
+json.dump(st, open(tmp, 'w'))
+os.replace(tmp, stato_f)
+if not st['cli']:
+ sys.exit(0)
+fuori = {'conversazione': str(e.get('session_id') or os.path.basename(p))[:80], 'cli': st['cli'], 'modello': st['mod'][:80], 'risposte': st['n'], **{k: tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta', 'output')}, **fonti_fuori(a)}
+if agenti.get('risposte'):
+ fuori['agenti'] = {**agenti, 'modello': agenti.get('modello', '')[:80]}
+print(json.dumps(fuori))
diff --git a/kit/en/copia-client b/kit/en/copia-client
new file mode 100644
index 0000000..a3f8af9
--- /dev/null
+++ b/kit/en/copia-client
@@ -0,0 +1,286 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La copia di sicurezza di ciò che c'era prima del collegamento (F777)."""
+import hashlib, json, os, re, shutil, sys, time
+exec(__import__('os').environ['DELMINIO_F_PY'])
+modo, radice, memoria, comune, url, gitdir = sys.argv[1:7]
+casa = os.path.expanduser('~')
+config = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.join(casa, '.claude')
+memoria = os.path.realpath(memoria) if memoria else ''
+
+def leggi(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return {}
+scelta, da = ('', '')
+for f, nome in ((os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(config, 'settings.json'), os.path.join(config, 'settings.json'))):
+ v = leggi(f).get('autoMemoryDirectory')
+ v = os.path.realpath(os.path.expanduser(v)) if isinstance(v, str) and v else ''
+ if v and v != memoria:
+ scelta, da = (v, nome)
+ break
+progetto = os.environ.get('CLAUDE_CODE_PROJECT_DIR_NAME') or re.sub('[^A-Za-z0-9]', '-', comune)
+vecchia = scelta or os.path.join(config, 'projects', progetto, 'memory')
+if modo == 'controlla':
+ if scelta and memoria:
+ print(f'{scelta}\t{da}')
+ sys.exit(0)
+segno_backup = os.path.join(gitdir, 'delminio-backup')
+cartella = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.join(casa, '.local', 'share'), 'delminio', 'backup', (re.sub('[^A-Za-z0-9._-]', '-', os.path.basename(comune)) or 'repo') + '-' + hashlib.sha256(comune.encode()).hexdigest()[:12])
+try:
+ cartella = open(segno_backup, encoding='utf-8').read().strip() or cartella
+except OSError:
+ pass
+
+def una_copia_c_e():
+ for c in (cartella, os.path.join(radice, '.claude', 'delminio-prima')):
+ if os.path.isdir(c) and any((os.path.isfile(os.path.join(c, d, 'fatti.json')) for d in os.listdir(c))):
+ return True
+ return False
+if os.environ.get('DELMINIO_PRIMA_VOLTA') != 'si' and una_copia_c_e():
+ sys.exit(0)
+dest = os.path.join(cartella, time.strftime('%Y-%m-%d-%H%M%S'))
+copie = []
+copiati = []
+non_copiati = []
+peso = 0
+SEGRETO = re.compile('(^|/)(auth\\.json|\\.credentials\\.json|oauth_creds\\.json|credentials(\\.json)?|\\.env(\\.[^/]*)?|[^/]*\\.(token|pem|key|p12|pfx)|id_(rsa|ed25519|ecdsa|dsa)[^/]*|\\.netrc|\\.git-credentials)$', re.I)
+TETTO_FILE = 20 * 1024 * 1024
+TETTO = 200 * 1024 * 1024
+
+def mostra(p):
+ p = os.path.abspath(p)
+ if p == radice or p.startswith(radice + os.sep):
+ return os.path.relpath(p, radice)
+ return '~' + p[len(casa):] if p.startswith(casa + os.sep) else p
+
+def impronta(p):
+ h = hashlib.sha256()
+ with open(p, 'rb') as f:
+ for pezzo in iter(lambda: f.read(1 << 20), b''):
+ h.update(pezzo)
+ return h.hexdigest()
+
+def metti(sorgente, rel, gruppo):
+ global peso
+ if not os.path.isfile(sorgente):
+ return False
+ if SEGRETO.search(sorgente):
+ non_copiati.append({'da': mostra(sorgente), 'perche': 'credenziali'})
+ return False
+ n = os.path.getsize(sorgente)
+ if n > TETTO_FILE or peso + n > TETTO:
+ non_copiati.append({'da': mostra(sorgente), 'perche': 'grande', 'byte': n})
+ return False
+ p = os.path.join(dest, rel)
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ shutil.copy2(sorgente, p)
+ prima, dopo = (impronta(sorgente), impronta(p))
+ if prima != dopo:
+ print(F('prima_copia_diversa', file=mostra(sorgente)), file=sys.stderr)
+ sys.exit(1)
+ peso += n
+ copiati.append({'da': mostra(sorgente), 'copia': rel, 'sha256': prima, 'byte': n, 'gruppo': gruppo})
+ return True
+
+def metti_cartella(d, rel, gruppo):
+ if not os.path.isdir(d):
+ return
+ for su, cartelle, files in os.walk(d):
+ cartelle[:] = sorted((c for c in cartelle if c not in ('.git', 'node_modules')))
+ for f in sorted(files):
+ metti(os.path.join(su, f), os.path.join(rel, os.path.relpath(os.path.join(su, f), d)), gruppo)
+
+def nel_progetto(rel, gruppo):
+ p = os.path.join(radice, rel)
+ if os.path.isdir(p):
+ metti_cartella(p, rel, gruppo)
+ else:
+ metti(p, rel, gruppo)
+
+def in_casa(p, gruppo):
+ p = os.path.abspath(p)
+ rel = os.path.join('casa', os.path.relpath(p, casa)) if p.startswith(casa + os.sep) else os.path.join('fuori', p.lstrip(os.sep))
+ if os.path.isdir(p):
+ metti_cartella(p, rel, gruppo)
+ else:
+ metti(p, rel, gruppo)
+codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
+qwen_casa = os.path.join(casa, '.qwen')
+for rel in (os.environ.get('DELMINIO_KIT_FILE') or '').split() + ['.claude/mneme.sh', '.claude/commands/risveglio.md']:
+ nel_progetto(rel, 'collegamento')
+for g in ('commit-msg', 'post-commit', 'post-rewrite'):
+ metti(os.path.join(os.environ.get('DELMINIO_GANCI') or os.path.join(gitdir, 'hooks'), g), os.path.join('git', 'hooks', g), 'collegamento')
+metti(os.path.join(gitdir, 'info', 'exclude'), os.path.join('git', 'info', 'exclude'), 'collegamento')
+in_casa(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'), 'collegamento')
+for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md', '.github/instructions', '.cursor/rules', '.windsurf/rules', 'memory-bank', '.serena/memories', '.claude/agents', '.claude/skills'):
+ nel_progetto(rel, 'istruzioni')
+for p in (os.path.join(config, 'CLAUDE.md'), os.path.join(codex, 'AGENTS.md'), os.path.join(codex, 'AGENTS.override.md'), os.path.join(casa, '.gemini', 'GEMINI.md'), os.path.join(qwen_casa, 'QWEN.md')):
+ in_casa(p, 'istruzioni')
+for rel in ('.claude/settings.json', '.mcp.json', '.codex/config.toml', '.qwen/commands'):
+ nel_progetto(rel, 'impostazioni')
+for p in (os.path.join(config, 'settings.json'), os.path.join(codex, 'config.toml'), os.path.join(codex, 'hooks.json'), os.path.join(qwen_casa, 'settings.json')):
+ in_casa(p, 'impostazioni')
+chiesti = [r.strip() for r in re.split('[\\n:]', os.environ.get('DELMINIO_COPIA_ANCHE') or '') if r.strip()]
+for r in chiesti:
+ p = os.path.realpath(os.path.join(radice, os.path.expanduser(r)))
+ if not (p.startswith(radice + os.sep) or p.startswith(casa + os.sep)):
+ non_copiati.append({'da': r, 'perche': 'fuori'})
+ elif not os.path.exists(p):
+ non_copiati.append({'da': r, 'perche': 'assente'})
+ elif p.startswith(radice + os.sep):
+ nel_progetto(os.path.relpath(p, radice), 'chiesto')
+ else:
+ in_casa(p, 'chiesto')
+for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', '.claude/settings.local.json', '.codex/hooks.json', '.qwen/settings.json'):
+ if os.path.isfile(os.path.join(radice, rel)):
+ copie.append(rel)
+for rel in ('.claude/commands/apertura.md', '.claude/commands/chiusura.md', '.qwen/commands/apertura.md', '.qwen/commands/chiusura.md'):
+ p = os.path.join(radice, rel)
+ segno = 'Delminio' if rel.startswith('.qwen/') else 'delminio.sh'
+ if os.path.isfile(p) and segno not in open(p, encoding='utf-8', errors='replace').read():
+ copie.append(rel)
+note = sorted((n for n in os.listdir(vecchia) if n.endswith('.md'))) if os.path.isdir(vecchia) and os.path.realpath(vecchia) != memoria else []
+if note:
+ metti_cartella(vecchia, 'memoria', 'note')
+mcp = (leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json')).get('projects', {}).get(radice, {}).get('mcpServers') or {}).get('memoria')
+if mcp and (not str(mcp.get('url', '')).startswith(url)):
+ os.makedirs(dest, exist_ok=True)
+ with open(os.path.join(dest, 'mcp-memoria.json'), 'w', encoding='utf-8') as f:
+ json.dump(mcp, f, indent=2)
+ copie.append('mcp-memoria.json')
+else:
+ mcp = None
+
+def nostro(testo):
+ return 'delminio.sh' in str(testo)
+
+def hook_di(s):
+ out = {}
+ for ev, lista in (s.get('hooks') or {} if isinstance(s.get('hooks'), dict) else {}).items():
+ n = sum((1 for b in lista or [] if isinstance(b, dict) for h in b.get('hooks') or [] if isinstance(h, dict) and (not nostro(h.get('command', '')))))
+ if n:
+ out[ev] = n
+ return out
+
+def file_in(d, est='.md'):
+ if not os.path.isdir(d):
+ return []
+ out = []
+ for n in sorted(os.listdir(d)):
+ p = os.path.join(d, n)
+ if n.endswith(est) and os.path.isfile(p):
+ try:
+ if nostro(open(p, encoding='utf-8', errors='replace').read()):
+ continue
+ except OSError:
+ pass
+ out.append(n[:-len(est)])
+ return out
+
+def cartelle_in(d):
+ return sorted((n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)))) if os.path.isdir(d) else []
+conf = {}
+
+def segna(dove, cosa, valore):
+ if valore:
+ conf.setdefault(dove, {})[cosa] = valore
+for f, dove in ((os.path.join(config, 'settings.json'), '~/.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json')):
+ s = leggi(f)
+ if not isinstance(s, dict):
+ continue
+ segna(dove, 'hook', hook_di(s))
+ segna(dove, 'plugin', sorted((k for k, on in (s.get('enabledPlugins') or {}).items() if on)) if isinstance(s.get('enabledPlugins'), dict) else [])
+ segna(dove, 'stile', s.get('outputStyle') if isinstance(s.get('outputStyle'), str) else '')
+ segna(dove, 'permessi_negati', len((s.get('permissions') or {}).get('deny') or []) if isinstance(s.get('permissions'), dict) else 0)
+ segna(dove, 'hook_spenti', s.get('disableAllHooks') is True)
+for base, dove in ((config, '~/.claude'), (os.path.join(radice, '.claude'), '.claude')):
+ segna(dove + '/commands', 'comandi', file_in(os.path.join(base, 'commands')))
+ segna(dove + '/agents', 'agenti', file_in(os.path.join(base, 'agents')))
+ segna(dove + '/skills', 'skill', cartelle_in(os.path.join(base, 'skills')))
+ segna(dove + '/output-styles', 'stili', file_in(os.path.join(base, 'output-styles')))
+cj = leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'))
+
+def suoi_server(d):
+ return sorted((k for k, s in (d or {}).items() if not (k in ('memoria', 'delminio') and isinstance(s, dict) and str(s.get('url', '')).startswith(url))))
+if isinstance(cj, dict):
+ segna('~/.claude.json', 'mcp', suoi_server(cj.get('mcpServers')))
+ segna('~/.claude.json (' + F('prima_questo_progetto') + ')', 'mcp', suoi_server((cj.get('projects') or {}).get(radice, {}).get('mcpServers')))
+mj = leggi(os.path.join(radice, '.mcp.json'))
+if isinstance(mj, dict):
+ segna('.mcp.json', 'mcp', suoi_server(mj.get('mcpServers')))
+codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
+ct = os.path.join(codex, 'config.toml')
+if os.path.isfile(ct):
+ testo = open(ct, encoding='utf-8', errors='replace').read()
+ segna('~/.codex/config.toml', 'mcp', sorted(set((m for m in re.findall('^\\[mcp_servers\\.([A-Za-z0-9_-]+)\\]', testo, re.M) if m != 'delminio'))))
+ segna('~/.codex/config.toml', 'profili', sorted(set(re.findall('^\\[profiles\\.([A-Za-z0-9_-]+)\\]', testo, re.M))))
+segna('~/.codex/hooks.json', 'hook', hook_di(leggi(os.path.join(codex, 'hooks.json')) or {}))
+segna('~/.codex/prompts', 'comandi', file_in(os.path.join(codex, 'prompts')))
+altri = {}
+
+def righe_di(p):
+ try:
+ with open(p, encoding='utf-8', errors='replace') as f:
+ testo = f.read()
+ except OSError:
+ return (None, '')
+ return (None, '') if nostro(testo) else (len(testo.splitlines()), testo)
+
+def voci_qwen(testo):
+ m = re.search('^##\\s*Qwen Added Memories\\s*$(.*?)(?=^##\\s|\\Z)', testo, re.M | re.S)
+ return sum((1 for r in m.group(1).splitlines() if r.lstrip().startswith('- '))) if m else 0
+
+def file_altro(dove, p, cosa):
+ n, testo = righe_di(p)
+ if n:
+ v = {'cosa': cosa, 'righe': n}
+ if os.path.basename(p) == 'QWEN.md' and (q := voci_qwen(testo)):
+ v['memorie'] = q
+ altri[dove] = v
+
+def cartella_altro(dove, d, cosa):
+ if os.path.isdir(d):
+ n = sum((1 for _, _, fs in os.walk(d) for f in fs if f.endswith(('.md', '.mdc', '.txt'))))
+ if n:
+ altri[dove + '/'] = {'cosa': cosa, 'file': n}
+for rel in ('AGENTS.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md'):
+ if os.path.isfile(os.path.join(radice, rel)):
+ file_altro(rel, os.path.join(radice, rel), 'istruzioni')
+for rel in ('.cursor/rules', '.windsurf/rules', '.clinerules', '.github/instructions'):
+ cartella_altro(rel, os.path.join(radice, rel), 'istruzioni')
+for rel in ('memory-bank', '.serena/memories'):
+ cartella_altro(rel, os.path.join(radice, rel), 'memoria')
+for p, dove in ((os.path.join(config, 'CLAUDE.md'), '~/.claude/CLAUDE.md'), (os.path.join(codex, 'AGENTS.md'), '~/.codex/AGENTS.md'), (os.path.join(casa, '.gemini', 'GEMINI.md'), '~/.gemini/GEMINI.md'), (os.path.join(casa, '.qwen', 'QWEN.md'), '~/.qwen/QWEN.md')):
+ file_altro(dove, p, 'istruzioni personali')
+for v in altri.values():
+ if v.get('memorie'):
+ v['cosa'] += ' + memoria'
+da_ripassare = bool(copie or note or conf or altri or chiesti)
+os.makedirs(dest, exist_ok=True)
+with open(os.path.join(dest, 'fatti.json'), 'w', encoding='utf-8') as f:
+ json.dump({'radice': radice, 'copie': copie, 'memoria': {'cartella': vecchia, 'scelta_in': da, 'note': note}, 'configurazioni': conf, 'altri_strumenti': altri, 'file': copiati, 'non_copiati': non_copiati, 'chiesti': chiesti, 'aggancio_di_prima': os.path.isfile(os.path.join(radice, '.claude', 'delminio.sh'))}, f, indent=2, ensure_ascii=False)
+if not da_ripassare:
+ with open(os.path.join(dest, 'RIPASSATO'), 'w', encoding='utf-8') as f:
+ f.write(time.strftime('%Y-%m-%d %H:%M') + ' ' + F('prima_niente_da_ripassare') + '\n')
+with open(segno_backup, 'w', encoding='utf-8') as f:
+ f.write(cartella + '\n')
+DETTO = {'CLAUDE.md': F('prima_claude_md'), '.claude/CLAUDE.md': F('prima_claude_md'), 'CLAUDE.local.md': F('prima_claude_local'), '.claude/settings.local.json': F('prima_settings'), '.codex/hooks.json': F('prima_hook_codex'), '.qwen/settings.json': F('prima_qwen'), '.claude/commands/apertura.md': F('prima_apertura'), '.claude/commands/chiusura.md': F('prima_chiusura'), '.qwen/commands/apertura.md': F('prima_apertura'), '.qwen/commands/chiusura.md': F('prima_chiusura'), 'mcp-delminio.json': F('prima_mcp', nome='delminio'), 'mcp-memoria.json': F('prima_mcp', nome='memoria')}
+righe = [f'- `{c}` — {DETTO[c]}' for c in copie]
+if note:
+ righe.append(F('prima_note', n=len(note), cartella=vecchia))
+if conf:
+ righe.append(F('prima_configurazioni'))
+if altri:
+ righe.append(F('prima_altri', elenco=', '.join((f'`{k}`' for k in altri))))
+if chiesti:
+ righe.append(F('prima_chiesti', elenco=', '.join((f'`{k}`' for k in chiesti))))
+righe.append(F('prima_tutti', n=len(copiati)))
+PERCHE = {'credenziali': F('prima_perche_credenziali'), 'grande': F('prima_perche_grande'), 'fuori': F('prima_perche_fuori'), 'assente': F('prima_perche_assente')}
+for v in non_copiati:
+ righe.append(F('prima_non_copiato', file=v['da'], perche=PERCHE[v['perche']]))
+with open(os.path.join(dest, 'LEGGIMI.md'), 'w', encoding='utf-8') as f:
+ f.write('# ' + F('prima_leggimi_titolo') + '\n\n' + F('prima_leggimi_testa') + '\n\n' + '\n'.join(righe) + '\n\n' + F('prima_leggimi_note') + '\n\n' + F('prima_leggimi_tornare') + '\n')
+print(mostra(dest))
diff --git a/kit/en/delminio-client b/kit/en/delminio-client
new file mode 100644
index 0000000..6a5e2b0
--- /dev/null
+++ b/kit/en/delminio-client
@@ -0,0 +1,3164 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+_conto_t0=${EPOCHREALTIME:-}
+: '⟦frasi: client⟧'
+M_delminio_risponde_prompt='⚠️ Delminio is not responding at {url}: the opening prompt didn'"'"'t arrive.'
+M_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”'
+M_delminio_dato_system='⚠️ Delminio ({url}) didn'"'"'t provide the system prompt of the agent role “{porta}” (HTTP {codice}).'
+M_agente_parte_meta=' The agent doesn'"'"'t start half-ready. It can be opened as before, with the standard prompt: claude, then /opening.'
+M_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.'
+M_agente_parte_meta_2=' The agent doesn'"'"'t start half-ready.'
+M_opencode_gratuito_scelgo=' Picking a free OpenCode model that answers right now (once a day, a few seconds)…'
+M_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.'
+M_delminio_argomenti_codex='⚠️ Delminio: Codex'"'"'s arguments can'"'"'t be put back together (python3?). The agent doesn'"'"'t start half-ready.'
+M_ruolo_sola_sua_2='⚠️ The role'"'"'s channel is missing on this machine: run `delminio agents` again, it prepares it.'
+M_delminio_mcp_qwen='⚠️ Delminio: the MCP for Qwen Code can'"'"'t be assembled (python3?). The agent doesn'"'"'t start half-ready.'
+M_ponte_muto='Delminio is not answering right now (restarting?): try again in a few seconds. If it stays silent, tell the user.'
+M_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'
+M_piu_agenti_insieme='❌ “Multiple agents” is switched off by the admin in this project: no session worktree.'
+M_chi_sei_bash='❌ I don'"'"'t know who you are: delminio {gesto} S<N>'
+M_gia_entraci_smontalo='❌ {wt} already exists: go into it, or remove it if it'"'"'s finished.'
+M_principale_aggiorna_remoto='⚠️ the main worktree doesn'"'"'t update from the remote: I'"'"'m starting from what'"'"'s there'
+M_ramo='✅ {wt} on the branch {ramo}.'
+M_codex_resta_dov=' Codex stays where it is: put `cd {wt} && …` at the start of every command, and absolute paths in patches.'
+M_entraci_col_tool=' Go into it with the EnterWorktree tool (a cd isn'"'"'t enough for the CLI);'
+M_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.'
+M_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.'
+M_merge_lancia_tuo='❌ the merge is run from your worktree ({wt}), not from {dove}'
+M_hai_lavoro_committato='❌ you have uncommitted work: commit first.'
+M_altro_merge_corso='❌ another merge has been in progress for 10 minutes: ask on the channel.'
+M_principale_lavoro_staging='❌ in the main worktree there'"'"'s someone else'"'"'s work IN STAGING: ask them to commit.'
+M_principale_aggiorna_remoto_2='❌ the main worktree doesn'"'"'t update from the remote (git pull --ff-only): look at it first.'
+M_merge_toccherebbe_file='❌ the merge would touch files that are modified and uncommitted in the main worktree:'
+M_principale_senza_remoto='✅ {ramo} is in the main worktree (no remote: it stays on this machine).'
+M_mergiato_locale_push='❌ merged locally but the push failed: look at it before ending.'
+M_principale_remoto='✅ {ramo} is in the main worktree and on the remote.'
+M_nessun_worktree='no worktree {wt}'
+M_file_committati_smonta='❌ {wt} has uncommitted files: it is NOT removed. Look at them: git -C {wt} status'
+M_principale_prima_merge='❌ {ramo} isn'"'"'t in the main worktree: merge first (delminio merge).'
+M_smontato_tolto='✅ {wt} removed, {ramo} deleted.'
+M_nessuna_track_misurata='No track measured: .delminio/audit/ is empty. You build the half that gets counted'
+M_revisione_memoria_meta='(“Memory review” § The half that gets counted) — today everything is read by hand.'
+M_track_pulite_finding='— {pulite} clean tracks, {con} with findings. The rest of the review is read (the tracks without a script).'
+M_chi_sei_bash_2='❌ I don'"'"'t know who you are: delminio focus "what you touch" S<N>'
+M_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.'
+M_quali_bash_claude='❌ which ones? delminio focus "what you touch"'
+M_lavora_altre_sessioni='✅ {nome} works on: {valore} — the other sessions see it when they start.'
+M_chi_sei_bash_3='❌ I don'"'"'t know who you are: delminio title "your name" S<N>'
+M_quale_bash_claude='❌ which one? delminio title "your name"'
+M_chiama='✅ {nome} is called: {valore}'
+M_prompt_chiusura_arrivato='⚠️ {perche}: the closing prompt didn'"'"'t arrive. Wrap up anyway:'
+M_lavoro_committato_pushato='the work committed and pushed; where you are, and one single question (“anything else?”); then a commit'
+M_vuoto_git_commit='empty (git commit --allow-empty) “Handoff S<N> — …” with the sections Summary and Where we are,'
+M_push_commit_passera='and push. The commit will go through without verification: tell me.'
+M_chiusura_stata_consegnata='❌ {perche}: the handoff wasn'"'"'t delivered. Try again shortly; if Delminio stays silent, tell the user.'
+M_ripassato_copia_prima='✅ reviewed ({n}): the backup stays in {cartella}, and “delminio disconnect” can still put it back.'
+M_stacca_lancia_terminale='❌ “delminio disconnect” is run from your own terminal, not from an agent: open a terminal outside the agent, in this folder'
+M_stacca_lancia_clone='❌ stacca is run from the main clone, not from a worktree'
+M_rimetto_cio_era=' Putting back what was there before, from {prima}'
+M_copia_prima_tolgo=' ⚠️ there'"'"'s no earlier copy: I only remove Delminio'"'"'s pieces.'
+M_niente_fatto='Nothing done.'
+M_tue_memorie_personali=' your {n} personal memories are in {personali}'
+M_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)'
+M_server_mcp_delminio=' the previous “{nome}” MCP server is back'
+M_server_mcp_prima=' ⚠️ the previous MCP server didn'"'"'t come back: its definition is in {prima}/mcp-{nome}.json'
+M_tuo_chiama_delminio=' ⚠️ {f} is yours and calls Delminio: remove the .claude/delminio.sh line yourself'
+M_revocare_questo_token=' ⚠️ I can'"'"'t revoke this token: do it from Delminio'"'"'s app (Access)'
+M_token_resta_valido=' the token stays valid: {altri} other projects connected on this machine use it'
+M_token_questo_aggancio=' this connection'"'"'s token is revoked'
+M_token_revocato_fallo=' ⚠️ the token wasn'"'"'t revoked ({perche}): do it from Delminio'"'"'s app (Access)'
+M_tolto_clone_memorie=' removed this machine'"'"'s memory clone (the memories live in their repository)'
+M_restano_worktree_sessioni=' ⚠️ {wt} session worktrees remain (git worktree list): if the work is merged, git worktree remove <folder>'
+M_staccato_cli_torna='✅ disconnected. The CLI goes back to reading its notes; the project'"'"'s memories stay in the memory repository.'
+M_tue_personali=' Your personal ones: {personali}'
+M_copia_prima_resta=' The earlier copy stays in {prima}: connecting again redoes it from scratch.'
+M_accetta_lancia_terminale='❌ “delminio accept” is run from your own terminal, not from an agent: open a terminal outside the agent, in this folder'
+M_lock_duri_sono='⚠️ {perche}: the protected decisions that block were not checked on this commit.'
+M_chiusura_passa_senza='⚠️ {perche}: the handoff goes through without verification, and Delminio won'"'"'t know you'"'"'ve ended.'
+M_delminio_chiusa_chi=' Delminio: {n} ended. The next session will read this handoff.'
+M_opere_avevi_mano=' The tasks you had in progress are free again: {m}.'
+M_risultera_morta_senza='⚠️ {perche}: {n} will show as ended without a handoff.'
+M_lancialo_dentro_repo='❌ run it inside a connected repository'
+M_spazio_repo_aggiunge='The space has no repositories: the admin adds them, from Git.'
+M_repo_dello_spazio='The space'"'"'s repositories, on this machine:'
+M_clonato_qui=' · {nome}: not cloned here'
+M_gia_collegato=' ✅ {nome}: already connected ({dove})'
+M_uso_bash_claude='usage: delminio why <file>:<line>'
+M_nessun_albero='no known worktree'
+M_albero_sporco='worktree {albero} with {n} uncommitted files'
+M_albero_pulito='worktree {albero} clean'
+M_merge_non_pulito='❌ the merge isn'"'"'t clean: rebase your branch on the main one (git rebase {ramo}) and try again.'
+M_stacco='Disconnecting {repo} from Delminio ({url}), on this machine.'
+M_procedo=' Go ahead? [y/N] '
+M_collegato_qui=' ✅ {nome}: connected ({dove})'
+M_collegamento_fallito=' ❌ {nome}: the connection in {dove} didn'"'"'t go through — {errore}'
+M_segno_non_versione='the existing mark isn'"'"'t a version, I won'"'"'t replace it'
+M_informativa_non_segnata='Delminio: Codex notice not marked as seen ({errore}).'
+M_non_risponde_5s='{script} didn'"'"'t respond within 5 seconds'
+M_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.'
+M_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.'
+M_riprova_al_primo=' It retries by itself at the user'"'"'s first message.'
+M_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.'
+M_nasce_senza_memoria='⚠️ {perche}. This session starts WITHOUT memory and without the other sessions: tell the user right away, before anything else.{riprova}'
+M_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.'
+M_invia_uso='usage: delminio send <file> ["note"]'
+M_invia_non_trovato='❌ {file} doesn'"'"'t exist or can'"'"'t be read'
+M_invia_senza_sessione='❌ Run it from an agent: the file leaves from its session.'
+M_invia_fallito='❌ The file wasn'"'"'t sent: {perche}'
+M_invia_fatto='✅ Sent: “{nome}”. The user finds it in the Delminio app, under Files, and gets a notification.'
+M_posta_arrivata='📬 Delminio: a message has arrived from another session — you'"'"'ll find it below.'
+M_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.
+ The command with the key is pasted in the TERMINAL, inside the project folder.
+ If you'"'"'ve already sent it elsewhere, revoke it: Delminio → Access.
+'
+M_gesto_umano='The user wrote “{parola}”: it'"'"'s THEIR action, like /{parola} on Claude.'
+M_lock_del_comando='🔒 {codice} — {cosa} (the admin'"'"'s decision on this command)
+ why: {perche}
+ If your command breaks it, ask them before running it.'
+M_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.'
+M_dove_albero_sporco='Worktree: {n} uncommitted files.'
+M_dove_albero_pulito='Worktree clean.'
+M_commit_non_pushati='{n} commits not pushed on {ramo}.'
+M_tutto_pushato='Everything pushed.'
+M_ramo_senza_remoto='The branch {ramo} has no remote: it isn'"'"'t pushed.'
+M_worktree_in_piu='{n} worktrees besides the main one: {alberi}.'
+M_script_non_risponde='⚠️ {script} didn'"'"'t respond: {errore}'
+M_chiusura_rifiutata='❌ Delminio rejects this handoff:'
+M_aggiunge_trailer=' Delminio adds “{trailer}”.'
+M_aggiunge_trailer_perche=' Delminio adds “{trailer}”: {perche}.'
+M_chiusa_nel_repo='✅ {nome} ended: the handoff is in the memory repository ({hash}). The next session will read it.'
+M_perche_tornata='the sessions you crossed paths with'
+M_perche_memoria='the memories, committed by Delminio (if the push didn'"'"'t go through, it says so below)'
+M_questo_repo='this repository'
+M_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.'
+M_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}.'
+M_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.'
+M_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.'
+M_tocco_duro=' (BLOCKING: at commit its check runs, and if it fails a member'"'"'s commit stops)'
+M_tocco_duro_ospite=' (BLOCKING in the owning space: its check doesn'"'"'t run here, respect it yourself)'
+M_tocco_dello_spazio=' (from the space “{spazio}”)'
+M_tocco_voce='
+{codice}{di} — {cosa}{duro}
+ why: {perche}
+ verified by: {guardia}'
+M_tocco_nessuno='NOBODY — if you break it, nothing complains'
+M_accetta_domanda='
+{codice} — {cosa}
+ written by: {chi}
+ the command that will run here, at every commit:
+
+ {comando}
+
+Do you accept it? [y/N] '
+M_accetta_si='y yes'
+M_accettate='✅ {nuove} accepted now · {tutte} in total · the list: {file}'
+M_perche_non_committata='{dove} isn'"'"'t committed yet: the why is in the current work.'
+M_perche_commit='{dove} → the commit {commit} of {data}, by {autore}: “{soggetto}”'
+M_perche_senza_sessione=' No Delminio session on this commit: it predates Delminio, or was made by hand.
+ The rest is told by the commit: git show {commit}'
+M_perche_sessione_muto=' → the session {sessione}; Delminio is not responding ({errore}), and it knows the rest.'
+M_perche_sessione=' → the session {sessione}{agente}{chi}{nata}'
+M_perche_con=', with {chi}'
+M_perche_nata=', started on {data}'
+M_perche_senza_chiusura=' It didn'"'"'t leave a handoff: the why is in its commits (git log --grep '"'"'Delminio-Sessione: {sessione}'"'"').'
+M_perche_chiusa=' → it ended on {data} with the commit {commit}{repo}: {comando}'
+M_perche_in_repo=' in {repo}'
+M_perche_memorie=' → the memories it touched:'
+M_perche_nessuna_memoria=' → no memory touched in that handoff.'
+M_perche_memorie_nel_commit=' → the memories touched are in the commit {commit} of the memory repository.'
+M_perche_le_memorie=' → the memories: {memorie}'
+M_fermato_codex='Stopped by Delminio: the agent received the why.'
+M_consegna_di_uso='❌ which one? delminio handoff-of S<N>'
+M_consegna_di_curata='⟳ The handoff of S{numero} is CORRECTED: this is the version to read, don'"'"'t open the original with git.'
+M_consegna_di_vuota='The handoff of S{numero} no longer has its text in the service: someone with permission deleted it.'
+M_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.'
+M_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'
+M_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.'
+M_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.'
+M_app_codex_tolto='Removed: the Codex app no longer has Delminio, and the rest of ~/.codex/config.toml is as it was.'
+M_app_codex_no='All right: I won'"'"'t suggest it again on this computer. If you change your mind: delminio app-codex'
+M_app_codex_uso='usage: delminio app-codex [via|no|stato]'
+M_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.'
+M_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'
+M_accetta_script_elenco='
+The 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:
+'
+M_accetta_script_riga=' {percorso} — {chi}, {quando}, {righe} lines'
+M_accetta_script_domanda='
+They will run with your permissions. Do you accept them? [a = all · o = one by one, reading them · N = none] '
+M_accetta_script_uno='
+{percorso} — {chi}, {quando}
+
+{testo}
+
+Do you accept it? [y/N] '
+M_accetta_script_tutti_si='a all'
+M_accetta_script_uno_si='o one'
+M_script_accettati='✅ scripts: {nuovi} accepted now · {fermi} stay stopped (if one changes, I'"'"'ll ask again)'
+M_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.
+ 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.'
+M_perche_muto='Delminio is not responding at {url}'
+M_perche_token='Delminio at {url} refuses this link'"'"'s token (HTTP {codice})'
+M_perche_rifiuta='Delminio at {url} said no (HTTP {codice}: {errore})'
+M_perche_errore='Delminio at {url} answered with an error (HTTP {codice}{errore})'
+M_prompt_rifiutato='⚠️ Delminio at {url} didn'"'"'t give the opening prompt (HTTP {codice}{errore}): tell the user.'
+M_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.'
+M_piu_agenti_non_concessa='❌ “Multiple agents” isn'"'"'t in this space'"'"'s licence: no session worktree.'
+M_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:
+ {comando}
+ Read it and, if you trust it, from a terminal of yours: delminio accept
+ The commit goes through, but this protected decision is not enforced on this machine until someone accepts the check.'
+M_lock_grida_muto='⚠️ {codice} cried out but Delminio is not responding: the commit goes through, and the admin won'"'"'t know.'
+M_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.'
+M_guardia_dice=' the check says:'
+M_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:
+ {comando}
+ 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'
+M_accetta_domanda_gesto='
+{codice} — {cosa}
+ written by: {chi}
+ the check that will run here, before every command matching {gesti}:
+
+ {comando}
+
+Do you accept it? [y/N] '
+M_sessione_non_viva='❌ {nome} isn'"'"'t an open session: nothing written. Your name is in the opening.'
+M_skill_nomi_pulita='✅ team skills: every path they name is in the repo (pieces checked: {n})'
+M_skill_nomi_finding='❌ {pezzo} ({file}): “{nome}” is not in the repo'
+M_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.'
+M_skill_nomi_nessuna='— the team has no skills, commands or agents to check against the repo.'
+M_skill_nomi_cieca='⚠️ team skills were not checked against the repo: Delminio does not answer ({perche}). It does not mean they are fine.'
+M_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'
+M_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'
+M_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.'
+M_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'
+M_aiuto='Delminio'"'"'s commands: run them in the folder of a connected project.
+
+ delminio agents writes this space'"'"'s agents on this computer (Agents view)
+ delminio agents status which agents are on this computer, and at which version
+ delminio accept accepts the agents'"'"' options and the team'"'"'s servers
+ delminio connect-all connects in one go the space'"'"'s projects that are on this computer
+ delminio backlog help the Backlog from the terminal: search, open, close items
+ delminio vault list the secrets agents can ask for, if the vault is on
+ delminio why <file>:<line> which session wrote that line, and its handoff
+ delminio handoff-of S<number> a session'"'"'s whole handoff
+ delminio errors [days] the tool calls that failed on this computer, in short
+ delminio review the project'"'"'s automatic checks, those of the review
+ delminio send <file> ["note"] sends a file to the people you work with: they find it in the Files view
+ delminio app-codex [via|no] Delminio in the Codex desktop app
+ delminio signoffs check [a..b] a branch'"'"'s changes: signed, to sign, with changed words
+ delminio signoffs description [a..b] the text of a pull request: the person'"'"'s words and the facts
+ delminio signoffs report [a..b] the report commit by commit, for the auditor
+ delminio disconnect disconnects this project from Delminio and puts everything back as it was
+
+The other commands are run by the agent itself. Each one is explained in the guide, on the “Commands” page.'
+M_comando_sconosciuto='unknown command “{nome}”.'
+M_uso_clona='usage: delminio clone <repository name> [--no]'
+M_clona_non_dello_spazio='“{nome}” isn'"'"'t a repository of this space: the opening lists them, or the app'"'"'s Git page.'
+M_clona_no='All right: I won'"'"'t suggest “{nome}” on this computer again. If it'"'"'s needed, delminio clone {nome}'
+M_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.'
+M_clona_in_corso='Cloning “{nome}” from {url} into {dove}…'
+M_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.'
+M_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.'
+M_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.'
+M_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.'
+M_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.'
+M_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.'
+M_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.'
+M_controllo_non_parte_breve='the check does not start ({comando}): make sure the command exists and is executable.'
+M_controllo_lento_breve='the check did not answer within {secondi} seconds ({comando}).'
+: '⟦fine frasi⟧'
+export ${!M_@}
+IFS= read -r -d '' DELMINIO_FIDATI_PY <<'FIDATI' || true
+import hashlib as _hl, os as _os, subprocess as _sp
+def _git_in(albero, *a):
+ r = _sp.run(["git", "-C", albero, *a], capture_output=True, text=True)
+ return r.returncode, r.stdout.strip()
+def accettati_file(albero):
+ rc, c = _git_in(albero, "rev-parse", "--path-format=absolute", "--git-common-dir")
+ return _os.path.join(c, "delminio-script-accettati") if rc == 0 and c else ""
+def accettati(albero):
+ try:
+ return set(open(accettati_file(albero), encoding="utf-8").read().split())
+ except OSError:
+ return set()
+def impronta_script(albero, f):
+ with open(f, "rb") as h:
+ return _hl.sha256(_os.path.relpath(f, albero).encode() + b"\0" + h.read()).hexdigest()
+def di_chi(albero, f):
+ rel = _os.path.relpath(f, albero)
+ if _git_in(albero, "ls-files", "--error-unmatch", "--", rel)[0] != 0:
+ return None
+ if _git_in(albero, "diff", "--quiet", "HEAD", "--", rel)[0] != 0:
+ return None
+ io = _git_in(albero, "config", "user.email")[1].lower()
+ ae, an, ad = (_git_in(albero, "log", "-1", "--format=%ae%x1f%an%x1f%ad", "--date=short", "--", rel)[1].split("\x1f") + ["", "", ""])[:3]
+ if io and ae.lower() == io:
+ return None
+ return (an or ae or "?", ad)
+def da_fidarsi(albero, f, gia):
+ return di_chi(albero, f) is None or impronta_script(albero, f) in gia
+def lascito_del_progetto(albero):
+ """F903 — .delminio/lascito.sh gira alla morte della CLI: come gli altri script
+ del progetto, solo se è di chi lavora qui o una persona l'ha accettato."""
+ f = _os.path.join(albero, ".delminio", "lascito.sh") if albero else ""
+ return [f] if f and _os.path.isfile(f) and _os.access(f, _os.X_OK) else []
+def script_del_progetto(albero, cartelle):
+ out = []
+ for d in cartelle:
+ c = _os.path.join(albero, ".delminio", d)
+ for s in (sorted(_os.listdir(c)) if albero and _os.path.isdir(c) else []):
+ f = _os.path.join(c, s)
+ if _os.path.isfile(f) and _os.access(f, _os.X_OK):
+ out.append(f)
+ return out
+FIDATI
+export DELMINIO_FIDATI_PY
+: '⟦protocollo⟧'
+P_CLOSE='Chiusura|Handoff|Close Session'
+P_TRAILER_TORNATA=Parallel-session
+P_TRAILER_AUDIT='Audit|Review'
+P_TRAILER_MEMORIA='Memoria|Memory'
+export P_CLOSE P_TRAILER_TORNATA P_TRAILER_AUDIT P_TRAILER_MEMORIA
+: '⟦fine protocollo⟧'
+STATO="${TMPDIR:-/tmp}/delminio-$(id -u)"
+mkdir -p "$STATO" 2>/dev/null; chmod 700 "$STATO" 2>/dev/null
+if [ -L "$STATO" ] || [ ! -O "$STATO" ]; then
+ STATO="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-stato"
+ mkdir -p "$STATO" && chmod 700 "$STATO"
+fi
+spazza_stato() {
+ local f p
+ for f in "$STATO"/{attesa,volo,no,nasci,fork,lock-detti,condiviso,avvisato,visto,sessione,cuore,posta-muta}-*; do
+ [ -e "$f" ] || continue
+ p=${f##*-}
+ case $p in *[!0-9]*|'') continue ;; esac
+ kill -0 "$p" 2>/dev/null || rm -f -- "$f"
+ done
+ find "$STATO" -maxdepth 1 -name 'volo-sid-*' -mmin +60 -delete 2>/dev/null || true
+ find "$STATO" -maxdepth 1 -name 'conto-*' -mmin +1440 -delete 2>/dev/null || true
+ find "$STATO" -maxdepth 1 -name 'skill-*' -mmin +1440 -delete 2>/dev/null || true
+}
+in_sottofondo() {
+ [ "${CLAUDE_CODE_SESSION_KIND:-}" = bg ] && return 0
+ [ -r "/proc/$1/environ" ] && tr '\0' '\n' < "/proc/$1/environ" 2>/dev/null | grep -qx 'CLAUDE_CODE_SESSION_KIND=bg'
+}
+madri_del_fork() {
+ printf '%s' "$1" | python3 -c 'import json, sys
+io = sys.argv[1]
+try:
+ t = json.loads(sys.stdin.read() or "{}").get("transcript_path") or ""
+except (ValueError, AttributeError):
+ t = ""
+viste = []
+try:
+ with open(t, encoding="utf-8", errors="replace") as h:
+ for riga in h:
+ try:
+ d = json.loads(riga)
+ except ValueError:
+ continue
+ for k in ("session_id", "sessionId"):
+ v = d.get(k) if isinstance(d, dict) else None
+ if isinstance(v, str) and v and v != io:
+ if v in viste:
+ viste.remove(v)
+ viste.append(v)
+except OSError:
+ pass
+print(json.dumps(viste[::-1][:5]))' "$2" 2>/dev/null || echo '[]'
+}
+zitta_la_prima() {
+ local prima q conv a
+ prima=$(printf '%s' "$1" | campo processo_di_prima)
+ [ -n "$prima" ] && [ "${prima%:*}" = "$(hostname)" ] || return 0
+ q=${prima##*:}
+ case $q in ''|*[!0-9]*) return 0 ;; esac
+ [ "$q" != "$2" ] || return 0
+ rm -f "$STATO/sessione-$q"
+ a=$(cat "$STATO/attesa-$q" 2>/dev/null || true)
+ [ -n "$a" ] && kill "$a" 2>/dev/null
+ rm -f "$STATO/attesa-$q"
+ conv=$(printf '%s' "$1" | campo conversazione_di_prima)
+ if [ -n "$conv" ] && kill -0 "$q" 2>/dev/null; then printf '%s' "$conv" > "$STATO/nasci-$q"; fi
+ return 0
+}
+cli_pid() {
+ if [ -n "${DELMINIO_CLI_PID:-}" ] && kill -0 "$DELMINIO_CLI_PID" 2>/dev/null; then
+ printf '%s' "$DELMINIO_CLI_PID"; return 0
+ fi
+ local p=$$ q exe stato args
+ for _ in 1 2 3 4 5 6 7 8; do
+ if [ -r "/proc/$p/stat" ]; then
+ read -r stato < "/proc/$p/stat"; stato=${stato##*) }; q=${stato#* }; q=${q%% *}
+ else
+ q=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d ' ')
+ fi
+ { [ -z "$q" ] || [ "$q" -le 1 ]; } 2>/dev/null && return 1
+ exe=$(readlink -f "/proc/$q/exe" 2>/dev/null || true)
+ case "$exe" in */claude|*/claude/*|*/versions/*|*/ccd-cli/*|*/bin/codex|*/bin/opencode) printf '%s' "$q"; return 0 ;; esac
+ case "$exe" in ''|*/node*) e_qwen "$q" && { printf '%s' "$q"; return 0; } ;; esac
+ if [ -r "/proc/$q/cmdline" ]; then
+ args=$(tr '\0' ' ' < "/proc/$q/cmdline")
+ else
+ args=$(ps -o args= -p "$q" 2>/dev/null)
+ fi
+ [[ " $args" =~ (^|/|\ )(claude|codex)(\ |$)|/versions/|/ccd-cli/ ]] && { printf '%s' "$q"; return 0; }
+ p=$q
+ done
+ return 1
+}
+_conto_segna() {
+ local t1=${EPOCHREALTIME:-} a b
+ [ -n "$t1" ] && [ -n "${_conto_t0:-}" ] || return 0
+ a=${_conto_t0/[.,]/}; b=${t1/[.,]/}
+ printf '%s %s\n' "$_conto_gesto" $(( (10#$b - 10#$a) / 1000 )) >> "$STATO/conto-$_conto_sid" 2>/dev/null || true
+}
+_conto_somme() {
+ local f="$STATO/conto-${_conto_sid:-}"
+ [ -n "${_conto_sid:-}" ] && [ -s "$f" ] || return 0
+ mv -f "$f" "$f.invio" 2>/dev/null || return 0
+ awk '$1 ~ /^[a-z]+$/ && $2 ~ /^[0-9]+$/ {v[$1]++; m[$1]+=$2}
+ END {s=""; for (g in v) s=s (s ? "," : "") "\"" g "\":[" v[g] "," m[g] "]"; printf "%s", s}' "$f.invio"
+ rm -f "$f.invio"
+}
+_skill_voci() {
+ local sid=${_skill_sid:-${_conto_sid:-}} s=""
+ local f="$STATO/skill-$sid"
+ [ -n "$sid" ] && [ -s "$f" ] || return 0
+ mv -f "$f" "$f.invio" 2>/dev/null || return 0
+ while read -r tipo nome; do
+ [[ $tipo =~ ^(skill|comando)$ && $nome =~ ^[A-Za-z0-9_.:-]+$ ]] || continue
+ s+="${s:+,}[\"$tipo\",\"$nome\"]"
+ done < "$f.invio"
+ rm -f "$f.invio"
+ printf '%s' "$s"
+}
+_quota() {
+ local LC_ALL=C s=$1 i c o=""
+ for ((i = 0; i < ${#s}; i++)); do
+ c=${s:i:1}
+ case $c in
+ [a-zA-Z0-9._~-]) o+=$c ;;
+ *) if [ "$c" = / ] && [ "${2-/}" = / ]; then o+=/; else printf -v c '%%%02X' "'$c"; o+=$c; fi ;;
+ esac
+ done
+ printf '%s' "$o"
+}
+_guardia_serve() {
+ local e=$1 m=${MEMORIA%/} cwd=""
+ [[ $e == *'`'* || $e == *pkill* || $e == *workdir* || $e == *'\u0060'* ]] && return 0
+ [ -n "$m" ] || return 1
+ [[ $e == *"$(basename "$(dirname "$m")")"* || $e == *"$(basename "$m")/"* ]] && return 0
+ [[ $e =~ \"cwd\":\ ?\"([^\"]*)\" ]] && cwd=${BASH_REMATCH[1]}
+ [ -n "$cwd" ] && [[ $m == "${cwd%/}"/* || $m == "$cwd" ]]
+}
+e_codex() { _args "$1" | head -1 | grep -qE '(^|/)codex$'; }
+e_qwen() {
+ _args "$1" | head -1 | grep -qE '(^|/)node[0-9.]*$' || return 1
+ _args "$1" | sed -n 2,4p | grep -v '^-' | head -1 | grep -qE '(^|/)qwen$|/@qwen-code/qwen-code/'
+}
+e_opencode() {
+ [ "$1" = "${DELMINIO_CLI_PID:-}" ] && [ "${DELMINIO_CLI_NOME:-}" = opencode ] && return 0
+ case "$(readlink -f "/proc/$1/exe" 2>/dev/null || true)" in */bin/opencode) return 0 ;; esac
+ _args "$1" | head -1 | grep -qE '(^|/)opencode$'
+}
+cli_di() {
+ if e_codex "$1" 2>/dev/null; then echo codex; elif e_qwen "$1" 2>/dev/null; then echo qwen
+ elif e_opencode "$1" 2>/dev/null; then echo opencode; else echo claude; fi
+}
+headless() {
+ if e_qwen "$1"; then
+ _args "$1" | python3 -c 'import re, sys
+CON_VALORE = {"-m", "--model", "-s", "--sandbox", "--approval-mode", "--mcp-config", "--input-file",
+ "--system-prompt", "--append-system-prompt", "-o", "--output-format", "--input-format",
+ "--session-id", "--include-directories", "--add-dir", "--allowed-tools", "--exclude-tools",
+ "--core-tools", "-e", "--extensions", "--auth-type", "--openai-api-key", "--openai-base-url",
+ "--openai-logging-dir", "--max-session-turns", "--max-wall-time", "--max-tool-calls",
+ "--max-subagent-depth", "--channel", "--json-fd", "--json-file", "--json-schema", "--proxy",
+ "--fallback-model", "--advisor", "--output-style", "--disabled-slash-commands",
+ "--allowed-mcp-server-names", "--disable-mcp-server", "--sandbox-image"}
+a = sys.stdin.read().split("\n")
+script = next((k for k, x in enumerate(a[1:4], 1)
+ if not x.startswith("-") and re.search(r"(^|/)qwen$|/@qwen-code/qwen-code/", x)), None)
+if script is None: sys.exit(1)
+a = a[script + 1:]; i = 0
+while i < len(a):
+ x = a[i]
+ if x in ("-i", "--prompt-interactive") or x.startswith("--prompt-interactive="): sys.exit(1)
+ if x in ("-p", "--prompt") or x.startswith("--prompt="): sys.exit(0)
+ if x == "--": sys.exit(0 if any(a[i + 1:]) else 1)
+ if x in CON_VALORE: i += 2; continue
+ if x in ("-r", "--resume"):
+ i += 2 if i + 1 < len(a) and a[i + 1] and not a[i + 1].startswith("-") else 1
+ continue
+ if x.startswith("-") or not x: i += 1; continue
+ sys.exit(0)
+sys.exit(1)'
+ elif e_opencode "$1"; then
+ [ "$1" = "${DELMINIO_CLI_PID:-}" ] && return 1
+ local chi=$1 su
+ if _args "$chi" | grep -qx -- --service; then
+ if [ -r "/proc/$chi/stat" ]; then read -r su < "/proc/$chi/stat"; su=${su##*) }; su=${su#* }; su=${su%% *}
+ else su=$(ps -o ppid= -p "$chi" 2>/dev/null | tr -d ' '); fi
+ [ -n "$su" ] && e_opencode "$su" && chi=$su
+ fi
+ _args "$chi" | sed 1d | python3 -c 'import sys
+CON_VALORE = {"-m", "--model", "--agent", "-s", "--session", "--port", "--hostname", "--log-level", "--prompt"}
+a = sys.stdin.read().split("\n"); i = 0
+while i < len(a):
+ x = a[i]
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-") or not x: i += 1; continue
+ sys.exit(0 if x == "run" else 1)
+sys.exit(1)'
+ elif _args "$1" | head -1 | grep -qE '(^|/)codex$'; then
+ _args "$1" | sed 1d | python3 -c 'import sys
+CON_VALORE = {"-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a",
+ "--ask-for-approval", "-C", "--cd", "--add-dir", "-i", "--image", "--enable", "--disable",
+ "--remote", "--remote-auth-token-env", "--local-provider"}
+a = sys.stdin.read().split("\n"); i = 0
+while i < len(a):
+ x = a[i]
+ if x == "--": sys.exit(1)
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-"): i += 1; continue
+ sys.exit(0 if x in ("exec", "e", "review") else 1)
+sys.exit(1)'
+ else
+ _args "$1" | grep -qxE -- '-p|--print'
+ fi
+}
+cartella_backup() { # dove sta la copia di sicurezza di questo clone (F777): la scrive il collegamento in .git
+ cat "$(git rev-parse --git-common-dir 2>/dev/null)/delminio-backup" 2>/dev/null || true
+}
+PY_SKILL_NOMI='
+import json, os, re, subprocess, sys
+radice = sys.argv[1]
+p = json.load(sys.stdin)
+plugin = p.get("plugin") or "squadra"
+pezzi = [x for x in p.get("pezzi") or [] if x.get("tipo") in ("skill", "comando", "agente")]
+if not pezzi:
+ print("NESSUNA"); sys.exit(0)
+fatti = subprocess.run(["git", "-C", radice, "ls-files", "-co", "--exclude-standard"],
+ capture_output=True, text=True).stdout.split("\n")
+fatti = {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
+cartelle = {os.path.dirname(f) for f in fatti}
+while any("/" in c and os.path.dirname(c) not in cartelle for c in cartelle):
+ cartelle |= {os.path.dirname(c) for c in cartelle}
+nomi_base = {os.path.basename(f) for f in fatti}
+try:
+ voluti = {r.strip() for r in open(os.path.join(radice, ".delminio", "skill-nomi-voluti.txt"), encoding="utf-8")
+ if r.strip() and not r.startswith("#")}
+except OSError:
+ voluti = set()
+EST = ("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 "
+ "conf csv xml env lock ps1").split()
+def parole(testo):
+ pezzi = re.findall(r"```[^\n]*\n(.*?)```", testo, re.S)
+ resto = re.sub(r"```.*?```", " ", testo, flags=re.S)
+ pezzi += re.findall(r"`([^`\n]+)`", resto)
+ for x in pezzi:
+ for w in re.split(r"[\s;,]+", x):
+ yield w.strip("\"\x27:.()")
+def percorso(w):
+ if not w or w.startswith(("~", "/", "-", "@", "$")) or "://" in w or re.search(r"[<>{}$*?|()\[\]=]", w):
+ return False
+ w = w[2:] if w.startswith("./") else w
+ return ("/" in w and re.fullmatch(r"[\w.@+-]+(/[\w.@+-]+)*/?", w) is not None) \
+ or (re.fullmatch(r"[\w@+-][\w.@+-]*\.(" + "|".join(EST) + ")", w) is not None)
+def c_e(w):
+ w = (w[2:] if w.startswith("./") else w).rstrip("/")
+ if w in fatti or w in cartelle or os.path.exists(os.path.join(radice, w)):
+ return True
+ if "/" not in w:
+ return w in nomi_base
+ return any(f.endswith("/" + w) for f in fatti) or any(c.endswith("/" + w) for c in cartelle)
+trovati = 0
+for x in pezzi:
+ for rel, testo in sorted((x.get("file") or {}).items()):
+ if not rel.endswith(".md"):
+ continue
+ visti = set()
+ for w in parole(testo):
+ if w in visti or w in voluti or not percorso(w):
+ continue
+ visti.add(w)
+ if not c_e(w):
+ trovati += 1
+ print("\t".join(("F", plugin + ":" + x["nome"], rel, w)))
+if trovati:
+ sys.exit(1)
+print("OK\t" + str(len(pezzi)))
+'
+chiedi() { # chiedi GET|POST <percorso> [json] → corpo; esce 1 se Delminio non risponde 200
+ local r c
+ local h=(-H "Content-Type: application/json")
+ [ -n "${CHIEDI_SESSIONE:-}" ] && h+=(-H "X-Delminio-Sessione: $CHIEDI_SESSIONE")
+ if [ -n "${3:-}" ]; then
+ r=$(printf '%s' "$3" | curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
+ "${h[@]}" --data-binary @- "$URL$2" 2>/dev/null)
+ else
+ r=$(curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
+ "${h[@]}" "$URL$2" 2>/dev/null)
+ fi
+ c=${r##*$'\n'}
+ if [ "$c" != 200 ]; then
+ local e; e=$(printf '%s' "${r%$'\n'*}" | campo error); e=${e//[$'\t\n']/ }
+ printf '%s\t%s' "${c:-000}" "$e" > "$STATO/no-$$" 2>/dev/null || true
+ return 1
+ fi
+ printf '%s' "${r%$'\n'*}"
+}
+
+carta_richiesta() { # stdin: l'evento della CLI · $1 la sessione
+ local f; f="$(cd "$(dirname "$0")" && pwd)/firme.py"
+ [ -f "$f" ] || return 0
+ DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_STATO="$STATO" python3 "$f" _richiesta "$1" 2>/dev/null || true
+}
+
+cure() {
+ local r d
+ d=$(git rev-parse --git-common-dir 2>/dev/null) || return 0
+ r=$(chiedi GET /api/cure) || return 0
+ printf '%s' "$r" | python3 -c '
+import json, os, re, subprocess, sys
+r, messe_file = json.load(sys.stdin), sys.argv[1]
+def git(*a, inp=None, vero=False):
+ pre = [] if vero else ["--no-replace-objects"]
+ return subprocess.run(["git", *pre, *a], input=inp, capture_output=True, text=True,
+ encoding="utf-8", errors="surrogateescape").stdout
+def testa_senza_firma(testa):
+ fuori, out = False, []
+ for riga in testa.split("\n"):
+ if riga.startswith(("gpgsig ", "gpgsig-sha256 ")):
+ fuori = True
+ continue
+ if fuori and riga.startswith(" "):
+ continue
+ fuori = False
+ out.append(riga)
+ return "\n".join(out)
+try:
+ messe = set(open(messe_file, encoding="utf-8").read().split())
+except OSError:
+ messe = set()
+vive = set()
+for k in r.get("cure") or []:
+ h, n = str(k.get("hash") or ""), int(k.get("numero") or 0)
+ if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h):
+ continue
+ full = git("rev-parse", "-q", "--verify", h + "^{commit}").strip()
+ if not full:
+ continue # quel close non sta in questo repo
+ testa, _, msg = git("cat-file", "commit", full).partition("\n\n")
+ sogg = msg.split("\n", 1)[0]
+ if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), sogg):
+ continue # non è il close di quel numero: non si tocca
+ vive.add(full) # viva anche se qui sotto qualcosa cade: non esce dal git per un giro
+ trailer = git("interpret-trailers", "--parse", inp=msg).strip()
+ corpo = (sogg + "\n\n" + str(k.get("intestazione") or "").strip() + "\n\n" + str(k.get("testo") or "").strip()
+ + "\n" + ("\n" + trailer + "\n" if trailer else ""))
+ nuovo = git("hash-object", "-t", "commit", "-w", "--stdin", inp=testa_senza_firma(testa) + "\n\n" + corpo).strip()
+ if not nuovo:
+ continue
+ if git("rev-parse", "-q", "--verify", "refs/replace/" + full).strip() != nuovo:
+ git("replace", "-f", full, nuovo, vero=True)
+for orig in messe - vive: # tolta nel motore: esce, ma solo se è nostra
+ git("replace", "-d", orig, vero=True)
+with open(messe_file + ".nuovo", "w", encoding="utf-8") as f:
+ f.write("\n".join(sorted(vive)) + ("\n" if vive else ""))
+os.replace(messe_file + ".nuovo", messe_file)
+' "$(_assoluto "$d")/delminio-cure" 2>/dev/null || true
+}
+
+_remoto() { git ${1:+-C "$1"} remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#'; }
+_urlenc() { python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$1"; }
+REPO_NO="${XDG_CONFIG_HOME:-$HOME/.config}/delminio/repo-no.json"
+repo_no_qui() { # → la lista JSON dei «no» di questo collegamento
+ DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" <<'REPO_NO' 2>/dev/null || printf '[]'
+import json, os, sys
+try:
+ d = json.load(open(sys.argv[1], encoding="utf-8"))
+except (OSError, ValueError):
+ d = {}
+v = d.get(os.environ["DELMINIO_CHI"]) if isinstance(d, dict) else None
+print(json.dumps([str(x) for x in v] if isinstance(v, list) else []))
+REPO_NO
+}
+_collega_clone() { # _collega_clone <nome> <cartella>: il clone si collega allo spazio, col token di qui
+ local log="$STATO/collega-$$.log" errore_log
+ if ( cd "$2" && f=$(mktemp) && curl -fsS "$URL/aggancia.sh?segnaposto=1" -o "$f" \
+ && { _firmato "$URL" aggancia.sh "$f" || { _f "$M_riaggancio_non_firmato" url "$URL" > "$log"; rm -f "$f"; exit 1; }; } \
+ && DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" bash "$f" < /dev/null > "$log" 2>&1; r=$?; rm -f "$f"; exit $r ) \
+ && [ -x "$2/.claude/delminio.sh" ]; then
+ rm -f "$log"; _f "$M_collegato_qui" nome "$1" dove "$2"; return 0
+ fi
+ errore_log=$(grep -v '^[[:space:]]*$' "$log" 2>/dev/null | tail -1 | cut -c1-200)
+ rm -f "$log"; _f "$M_collegamento_fallito" nome "$1" dove "$2" errore "$errore_log"; return 1
+}
+
+_segno_pubblico() { local d; d=$(git rev-parse --git-common-dir 2>/dev/null) || return 1; printf '%s/delminio-pubblico' "$(_assoluto "$d")"; }
+pubblico_segna() { # pubblico_segna <json con «pubblico»>: il file segue il motore
+ local f v
+ f=$(_segno_pubblico) || return 0
+ v=$(printf '%s' "$1" | python3 -c 'import json,sys
+try: d = json.load(sys.stdin)
+except Exception: sys.exit(0)
+d = d.get("repo", d) if isinstance(d, dict) else {}
+print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null)
+ case "$v" in si) : > "$f" ;; no) rm -f "$f" ;; esac
+}
+repo_stato() { # nel cuore: chi cambia l'interruttore lo vede qui entro un giro
+ local remoto r
+ remoto=$(_remoto) || return 0
+ [ -n "$remoto" ] || return 0
+ r=$(chiedi GET "/api/repo/stato?remoto=$(_urlenc "$remoto")") || return 0
+ pubblico_segna "$r"
+}
+
+testi() {
+ local r remoto corpo
+ remoto=$(_remoto) || return 0
+ [ -n "$remoto" ] || return 0
+ r=$(chiedi GET "/api/chiusure/testi?remoto=$(_urlenc "$remoto")") || return 0
+ corpo=$(printf '%s' "$r" | python3 -c '
+import json, os, re, subprocess, sys
+def git(*a):
+ return subprocess.run(["git", "--no-replace-objects", *a], capture_output=True, text=True,
+ encoding="utf-8", errors="replace").stdout
+testi, peso = [], 0
+for c in (json.load(sys.stdin).get("chiusure") or [])[:50]:
+ h, n = str(c.get("hash") or ""), int(c.get("numero") or 0)
+ if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h) or not git("rev-parse", "-q", "--verify", h + "^{commit}").strip():
+ continue # non sta in questo git: lo porterà chi lo ha
+ testo = git("log", "-1", "--format=%B", h)
+ if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), testo):
+ continue
+ voce = {"numero": n, "hash": h, "testo": testo}
+ p = len(json.dumps(voce, ensure_ascii=False).encode())
+ if p > 100_000:
+ continue # da solo non passerebbe mai: resta da leggere nel git
+ if peso + p > 100_000:
+ break
+ testi.append(voce)
+ peso += p
+print(json.dumps({"testi": testi}, ensure_ascii=False) if testi else "")
+' 2>/dev/null) || return 0
+ [ -n "$corpo" ] || return 0
+ chiedi POST /api/chiusure/testi "$corpo" >/dev/null || true
+}
+
+perche_no() { # la frase vera dopo un chiedi fallito
+ local c="" e=""
+ IFS=$'\t' read -r c e < "$STATO/no-$$" 2>/dev/null || true
+ rm -f "$STATO/no-$$"
+ case "$c" in
+ ''|000) if [ "${CODEX_SANDBOX_NETWORK_DISABLED:-}" = 1 ]; then _f "$M_sandbox_senza_rete" url "$URL"
+ else _f "$M_perche_muto" url "$URL"; fi ;;
+ 401) _f "$M_perche_token" url "$URL" codice "$c" ;;
+ 403) if [ -n "$e" ] && [ "$e" != unauthorized ]; then _f "$M_perche_rifiuta" url "$URL" codice "$c" errore "$e"
+ else _f "$M_perche_token" url "$URL" codice "$c"; fi ;;
+ *) _f "$M_perche_errore" url "$URL" codice "$c" errore "${e:+: $e}" ;;
+ esac
+}
+mia_sessione() { cat "$STATO/sessione-$1" 2>/dev/null; }
+chi_sei_no() {
+ if [ "${DELMINIO_CLI_NOME:-}" = codex ] || [ -n "${CODEX_SANDBOX_NETWORK_DISABLED:-}${CODEX_SANDBOX:-}" ]; then
+ echo "$M_chi_sei_sandbox" >&2
+ else
+ echo "$1" >&2
+ fi
+}
+albero_di() {
+ git worktree list --porcelain 2>/dev/null | awk -v n="$1" '
+ /^worktree /{w=substr($0, 10)} /^branch /{b=$2; sub(".*/", "", b); if (b == n) {print w; exit}}' \
+ || true
+}
+avvia_ritiro() { # avvia_ritiro <sessione> <albero>
+ local l="$STATO/ritiro-$1" v
+ v=$(cat "$l" 2>/dev/null || true)
+ [ -n "$v" ] && kill -0 "$v" 2>/dev/null && return 0
+ _staccato bash "$0" ritira-file "$1" "$2" >/dev/null 2>&1 < /dev/null &
+}
+ritira_file() { # ritira_file <sessione> <albero>
+ local nome=$1 albero=$2 r dir ex id nm dest tmp
+ [ -n "$albero" ] && [ -d "$albero" ] || return 1
+ r=$(chiedi GET "/api/file/in-arrivo?sessione=$(_urlenc "$nome")") || return 1
+ dir="$albero/.delminio/file"
+ mkdir -p "$dir" && chmod 700 "$dir" || return 1
+ if ex=$(git -C "$albero" rev-parse --git-path info/exclude 2>/dev/null); then
+ case $ex in /*) ;; *) ex="$albero/$ex" ;; esac
+ grep -qxF '/.delminio/file/' "$ex" 2>/dev/null || { mkdir -p "$(dirname "$ex")" && printf '/.delminio/file/\n' >> "$ex"; }
+ fi
+ find "$dir" -maxdepth 1 -type f -mtime +7 -delete 2>/dev/null || true
+ printf '%s' "$r" | python3 -c 'import json, sys
+for f in json.load(sys.stdin).get("file") or []:
+ print(f["id"] + "\t" + f["nome"].replace("\t", " ").replace("\n", " "))' | while IFS=$'\t' read -r id nm; do
+ dest=$(python3 -c 'import os, re, sys, unicodedata
+d, n = sys.argv[1], re.split(r"[\\/]", sys.argv[2])[-1]
+n = "".join(c for c in n if not unicodedata.category(c).startswith("C")).strip().lstrip(".-").strip() or "file"
+b, e = os.path.splitext(n); k, p = 1, os.path.join(d, n)
+while os.path.lexists(p):
+ k += 1; p = os.path.join(d, f"{b} ({k}){e}")
+print(p)' "$dir" "$nm") || continue
+ tmp="$dir/.in-arrivo-$id"
+ if ! curl -sS -f -m 900 -K <(_chiave "$TOKEN") -o "$tmp" "$URL/api/file/$id?scarica=1" 2>/dev/null; then
+ rm -f "$tmp"; continue
+ fi
+ chmod 600 "$tmp" && mv -f "$tmp" "$dest" || { rm -f "$tmp"; continue; }
+ chiedi POST "/api/file/$id/ritirato" "{\"sessione\":$(json_stringa "$nome"),\"percorso\":$(json_stringa "$dest")}" >/dev/null || true
+ done
+}
+chiave_in_uso() {
+ [ -n "${ANTHROPIC_API_KEY:-}" ] && [ "$(uname -s)" = Linux ] || return 0
+ [ -e "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json" ] && return 0
+ printf '%s' "$ANTHROPIC_API_KEY" | sha256sum | cut -c1-16
+}
+fatti_codex() { # cli, evento, fatti JSON
+ [ "$1" = codex ] || { printf '%s' "$3"; return; }
+ local programma
+ IFS= read -r -d '' programma <<'CODEX_FATTI' || true
+import json, os, sys
+from pathlib import Path
+d = json.load(os.fdopen(3))
+try:
+ evento = json.loads(sys.stdin.read() or '{}')
+except (ValueError, TypeError):
+ evento = {}
+if not isinstance(evento, dict):
+ evento = {}
+modo = evento.get('permission_mode', '')
+d['permission_mode'] = modo if modo in ('default', 'acceptEdits', 'plan', 'dontAsk', 'bypassPermissions') else ''
+scelta = os.environ.get('DELMINIO_PERMESSI', '')
+d['permessi_al_lancio'] = scelta if scelta in ('chiede', 'modifiche', 'classificatore') else ''
+casa = os.environ.get('CODEX_HOME')
+segno = Path(casa) / 'delminio-informativa-permessi' if casa else None
+try:
+ d['informativa_codex_vista'] = 0 if segno is None or segno.is_symlink() else int(segno.read_text().strip())
+except (OSError, ValueError):
+ d['informativa_codex_vista'] = 0
+d['sandbox_linux'] = os.environ.get('DELMINIO_SANDBOX_LINUX', '')
+print(json.dumps(d))
+CODEX_FATTI
+ python3 -c "$programma" 3<<< "$3" <<< "$2"
+}
+evento_dove() {
+ local programma
+ IFS= read -r -d '' programma <<'DOVE' || true
+import json, os, re, sys
+e = json.loads(sys.stdin.read() or "{}")
+t = e.get("tool_input") if isinstance(e.get("tool_input"), dict) else {}
+comando = t.get("command") if isinstance(t.get("command"), str) else ""
+base = e.get("cwd") or os.getcwd()
+
+def stringa(s, i):
+ """Il letterale JS che comincia in s[i] → (valore o None se ha ${…}, fine)."""
+ q, j, out = s[i], i + 1, []
+ while j < len(s) and s[j] != q:
+ if s[j] == "\\" and j + 1 < len(s):
+ c = s[j + 1]
+ if c == "u" and re.match(r"[0-9a-fA-F]{4}", s[j + 2:j + 6]):
+ out.append(chr(int(s[j + 2:j + 6], 16))); j += 6; continue
+ out.append({"n": "\n", "t": "\t", "r": "\r", "0": "\0"}.get(c, c)); j += 2; continue
+ if q == "`" and s.startswith("${", j):
+ return None, s.find(q, j) + 1 or len(s)
+ out.append(s[j]); j += 1
+ return "".join(out), j + 1
+
+def salta(js, i):
+ """Se in js[i] comincia un commento o una stringa, dove finisce; se no None."""
+ if js.startswith("//", i):
+ j = js.find("\n", i); return len(js) if j < 0 else j
+ if js.startswith("/*", i):
+ j = js.find("*/", i + 2); return len(js) if j < 0 else j + 2
+ if js[i] in "\"'`":
+ return stringa(js, i)[1]
+ return None
+
+def in_chiave(js, i):
+ """js[i] sta dove comincia una chiave: dopo «{» o «,»."""
+ j = i - 1
+ while j >= 0 and js[j].isspace():
+ j -= 1
+ return j >= 0 and js[j] in "{,"
+
+def chiamate_js(js):
+ """Le exec_command({…}) del CODICE (non di un commento o di una stringa):
+ (cmd, workdir), dove None = non letterale e "" = workdir assente.
+ ⚠️ Ogni altro modo di arrivarci è una chiamata muta (None, None): l'alias
+ (const f = tools.exec_command, tools["exec_command"]), che altrimenti spariva
+ dietro una chiamata letterale con lo stesso cmd scritta lì per finta."""
+ i = 0
+ while i < len(js):
+ if js[i] in "\"'`":
+ v, fine = stringa(js, i)
+ if v == "exec_command":
+ yield None, None
+ i = fine; continue
+ fine = salta(js, i)
+ if fine is not None:
+ i = fine; continue
+ m = re.match(r"exec_command\s*\(\s*(\{)?", js[i:i + 64])
+ if not m or (i and re.match(r"[\w$]", js[i - 1])):
+ if re.match(r"exec_command\b", js[i:i + 13]) and not (i and re.match(r"[\w$]", js[i - 1])):
+ yield None, None
+ i += 12; continue
+ i += 1; continue
+ if not m.group(1): # exec_command(args): una variabile, non si legge
+ yield None, None
+ i += m.end(); continue
+ i, prof, chiavi = i + m.end(), 1, {}
+ while i < len(js) and prof:
+ k = re.match(r"""(["']?)(cmd|workdir)\1\s*:\s*""", js[i:i + 16]) if prof == 1 else None
+ if k and not re.match(r"[\w$]", js[i - 1]):
+ i += k.end()
+ v = None
+ if i < len(js) and js[i] in "\"'`":
+ v, i = stringa(js, i)
+ if not re.match(r"\s*[,}]", js[i:i + 64]):
+ v = None
+ chiavi[k.group(2)] = v
+ continue
+ a = re.match(r"(cmd|workdir)\s*(?=[,}])", js[i:i + 16]) if prof == 1 and in_chiave(js, i) else None
+ if a:
+ chiavi[a.group(1)] = None
+ i += a.end(); continue
+ if prof == 1 and js[i] == "[" and in_chiave(js, i):
+ chiavi = {"cmd": None, "workdir": None}
+ if prof == 1 and js.startswith("...", i):
+ chiavi = {"cmd": None, "workdir": None}
+ i += 3; continue
+ fine = salta(js, i)
+ if fine is not None:
+ i = fine; continue
+ if js[i] in "{[(":
+ prof += 1
+ elif js[i] in "}])":
+ prof -= 1
+ i += 1
+ yield chiavi.get("cmd"), chiavi.get("workdir", "")
+
+def ultime_chiamate(percorso):
+ """Le chiamate dell'ultima risposta del modello, dalla coda del rollout. None se
+ il rollout non si legge o non mostra ancora la chiamata in corso (l'ultima cosa
+ scritta è un'uscita): mai le chiamate di prima al posto di questa."""
+ try:
+ with open(percorso, "rb") as f:
+ f.seek(max(0, os.path.getsize(percorso) - 524288))
+ righe = f.read().decode("utf-8", "replace").splitlines()
+ except OSError:
+ return None
+ viste, voci = [], 0
+ for r in reversed(righe):
+ try:
+ p = json.loads(r).get("payload") or {}
+ except ValueError:
+ continue
+ if p.get("type") == "custom_tool_call" and p.get("name") == "exec":
+ voci += 1
+ viste += list(chiamate_js(p.get("input") or ""))
+ elif p.get("type") == "function_call":
+ voci += 1
+ try:
+ a = json.loads(p.get("arguments") or "{}")
+ except ValueError:
+ a = None
+ if not isinstance(a, dict):
+ viste.append((None, None)); continue
+ if not ({"cmd", "command", "workdir"} & set(a)):
+ continue
+ c = a.get("cmd", a.get("command"))
+ viste.append((c if isinstance(c, str) else None,
+ a.get("workdir", "") if isinstance(a.get("workdir", ""), str) else None))
+ elif p.get("type") in ("custom_tool_call_output", "function_call_output"):
+ if not voci:
+ return None
+ break
+ elif p.get("type") in ("message", "reasoning") and voci:
+ break
+ return viste if voci else None
+
+def cd_letterale(testo):
+ """Un cd iniziale riuscito solo con &&, senza espansioni indovinate.
+ Restituisce destinazione e resto; la stessa prova assolve il rollout assente.
+ """
+ m = re.match(r"""\s*cd\s+("[^"]+"|'[^']+'|[^\s;&|]+)\s*&&""", testo)
+ if not m:
+ return None, testo
+ token = m.group(1)
+ casa = os.path.expanduser("~")
+ if token.startswith("'"):
+ d = token[1:-1]
+ elif token.startswith('"'):
+ d = re.sub(r"^\$(HOME\b|\{HOME\})", lambda _: casa, token[1:-1])
+ if any(c in d for c in ('$', '`', '\\')):
+ return None, testo
+ else:
+ d = re.sub(r"^(~(?=/|$)|\$HOME\b|\$\{HOME\})", lambda _: casa, token)
+ if re.search(r"[$`\\~*?\[\]{}()<>\"']", d):
+ return None, testo
+ return d, testo[m.end():]
+
+cwd, incerto = base, ""
+rollout = e.get("transcript_path") or ""
+if e.get("tool_name") == "Bash" and comando and os.path.basename(rollout).startswith("rollout-"):
+ viste = ultime_chiamate(rollout)
+ if viste is None:
+ viste, e["dove_non_visto"] = [], 1
+ incerto = "il rollout di Codex non mostra la chiamata di questo comando"
+ mie = {w for c, w in viste if c == comando}
+ possibili = mie | {w for c, w in viste if c is None}
+ if e.get("dove_non_visto"):
+ pass
+ elif not possibili:
+ incerto = "non trovo nel code mode la chiamata che lancia questo comando"
+ elif len(possibili) == 1 and None not in possibili:
+ w = possibili.pop()
+ cwd = os.path.join(base, os.path.expanduser(w)) if w else base
+ elif len(mie) > 1:
+ incerto = "lo stesso comando ha più cartelle in questa chiamata"
+ elif None in mie:
+ incerto = "la sua cartella (workdir) non è scritta per esteso"
+ else:
+ incerto = "nella chiamata ci sono un comando o una cartella non scritti per esteso"
+primo, _ = cd_letterale(comando)
+if primo is not None and os.path.isabs(primo):
+ cwd, incerto = base, ""
+resto = comando
+while not incerto:
+ d, dopo = cd_letterale(resto)
+ if d is None:
+ if re.match(r"\s*cd\b", resto) and os.path.basename(rollout).startswith("rollout-"):
+ incerto = "il cd iniziale non è una destinazione letterale seguita da &&"
+ break
+ cwd, resto = os.path.join(cwd, d), dopo
+e["cwd"] = os.path.normpath(cwd)
+if incerto:
+ e["dove_incerto"] = incerto
+print(json.dumps(e))
+DOVE
+ python3 -c "$programma"
+}
+segna_informativa_codex() { # risposta del motore; solo dopo una consegna riuscita a una CLI vera
+ local programma
+ IFS= read -r -d '' programma <<'CODEX_VISTA' || true
+import json, os, sys, tempfile
+from pathlib import Path
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+v = json.load(sys.stdin).get('informativa_codex')
+if not isinstance(v, int) or isinstance(v, bool) or v < 1:
+ sys.exit(0)
+casa = os.environ.get('CODEX_HOME')
+if not casa:
+ sys.exit(0) # un Codex nudo non autorizza scritture nella casa personale
+casa = Path(casa)
+segno = casa / 'delminio-informativa-permessi'
+try:
+ casa.mkdir(parents=True, exist_ok=True)
+ if segno.exists() and (segno.is_symlink() or not segno.read_text().strip().isdigit()):
+ raise ValueError(F("segno_non_versione"))
+ with tempfile.NamedTemporaryFile(mode='w', dir=casa, prefix='.delminio-permessi-', delete=False) as f:
+ f.write(str(v))
+ nome = f.name
+ os.replace(nome, segno)
+except (OSError, ValueError) as e:
+ print(F("informativa_non_segnata", errore=e), file=sys.stderr)
+CODEX_VISTA
+ python3 -c "$programma" <<< "$1"
+}
+strumenti_vivi() {
+ local f r k
+ read -r k _ <<<"$(printf '%s' "$URL$TOKEN" | cksum)"
+ f="$STATO/strumenti-$k"
+ if [ -n "$(find "$f" -mmin -1 2>/dev/null)" ]; then printf '%s' "$(<"$f")"; return 0; fi
+ if r=$(CHIEDI_TEMPO=3 chiedi GET /api/lock/strumenti); then
+ printf '%s' "$r" | python3 -c 'import json,sys
+print("\n".join(g for g in json.load(sys.stdin).get("strumenti") or [] if isinstance(g, str)))' > "$f.$$" 2>/dev/null \
+ && mv -f "$f.$$" "$f"
+ else
+ touch "$f" 2>/dev/null # un minuto senza richiedere: un motore muto non costa a ogni tool
+ fi
+ [ -f "$f" ] && printf '%s' "$(<"$f")"
+ return 0
+}
+accettate_file() {
+ local c w
+ c="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || echo .git)/delminio-guardie-accettate"
+ w=$(git rev-parse --path-format=absolute --git-path delminio-guardie-accettate 2>/dev/null || true)
+ if [ -n "$w" ] && [ "$w" != "$c" ] && [ -s "$w" ]; then
+ sort -u "$w" "$c" 2>/dev/null > "$c.$$" && mv -f "$c.$$" "$c" && rm -f "$w"
+ fi
+ printf '%s' "$c"
+}
+modello_dal_transcript() { # modello_dal_transcript <pid> <sessione> <evento json>
+ [ -z "${DELMINIO_MODELLO:-}" ] || return 0
+ local m
+ m=$(printf '%s' "$3" | _tempo 2 python3 -c '
+import json, os, sys
+try:
+ e = json.load(sys.stdin)
+ if isinstance(e.get("model"), str) and e["model"].strip():
+ print(e["model"].strip()[:80]); sys.exit(0)
+ p = e.get("transcript_path") or ""
+ with open(p, "rb") as f:
+ f.seek(max(0, os.path.getsize(p) - 524288))
+ righe = f.read().decode("utf-8", "replace").splitlines()
+except Exception:
+ sys.exit(0)
+for r in reversed(righe):
+ try:
+ d = json.loads(r)
+ except ValueError:
+ continue
+ if not isinstance(d, dict):
+ continue
+ m = ((d.get("payload") or {}).get("model") if d.get("type") == "turn_context"
+ else ((d.get("message") if isinstance(d.get("message"), dict) else {}).get("model") or d.get("model"))
+ if d.get("type") == "assistant" else None)
+ if isinstance(m, str) and m.strip() and not m.startswith("<"): # «<synthetic>» di Claude non è un modello
+ print(m.strip()[:80])
+ break
+' 2>/dev/null || true)
+ [ -n "$m" ] || return 0
+ [ "$m" = "$(cat "$STATO/modello-$1" 2>/dev/null || true)" ] && return 0
+ CHIEDI_TEMPO=2 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$2"),\"agente\":$(json_stringa "$m")}" >/dev/null 2>&1 \
+ && printf '%s' "$m" > "$STATO/modello-$1"
+ return 0
+}
+consumi_dal_transcript() { # consumi_dal_transcript <file di stato> <evento json>
+ printf '%s' "$2" | _tempo 5 python3 "$(dirname "$0")/consumi.py" "$1" 2>/dev/null || true
+}
+totale_cli_qwen() { # totale_cli_qwen <evento json>
+ [ -n "${QWEN_HOME:-}" ] || return 0
+ printf '%s' "$1" | _tempo 7 python3 -c '
+import json, os, sys, time
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+sid = str(e.get("session_id") or "")
+if e.get("hook_event_name") != "SessionEnd" or not sid:
+ sys.exit(0)
+f = os.path.join(os.environ["QWEN_HOME"], "usage_record.jsonl")
+riga = None
+for _ in range(25): # la CLI lo scrive mentre si spegne
+ try:
+ with open(f, encoding="utf-8") as h:
+ for r in h:
+ if sid in r:
+ d = json.loads(r)
+ if d.get("sessionId") == sid:
+ riga = d
+ except (OSError, ValueError):
+ pass
+ if riga:
+ break
+ time.sleep(0.2)
+if not riga:
+ sys.exit(0)
+t = {"input": 0, "cache_letta": 0, "cache_scritta": 0, "output": 0, "risposte": 0}
+for m in (riga.get("models") or {}).values():
+ letta = int(m.get("cachedTokens") or 0)
+ t["input"] += max(0, int(m.get("inputTokens") or 0) - letta)
+ t["cache_letta"] += letta
+ t["output"] += int(m.get("outputTokens") or 0) + int(m.get("thoughtsTokens") or 0)
+ t["risposte"] += int(m.get("requests") or 0)
+print(json.dumps({"conversazione": sid[:80], "cli": "qwen", "totale_cli": t}))
+' 2>/dev/null || true
+}
+fatti_nascita() { # fatti_nascita <pid> <evento json> [si = al primo messaggio]
+ local cli senza="" base programma; cli=$(cli_di "$1"); [ "$cli" = claude ] || senza=1
+ IFS= read -r -d '' programma <<'FATTI' || true
+import json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+processo, albero, agente, dove, memoria, primo, remoto = sys.argv[1:8]
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+try:
+ conversazione = str(json.loads(sys.stdin.read() or "{}").get("session_id") or "")
+except Exception:
+ conversazione = ""
+commit = subprocess.run(["git", "log", "-200", "--format=%h%x1f%s%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)"],
+ capture_output=True, text=True).stdout.splitlines()
+avvisi = []
+exec(os.environ["DELMINIO_FIDATI_PY"])
+gia, fermi = (accettati(albero) if albero else set()), []
+for f in lascito_del_progetto(albero):
+ if not da_fidarsi(albero, f, gia):
+ fermi.append(di_chi(albero, f)[0])
+for f in script_del_progetto(albero, ("apertura", "opening")):
+ s = os.path.basename(f)
+ if not da_fidarsi(albero, f, gia):
+ fermi.append(di_chi(albero, f)[0])
+ continue
+ try:
+ out = subprocess.run([f], cwd=albero, capture_output=True, text=True, timeout=5).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ out = F("non_risponde_5s", script=s)
+ avvisi += [r.strip() for r in out.splitlines() if r.strip()][:3]
+if fermi:
+ avvisi.insert(0, F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
+import glob
+mcp_fermi = 0
+for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
+ "delminio", "squadre", "*", ".mcp-fermi.json")):
+ try:
+ with open(x, encoding="utf-8") as h:
+ mcp_fermi += len(json.load(h))
+ except (OSError, ValueError, TypeError):
+ pass
+if mcp_fermi:
+ avvisi.insert(0, F("squadra_mcp_da_accettare", n=mcp_fermi))
+plugin_fermi = 0
+for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
+ "delminio", "squadre", "*", ".plugin-fermi.json")):
+ try:
+ with open(x, encoding="utf-8") as h:
+ plugin_fermi += len(json.load(h))
+ except (OSError, ValueError, TypeError):
+ pass
+if plugin_fermi:
+ avvisi.insert(0, F("squadra_plugin_da_accettare", n=plugin_fermi))
+try:
+ with open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
+ encoding="utf-8") as h:
+ righe_ferme = sum(len(sp.get("fermi") or []) for sp in (json.load(h).get("spazi") or {}).values()
+ if isinstance(sp, dict))
+except (OSError, ValueError, TypeError, AttributeError):
+ righe_ferme = 0
+if righe_ferme:
+ avvisi.insert(0, F("eseguibili_da_accettare", n=righe_ferme))
+propri = 0
+for d in ("apertura", "opening", "dove-siamo", "status"):
+ c = os.path.join(albero, ".delminio", d) if albero else ""
+ propri += sum(1 for s in (os.listdir(c) if c and os.path.isdir(c) else [])
+ if os.path.isfile(os.path.join(c, s)) and os.access(os.path.join(c, s), os.X_OK))
+prima = []
+if albero:
+ cartelle = [os.path.join(albero, ".claude", "delminio-prima")]
+ try:
+ cartelle.append(open(os.path.join(albero, ".git", "delminio-backup"), encoding="utf-8").read().strip())
+ except OSError:
+ pass
+ for c in cartelle:
+ for d in sorted(os.listdir(c) if c and os.path.isdir(c) else []):
+ if os.path.isfile(os.path.join(c, d, "fatti.json")) and not os.path.exists(os.path.join(c, d, "RIPASSATO")):
+ p = os.path.join(c, d)
+ prima.append(os.path.relpath(p, albero) if p.startswith(albero + os.sep) else p)
+print(json.dumps({"processo": processo, "albero": albero, "agente": agente, "dove": dove,
+ "commit": commit, "avvisi": avvisi[:12], "propri": propri, "remoto": remoto,
+ "repo_no": json.loads(os.environ.get("DELMINIO_REPO_NO") or "[]"),
+ "conversazione": conversazione, "prima": prima,
+ "madri": json.loads(os.environ.get("DELMINIO_MADRI") or "[]"),
+ "indice": bool(memoria) and os.path.isfile(os.path.join(memoria, "MEMORY.md"))
+ and not os.environ.get("DELMINIO_SENZA_INDICE"),
+ "al_primo_messaggio": primo == "si",
+ "contesto": int(os.environ.get("DELMINIO_CONTESTO") or 0) if (os.environ.get("DELMINIO_CONTESTO") or "").isdigit() else 0,
+ "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"}))
+FATTI
+ base=$(DELMINIO_CLI_NOME="$cli" DELMINIO_SENZA_INDICE="$senza" DELMINIO_REPO_NO="$(repo_no_qui)" \
+ python3 -c "$programma" "$(hostname):$1" "$(git rev-parse --show-toplevel 2>/dev/null)" \
+ "${DELMINIO_MODELLO:-}" "$(hostname)" "$MEMORIA" "${3:-}" "$(_remoto)" <<< "$2"
+ ) || return
+ fatti_codex "$cli" "$2" "$base"
+}
+eseguibili_indietro() { # eseguibili_indietro <impronta voluta> [giorno] → 0 se va riallineato
+ [ -z "${DELMINIO_PROVA:-}" ] && [ "${DELMINIO_ESEGUIBILE:-}" = si ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 1
+ python3 -c 'import json,os,sys,time
+try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
+except Exception: r = {}
+m = (r.get("spazi") or {}).get(sys.argv[2], {} if r.get("spazi") else r)
+vecchio = sys.argv[3] == "giorno" and time.time() - (m.get("quando") or 0) > 86400
+sys.exit(0 if (sys.argv[1] and m.get("registro") != sys.argv[1]) or vecchio else 1)' "$1" "$(spazio_qui)" "${2:-}"
+}
+riaggancio_stato() { printf '%s/riaggancio-%s' "$STATO" "$(printf '%s\n' "$1" | cksum | cut -d' ' -f1)"; }
+riaggancia() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] && [ "$1" != "${KIT:-}" ] && [ -d "$2" ] || return 0
+ ra=$(riaggancio_stato "$2")
+ if [ "${3:-}" = presto ] && [ "$(cat "$ra.verso" 2>/dev/null)" = "$1" ] && [ -e "$ra.log" ] \
+ && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -lt 3600 ]; then
+ return 0
+ fi
+ printf '%s' "$1" > "$ra.verso"
+ export -f _firmato
+ export KIT_FIRMA
+ ( cd "$2" && DELMINIO_TOKEN="$TOKEN" _staccato bash -c \
+ 'f=$(mktemp) && curl -fsS "$0/aggancia.sh?segnaposto=1" -o "$f" || exit 1
+ _firmato "$0" aggancia.sh "$f" || { printf "%s\n" "$1" >&2; rm -f "$f"; exit 1; }
+ DELMINIO_URL="$0" bash "$f"; r=$?; rm -f "$f"; exit $r' \
+ "$URL" "$(_f "$M_riaggancio_non_firmato" url "$URL")" > "$ra.log" 2>&1 < /dev/null & )
+}
+fratelli_indietro() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] || return 0
+ s="$STATO/fratelli.verso"
+ if [ "$(cat "$s" 2>/dev/null)" = "$1" ] && [ $(( $(date +%s) - $(_mtime "$s") )) -lt 3600 ]; then return 0; fi
+ printf '%s' "$1" > "$s"
+ ( _staccato bash "$0" riaggancia-fratelli "$1" > "$STATO/fratelli.log" 2>&1 < /dev/null & )
+}
+allinea_staccato() {
+ _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit allinea \
+ > "$STATO/eseguibili.log" 2>&1 < /dev/null &
+}
+skill_staccato() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 0
+ _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" skill \
+ > "$STATO/skill.log" 2>&1 < /dev/null &
+}
+spazio_qui() { python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" spazio 2>/dev/null || printf '%s' "${URL%/}"; }
+stato_eseguibile() { DELMINIO_SPAZIO="$(spazio_qui)" python3 - <<'STATO_ESEGUIBILE'
+import json, os
+try:
+ r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
+ encoding="utf-8"))
+except Exception:
+ r = {}
+u = os.environ["DELMINIO_SPAZIO"].rstrip("/")
+s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
+miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
+print("rifiutato" if s.get("rifiutato") else "si" if any(os.path.isfile(p) for p in miei) else "no")
+STATO_ESEGUIBILE
+}
+
+
+: '⟦comandi⟧'
+_comando() { # _comando <gruppo> <nome> → il nome canonico
+ case "$1:$2" in
+ client:rivisto) printf '%s\n' ripassato ;;
+ client:revisione) printf '%s\n' audit ;;
+ client:backlog) printf '%s\n' cantiere ;;
+ client:firme) printf '%s\n' carta ;;
+ client:accept) printf '%s\n' accetta ;;
+ client:focus) printf '%s\n' domini ;;
+ client:title) printf '%s\n' titolo ;;
+ client:new) printf '%s\n' nuovo ;;
+ client:teardown) printf '%s\n' smonta ;;
+ client:kit-files) printf '%s\n' file-del-kit ;;
+ client:send) printf '%s\n' invia ;;
+ client:agents) printf '%s\n' eseguibili ;;
+ client:vault) printf '%s\n' cassaforte ;;
+ client:reviewed) printf '%s\n' ripassato ;;
+ client:disconnect) printf '%s\n' stacca ;;
+ client:why) printf '%s\n' perche ;;
+ client:handoff) printf '%s\n' consegna ;;
+ client:handoff-of) printf '%s\n' consegna-di ;;
+ client:errors) printf '%s\n' errori ;;
+ client:connect-all) printf '%s\n' agganciali ;;
+ client:review) printf '%s\n' audit ;;
+ client:help) printf '%s\n' aiuto ;;
+ client:clone) printf '%s\n' clona ;;
+ client:signoffs) printf '%s\n' carta ;;
+ client:domains) printf '%s\n' domini ;;
+ eseguibili:status) printf '%s\n' stato ;;
+ eseguibili:rename) printf '%s\n' rinomina ;;
+ eseguibili:test) printf '%s\n' prova ;;
+ eseguibili:sync) printf '%s\n' allinea ;;
+ cassaforte:list) printf '%s\n' elenco ;;
+ cassaforte:propose) printf '%s\n' proponi ;;
+ cassaforte:open) printf '%s\n' apri ;;
+ cassaforte:access) printf '%s\n' finestre ;;
+ cassaforte:close) printf '%s\n' chiudi ;;
+ cassaforte:deposit) printf '%s\n' deposita ;;
+ cassaforte:windows) printf '%s\n' finestre ;;
+ carta:check) printf '%s\n' controlla ;;
+ carta:description) printf '%s\n' descrizione ;;
+ carta:report) printf '%s\n' resoconto ;;
+ carta:export) printf '%s\n' esporta ;;
+ carta:chain) printf '%s\n' catena ;;
+ carta:review) printf '%s\n' revisione ;;
+ carta:checks) printf '%s\n' prove ;;
+ *) printf '%s\n' "$2" ;;
+ esac
+}
+export 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"}}'
+: '⟦fine comandi⟧'
+if [ $# -gt 0 ]; then set -- "$(_comando client "$1")" "${@:2}"; fi
+case "${1:-}" in eseguibili|cassaforte|carta) [ $# -gt 1 ] && set -- "$1" "$(_comando "$1" "$2")" "${@:3}" ;; esac
+
+case "${1:-}" in guardia|condiviso|gesto|tocco|volo|umano|memorie|segreto|rito|attesa)
+ if [ -n "${EPOCHREALTIME:-}" ] && [ -z "${DELMINIO_NO_CODEX:-}" ] && [ ! -t 0 ]; then
+ _conto_gesto=$1
+ _conto_ev=$(cat); exec 0<<<"$_conto_ev"
+ [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _conto_sid=${BASH_REMATCH[1]}
+ [ -n "${_conto_sid:-}" ] && [ "$1" != attesa ] && trap '_conto_segna' EXIT
+ fi ;;
+esac
+case "${1:-}" in volo|umano)
+ if [ ! -t 0 ] && [ -z "${DELMINIO_NO_CODEX:-}" ]; then
+ [ -n "${_conto_ev+x}" ] || { _conto_ev=$(cat); exec 0<<<"$_conto_ev"; }
+ _skill_voce=""
+ if [ "$1" = volo ] && [[ $_conto_ev =~ \"tool_name\":\ ?\"([A-Za-z_]+)\" ]] \
+ && [[ ${BASH_REMATCH[1]} = [Ss]kill ]] \
+ && [[ $_conto_ev =~ \"skill\":\ ?\"([A-Za-z0-9_.:-]{1,161})\" ]]; then
+ _skill_voce="skill ${BASH_REMATCH[1]}"
+ elif [ "$1" = umano ] && [[ $_conto_ev =~ \"prompt\":\ ?\"/([A-Za-z0-9_.:-]{1,161})([\ \"\\]|$) ]]; then
+ _skill_voce="comando ${BASH_REMATCH[1]}"
+ fi
+ [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _skill_sid=${BASH_REMATCH[1]}
+ if [ -n "$_skill_voce" ] && [ -n "${_skill_sid:-}" ]; then
+ printf '%s\n' "$_skill_voce" >> "$STATO/skill-$_skill_sid" 2>/dev/null || true
+ fi
+ fi ;;
+esac
+case "${1:-}" in condiviso|gesto|guardia|tocco)
+ if [ -z "${DELMINIO_NO_CODEX:-}" ] && pid_cli=$(cli_pid) && e_codex "$pid_cli"; then
+ entrata=$(mktemp); uscita=$(mktemp); errori=$(mktemp)
+ cat > "$entrata"
+ DELMINIO_NO_CODEX=1 bash "$0" "$@" < "$entrata" > "$uscita" 2> "$errori"; rc=$?
+ if [ "$rc" = 2 ]; then
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
+ "permissionDecision": "deny", "permissionDecisionReason": sys.argv[1],
+ "additionalContext": open(sys.argv[2], encoding="utf-8", errors="replace").read()}}))' "$M_fermato_codex" "$errori"
+ rc=0
+ else
+ cat "$uscita"; cat "$errori" >&2
+ fi
+ rm -f "$entrata" "$uscita" "$errori"; exit "$rc"
+ fi ;;
+esac
+
+parte() { # parte <file accanto al client>
+ [ -f "$(dirname "$0")/$1" ] && return 0
+ _f "$M_parte_manca" file "$(dirname "$0")/$1" >&2
+ exit 1
+}
+
+case "${1:-}" in
+ cantiere) shift; exec python3 "$(dirname "$0")/cantiere.py" "$@" ;;
+ apertura)
+ pid=$(cli_pid || true)
+ cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
+ if [ -n "$pid" ] && headless "$pid"; then pid=""; fi # un -p non è una sessione
+ [ -n "${DELMINIO_PROVA:-}" ] && pid=""
+ DELMINIO_ESEGUIBILE=$(stato_eseguibile 2>/dev/null || true); export DELMINIO_ESEGUIBILE
+ DELMINIO_APP_CODEX=""
+ if [ -f "$(dirname "$0")/plugin.py" ]; then
+ _tempo 20 python3 "$(dirname "$0")/plugin.py" app-codex allinea >/dev/null 2>&1 || true
+ DELMINIO_APP_CODEX=$(python3 "$(dirname "$0")/plugin.py" app-codex stato 2>/dev/null || true)
+ fi
+ export DELMINIO_APP_CODEX
+ senza=""; [ "$cli" = claude ] || senza=1
+ 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")
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ if [ -n "$pid" ] && [ -z "${DELMINIO_PROVA:-}" ]; then
+ sorgente=$(printf '%s' "$evento" | campo source)
+ sid=$(printf '%s' "$evento" | campo session_id)
+ if [ -n "$sid" ] && { [ "$sorgente" = fork ] || in_sottofondo "$pid"; }; then
+ rm -f "$STATO/sessione-$pid"
+ printf '%s' "$sid" > "$STATO/nasci-$pid"
+ if [ "$sorgente" = fork ]; then madri_del_fork "$evento" "$sid" > "$STATO/fork-$pid"; else rm -f "$STATO/fork-$pid"; fi
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$M_nasce_al_primo"
+ exit 0
+ fi
+ fi
+ if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
+ GIT_TERMINAL_PROMPT=0 _tempo 5 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true
+ fi
+ if [ -n "$pid" ]; then fatti=$(fatti_nascita "$pid" "$evento")
+ else fatti=$(fatti_codex "$cli" "$evento" "$fatti"); fi
+ cure
+ if r=$(chiedi POST /api/apertura "$fatti"); then
+ [ "$cli" != codex ] || [ -z "$pid" ] || [ -n "${DELMINIO_PROVA:-}" ] || segna_informativa_codex "$r"
+ nome=$(printf '%s' "$r" | campo sessione); stato=$(printf '%s' "$r" | campo stato)
+ if [ -n "$pid" ] && [ -n "$nome" ]; then
+ rm -f "$STATO/nasci-$pid"
+ if [ "$stato" = chiusa ]; then
+ rm -f "$STATO/sessione-$pid"
+ [ "$(printf '%s' "$r" | campo al_primo_messaggio)" = True ] && \
+ printf '%s' "$evento" | campo session_id > "$STATO/nasci-$pid"
+ else
+ printf '%s' "$nome" > "$STATO/sessione-$pid"
+ zitta_la_prima "$r" "$pid"
+ _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
+ fi
+ fi
+ serve=$(printf '%s' "$r" | campo versione)
+ ra=$(riaggancio_stato "$(git rev-parse --show-toplevel 2>/dev/null)")
+ indietro=""
+ if [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$serve" ] && [ "$serve" != "${KIT:-}" ] && [ -s "$ra.log" ] \
+ && [ "$(cat "$ra.verso" 2>/dev/null)" = "$serve" ] \
+ && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -gt 120 ]; then # più giovane: è ancora in corsa
+ indietro=$(_f "$M_client_fermo" kit "${KIT:-?}" serve "$serve" errore "$(grep -v '^[[:space:]]*$' "$ra.log" | tail -1 | cut -c1-200)")
+ fi
+ riaggancia "$serve" "$(git rev-parse --show-toplevel 2>/dev/null)"
+ fratelli_indietro "$serve"
+ voluto=$(printf '%s' "$r" | campo eseguibili)
+ eseguibili_indietro "$voluto" giorno && allinea_staccato
+ skill_staccato
+ pubblico_segna "$r"
+ printf '%s' "$r" | DELMINIO_INDIETRO="$indietro" python3 -c 'import json,os,sys
+h = json.load(sys.stdin)["hookSpecificOutput"]
+if os.environ.get("DELMINIO_INDIETRO"):
+ h["additionalContext"] = os.environ["DELMINIO_INDIETRO"] + "\n\n" + h.get("additionalContext", "")
+print(json.dumps({"hookSpecificOutput": h}))'
+ exit 0
+ fi
+ perche=$(perche_no)
+ riprova=""
+ if [ -n "$pid" ]; then
+ sid=$(printf '%s' "$evento" | campo session_id)
+ [ -n "$sid" ] && printf '%s' "$sid" > "$STATO/nasci-$pid" && riprova=$M_riprova_al_primo
+ fi
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$(_f "$M_nasce_senza_memoria" perche "$perche" riprova "$riprova")"
+ [ -z "${DELMINIO_PROVA:-}" ] || exit 3
+ ;;
+ cuore)
+ pid="$2"; processo="$3"
+ io="$STATO/cuore-$pid"
+ altro=$(cat "$io" 2>/dev/null || true)
+ [ -n "$altro" ] && [ "$altro" != "$$" ] && kill -0 "$altro" 2>/dev/null && exit 0
+ echo "$$" > "$io"
+ spazza_stato
+ albero=$(git rev-parse --show-toplevel 2>/dev/null || true)
+ P=$(json_stringa "$processo")
+ fresco() { [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ] && \
+ GIT_TERMINAL_PROMPT=0 _tempo 20 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true; }
+ principale=$(dirname "$(_assoluto "$(git rev-parse --git-common-dir 2>/dev/null)")")
+ riservo() {
+ local r b corpo rif nome
+ [ -n "$principale" ] && [ "$principale" != . ] || return 0
+ r=$(chiedi GET /api/riservo) || return 0
+ b="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$principale" | _sha16)"
+ printf '%s' "$r" | (umask 077; python3 -c '
+import hashlib, json, os, re, shutil, sys
+b = sys.argv[1]
+r = json.load(sys.stdin)
+ist, rad = r.get("istanza") or "", r.get("radice") or ""
+if not rad:
+ sys.exit(0)
+d = os.path.join(b, rad[:16], "riservo")
+def leggi(p):
+ try:
+ return open(p, encoding="utf-8").read().strip()
+ except OSError:
+ return ""
+if not os.path.isdir(d) and ist and leggi(os.path.join(b, "riservo", "istanza")) == ist:
+ os.makedirs(os.path.dirname(d), exist_ok=True)
+ os.rename(os.path.join(b, "riservo"), d)
+def nome_file(n):
+ return (re.sub(r"[^a-z0-9]+", "_", n.lower()).strip("_")[:60] or "memoria") + "-" + hashlib.sha1(n.encode()).hexdigest()[:8] + ".md"
+def nome_md(testo):
+ m = re.search(r"^name:\s*(.+?)\s*$", testo, re.M)
+ v = m.group(1) if m else ""
+ try:
+ return json.loads(v) if v.startswith("\"") else v.strip("\x27")
+ except ValueError:
+ return v
+remoti = {k: {m["name"] for m in r.get(k) or []} for k in ("personali", "riservate")}
+if leggi(os.path.join(d, "radice")) == rad:
+ rif = os.path.join(d, "rifiutate")
+ no = set(leggi(rif).splitlines())
+ manca = []
+ for k in ("personali", "riservate"):
+ cart = os.path.join(d, k)
+ for f in sorted(os.listdir(cart)) if os.path.isdir(cart) else []:
+ testo = open(os.path.join(cart, f), encoding="utf-8").read()
+ n = nome_md(testo)
+ if n and n not in remoti[k] and n not in no:
+ manca.append(rif + "\t" + n + "\t" + json.dumps({"md": testo, "riservata": k == "riservate", "radice": rad}, ensure_ascii=False))
+ if manca:
+ print("\n".join(manca))
+ sys.exit(0)
+nuova = d + ".nuova"
+shutil.rmtree(nuova, ignore_errors=True)
+for k in ("personali", "riservate"):
+ os.makedirs(os.path.join(nuova, k))
+ for m in r.get(k) or []:
+ with open(os.path.join(nuova, k, nome_file(m["name"])), "w", encoding="utf-8") as f:
+ f.write(m["md"])
+for n, v in (("istanza", ist), ("radice", rad)):
+ with open(os.path.join(nuova, n), "w", encoding="utf-8") as f:
+ f.write(v)
+os.makedirs(os.path.dirname(d), exist_ok=True)
+vecchia = d + ".vecchia"
+shutil.rmtree(vecchia, ignore_errors=True)
+if os.path.isdir(d):
+ os.rename(d, vecchia)
+os.rename(nuova, d)
+shutil.rmtree(vecchia, ignore_errors=True)
+' "$b") | { umask 077; while IFS=$'\t' read -r rif nome corpo; do
+ if r=$(chiedi POST /api/riservo/riporta "$corpo"); then
+ printf '%s' "$r" | grep -q '"riportata": *false' && printf '%s\n' "$nome" >> "$rif"
+ else
+ case $(cut -f1 "$STATO/no-$$" 2>/dev/null) in 400|409) printf '%s\n' "$nome" >> "$rif" ;; esac
+ fi
+ done; }
+ }
+ giri=0
+ provata="" # l'impronta che questo cuore ha già provato ad allineare: una volta sola
+ passo=${DELMINIO_CUORE_SECONDI:-20}
+ case $passo in ''|*[!0-9]*|0) passo=20 ;; esac
+ while kill -0 "$pid" 2>/dev/null; do
+ vero=$(albero_di "$(mia_sessione "$pid")"); [ -n "$vero" ] && albero="$vero"
+ A=$(json_stringa "$albero")
+ b=$(chiedi POST /api/canale/battito "{\"processo\":$P,\"cuore\":true,\"albero\":$A}" || true)
+ voluto=$(printf '%s' "$b" | campo eseguibili)
+ if [ -n "$voluto" ] && [ "$voluto" != "$provata" ] && eseguibili_indietro "$voluto"; then
+ provata=$voluto
+ allinea_staccato
+ fi
+ giri=$((giri + 1)); [ $((giri % 15)) -eq 0 ] && fresco
+ { [ "$giri" -eq 1 ] || [ $((giri % 15)) -eq 0 ]; } && { cure; testi; repo_stato; riservo; }
+ sleep "$passo"
+ done
+ fresco
+ lascito=""
+ [ -n "$albero" ] && [ -x "$albero/.delminio/lascito.sh" ] && \
+ python3 -c 'import os,sys
+exec(os.environ["DELMINIO_FIDATI_PY"])
+a, f = sys.argv[1:]
+sys.exit(0 if da_fidarsi(a, f, accettati(a)) else 1)' "$albero" "$albero/.delminio/lascito.sh" 2>/dev/null && \
+ lascito=$(_tempo 30 bash "$albero/.delminio/lascito.sh" "$pid" "$albero" 2>/dev/null | head -c 1500 || true)
+ if [ -z "$lascito" ]; then
+ lascito="$M_nessun_albero"
+ if [ -n "$albero" ]; then
+ n=$(git -C "$albero" status --porcelain 2>/dev/null | grep -c . || true)
+ if [ "${n:-0}" -gt 0 ]; then lascito=$(_f "$M_albero_sporco" albero "$albero" n "$n")
+ else lascito=$(_f "$M_albero_pulito" albero "$albero"); fi
+ fi
+ fi
+ L=$(json_stringa "$lascito")
+ chiedi POST /api/sessioni/muori "{\"processo\":$P,\"lascito\":$L}" >/dev/null || true
+ rm -f -- "$STATO"/*-"$pid"
+ ;;
+ segreto)
+ python3 -c '
+import json, re, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+try:
+ p = json.load(sys.stdin).get("prompt") or ""
+except Exception:
+ sys.exit(0)
+if re.search(r"eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}|DELMINIO_TOKEN=\S", p):
+ sys.stderr.write(F("chiave_nel_messaggio"))
+ sys.exit(2)
+'
+ exit $?
+ ;;
+ umano|volo|attesa)
+ if [ "$1" = volo ]; then
+ ev=$(_tempo 2 cat 2>/dev/null || true)
+ if [[ $ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]]; then
+ presto="$STATO/volo-sid-${BASH_REMATCH[1]}"
+ [ -f "$presto" ] && [ $(( $(date +%s) - $(_mtime "$presto") )) -lt 10 ] && exit 0
+ touch "$presto"
+ fi
+ fi
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ headless "$pid" && exit 0
+ if e_qwen "$pid" && [ "$1" = umano ]; then
+ letto=""; [ -t 0 ] || letto=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$(printf '%s' "$letto" | campo prompt)" ] || exit 0
+ fi
+ if e_codex "$pid" || e_qwen "$pid" || e_opencode "$pid"; then
+ if [ "$1" = attesa ]; then
+ sid=$(_tempo 2 cat 2>/dev/null | campo session_id || true)
+ if [ -n "$sid" ]; then
+ _staccato bash "$0" attesa-codex "$pid" "$sid" >/dev/null 2>&1 < /dev/null &
+ fi
+ echo '{}'; exit 0
+ fi
+ [ "$1" = umano ] && { v=$(cat "$STATO/attesa-$pid" 2>/dev/null || true); [ -n "$v" ] && kill "$v" 2>/dev/null; rm -f "$STATO/attesa-$pid"; }
+ fi
+ if [ "$1" = volo ]; then
+ if grep -q '"agent_id"' <<<"$ev" && [ -n "$(printf '%s' "$ev" | campo agent_id)" ]; then exit 0; fi
+ fi
+ if [ "$1" = umano ] && [ -f "$STATO/nasci-$pid" ]; then
+ evento=${letto:-}; [ -n "$evento" ] || [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ if [ "$(printf '%s' "$evento" | campo session_id)" != "$(cat "$STATO/nasci-$pid" 2>/dev/null)" ]; then
+ rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
+ elif madri=$(cat "$STATO/fork-$pid" 2>/dev/null || true) \
+ && { [ ! -f "$STATO/fork-$pid" ] || [ "$madri" != '[]' ] || madri=$(madri_del_fork "$evento" "$(cat "$STATO/nasci-$pid")"); } \
+ && r=$(chiedi POST /api/apertura "$(DELMINIO_MADRI="$madri" fatti_nascita "$pid" "$evento" si)"); then
+ e_codex "$pid" && segna_informativa_codex "$r"
+ rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
+ nome=$(printf '%s' "$r" | campo sessione)
+ case "$(printf '%s' "$r" | campo stato)" in nuova|ripresa|adottata)
+ if [ -n "$nome" ]; then
+ printf '%s' "$nome" > "$STATO/sessione-$pid"
+ zitta_la_prima "$r" "$pid"
+ _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
+ printf '%s' "$r" | python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": json.load(sys.stdin)["hookSpecificOutput"]}))'
+ exit 0
+ fi ;;
+ esac
+ fi
+ fi
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ if [ "$1" = volo ]; then
+ ultima="$STATO/volo-$pid"
+ [ -f "$ultima" ] && [ $(( $(date +%s) - $(_mtime "$ultima") )) -lt 10 ] && exit 0
+ touch "$ultima"
+ fi
+ N=$(json_stringa "$nome")
+ albero=$(albero_di "$nome")
+ A=$(json_stringa "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}")
+ giri=0
+ if [ "$1" = attesa ]; then
+ io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
+ [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
+ echo "$$" > "$io"
+ fi
+ avviso=""
+ while :; do
+ somme=$(_conto_somme)
+ voci=$(_skill_voci)
+ if [ -n "$voci" ]; then
+ cli=claude; e_codex "$pid" && cli=codex; e_qwen "$pid" && cli=qwen; e_opencode "$pid" && cli=opencode
+ voci=",\"cli\":\"$cli\",\"skill\":[$voci]"
+ fi
+ if b=$(chiedi POST /api/canale/battito "{\"sessione\":$N,\"albero\":$A${somme:+,\"ganci\":{$somme\}}$voci}"); then
+ rm -f "$STATO/posta-muta-$pid"
+ case "$b" in *'"carta":true'*) : > "$STATO/carta"; rm -f "$STATO/carta-no" ;;
+ *) rm -f "$STATO/carta"; : > "$STATO/carta-no" ;; esac
+ ultimo=$(printf '%s' "$b" | campo ultimo)
+ [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}"
+ else
+ ultimo=""
+ if [ "$1" = umano ] && [ ! -f "$STATO/posta-muta-$pid" ]; then
+ touch "$STATO/posta-muta-$pid"
+ avviso=$(_f "$M_posta_non_arriva" perche "$(perche_no)")
+ fi
+ fi
+ cursore="$STATO/visto-$pid"; [ "$1" = attesa ] && cursore="$STATO/visto-attesa-$pid"
+ if [ -n "$ultimo" ] && [ "$(cat "$cursore" 2>/dev/null)" != "$ultimo" ] \
+ && t=$(chiedi GET "/api/canale/posta/testo?sessione=$nome&momento=$1"); then
+ printf '%s' "$ultimo" > "$cursore"
+ testo=$(printf '%s' "$t" | campo testo)
+ [ -n "$testo" ] && printf '%s' "$ultimo" > "$STATO/visto-$pid"
+ if [ -n "$testo" ]; then
+ if [ "$1" != attesa ]; then
+ evento=PostToolUse; [ "$1" = umano ] && evento=UserPromptSubmit
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": sys.argv[1], "additionalContext": sys.stdin.read()}}))' "$evento" <<<"$testo"
+ exit 0
+ fi
+ printf '%s\n' "$testo" >&2; exit 2
+ fi
+ fi
+ if [ -n "$avviso" ]; then
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.argv[1]}}))' "$avviso"
+ exit 0
+ fi
+ [ "$1" != attesa ] && exit 0
+ kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ] || exit 0
+ giri=$((giri + 1))
+ sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
+ done
+ ;;
+ consumi|consumi-tool)
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ passo="$STATO/consumi-$pid"
+ if [ "$1" = consumi-tool ] && [ -f "$passo" ] && [ $(( $(date +%s) - $(_mtime "$passo") )) -lt 30 ]; then exit 0; fi
+ touch "$passo"
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$evento" ] || exit 0
+ printf '%s' "$evento" > "$STATO/consumi-evento-$pid"
+ _staccato bash "$0" consumi-manda "$pid" "$nome" >/dev/null 2>&1 < /dev/null &
+ exit 0
+ ;;
+ consumi-manda)
+ exec 9>"$STATO/consumi-lock-$2"
+ command -v flock >/dev/null 2>&1 && { flock -w 10 9 || exit 0; }
+ evento=$(cat "$STATO/consumi-evento-$2" 2>/dev/null)
+ corpo=$(consumi_dal_transcript "$STATO/consumi-stato-$2" "$evento")
+ [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
+ corpo=$(totale_cli_qwen "$evento")
+ [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
+ ;;
+ memorie)
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ headless "$pid" && exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ modello_dal_transcript "$pid" "$nome" "$evento"
+ if [ -f "$STATO/carta" ] || [ ! -f "$STATO/carta-no" ]; then
+ printf '%s' "$evento" | carta_richiesta "$nome"
+ fi
+ corpo=$(printf '%s' "$evento" | python3 -c '
+import json, os, sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+testo = (e.get("prompt") or "").strip()
+if not testo:
+ sys.exit(0)
+
+def risposta(ev):
+ if not isinstance(ev, dict):
+ return ""
+ if ev.get("type") == "response_item":
+ p = ev.get("payload") or {}
+ if p.get("type") == "message" and p.get("role") == "assistant":
+ return "\n".join(b.get("text", "") for b in p.get("content") or []
+ if isinstance(b, dict) and b.get("type") == "output_text").strip()
+ return ""
+ if ev.get("type") != "assistant" or not isinstance(ev.get("message"), dict):
+ return ""
+ m = ev["message"]
+ if m.get("parts") is not None:
+ return "\n".join(x.get("text", "") for x in m["parts"] if isinstance(x, dict)
+ and isinstance(x.get("text"), str) and not x.get("thought")).strip()
+ return "\n".join(b.get("text", "") for b in m.get("content") or []
+ if isinstance(b, dict) and b.get("type") == "text").strip()
+
+coda = e.get("coda") if isinstance(e.get("coda"), str) else ""
+try:
+ with open("" if coda else (e.get("transcript_path") or ""), "rb") as f:
+ f.seek(0, os.SEEK_END)
+ f.seek(max(0, f.tell() - 2_000_000))
+ for riga in reversed(f.read().decode("utf-8", "replace").splitlines()):
+ try:
+ coda = risposta(json.loads(riga))
+ except ValueError:
+ continue
+ if coda:
+ break
+except OSError:
+ pass
+print(json.dumps({"testo": testo[:1500], "coda": coda[-1200:]}, ensure_ascii=False))
+' 2>/dev/null || true)
+ [ -n "$corpo" ] || exit 0
+ r=$(CHIEDI_TEMPO=2 CHIEDI_SESSIONE="$nome" chiedi POST /api/memorie/messaggio "$corpo") || exit 0
+ testo=$(printf '%s' "$r" | campo testo)
+ [ -n "$testo" ] || exit 0
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.stdin.read()}}))' <<<"$testo"
+ ;;
+ rito)
+ pid=$(cli_pid || true); [ -n "$pid" ] && { e_codex "$pid" || e_qwen "$pid"; } || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ rito=$(printf '%s' "$evento" | python3 -c 'import json,re,sys
+try:
+ p = (json.load(sys.stdin).get("prompt") or "").strip()
+except Exception:
+ sys.exit(0)
+prima, _, resto = p.partition("\n")
+riti = json.loads(__import__("os").environ.get("DELMINIO_COMANDI") or "{}").get("riti") or {"apertura": "apertura", "chiusura": "chiusura"}
+nomi = "|".join(re.escape(n) for n in sorted(riti, key=len, reverse=True))
+m = (re.fullmatch(r"/(" + nomi + r")(?:\s+(.*))?", prima.strip(), re.I | re.S)
+ or re.fullmatch(r"(" + nomi + r")\s*(?::\s*(.*))?", prima.strip(), re.I | re.S))
+if m and re.match(r"/" + m.group(1) + r"\b", resto.strip(), re.I):
+ resto = resto.strip()[len(m.group(1)) + 1:]
+if m:
+ 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)
+ [ -n "$rito" ] || exit 0
+ parola=${rito%%$'\t'*}; dopo=${rito#*$'\t'}
+ if [ "$parola" = apertura ]; then testo=$(bash "$0" prompt); else testo=$(bash "$0" chiusura "$dopo"); fi
+ python3 -c 'import json,sys
+print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext":
+ sys.argv[1] + "\n\n" + sys.stdin.read()}}))' "$(_f "$M_gesto_umano" parola "$parola")" <<<"$testo"
+ ;;
+ ritira-file)
+ echo "$$" > "$STATO/ritiro-$2"
+ ritira_file "$2" "$3"
+ rm -f "$STATO/ritiro-$2"
+ ;;
+ invia)
+ f=${2:-}; nota=${3:-}
+ [ -n "$f" ] || { echo "$M_invia_uso" >&2; exit 1; }
+ [ -f "$f" ] && [ -r "$f" ] || { _f "$M_invia_non_trovato" file "$f" >&2; exit 1; }
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { echo "$M_invia_senza_sessione" >&2; exit 1; }
+ tipo=$(python3 -c 'import mimetypes, sys; print(mimetypes.guess_type(sys.argv[1])[0] or "application/octet-stream")' "$f")
+ q="verso=persona&sessione=$(_urlenc "$nome")&nome=$(_urlenc "$(basename "$f")")¬a=$(_urlenc "$nota")"
+ r=$(curl -sS -m 900 -w '\n%{http_code}' -K <(_chiave "$TOKEN") -H "Content-Type: $tipo" \
+ --data-binary @"$f" "$URL/api/file?$q" 2>/dev/null)
+ c=${r##*$'\n'}; r=${r%$'\n'*}
+ if [ "$c" != 200 ]; then
+ e=$(printf '%s' "$r" | campo error); _f "$M_invia_fallito" perche "${e:-HTTP ${c:-000}}" >&2; exit 1
+ fi
+ _f "$M_invia_fatto" nome "$(printf '%s' "$r" | campo nome)"
+ ;;
+ attesa-codex)
+ pid=$2; sid=$3
+ [ -n "$sid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
+ [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
+ echo "$$" > "$io"
+ N=$(json_stringa "$nome")
+ giri=0
+ albero=$(albero_di "$nome"); albero=${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}
+ while kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ]; do
+ b=$(chiedi POST /api/canale/battito "{\"sessione\":$N}" || true)
+ ultimo=$(printf '%s' "$b" | campo ultimo)
+ [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "$albero"
+ if [ -n "$ultimo" ] && [ "$ultimo" != "${guardato:-}" ] \
+ && [ "$(cat "$STATO/visto-$pid" 2>/dev/null)" != "$ultimo" ] \
+ && [ "$(cat "$STATO/avvisato-$pid" 2>/dev/null)" != "$ultimo" ]; then
+ guardato=$ultimo
+ per_lei=$(chiedi GET "/api/canale/posta?sessione=$nome&segna=0" | python3 -c 'import json,sys
+try:
+ r = json.load(sys.stdin); print(r["sveglie"] if "sveglie" in r else len(r.get("messaggi") or []))
+except Exception: print(0)')
+ [ "${per_lei:-0}" -gt 0 ] || { giri=$((giri + 1)); sleep 3; continue; }
+ avviso_posta=$M_posta_arrivata
+ if e_opencode "$pid"; then
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ printf '%s\n' "$avviso_posta"
+ elif e_qwen "$pid"; then
+ f="${DELMINIO_QWEN_POSTA:-}"
+ 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
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ fi
+ elif "${DELMINIO_CLI:-codex}" queue --thread "$sid" --message "$avviso_posta" >/dev/null 2>&1; then
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ fi
+ rm -f "$io"; exit 0
+ fi
+ giri=$((giri + 1))
+ sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
+ done
+ ;;
+ prompt)
+ porta="${DELMINIO_PORTA:-${DELMINIO_MODELLO:-}}"
+ r=$(curl -sS -m 15 -G -w '\n%{http_code}' -K <(_chiave "$TOKEN") \
+ --data-urlencode "ordine=$porta" --data-urlencode "sistema=$([ -n "${DELMINIO_SISTEMA:-}" ] && echo 1 || echo 0)" \
+ "$URL/api/porte/prompt" 2>/dev/null)
+ codice=${r##*$'\n'}
+ case "$codice" in
+ ''|000) _f "$M_delminio_risponde_prompt" url "$URL" ;;
+ 200) printf '%s\n' "${r%$'\n'*}" ;;
+ *) e=$(printf '%s' "${r%$'\n'*}" | campo error 2>/dev/null || true)
+ _f "$M_prompt_rifiutato" url "$URL" codice "$codice" errore "${e:+: $e}" ;;
+ esac
+ ;;
+ claude|codex|app-codex|qwen|opencode)
+ parte lanciatori.sh && . "$(dirname "$0")/lanciatori.sh" "$@"
+ ;;
+ cassaforte)
+ shift
+ python3 "$(cd "$(dirname "$0")" && pwd)/cassaforte.py" "$@"
+ ;;
+ eseguibili|eseguibile)
+ shift
+ [ $# -eq 0 ] && set -- allinea
+ python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit "$@"
+ ;;
+ condiviso)
+ evento=$(cat)
+ if [[ $evento == *'cd '* || $evento == *workdir* || $evento == *exec_command* || $evento == *rollout-* ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ dove=$(printf '%s' "$evento" | campo cwd)
+ radice=$(git -C "${dove:-.}" rev-parse --show-toplevel 2>/dev/null) || radice=""
+ if [ -z "$radice" ] || [ ! -f "$radice/.delminio/condivisi" ]; then
+ radice=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
+ fi
+ [ -f "$radice/.delminio/condivisi" ] || exit 0
+ corpo=$(printf '%s' "$evento" | python3 -c '
+import json, re, sys
+try:
+ c = (json.load(sys.stdin).get("tool_input") or {}).get("command") or ""
+except Exception:
+ c = ""
+for r in open(sys.argv[1], encoding="utf-8"):
+ r = r.strip()
+ if c and r and not r.startswith("#"):
+ try:
+ if re.search(r, c, re.I):
+ print(json.dumps({"sessione": sys.argv[2], "comando": c}))
+ break
+ except re.error:
+ pass' "$radice/.delminio/condivisi" "")
+ [ -n "$corpo" ] || exit 0
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ tregua="$STATO/condiviso-$pid"
+ if [ -f "$tregua" ] && [ $(( $(date +%s) - $(_mtime "$tregua") )) -lt 600 ]; then exit 0; fi
+ corpo=$(printf '%s' "$corpo" | python3 -c 'import json,sys; d = json.load(sys.stdin); d["sessione"] = sys.argv[1]; print(json.dumps(d))' "$nome")
+ [ -n "$corpo" ] || exit 0
+ r=$(chiedi POST /api/condiviso "$corpo") || exit 0
+ if DELMINIO_R="$r" python3 -c 'import json,os,sys
+r = json.loads(os.environ["DELMINIO_R"])
+if r.get("ferma"):
+ print(r.get("testo", ""), file=sys.stderr)
+ sys.exit(2)'; then exit 0; fi
+ touch "$tregua"; exit 2
+ ;;
+ gesto)
+ evento=$(cat)
+ strumento=""; [[ $evento =~ \"tool_name\":\ ?\"([^\"]+)\" ]] && strumento=${BASH_REMATCH[1]}
+ case "$strumento" in Bash|exec_command|run_shell_command|"") di_shell=1 ;; *) di_shell="" ;; esac
+ if [ -z "$di_shell" ]; then
+ globi=$(strumenti_vivi) && [ -n "$globi" ] || exit 0
+ combacia=""; shopt -s nocasematch
+ while IFS= read -r g; do
+ [ -n "$g" ] && [[ $strumento == $g ]] && { combacia=1; break; }
+ done <<<"$globi"
+ shopt -u nocasematch
+ [ -n "$combacia" ] || exit 0
+ fi
+ dove_fatto=""
+ if [ -n "$di_shell" ] && [[ $evento == *'"workdir"'* || $evento =~ \"command\":\ ?\"[[:space:]]*cd[[:space:]] ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
+ fi
+ gira="$PWD"; [[ $evento =~ \"cwd\":\ ?\"([^\"]+)\" ]] && gira=${BASH_REMATCH[1]}
+ repo_gesto=$(_remoto "$gira" || true)
+ corpo=$(printf '%s' "$evento" | python3 -c 'import json,sys
+try:
+ e = json.load(sys.stdin)
+ c = (e.get("tool_input") or {}).get("command") or "" if sys.argv[1] else ""
+except Exception:
+ c = ""
+d = {"comando": c} if c else {}
+if sys.argv[2]:
+ d["strumento"] = sys.argv[2]
+if d and sys.argv[3]:
+ d["repo"] = sys.argv[3]
+print(json.dumps(d) if d else "")' "$di_shell" "$strumento" "$repo_gesto")
+ [ -n "$corpo" ] || exit 0
+ r=$(chiedi POST /api/lock "$corpo") || exit 0
+ [[ $r == *'"lock":[]}' || $r == *'"lock": []}' ]] && exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ detti="${pid:+$STATO/lock-detti-$pid}"
+ if [ -z "$dove_fatto" ] && [[ $r =~ \"comando_gesto\":\ ?\"[^\"] ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ read -r -d '' _gesto_py <<'GESTO' || true
+import hashlib, json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+detti_f = sys.argv[1]
+try:
+ detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
+except OSError:
+ detti = set()
+lock = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
+ATTESA_DI_SERIE = 5 # B938: come lock.ATTESA_DI_SERIE nel motore
+evento = sys.stdin.read()
+try:
+ accettate = set(open(os.environ.get("DELMINIO_ACCETTATE") or "", encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+nuovi_detti = []
+
+
+def una_volta(segno, testo):
+ if segno not in detti and segno not in nuovi_detti:
+ nuovi_detti.append(segno)
+ print("dire", json.dumps(testo))
+
+
+def cieco(l, motivo, secondi):
+ """B938 — il controllo non ha detto niente: si conta sempre. In una decisione che
+ blocca, se non parte (o è lento e la decisione lo vuole) il comando si ferma come per
+ una violazione: decide il motore (l'amministratore passa con un avviso). Se no passa."""
+ cmd = l["comando_gesto"]
+ print("cieco", l["codice"], motivo)
+ if l.get("duro") and (motivo == "non_parte" or l.get("se_lento")):
+ if motivo == "non_parte":
+ fermo = F("gesto_controllo_non_parte_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd)
+ breve = F("controllo_non_parte_breve", comando=cmd)
+ else:
+ fermo = F("gesto_controllo_lento_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd, secondi=secondi)
+ breve = F("controllo_lento_breve", comando=cmd, secondi=secondi)
+ print("viola_cieco", json.dumps({"codice": l["codice"], "breve": breve, "fermo": fermo}))
+ return
+ if motivo == "non_parte":
+ una_volta("?" + l["codice"], F("gesto_controllo_non_parte_passa", codice=l["codice"], comando=cmd))
+ else:
+ una_volta("?" + l["codice"], F("gesto_controllo_lento_passa", codice=l["codice"], comando=cmd, secondi=secondi))
+
+
+def prova(l):
+ """Il controllo di una decisione prima del comando: (gridato, uscita) o None se
+ non ha potuto dire niente — e allora l'ha già detto, o l'ha passato a ``cieco``."""
+ cmd = l["comando_gesto"]
+ impronta = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + cmd).encode()).hexdigest()
+ if impronta not in accettate:
+ una_volta("?" + l["codice"], F("gesto_controllo_non_accettato", codice=l["codice"], cosa=l["cosa"], comando=cmd))
+ return None
+ try:
+ e = json.loads(evento)
+ except ValueError:
+ e = {}
+ dove = str(e.get("cwd") or "")
+ radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True,
+ cwd=dove if os.path.isdir(dove) else None).stdout.strip() or "."
+ comando = str((e.get("tool_input") or {}).get("command") or "")
+ amb = {**os.environ, "DELMINIO_CWD": str(e.get("cwd") or os.getcwd())}
+ if len(comando) < 100000:
+ amb["DELMINIO_COMANDO"] = comando
+ secondi = int(l.get("attesa") or 0) or ATTESA_DI_SERIE
+ try:
+ p = subprocess.run(cmd, shell=True, cwd=radice, input=evento, capture_output=True, text=True,
+ timeout=secondi, env=amb)
+ except subprocess.TimeoutExpired:
+ cieco(l, "lento", secondi)
+ return None
+ except OSError:
+ p = None
+ if p is None or p.returncode in (126, 127):
+ cieco(l, "non_parte", secondi)
+ return None
+ return p.returncode != 0, (p.stdout + p.stderr).strip()
+
+
+for l in lock:
+ if l.get("comando_gesto"):
+ esito = prova(l)
+ if not esito or not esito[0]:
+ continue
+ uscita = esito[1]
+ if l.get("duro"):
+ print("viola", l["codice"], json.dumps(uscita[-3000:]))
+ else:
+ righe = "".join("\n " + r for r in uscita.splitlines()[-15:])
+ testo = F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"])
+ print("dire", json.dumps(testo + ("\n" + F("guardia_dice") + righe if righe else "")))
+ print("conta", l["codice"])
+ continue
+ if l.get("duro"):
+ print("duro", l["codice"])
+ else:
+ una_volta(l["codice"], F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"]))
+if nuovi_detti and detti_f:
+ with open(detti_f, "a", encoding="utf-8") as f:
+ f.write("".join(x + "\n" for x in nuovi_detti))
+GESTO
+ piano=$(printf '%s' "$evento" | DELMINIO_LOCK="$r" DELMINIO_ACCETTATE="$(accettate_file 2>/dev/null)" python3 -c "$_gesto_py" "$detti")
+ [ -n "$piano" ] || exit 0
+ contesto=""; impronta=$(chiave_in_uso)
+ descr=$(printf '%s' "$evento" | python3 -c 'import json,sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ e = {}
+t = e.get("tool_input") or {}
+if sys.argv[1]:
+ print("comando: " + str(t.get("command") or ""), end="")
+else:
+ print("strumento: " + sys.argv[2] + " · " + json.dumps(t, ensure_ascii=False)[:300], end="")' "$di_shell" "$strumento")
+ sullo_strumento=false; [ -z "$di_shell" ] && sullo_strumento=true
+ while read -r tipo resto; do
+ case "$tipo" in
+ dire) contesto="$contesto$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]))' "$resto")"$'\n' ;;
+ duro)
+ 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")
+ v=$(chiedi POST /api/lock/violazione "$corpo") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ if [ "$esito" = ferma ]; then echo "🔒 $msg" >&2; exit 2; fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n' ;;
+ cieco)
+ 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")
+ CHIEDI_TEMPO=2 chiedi POST /api/lock/cieco "$corpo_k" >/dev/null 2>&1 || true ;;
+ viola_cieco)
+ corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
+c = json.loads(sys.argv[1])
+print(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")
+ v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ if [ "$esito" = ferma ]; then
+ printf '%s' "$resto" | campo fermo >&2
+ echo "🔒 $msg" >&2; exit 2
+ fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n'"$(printf '%s' "$resto" | campo breve)"$'\n' ;;
+ conta)
+ 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")
+ CHIEDI_TEMPO=2 chiedi POST /api/lock/violazione "$corpo_c" >/dev/null 2>&1 || true ;;
+ viola)
+ corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
+codice, uscita = sys.argv[1].split(" ", 1)
+uscita = json.loads(uscita)
+print(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")
+ v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ dice=$(printf '%s' "$resto" | python3 -c 'import json,sys
+_, u = sys.stdin.read().split(" ", 1)
+print("".join("\n " + r for r in json.loads(u).splitlines()[-15:]), end="")')
+ if [ "$esito" = ferma ]; then printf '🔒 %s%s\n' "$msg" "${dice:+$'\n'$M_guardia_dice$dice}" >&2; exit 2; fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg${dice:+$'\n'$M_guardia_dice$dice}"$'\n' ;;
+ esac
+ done <<<"$piano"
+ [ -n "$contesto" ] && python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$contesto"
+ exit 0
+ ;;
+ dove)
+ evento=$(cat); printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"
+ ;;
+ guardia)
+ evento=$(cat)
+ dove_fatto=""
+ if [[ $evento == *rollout-* || $evento =~ \"tool_name\":\ ?\"apply_patch\" ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
+ fi
+ if [ -z "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
+ _guardia_serve "$evento" || exit 0
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ if incerto=$(printf '%s' "$evento" | campo dove_incerto) && [ -n "$incerto" ]; then
+ _f "$M_guardia_cartella_gira" incerto "$incerto" >&2
+ exit 2
+ fi
+ if [ -n "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
+ _guardia_serve "$evento" || exit 0
+ fi
+ corpo=$(printf '%s' "$evento" | DELMINIO_MEMORIA="$MEMORIA" IMPRONTA="$(chiave_in_uso)" python3 -c 'import json,os,re,sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+t = e.get("tool_input") or {}
+cwd = os.path.realpath(e.get("cwd") or os.getcwd())
+scritti = [t.get("file_path") or t.get("notebook_path") or ""]
+if e.get("tool_name") == "apply_patch":
+ patch = t.get("command") or t.get("input") or t.get("patch") or ""
+ scritti += [p.strip() for p in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M)]
+veri = {p: os.path.realpath(os.path.join(cwd, os.path.expanduser(p))) for p in scritti if p}
+m = os.environ.get("DELMINIO_MEMORIA") or ""
+print(json.dumps({"memoria": os.path.realpath(m) if m else "", "home": os.path.expanduser("~"),
+ "cwd": cwd, "evento": e, "veri": veri, "chiave": os.environ.get("IMPRONTA", ""),
+ "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))') || exit 0
+ [ -n "$corpo" ] || exit 0
+ r=$(printf '%s' "$corpo" | curl -sS -m 3 -w '\n%{http_code}' -X POST -K <(_chiave "$TOKEN") \
+ -H "Content-Type: application/json" --data-binary @- "$URL/api/guardia" 2>/dev/null)
+ if [ "${r##*$'\n'}" != 200 ]; then
+ giu="$STATO/guardia-giu"
+ if [ ! -f "$giu" ] || [ $(( $(date +%s) - $(_mtime "$giu") )) -ge 600 ]; then
+ touch "$giu"
+ case "${r##*$'\n'}" in ''|000) avviso=$M_guardie_giu ;; *) avviso=$(_f "$M_guardie_errore" codice "${r##*$'\n'}") ;; esac
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$avviso"
+ fi
+ exit 0
+ fi
+ [[ ${r%$'\n'*} == '{"ferma":false}' || ${r%$'\n'*} == '{"ferma": false}' ]] && exit 0
+ DELMINIO_R="${r%$'\n'*}" python3 -c 'import json,os,sys
+try:
+ r = json.loads(os.environ["DELMINIO_R"])
+except Exception:
+ sys.exit(0)
+if r.get("ferma"):
+ print(r.get("testo", ""), file=sys.stderr)
+ sys.exit(2)'
+ ;;
+ nuovo|merge|smonta)
+ parte worktree.sh && . "$(dirname "$0")/worktree.sh" "$@"
+ ;;
+ audit)
+ radice=$(git rev-parse --show-toplevel)
+ cartella="$radice/.delminio/audit"
+ if squadra=$(chiedi GET /api/skill/squadra); then
+ nomi=$(printf '%s' "$squadra" | python3 -c "$PY_SKILL_NOMI" "$radice"); e=$?
+ while IFS=$'\t' read -r k a b c; do
+ [ "$k" = F ] && _f "$M_skill_nomi_finding" pezzo "$a" file "$b" nome "$c"
+ done <<<"$nomi"
+ case "$e:$nomi" in
+ 0:NESSUNA*) echo "$M_skill_nomi_nessuna" ;;
+ 0:OK*) _f "$M_skill_nomi_pulita" n "${nomi#OK$'\t'}" ;;
+ 1:*) echo "$M_skill_nomi_voluti" ;;
+ *) _f "$M_skill_nomi_cieca" perche "python3 $e" ;;
+ esac
+ else
+ _f "$M_skill_nomi_cieca" perche "$(perche_no)"
+ fi
+ if [ ! -d "$cartella" ] || [ -z "$(ls -A "$cartella" 2>/dev/null)" ]; then
+ echo "$M_nessuna_track_misurata"
+ echo "$M_revisione_memoria_meta"
+ exit 0
+ fi
+ pulite=0; con=0
+ for s in "$cartella"/*; do
+ [ -f "$s" ] && [ -x "$s" ] || continue
+ out=$(cd "$(git rev-parse --show-toplevel)" && _tempo 300 "$s" 2>&1); e=$?
+ if [ $e = 0 ]; then pulite=$((pulite + 1)); echo "✅ $(basename "$s")"
+ else con=$((con + 1)); echo "❌ $(basename "$s") (uscita $e)"; printf '%s\n' "$out" | head -20 | sed 's/^/ /'
+ fi
+ done
+ _f "$M_track_pulite_finding" pulite "$pulite" con "$con"
+ ;;
+ domini)
+ pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_2"; exit 1; }
+ [ -n "${2:-}" ] || { echo "$M_quali_bash_claude" >&2; exit 1; }
+ D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "domini": sys.argv[2]}))' "$nome" "$2")
+ r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
+ _f "$M_lavora_altre_sessioni" nome "$nome" valore "$2"
+ ;;
+ titolo)
+ pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_3"; exit 1; }
+ [ -n "${2:-}" ] || { echo "$M_quale_bash_claude" >&2; exit 1; }
+ D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "titolo": sys.argv[2]}))' "$nome" "$2")
+ r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
+ _f "$M_chiama" nome "$nome" valore "$2"
+ ;;
+ file-del-kit)
+ printf '%s\n' $KIT_FILE
+ ;;
+ ambiente)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ printf '%s\n%s\n%s\n' "$URL" "$FILE_TOKEN" "$nome"
+ ;;
+ chiusura)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
+ corpo=$(DELMINIO_CLI_NOME="$cli" python3 - "$nome" "${2:-}" "$(_remoto)" <<'CHIUSURA'
+import json, os, subprocess, sys
+def git(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+commit = git("log", "-200", "--format=%h%x1f%s%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)").splitlines()
+import re, time
+NOMI_COMUNI = 100
+def nomi_cambiati(sessione):
+ if not sessione:
+ return []
+ hh = []
+ for riga in git("log", "-300", "--no-merges",
+ "--format=%H%x1f%(trailers:key=Delminio-Sessione,valueonly,separator=%x20)").splitlines():
+ h, _, chi = riga.partition("\x1f")
+ if sessione in chi.split():
+ hh.append(h)
+ if not hh:
+ return []
+ try:
+ diff = subprocess.run(["git", "show", "-U0", "--format=", *hh], capture_output=True,
+ text=True, errors="replace", timeout=20).stdout
+ except subprocess.TimeoutExpired:
+ return []
+ saldo = {}
+ for l in diff.splitlines():
+ if not l or l[0] not in "+-" or l.startswith(("+++", "---")):
+ continue
+ segno = 1 if l[0] == "+" else -1
+ for n in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", l[1:]):
+ if "_" in n.strip("_") or re.search(r"[a-z][A-Z]", n) or (n.isupper() and len(n) >= 4):
+ saldo[n] = saldo.get(n, 0) + segno
+ fuori, inizio = [], time.time()
+ for n in sorted((n for n, v in saldo.items() if v), key=lambda n: -abs(saldo[n]))[:150]:
+ if time.time() - inizio > 10:
+ break
+ if len(git("grep", "-lwF", "-e", n, "--", ".").splitlines()) <= NOMI_COMUNI:
+ fuori.append(n)
+ return fuori
+righe = []
+sporchi = [r for r in git("status", "--porcelain").splitlines() if r.strip()]
+righe.append(F("dove_albero_sporco", n=len(sporchi)) if sporchi else F("dove_albero_pulito"))
+if git("rev-parse", "--abbrev-ref", "@{u}"):
+ n = git("rev-list", "--count", "@{u}..HEAD")
+ righe.append(F("commit_non_pushati", n=n, ramo=git("rev-parse", "--abbrev-ref", "@{u}"))
+ if n not in ("", "0") else F("tutto_pushato"))
+else:
+ righe.append(F("ramo_senza_remoto", ramo=git("rev-parse", "--abbrev-ref", "HEAD")))
+alberi = [r for r in git("worktree", "list", "--porcelain").splitlines() if r.startswith("worktree ")]
+if len(alberi) > 1:
+ righe.append(F("worktree_in_piu", n=len(alberi) - 1, alberi=", ".join(a[9:] for a in alberi[1:])))
+exec(os.environ["DELMINIO_FIDATI_PY"])
+radice = git("rev-parse", "--show-toplevel")
+gia, fermi = accettati(radice), []
+for f in script_del_progetto(radice, ("dove-siamo", "status")):
+ s = os.path.basename(f)
+ if not da_fidarsi(radice, f, gia):
+ fermi.append(di_chi(radice, f)[0])
+ continue
+ try:
+ out = subprocess.run([f], capture_output=True, text=True, timeout=30).stdout.strip()
+ except (OSError, subprocess.TimeoutExpired) as e:
+ out = F("script_non_risponde", script=s, errore=e)
+ righe += [r for r in out.splitlines() if r.strip()][:3]
+if fermi:
+ righe.append(F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
+print(json.dumps({"sessione": sys.argv[1], "richieste": sys.argv[2], "commit": commit,
+ "dove_siamo": righe, "remoto": sys.argv[3], "nomi": nomi_cambiati(sys.argv[1]),
+ "cli": os.environ.get("DELMINIO_CLI_NOME") or "claude"}))
+CHIUSURA
+)
+ if r=$(chiedi POST /api/chiusura/prompt "$corpo"); then
+ printf '%s' "$r" | campo testo
+ else
+ echo "Chiudiamo. ${2:-}"
+ echo
+ _f "$M_prompt_chiusura_arrivato" perche "$(perche_no)"
+ echo "$M_lavoro_committato_pushato"
+ echo "$M_vuoto_git_commit"
+ echo "$M_push_commit_passera"
+ fi
+ ;;
+ consegna)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ corpo=$(python3 -c 'import json,sys; print(json.dumps({"messaggio": sys.stdin.read(), "sessione": sys.argv[1], "remoto": sys.argv[2]}))' \
+ "$nome" "$(_remoto)") || exit 1
+ if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/consegna "$corpo"); then
+ _f "$M_chiusura_stata_consegnata" perche "$(perche_no)" >&2
+ exit 1
+ fi
+ printf '%s' "$r" | python3 -c 'import json,sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+r = json.load(sys.stdin)
+if not r.get("ok"):
+ print(F("chiusura_rifiutata"), file=sys.stderr)
+ for m in r.get("motivi") or []:
+ print(f" • {m}", file=sys.stderr)
+ sys.exit(1)
+for k, v in (r.get("aggiunti") or {}).items():
+ print(F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
+for a in r.get("avvisi") or []:
+ print(f"⚠️ {a}", file=sys.stderr)
+nome, h = r.get("sessione"), r.get("hash")
+print(F("chiusa_nel_repo", nome=nome, hash=h))
+if r.get("mollate"):
+ print(F("opere_avevi_mano", m=", ".join(r["mollate"])))'
+ ;;
+ consegna-di)
+ n=${2:-}; n=${n#[Ss]}
+ [[ "$n" =~ ^[0-9]+$ ]] || { echo "$M_consegna_di_uso" >&2; exit 1; }
+ r=$(chiedi GET "/api/chiusure/$n") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | M_CURATA="$(_f "$M_consegna_di_curata" numero "$n")" \
+ M_VUOTA="$(_f "$M_consegna_di_vuota" numero "$n")" python3 -c '
+import json, os, sys
+c = json.load(sys.stdin)
+if c.get("cura"):
+ print(os.environ["M_CURATA"] + "\n\n" + c["cura"]["testo"])
+elif c.get("testo"):
+ print(c["testo"])
+else:
+ print(os.environ["M_VUOTA"])'
+ ;;
+ tocco)
+ percorsi=$(python3 -c 'import json,os,re,sys
+try:
+ e = json.load(sys.stdin); t = e.get("tool_input") or {}
+except Exception:
+ sys.exit(0)
+if e.get("tool_name") == "apply_patch":
+ patch = t.get("command") or t.get("input") or t.get("patch") or ""
+ for f in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M):
+ print(os.path.join(e.get("cwd") or os.getcwd(), f.strip()))
+else:
+ print(t.get("file_path") or t.get("notebook_path") or "")')
+ percorso=$(printf '%s\n' "$percorsi" | head -1)
+ [ -n "$percorso" ] || exit 0
+ altro=""
+ cima=$(python3 -c 'import os,sys
+d = os.path.dirname(os.path.abspath(sys.argv[1]))
+while d != os.path.dirname(d) and not os.path.exists(os.path.join(d, ".git")):
+ d = os.path.dirname(d)
+print(d if os.path.exists(os.path.join(d, ".git")) else "")' "$percorso" 2>/dev/null || true)
+ qui=$(cd "$(dirname "$0")/.." && pwd)
+ remoto_cima=$(_remoto "${cima:-$qui}" || true)
+ if [ -n "$cima" ] && [ "$cima" != "$qui" ] && [ -f "$cima/.claude/delminio.sh" ] && [ -f "$cima/.claude/eseguibili.py" ]; then
+ suo=$(python3 "$cima/.claude/eseguibili.py" spazio --da "$cima/.claude/delminio.sh" 2>/dev/null || true)
+ mio=$(spazio_qui)
+ if [ -n "$suo" ] && [ "$suo" != "$mio" ]; then
+ altro=$(python3 -c 'import sys
+n = lambda k: k.rsplit("#", 1)[1] if "#" in k else "principale"
+a, b = n(sys.argv[2]), n(sys.argv[3])
+if a == b: a, b = sys.argv[2], sys.argv[3]
+print(sys.argv[1] + "\t" + a + "\t" + b)' "$cima" "$suo" "$mio")
+ fi
+ fi
+ r='{"lock": []}'; con_lock=""
+ qrepo=""
+ [ -z "$remoto_cima" ] || qrepo="&repo=$(_quota "$remoto_cima" "")"
+ while IFS= read -r x; do
+ [ -n "$x" ] || continue
+ uno=$(chiedi GET "/api/lock?percorso=$(_quota "$x" /)$qrepo") || continue
+ printf '%s' "$uno" | grep -q '"codice"' || continue
+ con_lock="$con_lock$x"$'\n'
+ r=$(python3 -c 'import json,sys
+a, b = json.loads(sys.argv[1]), json.loads(sys.argv[2])
+visti = {(l.get("spazio"), l["codice"]) for l in a.get("lock") or []}
+a["lock"] = (a.get("lock") or []) + [l for l in b.get("lock") or [] if (l.get("spazio"), l["codice"]) not in visti]
+a.update({k: b[k] for k in ("condiviso_da", "altro_spazio") if b.get(k)})
+print(json.dumps(a))' "$r" "$uno" 2>/dev/null || printf '%s' "$r")
+ done <<< "$percorsi"
+ pid=$(cli_pid || true); detti="${pid:+$STATO/lock-detti-$pid}"
+ DELMINIO_LOCK="$r" DELMINIO_ALTRO="$altro" DELMINIO_CIMA="$cima" DELMINIO_PERCORSI="${con_lock:-$percorso}" python3 - "$detti" "$percorso" <<'TOCCO'
+import json, os, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+detti_f, percorso = sys.argv[1], sys.argv[2]
+try:
+ detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
+except OSError:
+ detti = set()
+righe, segni = [], []
+risposta = json.loads(os.environ["DELMINIO_LOCK"])
+cima = os.environ.get("DELMINIO_CIMA", "")
+nome_cima = os.path.basename(cima) or F("questo_repo")
+altro = os.environ.get("DELMINIO_ALTRO", "").split("\t")
+if risposta.get("condiviso_da") and ("condiviso:" + cima) not in detti:
+ di = risposta["condiviso_da"]
+ segni.append("condiviso:" + cima)
+ righe.append(F("tocco_ospite", repo=nome_cima, di=di))
+elif len(altro) == 3 and ("spazio:" + altro[0]) not in detti:
+ cima, suo, mio = altro
+ segni.append("spazio:" + cima)
+ righe.append(F("tocco_altro_spazio_tuo", repo=os.path.basename(cima), suo=suo, mio=mio))
+elif risposta.get("altro_spazio") and ("spazio:" + cima) not in detti:
+ di = risposta["altro_spazio"]
+ segni.append("spazio:" + cima)
+ righe.append(F("tocco_non_condiviso", repo=nome_cima, di=di))
+nuovi = [l for l in risposta.get("lock") or []
+ if (l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"]) not in detti]
+segni += [l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"] for l in nuovi]
+if not righe and not nuovi:
+ sys.exit(0)
+if detti_f:
+ with open(detti_f, "a", encoding="utf-8") as f:
+ f.write("".join(x + "\n" for x in segni))
+if nuovi:
+ tocchi = ", ".join(os.path.basename(x) for x in os.environ.get("DELMINIO_PERCORSI", percorso).split("\n") if x)
+ righe.append(F("tocco_lock", file=tocchi))
+for l in nuovi:
+ duro = F("tocco_duro") if l.get("duro") else ""
+ if l.get("spazio"):
+ duro = F("tocco_duro_ospite") if l.get("duro") else ""
+ di = F("tocco_dello_spazio", spazio=l["spazio"]) if l.get("spazio") else ""
+ guardia = l.get("guardia") or F("tocco_nessuno")
+ righe.append(F("tocco_voce", codice=l["codice"], di=di, cosa=l["cosa"], duro=duro, perche=l["perche"], guardia=guardia))
+print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
+ "additionalContext": "\n".join(righe)}}))
+TOCCO
+ ;;
+ ripassato)
+ radice=$(git rev-parse --show-toplevel) || exit 1
+ n=0; cartella=$(cartella_backup)
+ copie_fatte=("$radice"/.claude/delminio-prima/*/)
+ [ -n "$cartella" ] && copie_fatte+=("$cartella"/*/)
+ for d in "${copie_fatte[@]}"; do
+ [ -f "$d/fatti.json" ] && [ ! -e "$d/RIPASSATO" ] || continue
+ date '+%Y-%m-%d %H:%M' > "$d/RIPASSATO"; n=$((n + 1))
+ done
+ _f "$M_ripassato_copia_prima" n "$n" cartella "${cartella:-.claude/delminio-prima}"
+ ;;
+ stacca)
+ { exec 3</dev/tty; } 2>/dev/null || { echo "$M_stacca_lancia_terminale" >&2; exit 1; }
+ radice=$(git rev-parse --show-toplevel) || exit 1
+ [ "$(_assoluto "$(git rev-parse --git-common-dir)")" = "$(_assoluto "$radice/.git")" ] \
+ || { echo "$M_stacca_lancia_clone" >&2; exit 1; }
+ cd "$radice"
+ cartella=$(cartella_backup)
+ prima=$( { [ -n "$cartella" ] && ls -d "$cartella"/*/fatti.json 2>/dev/null; } | tail -1 || true)
+ prima=${prima%fatti.json}
+ [ -n "$prima" ] || prima=$(ls -d .claude/delminio-prima/*/ 2>/dev/null | tail -1 || true)
+ [ -n "$cartella" ] || cartella=$(python3 -c 'import hashlib, os, re, sys
+c = os.path.realpath(sys.argv[1])
+print(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share"), "delminio", "backup",
+ (re.sub(r"[^A-Za-z0-9._-]", "-", os.path.basename(c)) or "repo") + "-" + hashlib.sha256(c.encode()).hexdigest()[:12]))' "$radice")
+ nome_repo=$(basename "$radice")
+ _f "$M_stacco" repo "$nome_repo" url "$URL"
+ [ -n "$prima" ] && _f "$M_rimetto_cio_era" prima "$prima" \
+ || echo "$M_copia_prima_tolgo"
+ read -rp "$M_procedo" si <&3
+ case "$si" in s|S|si|sì|y|yes) ;; *) echo "$M_niente_fatto"; exit 0 ;; esac
+ personali="$cartella/personali-$(date +%Y-%m-%d-%H%M%S)"
+ if r=$(chiedi GET /api/personali); then
+ n=$(umask 077; printf '%s' "$r" | python3 -c '
+import json, os, re, sys
+dest = sys.argv[1]
+mie = json.load(sys.stdin).get("personali") or []
+for m in mie:
+ os.makedirs(dest, exist_ok=True)
+ nome = re.sub(r"[^a-z0-9]+", "_", m["name"].lower()).strip("_")[:80] or "memoria"
+ i = 1
+ while True:
+ percorso = os.path.join(dest, nome + ("" if i == 1 else "_" + str(i)) + ".md")
+ try:
+ f = open(percorso, "x", encoding="utf-8")
+ except FileExistsError:
+ i += 1
+ continue
+ with f:
+ f.write(m["md"])
+ break
+print(len(mie))' "$personali") || exit 1
+ if [ "${n:-0}" -gt 0 ] 2>/dev/null; then _f "$M_tue_memorie_personali" n "$n" personali "$personali"; else personali=""; fi
+ else
+ personali=""
+ _f "$M_tue_memorie_personali_2" perche "$(perche_no)"
+ fi
+ if [ -f .claude/plugin.py ]; then python3 .claude/plugin.py rimuovi "$radice" || true; fi
+ DELMINIO_PRIMA="$prima" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" python3 - <<'STACCA'
+import json, os, pathlib, shutil
+exec(os.environ["DELMINIO_GANCI_PY"])
+prima = os.environ.get("DELMINIO_PRIMA", "").rstrip("/")
+try:
+ fatti = json.load(open(os.path.join(prima, "fatti.json"), encoding="utf-8")) if prima else {}
+except (OSError, ValueError):
+ fatti = {}
+copie = set(fatti.get("copie") or [])
+p = pathlib.Path(".claude/settings.local.json")
+if p.exists():
+ s = json.loads(p.read_text(encoding="utf-8") or "{}")
+ togli_ganci(s)
+ allow = (s.get("permissions") or {}).get("allow")
+ if allow is not None:
+ nostri = ({f"mcp__{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")}
+ | {f"mcp__plugin_delminio_{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")})
+ allow[:] = [a for a in allow if a not in nostri]
+ s.pop("autoMemoryDirectory", None)
+ if (fatti.get("memoria") or {}).get("scelta_in") == ".claude/settings.local.json":
+ s["autoMemoryDirectory"] = fatti["memoria"]["cartella"]
+ if s or ".claude/settings.local.json" in copie:
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ else:
+ p.unlink()
+e = pathlib.Path(".qwen/.env")
+if e.is_file() and e.read_text(encoding="utf-8", errors="replace").strip() == "# delminio":
+ e.unlink()
+ try:
+ e.parent.rmdir()
+ except OSError:
+ pass
+for c in (pathlib.Path(".codex/hooks.json"), pathlib.Path(".qwen/settings.json")):
+ if c.exists():
+ try:
+ s = json.loads(c.read_text(encoding="utf-8") or "{}")
+ except ValueError:
+ s = None
+ if s is not None:
+ togli_ganci(s)
+ if s or str(c) in copie:
+ c.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ else:
+ c.unlink()
+ try:
+ c.parent.rmdir() # solo se vuota: il resto di .codex e di .qwen è dell'umano
+ except OSError:
+ pass
+for rel in (f for f in os.environ["DELMINIO_KIT_FILE"].split() if "/commands/" in f):
+ if rel in copie:
+ os.makedirs(os.path.dirname(rel), exist_ok=True)
+ shutil.copy2(os.path.join(prima, rel), rel)
+ elif os.path.isfile(rel) and ("Delminio" if rel.startswith(".qwen/") else "delminio.sh") in open(rel, encoding="utf-8").read():
+ os.unlink(rel)
+STACCA
+ mcp_claude_nostro() { # mcp_claude_nostro <nome>: il server locale di questo repo è il nostro (punta qui)
+ python3 -c 'import json, os, sys
+f = os.path.join(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~"), ".claude.json")
+try:
+ s = json.load(open(f, encoding="utf-8"))["projects"][sys.argv[1]]["mcpServers"][sys.argv[2]]
+except (OSError, ValueError, KeyError, TypeError):
+ sys.exit(1)
+sys.exit(0 if str(s.get("url", "")).startswith(sys.argv[3]) else 1)' "$radice" "$1" "$URL" 2>/dev/null
+ }
+ for n in memoria delminio; do
+ mcp_claude_nostro "$n" && claude mcp remove "$n" -s local >/dev/null 2>&1
+ if [ -n "$prima" ] && [ -f "$prima/mcp-$n.json" ]; then
+ claude mcp add-json -s local "$n" "$(cat "$prima/mcp-$n.json")" >/dev/null \
+ && _f "$M_server_mcp_delminio" nome "$n" \
+ || _f "$M_server_mcp_prima" prima "$prima" nome "$n"
+ fi
+ done
+ ganci=$(git config core.hooksPath || git rev-parse --git-path hooks)
+ for g in commit-msg post-commit post-rewrite; do
+ f="$ganci/$g"
+ [ -f "$f" ] && grep -q "delminio.sh" "$f" || continue
+ if sed -n 2p "$f" | grep -q '^# Delminio (aggancia.sh)'; then rm -f "$f"
+ else _f "$M_tuo_chiama_delminio" f "$f"; fi
+ done
+ escludi=$(git rev-parse --git-path info/exclude)
+ if [ -f "$escludi" ]; then
+ printf '%s\n' $KIT_FILE $KIT_DI_PRIMA $([ -e .qwen/.env ] || echo .qwen/.env) | grep -vxF -f - "$escludi" > "$escludi.delminio" || true
+ mv -f "$escludi.delminio" "$escludi"
+ fi
+ messe="$(git rev-parse --git-common-dir)/delminio-cure"
+ if [ -f "$messe" ]; then
+ while read -r h; do [ -n "$h" ] && git replace -d "$h" >/dev/null 2>&1 || true; done < "$messe"
+ fi
+ 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
+ rm -f "$(git rev-parse --git-path "$s")" "$(git rev-parse --git-common-dir)/$s" 2>/dev/null || true
+ done
+ jti=$(printf '%s' "$TOKEN" | python3 -c '
+import base64, json, sys
+try:
+ p = sys.stdin.read().split(".")[1]
+ print(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))).get("jti") or "")
+except Exception:
+ print("")')
+ altri=$(grep -lxF -- "$TOKEN" "$(dirname "$FILE_TOKEN")"/*.token 2>/dev/null | grep -vxF "$FILE_TOKEN" | wc -l)
+ if [ -z "$jti" ]; then
+ echo "$M_revocare_questo_token"
+ elif [ "$altri" -gt 0 ]; then
+ _f "$M_token_resta_valido" altri "$altri"
+ elif chiedi DELETE "/api/tokens/$jti" >/dev/null; then
+ echo "$M_token_questo_aggancio"
+ else
+ _f "$M_token_revocato_fallo" perche "$(perche_no)"
+ fi
+ if [ "$altri" -eq 0 ] 2>/dev/null && [ -f .claude/eseguibili.py ]; then
+ python3 .claude/eseguibili.py --url "$URL" --token-file "$FILE_TOKEN" lascia || true
+ fi
+ rm -f "$FILE_TOKEN"
+ if ! ls "$(dirname "$FILE_TOKEN")"/*.token >/dev/null 2>&1; then
+ dati="${XDG_DATA_HOME:-$HOME/.local/share}"; cache="${XDG_CACHE_HOME:-$HOME/.cache}"
+ if [ -f .claude/plugin.py ]; then
+ esito=0; python3 .claude/plugin.py app-codex lascia >/dev/null 2>&1 || esito=$?
+ [ "$esito" -eq 2 ] && echo "$M_app_codex_tolto"
+ fi
+ rm -rf "$dati/delminio/plugin" "$dati/codex/versions" "$dati/qwen-code/versions" "$dati/delminio/opencode" \
+ "$cache"/delminio-stato "$cache"/delminio-eseguibili "$cache"/delminio-cassaforte 2>/dev/null || true
+ comando="${DELMINIO_BIN:-$HOME/.local/bin}/delminio"
+ grep -q '^# delminio-comando$' "$comando" 2>/dev/null && rm -f "$comando"
+ echo "$M_pulito_ultimo"
+ fi
+ for f in $KIT_FILE $KIT_DI_PRIMA; do
+ case "$f" in .claude/*.py|.claude/rules/*) rm -f "$f" ;; esac # il resto l'ha già rimesso il python
+ done
+ rmdir .claude/rules "$(dirname "$FILE_TOKEN")" 2>/dev/null || true
+ if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
+ case "$MEMORIA" in "${XDG_DATA_HOME:-$HOME/.local/share}"/delminio/*/memoria) rm -rf "$(dirname "$MEMORIA")"
+ echo "$M_tolto_clone_memorie" ;; esac
+ fi
+ wt=$(git worktree list --porcelain | grep -c '^branch refs/heads/sessione/' || true)
+ [ "$wt" -gt 0 ] && _f "$M_restano_worktree_sessioni" wt "$wt"
+ echo "$M_staccato_cli_torna"
+ [ -n "$personali" ] && _f "$M_tue_personali" personali "$personali"
+ [ -n "$prima" ] && _f "$M_copia_prima_resta" prima "$prima"
+ rm -f .claude/delminio.sh
+ exit 0
+ ;;
+ accetta)
+ { exec 3</dev/tty; } 2>/dev/null || { echo "$M_accetta_lancia_terminale" >&2; exit 1; }
+ DELMINIO_ALBERO="$(git rev-parse --show-toplevel)" python3 - <<'SCRIPT'
+import os
+exec(os.environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+exec(os.environ["DELMINIO_FIDATI_PY"])
+albero = os.environ["DELMINIO_ALBERO"]
+gia = accettati(albero)
+fermi = [f for f in script_del_progetto(albero, ("apertura", "opening", "dove-siamo", "status")) + lascito_del_progetto(albero)
+ if not da_fidarsi(albero, f, gia)]
+if fermi:
+ tty_in, tty = open("/dev/tty"), open("/dev/tty", "w")
+ tty.write(F("accetta_script_elenco"))
+ for f in fermi:
+ chi, quando = di_chi(albero, f)
+ righe = sum(1 for _ in open(f, encoding="utf-8", errors="replace"))
+ tty.write(F("accetta_script_riga", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, righe=righe) + "\n")
+ tty.write(F("accetta_script_domanda"))
+ tty.flush()
+ r, scelti = tty_in.readline().strip().lower(), []
+ if r in F("accetta_script_tutti_si").split():
+ scelti = fermi
+ elif r in F("accetta_script_uno_si").split():
+ for f in fermi:
+ chi, quando = di_chi(albero, f)
+ testo = open(f, encoding="utf-8", errors="replace").read()
+ tty.write(F("accetta_script_uno", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, testo=testo[:4000]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ scelti.append(f)
+ if scelti:
+ with open(accettati_file(albero), "w", encoding="utf-8") as out:
+ out.write("".join(x + "\n" for x in sorted(gia | {impronta_script(albero, f) for f in scelti})))
+ print(F("script_accettati", nuovi=len(scelti), fermi=len(fermi) - len(scelti)))
+SCRIPT
+ if [ -f "$(dirname "$0")/squadra.py" ]; then python3 "$(dirname "$0")/squadra.py" accetta || true; fi
+ if [ -f "$(dirname "$0")/eseguibili.py" ]; then
+ python3 "$(dirname "$0")/eseguibili.py" accetta && [ -z "${DELMINIO_PROVA:-}" ] && allinea_staccato || true
+ fi
+ tutti=$(chiedi GET /api/lock) || { echo "❌ $(perche_no)" >&2; exit 1; }
+ DELMINIO_LOCK="$tutti" DELMINIO_ACCETTATE="$(accettate_file)" python3 - <<'ACCETTA'
+import hashlib, json, os
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+tutti = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
+lock = [l for l in tutti if (l.get("duro") or l.get("firme")) and l.get("comando")]
+prima = [l for l in tutti if l.get("comando_gesto")] # su comandi e strumenti (F903)
+f = os.environ["DELMINIO_ACCETTATE"]
+try:
+ accettate = set(open(f, encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+tty_in, tty = open("/dev/tty"), open("/dev/tty", "w") # r+ vuole un seek, e un terminale non lo ha
+nuove = 0
+for l in lock:
+ h = hashlib.sha256((l["codice"] + "\0" + l["comando"]).encode()).hexdigest()
+ if h in accettate:
+ continue
+ tty.write(F("accetta_domanda", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", comando=l["comando"]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ accettate.add(h); nuove += 1
+for l in prima:
+ h = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + l["comando_gesto"]).encode()).hexdigest()
+ if h in accettate:
+ continue
+ gesti = ", ".join((l.get("gesti") or []) + (l.get("strumenti") or []))
+ tty.write(F("accetta_domanda_gesto", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", gesti=gesti, comando=l["comando_gesto"]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ accettate.add(h); nuove += 1
+with open(f, "w", encoding="utf-8") as out:
+ out.write("".join(x + "\n" for x in sorted(accettate)))
+print(F("accettate", nuove=nuove, tutte=len(accettate), file=f))
+ACCETTA
+ ;;
+ commit-msg|post-rewrite|post-commit|post-rewrite-dopo|post-commit-dopo)
+ parte ganci-git.sh && . "$(dirname "$0")/ganci-git.sh" "$@"
+ ;;
+ errore)
+ [ -f "$(dirname "$0")/eseguibili.py" ] || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$evento" ] || exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid" 2>/dev/null || true)
+ printf '%s' "$evento" | DELMINIO_SESSIONE_NOME="$nome" _tempo 4 python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori-registra >/dev/null 2>&1 || true
+ exit 0
+ ;;
+ errori)
+ shift; exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori "$@"
+ ;;
+ pulizia)
+ [ -n "${DELMINIO_CONVERSAZIONI:-}" ] || exit 0
+ exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" pulizia
+ ;;
+ ponte)
+ DELMINIO_T="$TOKEN" exec bash "$0" ponte-mcp "$URL"
+ ;;
+ ponte-mcp)
+ programma=$(cat <<'PONTE'
+import json, os, sys, time, urllib.error, urllib.request
+
+URL = sys.argv[1].rstrip("/") + "/mcp"
+TESTA = {"Authorization": "Bearer " + os.environ.pop("DELMINIO_T", ""),
+ "X-Delminio-Modello": os.environ.get("DELMINIO_MODELLO", ""),
+ "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+MUTO = os.environ.get("DELMINIO_PONTE_MUTO", "Delminio non risponde.")
+RIFIUTO = os.environ.get("DELMINIO_PONTE_RIFIUTO", "HTTP {codice}")
+stato = {"sessione": None, "versione": "2025-06-18"}
+
+
+def _sessione():
+ try:
+ with open(os.environ.get("DELMINIO_SESSIONE_FILE") or "/nonesiste", encoding="utf-8") as f:
+ return f.read().strip()[:40]
+ except OSError:
+ return ""
+
+
+def manda(msg, timeout=120):
+ h = dict(TESTA)
+ if s := _sessione():
+ h["X-Delminio-Sessione"] = s
+ if stato["sessione"]:
+ h["Mcp-Session-Id"] = stato["sessione"]
+ h["MCP-Protocol-Version"] = stato["versione"]
+ r = urllib.request.Request(URL, data=json.dumps(msg).encode(), headers=h, method="POST")
+ with urllib.request.urlopen(r, timeout=timeout) as risp:
+ sid, tipo = risp.headers.get("mcp-session-id"), risp.headers.get("content-type", "")
+ corpo = risp.read().decode("utf-8", "replace")
+ if "id" not in msg:
+ return None, sid
+ if tipo.startswith("text/event-stream"):
+ for riga in corpo.splitlines():
+ if riga.startswith("data:"):
+ d = json.loads(riga[5:].strip())
+ if d.get("id") == msg["id"]:
+ return d, sid
+ raise OSError("lo stream non porta la risposta")
+ return json.loads(corpo), sid
+
+
+def apri():
+ stato["sessione"] = None
+ d, sid = manda({"jsonrpc": "2.0", "id": "ponte", "method": "initialize",
+ "params": {"protocolVersion": stato["versione"], "capabilities": {},
+ "clientInfo": {"name": "delminio-ponte", "version": "1"}}}, 15)
+ stato["sessione"], stato["versione"] = sid, d["result"].get("protocolVersion", stato["versione"])
+ manda({"jsonrpc": "2.0", "method": "notifications/initialized"}, 15)
+ return d["result"]
+
+
+def chiedi(metodo, params, tentativi):
+ """La domanda al motore; a un errore riapre la sessione e riprova (il motore
+ riavviato non conosce più la sessione di prima)."""
+ for n in range(tentativi):
+ try:
+ if stato["sessione"] is None:
+ apri()
+ d, _ = manda({"jsonrpc": "2.0", "id": "p", "method": metodo, "params": params})
+ return d # anche un errore JSON-RPC: è del motore, non della sessione
+ except urllib.error.HTTPError as e:
+ if e.code in (401, 403):
+ return {"result": {"content": [{"type": "text", "text": RIFIUTO.replace("{codice}", str(e.code))}],
+ "isError": True}}
+ except Exception: # noqa: BLE001
+ pass
+ stato["sessione"] = None
+ time.sleep(min(2 * (n + 1), 6))
+ return None
+
+
+inizio = tools = None
+for n in range(8):
+ try:
+ inizio = apri()
+ tools = manda({"jsonrpc": "2.0", "id": "t", "method": "tools/list", "params": {}})[0]["result"]["tools"]
+ break
+ except Exception: # noqa: BLE001
+ time.sleep(1)
+inizio = inizio or {"serverInfo": {"name": "Delminio", "version": "?"}}
+VUOTI = {"prompts/list": "prompts", "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates"}
+
+for riga in sys.stdin:
+ try:
+ m = json.loads(riga)
+ except ValueError:
+ continue
+ if "id" not in m:
+ continue # le notifiche di Qwen non servono al motore
+ metodo, rid = m.get("method"), m["id"]
+ if metodo == "initialize":
+ res = {"protocolVersion": m.get("params", {}).get("protocolVersion", stato["versione"]),
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": inizio.get("serverInfo"), "instructions": inizio.get("instructions", "")}
+ elif metodo == "tools/list":
+ res = {"tools": tools or []}
+ elif metodo == "tools/call":
+ d = chiedi("tools/call", m.get("params", {}), 4)
+ if d is not None and "error" in d:
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": d["error"]}, ensure_ascii=False), flush=True)
+ continue
+ res = (d or {}).get("result") or {"content": [{"type": "text", "text": MUTO}], "isError": True}
+ elif metodo in VUOTI:
+ res = {VUOTI[metodo]: []}
+ elif metodo == "ping":
+ res = {}
+ else:
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": metodo}}), flush=True)
+ continue
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "result": res}, ensure_ascii=False), flush=True)
+PONTE
+)
+ p_cli=$(cli_pid || true)
+ DELMINIO_SESSIONE_FILE="${p_cli:+$STATO/sessione-$p_cli}" \
+ DELMINIO_PONTE_MUTO="$M_ponte_muto" DELMINIO_PONTE_RIFIUTO="$(_f "$M_perche_token" url "${2:-$URL}" codice "{codice}")" \
+ exec python3 -c "$programma" "${2:-$URL}"
+ ;;
+ riaggancia-fratelli)
+ serve=${2:-}; [ -n "$serve" ] || exit 0
+ qui=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd -P)
+ python3 - "$qui" "$URL" "$serve" "${DELMINIO_CERCA_IN:-}" <<'FRATELLI' | while IFS=$'\t' read -r dove tf suo; do
+import os, shlex, sys
+qui, url, serve = sys.argv[1:4]
+radici = [os.path.dirname(qui), os.path.expanduser("~")] + [x for x in sys.argv[4].split(":") if x]
+visti = {os.path.realpath(qui)}
+for radice in radici:
+ for d, sotto, _ in os.walk(radice):
+ livello = d[len(radice):].count(os.sep)
+ c = os.path.join(d, ".claude", "delminio.sh")
+ if os.path.isdir(os.path.join(d, ".git")) and os.path.isfile(c) and os.path.realpath(d) not in visti:
+ visti.add(os.path.realpath(d))
+ testa = {}
+ try:
+ for i, riga in zip(range(30), open(c, encoding="utf-8", errors="replace")):
+ k, _, v = riga.strip().partition("=")
+ if k in ("URL", "FILE_TOKEN", "KIT") and v and k not in testa:
+ testa[k] = (shlex.split(v) or [""])[0]
+ except (OSError, ValueError):
+ continue
+ if testa.get("URL", "").rstrip("/") == url.rstrip("/") and testa.get("KIT") != serve and testa.get("FILE_TOKEN"):
+ print(os.path.realpath(d) + "\t" + testa["FILE_TOKEN"] + "\t" + testa.get("KIT", ""))
+ sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
+FRATELLI
+ [ -r "$tf" ] || continue
+ TOKEN=$(cat "$tf") KIT="${suo:-?}" riaggancia "$serve" "$dove" presto
+ echo "$dove"
+ done
+ ;;
+ clona)
+ nome="${2:-}"; [ -n "$nome" ] && [ "$nome" != --no ] || { echo "$M_uso_clona" >&2; exit 2; }
+ qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
+ r=$(chiedi GET /api/repo/spazio) || { echo "❌ $(perche_no)" >&2; exit 1; }
+ riga=$(printf '%s' "$r" | python3 -c 'import json,re,sys
+n = sys.argv[1]
+ok = lambda c: bool(re.fullmatch(r"[\w.-]+", c)) and c not in (".", "..") and not c.startswith("-")
+for x in json.load(sys.stdin).get("repo") or []:
+ if n in (x.get("nome"), x.get("chiave")):
+ k = str(x.get("chiave") or "")
+ c = str(x.get("nome") or "")
+ if not ok(c):
+ c = re.split(r"[/:]", k.rstrip("/"))[-1].removesuffix(".git")
+ print(k); print(c if ok(c) else ""); break' "$nome")
+ { read -r chiave; read -r cartella; } <<<"$riga"
+ [ -n "$chiave" ] && [ -n "$cartella" ] || { _f "$M_clona_non_dello_spazio" nome "$nome" >&2; exit 1; }
+ if [ "${3:-}" = --no ]; then
+ DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" "$chiave" <<'REPO_NO_SCRIVI' || exit 1
+import json, os, sys
+f, chiave = sys.argv[1], sys.argv[2]
+try:
+ d = json.load(open(f, encoding="utf-8"))
+except (OSError, ValueError):
+ d = {}
+d = d if isinstance(d, dict) else {}
+v = [x for x in d.get(os.environ["DELMINIO_CHI"]) or [] if x != chiave] + [chiave]
+d[os.environ["DELMINIO_CHI"]] = v
+os.makedirs(os.path.dirname(f), exist_ok=True)
+nuovo = f + ".nuovo"
+with open(nuovo, "w", encoding="utf-8") as h:
+ json.dump(d, h, ensure_ascii=False, indent=1)
+os.replace(nuovo, f)
+REPO_NO_SCRIVI
+ _f "$M_clona_no" nome "$nome"; exit 0
+ fi
+ url=$(python3 - "$(git -C "$qui" remote get-url origin 2>/dev/null)" "$chiave" <<'CLONA_URL'
+import sys
+PUBBLICI = {"github.com", "gitlab.com", "codeberg.org", "bitbucket.org", "gitea.com", "git.sr.ht"}
+def parti(u):
+ """(host, percorso, come si rifà l'indirizzo con un altro percorso)"""
+ if "://" in u:
+ schema, resto = u.split("://", 1)
+ autorita, _, percorso = resto.partition("/")
+ return autorita.rsplit("@", 1)[-1].split(":", 1)[0].lower(), percorso, lambda q: f"{schema}://{autorita}/{q}"
+ if ":" in u and not u.startswith("/"):
+ testa, _, percorso = u.partition(":")
+ return testa.split("@", 1)[-1].lower(), percorso, lambda q: f"{testa}:{q}"
+ return "", u, None
+origine, chiave = sys.argv[1], sys.argv[2]
+ho, po, rifai = parti(origine)
+ht, pt, _ = parti(chiave)
+pt = pt.strip("/")
+if rifai and ht and pt and (ht == ho or (ht not in PUBBLICI and ho not in PUBBLICI)):
+ print(rifai(pt.removesuffix(".git") + (".git" if po.rstrip("/").endswith(".git") else "")))
+else:
+ print(chiave)
+CLONA_URL
+)
+ dove="$(dirname "$qui")/$cartella"
+ if [ -e "$dove" ]; then
+ if [ -d "$dove/.git" ] && corpo=$(python3 -c 'import json,sys; print(json.dumps({"remoti": [sys.argv[1]]}))' "$(_remoto "$dove")") \
+ && r2=$(chiedi POST /api/repo/riconosci "$corpo") \
+ && printf '%s' "$r2" | python3 -c 'import json,sys
+sys.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
+ _collega_clone "$nome" "$dove"; exit $?
+ fi
+ _f "$M_clona_occupata" dove "$dove" >&2; exit 1
+ fi
+ _f "$M_clona_in_corso" nome "$nome" url "$url" dove "$dove"
+ log="$STATO/clona-$$.log"
+ if ! GIT_TERMINAL_PROMPT=0 _tempo 600 git clone -q -- "$url" "$dove" > "$log" 2>&1; then
+ errore_log=$(grep -v '^[[:space:]]*$' "$log" | tail -1 | cut -c1-200); rm -f "$log"
+ _f "$M_clona_fallito" nome "$nome" url "$url" errore "$errore_log" >&2; exit 1
+ fi
+ rm -f "$log"
+ _collega_clone "$nome" "$dove"
+ ;;
+ agganciali)
+ qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
+ trovati=$(python3 - "$qui" "${DELMINIO_CERCA_IN:-}" <<'CERCA'
+import json, os, subprocess, sys
+qui, altre = sys.argv[1], [x for x in sys.argv[2].split(":") if x]
+radici = [os.path.dirname(qui), os.path.expanduser("~")] + altre
+visti, cloni = set(), []
+for radice in radici:
+ for d, sotto, _ in os.walk(radice):
+ livello = d[len(radice):].count(os.sep)
+ if ".git" in sotto and os.path.isdir(os.path.join(d, ".git")): # un clone, non un worktree
+ p = os.path.realpath(d)
+ if p not in visti:
+ visti.add(p)
+ r = subprocess.run(["git", "-C", d, "remote", "get-url", "origin"], capture_output=True, text=True)
+ if r.returncode == 0 and r.stdout.strip():
+ cloni.append((p, r.stdout.strip()))
+ sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
+print(json.dumps({"cloni": cloni}))
+CERCA
+)
+ corpo=$(printf '%s' "$trovati" | python3 -c 'import json,re,sys
+c = json.load(sys.stdin)["cloni"]
+print(json.dumps({"remoti": [re.sub(r"^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@", r"\1", r) for _, r in c]}))')
+ r=$(chiedi POST /api/repo/riconosci "$corpo") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ elenco=$(DELMINIO_CLONI="$trovati" python3 -c 'import json,os,sys
+cloni = json.loads(os.environ["DELMINIO_CLONI"])["cloni"]
+for x in json.load(sys.stdin)["repo"]:
+ dove = [cloni[i][0] for i in x["trovati"]]
+ print(x["nome"] + "\t" + (dove[0] if dove else ""))' <<< "$r")
+ [ -n "$elenco" ] || { echo "$M_spazio_repo_aggiunge"; exit 0; }
+ echo "$M_repo_dello_spazio"
+ falliti=0
+ while IFS=$'\t' read -r nome dove; do
+ if [ -z "$dove" ]; then _f "$M_clonato_qui" nome "$nome"; continue; fi
+ if [ -x "$dove/.claude/delminio.sh" ]; then _f "$M_gia_collegato" nome "$nome" dove "$dove"; continue; fi
+ _collega_clone "$nome" "$dove" || falliti=$((falliti + 1))
+ done <<< "$elenco"
+ [ "$falliti" -eq 0 ]
+ ;;
+ carta)
+ shift
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_SESSIONE="$sess" DELMINIO_STATO="$STATO" \
+ python3 "$(cd "$(dirname "$0")" && pwd)/firme.py" "$@"
+ ;;
+ perche)
+ dove="${2:-}"
+ case "$dove" in *:[0-9]*) ;; *) echo "$M_uso_bash_claude" >&2; exit 2 ;; esac
+ DELMINIO_U="$URL" DELMINIO_T="$TOKEN" python3 - "$dove" <<'PERCHE'
+import json, os, shlex, subprocess, sys, urllib.parse, urllib.request
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+f, _, riga = sys.argv[1].rpartition(":")
+q = shlex.quote
+
+def g(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True)
+
+def delminio(q):
+ req = urllib.request.Request(os.environ["DELMINIO_U"] + "/api/perche?" + urllib.parse.urlencode(q),
+ headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"]})
+ return json.loads(urllib.request.urlopen(req, timeout=8).read())
+
+b = g("blame", "-L", f"{riga},{riga}", "--porcelain", "--", f)
+if b.returncode:
+ sys.exit(f"❌ {b.stderr.strip()}")
+h = b.stdout.split()[0]
+if set(h) == {"0"}:
+ sys.exit(print(F("perche_non_committata", dove=f"{f}:{riga}")))
+info = g("log", "-1", "--date=short", "--format=%h%x00%an%x00%ad%x00%s%x00%(trailers:key=Delminio-Sessione,valueonly)", h)
+corto, autore, data, soggetto, sess = (info.stdout.split("\0") + [""] * 5)[:5]
+print(F("perche_commit", dove=f"{f}:{riga}", commit=corto, data=data, autore=autore, soggetto=soggetto))
+sess = (sess.strip().splitlines() or [""])[0].strip()
+if not sess:
+ print(F("perche_senza_sessione", commit=corto))
+ sys.exit(0)
+try:
+ r = delminio({"sessione": sess})
+except Exception as e:
+ sys.exit(print(F("perche_sessione_muto", sessione=sess, errore=e)))
+agente = f" ({r['agente']})" if r.get("agente") else ""
+con = F("perche_con", chi=r["chi"]) if r.get("chi") else ""
+nata = F("perche_nata", data=r["nata"][:10]) if r.get("nata") else ""
+print(F("perche_sessione", sessione=r["sessione"], agente=agente, chi=con, nata=nata))
+c = r.get("chiusura")
+h = (c or {}).get("hash") or ""
+if c and not (7 <= len(h) <= 40 and all(x in "0123456789abcdef" for x in h)):
+ c = None
+if not c:
+ sys.exit(print(F("perche_senza_chiusura", sessione=sess)))
+qui = g("cat-file", "-e", f"{c['hash']}^{{commit}}").returncode == 0
+in_repo = F("perche_in_repo", repo=c["repo"]) if c.get("repo") else ""
+comando = (f"git show {q(c['hash'])}" if qui or not c.get("remoto")
+ else f"git fetch -q {q(c['remoto'])} && git show {q(c['hash'])}")
+print(F("perche_chiusa", data=(c.get("quando") or "?")[:10], commit=c["hash"], repo=in_repo, comando=comando))
+mem = g("log", "-1", "--format=%(trailers:" + ",".join("key=" + k for k in os.environ["P_TRAILER_MEMORIA"].split("|"))
+ + ",valueonly)", c["hash"]).stdout.strip() if qui else ""
+primo = mem.split()[0] if mem else ""
+if primo and all(x in "0123456789abcdef" for x in primo) and len(primo) >= 7:
+ try:
+ nomi = delminio({"sessione": sess, "memoria": primo}).get("memorie")
+ except Exception:
+ nomi = None
+ if nomi:
+ print(F("perche_memorie") + "\n" + "\n".join(f" · {n}" for n in nomi))
+ elif nomi == []:
+ print(F("perche_nessuna_memoria"))
+ else:
+ print(F("perche_memorie_nel_commit", commit=primo))
+elif mem:
+ print(F("perche_le_memorie", memorie=mem))
+PERCHE
+ ;;
+ ""|aiuto|-h|--help) echo "$M_aiuto" ;;
+ *) _f "$M_comando_sconosciuto" nome "$1" >&2; echo "$M_aiuto" >&2; exit 2 ;;
+esac
diff --git a/kit/en/eseguibili-client b/kit/en/eseguibili-client
new file mode 100644
index 0000000..19bbaeb
--- /dev/null
+++ b/kit/en/eseguibili-client
@@ -0,0 +1,3884 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Gli eseguibili di Delminio su questa macchina, in pari col registro."""
+import argparse
+import base64
+import collections
+import datetime
+import difflib
+import hashlib
+import io
+import json
+import math
+import os
+import platform
+import re
+import runpy
+import shlex
+import shutil
+import socket
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+try:
+ import fcntl
+except ImportError:
+ fcntl = None
+RILASCI = 'https://downloads.claude.ai/claude-code-releases'
+CANALI = {'stabile': 'stable', 'latest': 'latest'}
+CODEX_RILASCI = 'https://releases.openai.com/codex/releases'
+CODEX_TARGET = {'linux-x64': 'x86_64-unknown-linux-musl', 'linux-x64-musl': 'x86_64-unknown-linux-musl', 'linux-arm64': 'aarch64-unknown-linux-musl', 'linux-arm64-musl': 'aarch64-unknown-linux-musl', 'darwin-x64': 'x86_64-apple-darwin', 'darwin-arm64': 'aarch64-apple-darwin'}
+NODE_QWEN = '22.23.4'
+CLI_NOMI = {'claude': 'Claude Code', 'codex': 'Codex', 'qwen': 'Qwen Code', 'opencode': 'OpenCode'}
+SERVER_RUOLO = 'memoria-ruolo'
+NODE_RILASCI = 'https://nodejs.org/dist'
+NODE_TARGET = {'linux-x64': 'linux-x64', 'linux-arm64': 'linux-arm64', 'darwin-x64': 'darwin-x64', 'darwin-arm64': 'darwin-arm64'}
+_VERSIONE = re.compile('^\\d+\\.\\d+\\.\\d+$')
+_NOME_OK = re.compile('[A-Za-z0-9][A-Za-z0-9._-]{0,63}')
+FRASI = {
+ "modello_gratuito_nessuno": "none of the {n} free OpenCode models answers right now: a provider's key is needed",
+ "modello_gratuito_risposta": "ready",
+ "modello_gratuito_domanda": "Answer only with the word: ready",
+ "modello_gratuito_uso": "usage: modello-gratuito <the opencode binary>",
+ "installa_agente_uso": "usage: installa-agente claude|codex|qwen|opencode <version>",
+ "installa_agente_no": "{cli} did not install: {errore}",
+ "skill_riferite": "\U0001f9e9 This machine's skills told to Delminio, with commands, agents and MCP servers: {n}; the Skills view choices applied: {scelte}.",
+ "posta_arrivata": "\U0001f4ec Delminio: a message has arrived from another session \u2014 you'll find it below.",
+ "riga_senza_numero": "the {cli} row doesn't have a version number yet: save it again in the Agents view",
+ "non_versione": "\u201c{versione}\u201d isn't a version",
+ "senza_cli_ufficiale": "this machine ({sistema}) has no official CLI: Linux or macOS (on Windows, inside WSL)",
+ "versione_assente": "version {versione} doesn't exist for {piattaforma}",
+ "scarico_cli": " downloading CLI {versione} for {piattaforma} ({mb} MB)\u2026",
+ "checksum_cli": "the checksum of CLI {versione} doesn't match: I won't install it",
+ "senza_codex_ufficiale": "this machine ({sistema}) has no official Codex: Linux or macOS (on Windows, inside WSL)",
+ "codex_senza_pacchetto": "Codex version {versione} has no package for {piattaforma}",
+ "scarico_codex": " downloading Codex {versione} for {piattaforma}\u2026",
+ "digest_codex": "the digest of Codex {versione} doesn't match: I won't install it",
+ "pacchetto_fuori": "the {chi} package reaches outside its folder: I won't install it",
+ "codex_senza_binario": "there's no bin/codex in the Codex {versione} package",
+ "senza_node_ufficiale": "this machine ({sistema}) has no official Node for Qwen Code: Linux or macOS with glibc (on Windows, inside WSL)",
+ "node_senza_pacchetto": "Node {versione} has no package for {piattaforma}",
+ "scarico_node": " downloading Node {versione} for Qwen Code\u2026",
+ "checksum_node": "the checksum of Node {versione} doesn't match: I won't install it",
+ "installo_qwen": " installing Qwen Code {versione}\u2026",
+ "installo_opencode": " installing OpenCode {versione}\u2026",
+ "opencode_integrita": "OpenCode {versione}: the package does not match the npm registry integrity, and is not installed",
+ "opencode_senza_binario": "the OpenCode {versione} package has no bin/opencode",
+ "opencode_solo_v2": "OpenCode {versione} is version 1, which Delminio no longer supports: choose a version 2 in the Agents view",
+ "wrapper_opencode_solo_kit": "\u26a0\ufe0f {nome}: an OpenCode agent starts from a project connected to Delminio, where its plugin brings memory, messages and the opening and closing commands.",
+ "commento_config_opencode": "The OpenCode configuration for this agent: provider and model, no self-updates. The client adds the role prompt at launch.",
+ "qwen_non_installato": "Qwen Code {versione} didn't install: {perche}",
+ "npm_muto": "npm silent",
+ "cosa_posta_ruolo": "the agent role's messages",
+ "settings_file": "\u26a0\ufe0f this row's --settings are a file: {cosa} doesn't fit in",
+ "cosa_ricerca_spenta": "web search switched off",
+ "rito_apertura_descrizione": "Opens the session with the user: Delminio brings you your role's steps",
+ "rito_apertura_corpo": "I'm opening the session.",
+ "rito_chiusura_descrizione": "Ends the session with the user: Delminio brings you your role's steps",
+ "rito_chiusura_corpo": "I'm ending the session.",
+ "rito_plugin": "/opening and /closing for agents with a Delminio agent role",
+ "rito_negato": "\u26a0\ufe0f Delminio didn't provide the text of /{parola}: {perche}. Tell the user.",
+ "rito_muto": "\u26a0\ufe0f Delminio is not responding: the text of /{parola} didn't arrive. Tell the user.",
+ "chiudi_commento": "At the end of the session: what you've written goes into your workspace's history, and to its\nrepository if it has one. Delminio writes it at every startup; it takes no arguments. If the workspace has its own prima-di-chiudere.sh, it runs that first.",
+ "chiudi_niente": "nothing new to put in the history",
+ "chiudi_nella_storia": "\u2705 in the history: {commit}",
+ "chiudi_senza_repo": "your workspace has no repository to send it to: the history stays here",
+ "chiudi_mandata": "\u2705 sent to its repository",
+ "chiudi_push_fallito": "\u26a0\ufe0f the push didn't go through, tell the user: {errore}",
+ "non_si_clona": "can't be cloned",
+ "pull_fallito": "the pull didn't go through",
+ "altri_file": "- \u2026 and {n} more files",
+ "repo_ruolo_lontano_nuova": "the agent role's repository ({repo}) can't be reached from here: the history stays in the workspace",
+ "repo_ruolo_cambiato": "the agent role's repository has changed: now {repo}",
+ "repo_ruolo_lontano": "the agent role's repository can't be reached from here: you're working on the previous workspace",
+ "casa_ferma": "the workspace doesn't update from its repository: you're working on the previous one",
+ "uso_casa": "usage: casa <the project's delminio.sh> <role> <agent> [<folder>]",
+ "casa_nel_progetto": "\u26a0\ufe0f {agente}: the isolated workspace can't be inside the project (or contain it): its real files are there. Change the agent's folder in the Agents view.",
+ "casa_non_detta": "\u26a0\ufe0f {agente}: Delminio didn't say where the workspace is ({errore}): you're working on the previous one.",
+ "casa_senza_repo": "\u26a0\ufe0f {agente}: Delminio didn't say which repositories the agent role sees ({errore}): the workspace isn't created.",
+ "novita_titolo": "What has changed",
+ "novita_uscito": "Your agent role doesn't see it any more: it has left the workspace.",
+ "novita_non_si_clona": "\u26a0\ufe0f It can't be cloned from this machine ({repo}): {perche}. Tell the user.",
+ "novita_copia_repo": "The copy was created just now: it's the repository as it is.",
+ "avviso_non_si_clona": "{repo} can't be cloned: {perche}",
+ "avviso_non_si_aggiorna": "{repo} doesn't update: {perche}",
+ "novita_non_si_aggiorna": "\u26a0\ufe0f It doesn't update ({perche}): you're working on the previous copy.",
+ "novita_niente": "Nothing new since last time.",
+ "novita_uscito_spazio": "(The repository \u201c{repo}\u201d no longer belongs to the space: it isn't copied.)",
+ "copia_progetto_ferma": "the project's copy doesn't update: {perche}",
+ "progetto_non_si_copia": "\u26a0\ufe0f {agente}: I can't copy the project into {casa}",
+ "novita_copia_progetto": "The copy was created just now: it's the project as it is, in the progetto/ folder.",
+ "novita_al_tecnico": "To tell the user",
+ "commento_al_lancio": "Before starting, the registry: if another version was chosen in the Agents view,\nthe command syncs now and restarts rewritten. If that fails, it starts as it was.",
+ "commento_prompt": "The system prompt from Delminio, in a file with the pid (which exec leaves to the CLI): those\nof CLIs already closed are deleted by the next startup. Without a prompt the agent doesn't start half-ready.",
+ "prompt_negato": "\u26a0\ufe0f {nome}: Delminio didn't provide the system prompt of the agent role \u201c{porta}\u201d (HTTP {codice}).",
+ "commento_hook_sistema": "The hooks read it: the rules are already at the top.",
+ "codex_ruolo_solo": "an agent role with only its own half isn't available on Codex yet: the role's memory goes through --mcp-config, which Codex doesn't have",
+ "wrapper_descrizione_serie": "a Delminio command",
+ "wrapper_commento": "Written by Delminio's \u201ceseguibili\u201d client from its register (Agents view):\nuntouched, it's rewritten at every sync; if you change it, it stays yours, and Delminio doesn't touch it any more.",
+ "commento_login_codex": "The login belongs to the person: that of their Codex, with a link (never a copy).",
+ "wrapper_senza_repo": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone.",
+ "fornitore_ignoto": "this Delminio doesn't know the Qwen Code provider \u201c{fornitore}\u201d",
+ "wrapper_senza_chiave": "\u26a0\ufe0f {nome}: the {fornitore} key is missing. Put it in your environment, as {variabile}=\u2026 (in the shell profile), and start it again.",
+ "commento_settings_qwen": "Qwen Code's settings for this agent: provider and model, and nothing that talks to Alibaba.",
+ "commento_mie_qwen": "The person's layer: ~/.config/delminio/mie-qwen.json and, for this agent only, mie.json in this folder, merged over the settings above at every start. Delminio never writes them; only the keys in QWEN_DI_DELMINIO stay Delminio's, and its options give way to the keys the layer writes.",
+ "mie_qwen_illeggibili": "\u26a0\ufe0f {file} is not valid JSON, and the agent starts with Delminio's settings only: {errore}",
+ "commento_mie_codex": "The person's layer: ~/.config/delminio/mie-codex.toml, merged at every start into the config.toml Delminio prepares for Codex. Delminio never writes it; only the keys in CODEX_DI_DELMINIO stay Delminio's, and its options give way to the keys the layer writes.",
+ "mie_di_delminio": "\u26a0\ufe0f {nome} stays Delminio's: in your settings it does not count, and the agent uses Delminio's.",
+ "mie_della_riga": "\u26a0\ufe0f {nome} is chosen by the agent (Agents view): in your settings it does not count.",
+ "mie_codex_illeggibili": "\u26a0\ufe0f {file} cannot be read as TOML, and the agent starts with Delminio's settings only: {errore}",
+ "mie_codex_casa_illeggibile": "\u26a0\ufe0f {file} cannot be read piece by piece: your settings do not go in this time, and the file stays as it is ({errore})",
+ "mie_codex_scontro": "\u26a0\ufe0f {file} clashes with the configuration Delminio prepares for Codex, and the agent starts without your settings: {errore}",
+ "mie_toml_chiave": "line {riga}: a key or a header is needed here",
+ "mie_toml_aperta": "line {riga}: a multi-line string that never closes",
+ "explore_descrizione": "Fast read-only agent for exploring codebases: finds files by pattern (eg. \"src/components/**/*.tsx\"), searches code for keywords (eg. \"API endpoints\") or answers questions about the code (eg. \"how do the endpoints work?\"). Say how thorough: \"quick\", \"medium\" or \"very thorough\".",
+ "explore_prompt": "You are a file search specialist agent: you explore codebases thoroughly.\n\nThis is a READ-ONLY task: you only have tools to find, search and read files. Do not try to create, modify, move or delete anything, and do not try to run commands.\n\nHow you work:\n- glob to find files by pattern\n- grep_search to search file contents with a regex\n- read_file when you know which file you need\n- adapt the search to the thoroughness you were asked for\n- whenever you can, run several searches and reads in parallel\n- file paths in your final answer are always absolute\n- write your report directly as a message, without emojis\n\nIn your final answer give the absolute paths of the files that matter for the task. Quote code only when the exact text matters (a bug you found, a function signature you were asked for): do not recap code you merely read.",
+ "commento_casa": "The isolated workspace: the repositories its agent role sees, up to date, and `consegne/` where it writes.",
+ "commento_autoupdater": "the version is decided by the register, not by the CLI",
+ "commento_catalogo_opencode": "the model list is the one built into OpenCode: no requests to models.opencode.ai",
+ "commento_token_progetto": "The token belongs to the project: it goes through the client of the connected repository you're in\n(a worktree doesn't have the client, which lives in the main clone).",
+ "wrapper_senza_repo_claude": "\u26a0\ufe0f {nome}: there's no repository connected to Delminio here. Go into the project's clone, or open claude.",
+ "wrapper_altro_spazio": "\u26a0\ufe0f {nome}: it's an agent role of the space \u201c{spazio}\u201d, and this folder is connected to another space. Go into the clone of a project from that space.",
+ "spazio_principale": "main",
+ "pulizia": " clean-up: removed {n} versions ({tolte}), kept {tenute}{riparo}",
+ "potate": " versions nobody uses, deleted: {tolte}",
+ "errori_testa": "Tool calls that failed on this computer in the last {giorni} days: {n} (the log: {file})",
+ "errori_nascosti": " {n} are not errors (an Esc, a command that says no by design): --tutti shows them",
+ "errori_nessuno": " none.",
+ "errori_per_specie": "By kind:",
+ "errori_per_programma": "By tool and program:",
+ "errori_ultime": "The latest:",
+ "nessuna": "none",
+ "al_riparo": " (rollback version: {versione})",
+ "installo_chiesta": " the admin asks for {cli} on this machine: installing it",
+ "prova_strumento": "Counts the letters of a word.",
+ "prova_chiedi": "Use the conta_lettere tool on the word \u201cDelminio\u201d. Don't answer in words.",
+ "prova_regola": "Rule {i} of this test: answer briefly, in the language the user writes in, and don't make up what you don't know.",
+ "prova_senza_chiave": "the key is missing: put it in the environment as {variabile}=\u2026 and start again",
+ "prova_sistema": "You are an assistant that uses tools.",
+ "prova_chiave_rifiutata": "the provider rejects the key ({codice}): {testo}",
+ "prova_strumento_errore": "the request with the tool answers {codice}",
+ "prova_ok": "Reply only: ok.",
+ "prova_senza_strumento": "the model didn't call the tool: it can't work with Delminio",
+ "prova_contesto_stretto": "context of {contesto} tokens: tight",
+ "prova_cache_muta": "the provider doesn't say what it reads from the cache",
+ "aiuto_descrizione": "Delminio's commands on this machine, synced with the register.",
+ "aiuto_nomi": "for rinomina: the old and the new",
+ "aiuto_da": "for the space: the .claude/delminio.sh client of a connected project",
+ "aiuto_converti": "with --modo kit, also rewrites the wrappers written with `--modo casa`",
+ "aiuto_vuoi": "the CLI the person chose when connecting: it is installed even if it is not here",
+ "aiuto_primo": "a file to write the command of that CLI's first agent into, to launch it",
+ "nessun_agente_di": "There is no {cli} agent in this space yet: the administrator switches one on in the Agents view, with \u201cAdd agent\u201d, then the connection is run again.",
+ "aiuto_al_lancio": "sync: asked by the wrapper before starting \u2014 exits 0 if the registry is already the applied one, 3 if it synced and the command must be relaunched",
+ "servono_url_token": "--url and --token-file (or --da) are needed",
+ "rifiutati": "noted: Delminio's commands are no longer offered on this machine",
+ "lasciati": " this space's commands: {n} removed from this machine",
+ "registro_muto": "\u26a0\ufe0f the command register doesn't arrive from {url}: {errore}",
+ "nomi_fuori_forma": "\u26a0\ufe0f register rows with a malformed name, skipped: {nomi}",
+ "uso_prova": "prova NAME \u2014 the name of a Qwen Code agent in the register (Agents view)",
+ "prova_inizio_locale": "Test of {nome} ({modello}): three requests to the local server\u2026",
+ "prova_inizio_fornitore": "Test of {nome} ({modello}): three requests to the provider, a few cents\u2026",
+ "prova_non_fatta": "\u26a0\ufe0f the test didn't run: {errore}",
+ "prova_riga_strumenti": " tools: {valore}",
+ "prova_si": "yes",
+ "prova_no": "NO",
+ "prova_riga_cache": " cache: {valore}",
+ "prova_cache_non_detta": "the provider doesn't say",
+ "prova_cache_letti": "{letti} tokens read out of {totale}",
+ "prova_riga_contesto": " context: {valore}",
+ "prova_non_lo_dice": "doesn't say",
+ "prova_riga_verdetto": " verdict: {valore}{nota}",
+ "prova_va": "works",
+ "prova_senza_cache": "works, but without cache: every request is paid in full",
+ "prova_non_va": "doesn't work",
+ "verdetto_perso": "\u26a0\ufe0f the verdict didn't reach Delminio: {errore}",
+ "uso_rinomina": "rinomina OLD NEW",
+ "rinomina_assente": "\u274c \u201c{nome}\u201d isn't in the register",
+ "rinomina_rifiutata": "\u274c Delminio won't rename: {errore}",
+ "rinominato": "\u2705 \u201c{vecchio}\u201d is now called \u201c{nuovo}\u201d in the register: \u201callinea\u201d writes the new command and removes the old one on every machine",
+ "stato_assente": "missing",
+ "stato_cambiato": "changed by its user: it stays theirs",
+ "stato_non_suo": "present, but not Delminio's",
+ "stato_intatto": "untouched",
+ "stato_altro_spazio": "untouched, but it's the command of another space ({spazi})",
+ "stato_riga": "{nome}: CLI {versione}{da_scaricare} \xb7 {modello} \xb7 role {porta} \xb7 {stato}",
+ "da_scaricare": " (to download)",
+ "modello_di_serie": "default model",
+ "stato_rifiutato": "the user said they don't want them on this machine (allinea writes them anyway)",
+ "registro_vuoto": "the register is empty: no commands",
+ "allinea_in_corso": " another sync is in progress on this machine: I'll let it finish",
+ "al_lancio": "\u23f3 The Agents view has changed: updating the agent commands before starting\u2026",
+ "al_lancio_attesa": "\u23f3 a sync is already running on this machine: waiting for it to finish, then starting on the new version\u2026",
+ "senza_cli_qui": " {nome}: {cli} isn't on this machine, I won't download it",
+ "passo_controllo": "{nome}: checking {cli} {versione}",
+ "passo_scarico": "{nome}: downloading {cli} {versione}, {mb} MB",
+ "passo_di": " of {mb}",
+ "non_di_delminio": "\u274c {percorso} already exists and isn't Delminio's: choose another name in the Agents view.",
+ "toccato_resta": " {percorso}: changed by its user, it stays as it is",
+ "smista_testa": "agent of more than one space on this machine: the folder you launch it from decides the space",
+ "smista_fuori": "\u26a0\ufe0f {nome} is an agent of more than one space on this machine ({spazi}): launch it from the folder of a connected project, and the folder decides the space.",
+ "smista_non_qui": "\u26a0\ufe0f {nome} is not an agent of this folder's space: it belongs to {spazi}. Launch it from the folder of a project in one of those spaces.",
+ "smistato": "\U0001f500 {nome}: more than one space on this machine wants it, with different rows ({spazi}). The name stays one: the folder you launch it from decides the space.",
+ "scritto": "\u2705 {percorso}: written (CLI {versione})",
+ "aggiornato": "\u2705 {percorso}: updated, CLI {prima} \u2192 {versione}",
+ "rinfrescato": "\u267b\ufe0f {percorso}: regenerated with the same CLI {versione} ({righe} lines changed; the reason is in eseguibili-diario.log, next to the command registry)",
+ "passo_scritto": "{nome}: written, {cli} {versione}",
+ "lasciato_ad_altri": " {percorso}: this space lets it go, it stays for {spazi}",
+ "tolto": " {percorso}: removed, it's no longer in the register",
+ "fuori_dal_path": "\u26a0\ufe0f {cartella} isn't in the PATH: add export PATH=\"{cartella}:$PATH\" to the shell profile (~/.bashrc, ~/.zshrc), or run the commands with the full path.",
+ "wrapper_chiave_negata": "\u26a0\ufe0f {nome}: Delminio won't give me the key \u201c{scelta}\u201d chosen in the Agents view. The answer:",
+ "commento_chiave_dal_motore": "The provider key is chosen by the admin in the Agents view: it's requested from Delminio at every\nstart and stays only in this process's environment \u2014 never in a file, never in the shell profile.",
+ "commento_chiave_di_qwen": "The key given to Qwen Code at its first start, if the environment doesn't have it.",
+ "prova_chiave_negata": "Delminio won't give the key \u201c{scelta}\u201d chosen in the Agents view: {errore}",
+ "commento_progetto_di_riserva": "Started from outside a connected repository (its own folder, any folder): the repository of\nthis space from which the client last synced.",
+ "wrapper_casa_senza_repo": "\u26a0\ufe0f {nome}: I don't know yet which connected repository to take the key from. Start it once from inside a repository connected to this space: after that it starts from anywhere.",
+ "commento_plugin_codex": "Delminio's plugin in this agent's Codex folder: the hooks come from there.",
+ "posta_ruolo_rifiutata": "\u26a0\ufe0f Delminio refuses this agent role's token (HTTP {codice}): the other sessions' messages don't reach you. It retries at every message; this notice appears only once, tell the user.",
+ "porto_non_qui": "\U0001f4e6 \u201c{cartella}\u201d is not sent to the team: it is not a skill, a command or an agent inside the folders the CLIs read.",
+ "porto_troppo": "\U0001f4e6 \u201c{cartella}\u201d is too big for the team: at most {file} files and {peso} bytes of text.",
+ "porto_fatto": "\U0001f4e6 \u201c{nome}\u201d is in the team: from the next start every agent gets it.",
+ "porto_no": "\U0001f4e6 \u201c{cartella}\u201d stays out of the team: {errore}",
+ "squadra_muta": "\U0001f465 The team skills did not arrive ({errore}): the previous ones stay, and it retries at the next start.",
+ "squadra_qui": "\U0001f465 The team on this computer, in the \u201c{plugin}\u201d plugin: {skill} skills, {comandi} commands, {agenti} agents, {mcp} MCP servers.",
+ "squadra_plugin_qui": "\U0001f50c The team's plugins: {accettati} accepted on this computer \xb7 {fermi} waiting for your user's approval (delminio accept, from their own terminal).",
+ "riga_da_accettare": "\u23f8 {nome}: the registry gives it arguments or environment variables you haven't accepted on this computer yet. The previous command stays; from your own terminal: delminio accept",
+ "accetta_senza_terminale": "delminio accept runs from a terminal: an agent can't accept on your behalf.",
+ "accetta_riga_domanda": "\nThe agent \u201c{nome}\u201d ({cli}) of the space {spazio} would start with:\n arguments: {argomenti}\n environment: {ambiente}\n\nThey run on this computer, with your permissions, every time you launch it. Accept them? [y/N] ",
+ "accetta_si": "y yes s si s\xec",
+ "accetta_righe_esito": "\u2705 agents: {nuovi} accepted now \xb7 {restano} stay on hold (if one changes, I'll ask again). The commands are rewritten at the next start."
+}
+
+def F(chiave, **sost):
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+def _esc(t):
+ return re.sub('([\\\\"$`])', '\\\\\\1', t)
+
+def _sh(t, **codice):
+ q = '"' + _esc(t) + '"'
+ for k, v in codice.items():
+ q = q.replace('{' + k + '}', v)
+ return q
+
+def _printf(t, **args):
+ ordine = sorted(((t.index('{' + k + '}'), k) for k in args if '{' + k + '}' in t))
+ fmt = _esc(t.replace('%', '%%'))
+ for k in args:
+ fmt = fmt.replace('{' + k + '}', '%s')
+ return f'printf "{fmt}\\n" ' + ' '.join((args[k] for _, k in ordine))
+
+def _commento(testo):
+ return ['# ' + r for r in testo.split('\n')]
+
+def _v(t):
+ return tuple((int(x) for x in t.split('.')))
+
+def _get(url, token=None, timeout=30, metodo='GET', corpo=None, nome=False):
+ h = {'Authorization': f'Bearer {token}'} if token else {}
+ if nome:
+ h['User-Agent'] = 'delminio-eseguibili'
+ dati = None
+ if corpo is not None:
+ dati, h['Content-Type'] = (json.dumps(corpo).encode(), 'application/json')
+ req = urllib.request.Request(url, data=dati, headers=h, method=metodo)
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return r.read()
+
+def _scarica(url, timeout, su=None, nome=False):
+ h = {'User-Agent': 'delminio-eseguibili'} if nome else {}
+ with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r:
+ totale = int(r.headers.get('Content-Length') or 0)
+ pezzi, fatti, detti = ([], 0, 0)
+ while True:
+ pezzo = r.read(1 << 20)
+ if not pezzo:
+ break
+ pezzi.append(pezzo)
+ fatti += len(pezzo)
+ if su and fatti - detti >= 4 << 20:
+ detti = fatti
+ su(fatti, totale)
+ return b''.join(pezzi)
+
+def piattaforma():
+ s, m = (platform.system().lower(), platform.machine().lower())
+ arch = {'x86_64': 'x64', 'amd64': 'x64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(m)
+ if s not in ('linux', 'darwin') or not arch:
+ return None
+ p = f'{s}-{arch}'
+ if s == 'linux':
+ try:
+ ldd = subprocess.run(['ldd', '--version'], capture_output=True, text=True).stdout
+ ldd += subprocess.run(['ldd', '--version'], capture_output=True, text=True).stderr
+ except OSError:
+ ldd = ''
+ if 'musl' in ldd.lower() or any((f.startswith('ld-musl-') for f in os.listdir('/lib') if os.path.isdir('/lib'))):
+ p += '-musl'
+ return p
+
+def versione_voluta(riga, canali):
+ v = riga['versione']
+ if v in CANALI and _VERSIONE.match(str(riga.get('versione_oggi') or '')):
+ v = riga['versione_oggi']
+ if v in CANALI and riga.get('cli') != 'claude':
+ chi = CLI_NOMI.get(riga.get('cli'), riga.get('cli'))
+ raise RuntimeError(F('riga_senza_numero', cli=chi))
+ if v in CANALI:
+ if v not in canali:
+ canali[v] = _get(f'{RILASCI}/{CANALI[v]}', timeout=15).decode().strip()
+ v = canali[v]
+ if riga.get('minimo') and _VERSIONE.match(riga['minimo']) and _VERSIONE.match(v) and (_v(v) < _v(riga['minimo'])):
+ v = riga['minimo']
+ if not _VERSIONE.match(v):
+ raise RuntimeError(F('non_versione', versione=v))
+ return v
+
+def assicura_cli(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ if os.path.isfile(dove) and os.access(dove, os.X_OK):
+ return dove
+ p = piattaforma()
+ if not p:
+ raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ manifesto = json.loads(_get(f'{RILASCI}/{versione}/manifest.json', timeout=20))
+ voce = (manifesto.get('platforms') or {}).get(p)
+ if not voce:
+ raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p))
+ print(F('scarico_cli', versione=versione, piattaforma=p, mb=voce.get('size', 0) // 1000000), flush=True)
+ dati = _scarica(f"{RILASCI}/{versione}/{p}/{voce.get('binary', 'claude')}", 600, su=su)
+ if hashlib.sha256(dati).hexdigest() != voce.get('checksum'):
+ raise RuntimeError(F('checksum_cli', versione=versione))
+ os.makedirs(cartella, exist_ok=True)
+ with open(dove + '.nuovo', 'wb') as f:
+ f.write(dati)
+ os.chmod(dove + '.nuovo', 493)
+ os.replace(dove + '.nuovo', dove)
+ return dove
+
+def assicura_codex(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'codex')
+ if os.path.isfile(binario) and os.access(binario, os.X_OK):
+ return binario
+ target = CODEX_TARGET.get(piattaforma() or '')
+ if not target:
+ raise RuntimeError(F('senza_codex_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ rilascio = json.loads(_get(f'{CODEX_RILASCI}/{versione}/release.json', timeout=20, nome=True))
+ nome = f'codex-package-{target}.tar.gz'
+ voce = next((x for x in rilascio.get('assets') or [] if x.get('name') == nome), None)
+ if not voce or not str(voce.get('digest') or '').startswith('sha256:'):
+ raise RuntimeError(F('codex_senza_pacchetto', versione=versione, piattaforma=target))
+ print(F('scarico_codex', versione=versione, piattaforma=target), flush=True)
+ dati = _scarica(f'{CODEX_RILASCI}/{versione}/{nome}', 600, su=su, nome=True)
+ if hashlib.sha256(dati).hexdigest() != voce['digest'].split(':', 1)[1]:
+ raise RuntimeError(F('digest_codex', versione=versione))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
+ for m in t.getmembers():
+ fuori = lambda x: x.startswith('/') or '..' in x.split('/')
+ if fuori(m.name) or m.islnk() or m.isdev() or (m.issym() and fuori(m.linkname)):
+ raise RuntimeError(F('pacchetto_fuori', chi=f'Codex {versione}'))
+ t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
+ if not os.path.isfile(os.path.join(tappa, 'bin', 'codex')):
+ shutil.rmtree(tappa, ignore_errors=True)
+ raise RuntimeError(F('codex_senza_binario', versione=versione))
+ for f in ('bin/codex', 'bin/codex-code-mode-host', 'codex-path/rg', 'codex-resources/bwrap'):
+ if os.path.isfile(os.path.join(tappa, f)):
+ os.chmod(os.path.join(tappa, f), 493)
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+
+def _estrai(dati, tappa, chi):
+ with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
+ for m in t.getmembers():
+ dentro = os.path.normpath(m.name)
+ if m.name.startswith('/') or dentro.startswith('..') or m.islnk() or m.isdev():
+ raise RuntimeError(F('pacchetto_fuori', chi=chi))
+ if m.issym():
+ dove = os.path.normpath(os.path.join(os.path.dirname(dentro), m.linkname))
+ if m.linkname.startswith('/') or dove.startswith('..'):
+ raise RuntimeError(F('pacchetto_fuori', chi=chi))
+ t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
+
+def node_di(versioni_qwen):
+ return os.path.join(os.path.dirname(os.path.normpath(versioni_qwen)), f'node-{NODE_QWEN}')
+
+def assicura_node(versioni_qwen, su=None):
+ dove = node_di(versioni_qwen)
+ if os.access(os.path.join(dove, 'bin', 'node'), os.X_OK):
+ return dove
+ target = NODE_TARGET.get(piattaforma() or '')
+ if not target:
+ raise RuntimeError(F('senza_node_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ nome = f'node-v{NODE_QWEN}-{target}'
+ somme = _get(f'{NODE_RILASCI}/v{NODE_QWEN}/SHASUMS256.txt', timeout=20).decode()
+ attesa = next((r.split()[0] for r in somme.splitlines() if r.endswith(f' {nome}.tar.gz')), '')
+ if not attesa:
+ raise RuntimeError(F('node_senza_pacchetto', versione=NODE_QWEN, piattaforma=target))
+ print(F('scarico_node', versione=NODE_QWEN), flush=True)
+ dati = _scarica(f'{NODE_RILASCI}/v{NODE_QWEN}/{nome}.tar.gz', 600, su=su)
+ if hashlib.sha256(dati).hexdigest() != attesa:
+ raise RuntimeError(F('checksum_node', versione=NODE_QWEN))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(tappa)
+ _estrai(dati, tappa, f'Node {NODE_QWEN}')
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(os.path.join(tappa, nome), dove)
+ shutil.rmtree(tappa, ignore_errors=True)
+ return dove
+
+def assicura_qwen(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'qwen')
+ if os.path.isfile(binario):
+ return binario
+ node = assicura_node(cartella, su=su)
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ print(F('installo_qwen', versione=versione), flush=True)
+ env = {**os.environ, 'PATH': os.path.join(node, 'bin') + os.pathsep + os.environ.get('PATH', ''), 'npm_config_update_notifier': 'false', 'npm_config_fund': 'false', 'npm_config_audit': 'false'}
+ r = subprocess.run([os.path.join(node, 'bin', 'npm'), 'install', '-g', '--prefix', tappa, '--cache', os.path.join(os.path.dirname(os.path.normpath(cartella)), 'npm-cache'), '--ignore-scripts', '--no-fund', '--no-audit', f'@qwen-code/qwen-code@{versione}'], env=env, capture_output=True, text=True, timeout=900)
+ if r.returncode != 0 or not os.path.isfile(os.path.join(tappa, 'bin', 'qwen')):
+ shutil.rmtree(tappa, ignore_errors=True)
+ coda = (r.stderr or r.stdout or '').strip().splitlines()[-3:]
+ raise RuntimeError(F('qwen_non_installato', versione=versione, perche=' / '.join(coda) or F('npm_muto')))
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+OPENCODE_NPM = 'https://registry.npmjs.org'
+OPENCODE_PACCHETTO = '@opencode/cli-{p}'
+
+def assicura_opencode(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ if not opencode_v2(versione):
+ raise RuntimeError(F('opencode_solo_v2', versione=versione))
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'opencode')
+ if os.path.isfile(binario) and os.access(binario, os.X_OK):
+ return binario
+ p = piattaforma()
+ if not p:
+ raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ pacchetto = OPENCODE_PACCHETTO.format(p=p)
+ try:
+ meta = json.loads(_get(f"{OPENCODE_NPM}/{pacchetto.replace('/', '%2F')}/{versione}", timeout=20))
+ except Exception:
+ raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p)) from None
+ dist = meta.get('dist') or {}
+ integrity = str(dist.get('integrity') or '')
+ if not integrity.startswith('sha512-') or not dist.get('tarball'):
+ raise RuntimeError(F('opencode_integrita', versione=versione))
+ print(F('installo_opencode', versione=versione), flush=True)
+ dati = _scarica(dist['tarball'], 600, su=su)
+ if 'sha512-' + base64.b64encode(hashlib.sha512(dati).digest()).decode() != integrity:
+ raise RuntimeError(F('opencode_integrita', versione=versione))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ _estrai(dati, tappa, f'OpenCode {versione}')
+ dentro = os.path.join(tappa, 'package', 'bin', 'opencode')
+ if not os.path.isfile(dentro):
+ shutil.rmtree(tappa, ignore_errors=True)
+ raise RuntimeError(F('opencode_senza_binario', versione=versione))
+ os.makedirs(os.path.join(tappa, 'bin'), exist_ok=True)
+ os.replace(dentro, os.path.join(tappa, 'bin', 'opencode'))
+ os.chmod(os.path.join(tappa, 'bin', 'opencode'), 493)
+ shutil.rmtree(os.path.join(tappa, 'package'), ignore_errors=True)
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+
+def _q(s):
+ return shlex.quote(str(s))
+
+def cli_qui(cli, versioni, versioni_codex, prova, versioni_qwen='', volute=(), versioni_opencode=''):
+ if prova:
+ return True
+ nome = cli if cli in CLI_NOMI else 'claude'
+ if shutil.which(nome) or cli in volute:
+ return True
+ cartella = {'codex': versioni_codex, 'qwen': versioni_qwen, 'opencode': versioni_opencode}.get(cli) or versioni
+ try:
+ return any((_VERSIONE.match(f) for f in os.listdir(cartella)))
+ except OSError:
+ return False
+
+def installa_agente(argv):
+ if len(argv) != 2 or argv[0] not in ('claude', 'codex', 'qwen', 'opencode'):
+ print(F('installa_agente_uso'), file=sys.stderr)
+ return 2
+ cli, versione = argv
+ prova = os.environ.get('DELMINIO_CLI_PROVA', '')
+ registro = os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
+ try:
+ v = versione if cli in ('qwen', 'opencode') else versione_voluta({'versione': versione, 'cli': cli}, {})
+ if not _VERSIONE.match(v):
+ raise RuntimeError(F('non_versione', versione=v))
+ if cli == 'claude':
+ binario = assicura_cli(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions'), prova)
+ elif cli == 'codex':
+ binario = assicura_codex(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions'), prova)
+ elif cli == 'qwen':
+ versioni_qwen = os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
+ binario = assicura_qwen(v, versioni_qwen, prova)
+ if not prova:
+ print('DELMINIO_NODE=' + os.path.join(node_di(versioni_qwen), 'bin'), flush=True)
+ else:
+ binario = assicura_opencode(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions'), prova)
+ except (RuntimeError, OSError, ValueError, urllib.error.URLError) as e:
+ print(F('installa_agente_no', cli=CLI_NOMI[cli], errore=e), file=sys.stderr)
+ return 1
+ mio = _leggi(registro)
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {cli})
+ _scrivi(registro, mio)
+ print(binario)
+ return 0
+
+def modello_gratuito(argv):
+ if len(argv) != 1 or not os.access(argv[0], os.X_OK):
+ print(F('modello_gratuito_uso'), file=sys.stderr)
+ return 2
+ oc = argv[0]
+ try:
+ elenco = subprocess.run([oc, '--standalone', 'models'], capture_output=True, text=True, timeout=60).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ elenco = ''
+ candidati = [r.strip() for r in elenco.splitlines() if r.strip().startswith('opencode/') and r.strip().endswith('-free')]
+ for m in candidati:
+ try:
+ r = subprocess.run([oc, '--standalone', 'run', '-m', m, F('modello_gratuito_domanda')], capture_output=True, text=True, timeout=90, cwd=tempfile.gettempdir())
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+ if r.returncode == 0 and F('modello_gratuito_risposta').lower() in r.stdout.lower():
+ print(m)
+ return 0
+ print(F('modello_gratuito_nessuno', n=len(candidati)), file=sys.stderr)
+ return 1
+
+def personaggio(riga):
+ return bool(riga.get('porta')) and riga.get('nascita') == 'porta'
+
+def spazio_di(url, token):
+ u = url.rstrip('/')
+ try:
+ pezzo = token.split('.')[1]
+ cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
+ except (IndexError, ValueError, AttributeError):
+ cli = ''
+ k = u if cli in ('', 'unico') else f'{u}#{cli}'
+ return _ALIASI.get(k, k)
+_ALIASI = {}
+
+def _alias(mio, chiave, istanza):
+ if not istanza:
+ return chiave
+ for k, sp in list((mio.get('spazi') or {}).items()):
+ if k != chiave and sp.get('istanza') == istanza and (k not in (mio.get('alias') or {})):
+ mio.setdefault('alias', {})[chiave] = k
+ _ALIASI[chiave] = k
+ mio.get('spazi', {}).pop(chiave, None)
+ for chi in (mio.get('padroni') or {}).values():
+ if chiave in chi:
+ chi[:] = list(dict.fromkeys((k if c == chiave else c for c in chi)))
+ return k
+ return chiave
+
+def _istanza_di(url, token):
+ try:
+ return json.loads(_get(url.rstrip('/') + '/api/eseguibili', token, timeout=10)).get('istanza') or ''
+ except (OSError, ValueError, AttributeError, urllib.error.URLError):
+ return ''
+
+def nome_spazio(spazio):
+ return spazio.rsplit('#', 1)[1] if '#' in spazio else F('spazio_principale')
+
+def _token_di(token_file):
+ try:
+ with open(os.path.expanduser(token_file), encoding='utf-8') as f:
+ return f.read().strip()
+ except OSError:
+ return ''
+
+def canale_del_ruolo(spazio, porta):
+ spazio = hashlib.sha256(spazio.encode()).hexdigest()[:12]
+ chiave = re.sub('[^a-z0-9._-]+', '-', porta.lower()).strip('-') or 'ruolo'
+ return os.path.join(os.path.expanduser('~/.config/delminio/ruoli'), spazio, chiave + '.json')
+
+def progetto_dello_spazio(spazio):
+ return os.path.join(os.path.dirname(canale_del_ruolo(spazio, 'x')), 'progetto')
+
+def ricorda_il_progetto(spazio):
+ qui = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ try:
+ c = subprocess.run(['git', '-C', qui, 'rev-parse', '--path-format=absolute', '--git-common-dir'], capture_output=True, text=True, timeout=10)
+ if c.returncode == 0 and c.stdout.strip():
+ qui = os.path.dirname(c.stdout.strip())
+ except (OSError, subprocess.SubprocessError):
+ pass
+ if not os.access(os.path.join(qui, '.claude', 'delminio.sh'), os.X_OK):
+ return
+ f = progetto_dello_spazio(spazio)
+ try:
+ with open(f, encoding='utf-8') as fh:
+ if fh.read().strip() == qui:
+ return
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
+ tmp = f + '.nuovo'
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as fh:
+ fh.write(qui + '\n')
+ os.replace(tmp, f)
+
+def _righe_del_repo(riga, spazio, avviso):
+ righe = ['r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi']
+ if (riga.get('scelte') or {}).get('casa') == 'separata' or riga.get('cartella'):
+ righe += [*_commento(F('commento_progetto_di_riserva')), 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', f' r=$(cat {_q(progetto_dello_spazio(spazio))} 2>/dev/null) || r=""', 'fi']
+ avviso = F('wrapper_casa_senza_repo', nome=riga['nome'])
+ return righe + ['if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' echo ' + _sh(avviso) + ' >&2', ' exit 1', 'fi']
+
+def assicura_canale(base_url, token, porta):
+ f = canale_del_ruolo(spazio_di(base_url, token), porta)
+ precedente, col_nome = ('', False)
+ if os.path.isfile(f):
+ try:
+ with open(f, encoding='utf-8') as h:
+ srv = json.load(h)['mcpServers']
+ col_nome = SERVER_RUOLO in srv
+ precedente = (srv.get(SERVER_RUOLO) or srv['delminio-ruolo'])['headers']['Authorization'].removeprefix('Bearer ')
+ except (ValueError, KeyError, TypeError, FileNotFoundError):
+ pass
+ d = json.loads(_get(base_url.rstrip('/') + '/api/porte/' + urllib.parse.quote(porta) + '/token', token, metodo='POST', corpo={'precedente': precedente}))
+ if precedente and d['token'] == precedente and col_nome:
+ return f
+ os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
+ conf = {'mcpServers': {SERVER_RUOLO: {'type': 'http', 'url': base_url.rstrip('/') + '/mcp', 'headers': {'Authorization': 'Bearer ' + d['token']}}}}
+ fd = os.open(f + '.nuovo', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as h:
+ json.dump(conf, h)
+ os.replace(f + '.nuovo', f)
+ return f
+
+def ganci_della_posta(canale):
+
+ def cmd(momento):
+ return f'python3 "$DELMINIO_POSTA_CLIENT" posta-ruolo {_q(canale)} {momento}'
+ pulizia = {'type': 'command', 'command': 'python3 "$DELMINIO_POSTA_CLIENT" pulizia', 'timeout': 10}
+ return {'UserPromptSubmit': [{'hooks': [{'type': 'command', 'command': cmd('umano'), 'timeout': 30}]}], 'PostToolUse': [{'hooks': [{'type': 'command', 'command': cmd('volo'), 'timeout': 10}]}], 'Stop': [{'hooks': [{'type': 'command', 'command': cmd('attesa'), 'timeout': 43200, 'asyncRewake': True}, dict(pulizia)]}], 'SessionEnd': [{'hooks': [dict(pulizia)]}]}
+
+def con_i_ganci(args, ganci):
+ return con_le_impostazioni(args, {'hooks': ganci}, F('cosa_posta_ruolo'))
+
+def _unisci(s, extra):
+ for k, v in extra.items():
+ if isinstance(v, dict) and isinstance(s.get(k), dict):
+ _unisci(s[k], v)
+ elif isinstance(v, list) and isinstance(s.get(k), list):
+ s[k].extend((x for x in v if x not in s[k]))
+ else:
+ s.setdefault(k, v)
+
+def con_le_impostazioni(args, extra, cosa):
+ args = list(args)
+ for i, a in enumerate(args[:-1]):
+ if a == '--settings' and args[i + 1].lstrip().startswith('{'):
+ try:
+ s = json.loads(args[i + 1])
+ except ValueError:
+ break
+ _unisci(s, json.loads(json.dumps(extra)))
+ args[i + 1] = json.dumps(s, ensure_ascii=False, separators=(',', ':'))
+ return args
+ if '--settings' in args:
+ sys.stderr.write(F('settings_file', cosa=cosa) + '\n')
+ return args
+ return args + ['--settings', json.dumps(extra, ensure_ascii=False, separators=(',', ':'))]
+PERMESSI = {'claude': {'chiede': ['--permission-mode', 'manual'], 'modifiche': ['--permission-mode', 'acceptEdits'], 'classificatore': ['--permission-mode', 'auto']}, 'codex': {'chiede': ['-s', 'read-only', '-a', 'on-request'], 'modifiche': ['-s', 'workspace-write', '-a', 'on-request'], 'classificatore': ['--approve-for-me']}, 'qwen': {'chiede': ['--approval-mode', 'default'], 'modifiche': ['--approval-mode', 'auto-edit'], 'classificatore': ['--approval-mode', 'auto']}}
+
+def ambiente_della_riga(riga):
+ return {k: v for k, v in (riga.get('ambiente') or {}).items() if not str(k).startswith('DELMINIO_')}
+
+def lancio_delle_scelte(riga):
+ sc, cli = (riga.get('scelte') or {}, riga.get('cli') or 'claude')
+ args, env = (list(PERMESSI.get(cli, {}).get(sc.get('permessi'), [])), {})
+ if sc.get('conversazioni') in CONVERSAZIONI:
+ env['DELMINIO_CONVERSAZIONI'] = sc['conversazioni']
+ if cli == 'opencode':
+ return (args, env)
+ if cli == 'qwen':
+ if sc.get('ricerca_web') == 'spenta':
+ args += ['--exclude-tools', 'web_search', '--exclude-tools', 'web_fetch']
+ return (args, env)
+ if cli == 'codex':
+ if sc.get('ricerca_web') == 'spenta':
+ args += ['-c', 'web_search="disabled"']
+ if sc.get('telemetria') == 'spenta':
+ args += ['-c', 'analytics.enabled=false', '-c', 'feedback.enabled=false']
+ if sc.get('velocita') == 'fast':
+ args += ['-c', 'service_tier="fast"', '-c', 'features.fast_mode=true']
+ return (args, env)
+ if sc.get('ricerca_web') == 'spenta':
+ args = con_le_impostazioni(args, {'permissions': {'deny': ['WebSearch', 'WebFetch']}}, F('cosa_ricerca_spenta'))
+ if sc.get('telemetria') == 'spenta':
+ env.update({'DISABLE_TELEMETRY': '1', 'DISABLE_ERROR_REPORTING': '1', 'CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY': '1'})
+ if sc.get('classificatore'):
+ env['CLAUDE_CODE_AUTO_MODE_MODEL'] = sc['classificatore']
+ if sc.get('casa') == 'separata':
+ args += ['--restricted', '--allowedTools=Edit(consegne/**)']
+ return (args, env)
+
+def _pid_della_cli():
+ pid = os.getppid()
+ for _ in range(4):
+ try:
+ exe = os.path.basename(os.readlink(f'/proc/{pid}/exe'))
+ if _VERSIONE.match(exe) or exe == 'claude':
+ return pid
+ with open(f'/proc/{pid}/stat', encoding='utf-8') as f:
+ pid = int(f.read().rsplit(')', 1)[1].split()[1])
+ except (OSError, ValueError, IndexError):
+ break
+ return os.getppid()
+
+def _rito_del_ruolo():
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'rito-del-ruolo')
+_SKILL_DEL_RITO = {'apertura': (F('rito_apertura_descrizione'), F('rito_apertura_corpo')), 'chiusura': (F('rito_chiusura_descrizione'), F('rito_chiusura_corpo'))}
+COMANDI = {
+ "riti": {
+ "apertura": "apertura",
+ "chiusura": "chiusura",
+ "closing": "chiusura",
+ "handoff": "chiusura",
+ "opening": "apertura",
+ "start": "apertura"
+ }
+}
+_SINONIMI_DEL_RITO = dict(COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'})
+_SKILL_DEL_RITO.update({nome: _SKILL_DEL_RITO[nostra] for nome, nostra in _SINONIMI_DEL_RITO.items()})
+
+def assicura_rito():
+ voluti = {os.path.join('.claude-plugin', 'plugin.json'): json.dumps({'name': 'delminio', 'description': F('rito_plugin')}, ensure_ascii=False, indent=2) + '\n'}
+ for nome, (descrizione, corpo) in _SKILL_DEL_RITO.items():
+ voluti[os.path.join('skills', nome, 'SKILL.md')] = f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\ndisable-model-invocation: true\n---\n{corpo} $ARGUMENTS\n'
+ for rel, testo in voluti.items():
+ p = os.path.join(_rito_del_ruolo(), rel)
+ try:
+ with open(p, encoding='utf-8') as f:
+ if f.read() == testo:
+ continue
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.replace(p + '.nuovo', p)
+ return _rito_del_ruolo()
+_NOMI_DEL_RITO = '|'.join((re.escape(n) for n in sorted(_SINONIMI_DEL_RITO, key=len, reverse=True)))
+_GESTO_DEL_RITO = re.compile('(?:/(?:delminio:)?(' + _NOMI_DEL_RITO + ')(?:\\s.*)?|(' + _NOMI_DEL_RITO + ')\\s*(?::.*)?)', re.I | re.S)
+
+def _rito_del_messaggio(base, token, radice, evento):
+ prima = (evento.get('prompt') or '').strip().split('\n', 1)[0].strip()
+ m = _GESTO_DEL_RITO.fullmatch(prima)
+ parola = (m.group(1) or m.group(2)).lower() if m else ''
+ parola = _SINONIMI_DEL_RITO.get(parola, parola)
+ segno = radice + '.aperta'
+ if not parola and os.path.exists(segno):
+ return ''
+ q = urllib.parse.urlencode({'parola': parola or 'apertura', 'da_se': '' if parola else '1'})
+ try:
+ testo = json.loads(_get(f'{base}/api/canale/ruolo/rito?{q}', token, timeout=15)).get('testo') or ''
+ open(segno, 'w').close()
+ return testo
+ except urllib.error.HTTPError as e:
+ if not parola:
+ return ''
+ try:
+ perche = json.loads(e.read()).get('error') or str(e)
+ except ValueError:
+ perche = str(e)
+ return F('rito_negato', parola=parola, perche=perche)
+ except (OSError, ValueError, urllib.error.URLError):
+ return F('rito_muto', parola=parola) if parola else ''
+CHIUDI_SH = '\n'.join(['#!/bin/bash', *_commento(F('chiudi_commento')), 'CASA="$(cd "$(dirname "$0")" && pwd)"\ncd "$CASA" || exit 1\n[ -f "$CASA/prima-di-chiudere.sh" ] && bash "$CASA/prima-di-chiudere.sh"\ngit add -A\nif git diff --cached --quiet; then', ' echo ' + _sh(F('chiudi_niente')), 'else\n file=$(git diff --cached --name-only | head -8 | tr \'\\n\' \' \')\n git commit -q -m "$(git config user.name): $(date \'+%d/%m %H:%M\') — $file" \\', ' && echo ' + _sh(F('chiudi_nella_storia', commit='{commit}'), commit="$(git log -1 --format='%h %s')"), 'fi\nif ! git remote get-url origin >/dev/null 2>&1; then', ' echo ' + _sh(F('chiudi_senza_repo')), 'elif out=$(git push -q origin HEAD 2>&1); then echo ' + _sh(F('chiudi_mandata')), 'else echo ' + _sh(F('chiudi_push_fallito', errore='{errore}'), errore='$out') + '; fi', ''])
+_IGNORATI_DELLA_CASA = ('/repo/', '/progetto/', '/NOVITA.md', '/.visto*')
+
+def _riga_exec(*pezzi):
+ return 'exec ' + ' '.join((p for p in pezzi if p))
+
+def _chiave_repo(remoto):
+ r = (remoto or '').strip()
+ if not r or r.startswith('locale:'):
+ return r
+ if '://' in r:
+ r = r.split('://', 1)[1]
+ autorita, separatore, percorso = r.partition('/')
+ r = autorita.rsplit('@', 1)[-1] + separatore + percorso
+ host, _, percorso = r.partition('/')
+ host = host.split(':', 1)[0]
+ elif ':' in r and (not r.startswith('/')):
+ host, _, percorso = r.partition(':')
+ host = host.split('@', 1)[-1]
+ else:
+ return r.rstrip('/').removesuffix('.git')
+ return f"{host.lower()}/{percorso.strip('/').removesuffix('.git').rstrip('/')}"
+
+def _git(*args, cwd=None):
+ env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'}
+ return subprocess.run(['git', *args], cwd=cwd, env=env, capture_output=True, text=True)
+
+def _origine(cartella):
+ o = _git('remote', 'get-url', 'origin', cwd=cartella).stdout.strip()
+ if o and os.path.isdir(o):
+ o = _git('remote', 'get-url', 'origin', cwd=o).stdout.strip() or o
+ return o
+
+def _https(remoto):
+ c = _chiave_repo(remoto)
+ return f'https://{c}.git' if '/' in c and '.' in c.split('/', 1)[0] else ''
+
+def _clona(remoto, progetto, dest, cartelle):
+ fonti = []
+ if progetto and _chiave_repo(_origine(progetto)) == _chiave_repo(remoto):
+ fonti.append(progetto)
+ fonti += [remoto] + ([_https(remoto)] if _https(remoto) else [])
+ ultimo = ''
+ for f in fonti:
+ r = _git('clone', '-q', '--no-checkout', f, dest)
+ if r.returncode == 0:
+ if cartelle:
+ _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
+ c = _git('checkout', '-q', cwd=dest)
+ if c.returncode == 0:
+ return ''
+ ultimo = c.stderr.strip()
+ else:
+ ultimo = r.stderr.strip()
+ shutil.rmtree(dest, ignore_errors=True)
+ return ultimo.splitlines()[-1] if ultimo else F('non_si_clona')
+
+def _aggiorna(dest, cartelle):
+ if cartelle:
+ _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
+ elif _git('config', 'core.sparseCheckout', cwd=dest).stdout.strip() == 'true':
+ _git('sparse-checkout', 'disable', cwd=dest)
+ r = _git('pull', '-q', '--ff-only', cwd=dest)
+ return '' if r.returncode == 0 else (r.stderr.strip().splitlines() or [F('pull_fallito')])[-1]
+
+def _testa(cartella):
+ return _git('rev-parse', 'HEAD', cwd=cartella).stdout.strip()
+
+def _uscito(cartella, prima, cartelle=(), quanti=40):
+ spec = [f":(exclude){c[1:].lstrip('/')}" if c.startswith('!') else c.lstrip('/') or '*' for c in cartelle]
+ file = _git('diff', '--name-only', f'{prima}..HEAD', '--', *spec, cwd=cartella).stdout.splitlines()
+ righe = [f'- {f}' for f in file[:quanti]]
+ if len(file) > quanti:
+ righe.append(F('altri_file', n=len(file) - quanti))
+ return righe
+
+def _la_casa_e_un_repo(casa, suo, agente):
+ avvisi = []
+ if not os.path.isdir(os.path.join(casa, '.git')):
+ vuota = not os.path.isdir(casa) or not os.listdir(casa)
+ if suo and vuota and (_git('clone', '-q', suo, casa).returncode == 0):
+ pass
+ else:
+ os.makedirs(casa, exist_ok=True)
+ _git('init', '-q', '-b', 'main', cwd=casa)
+ if suo:
+ _git('remote', 'add', 'origin', suo, cwd=casa)
+ if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
+ avvisi.append(F('repo_ruolo_lontano_nuova', repo=suo))
+ elif _git('rev-parse', '-q', '--verify', 'origin/main', cwd=casa).returncode == 0:
+ _git('checkout', '-q', '-B', 'main', 'origin/main', cwd=casa)
+ else:
+ ora = _git('remote', 'get-url', 'origin', cwd=casa).stdout.strip()
+ if suo and (not ora):
+ _git('remote', 'add', 'origin', suo, cwd=casa)
+ elif suo and _chiave_repo(ora) != _chiave_repo(suo):
+ _git('remote', 'set-url', 'origin', suo, cwd=casa)
+ avvisi.append(F('repo_ruolo_cambiato', repo=suo))
+ if suo or ora:
+ ramo = _git('rev-parse', '--abbrev-ref', 'HEAD', cwd=casa).stdout.strip() or 'main'
+ if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
+ avvisi.append(F('repo_ruolo_lontano'))
+ elif _git('rev-parse', '-q', '--verify', f'origin/{ramo}', cwd=casa).returncode == 0 and _git('merge', '-q', '--ff-only', f'origin/{ramo}', cwd=casa).returncode != 0:
+ avvisi.append(F('casa_ferma'))
+ if not _git('config', '--local', 'user.name', cwd=casa).stdout.strip():
+ _git('config', 'user.name', agente, cwd=casa)
+ _git('config', 'user.email', f'{agente}@ruoli.delminio', cwd=casa)
+ return avvisi
+
+def _scrivi_se_cambia(percorso, testo, modo=None):
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ if f.read() == testo:
+ return
+ except OSError:
+ pass
+ with open(percorso + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ if modo:
+ os.chmod(percorso + '.nuovo', modo)
+ os.replace(percorso + '.nuovo', percorso)
+
+def casa(argv):
+ if len(argv) not in (3, 4):
+ sys.stderr.write(F('uso_casa') + '\n')
+ return 2
+ client, ruolo, agente = argv[:3]
+ url = token_file = ''
+ for riga in open(client, encoding='utf-8'):
+ k, _, v = riga.strip().partition('=')
+ if k == 'URL' and v:
+ url = (shlex.split(v) or [''])[0]
+ elif k == 'FILE_TOKEN' and v:
+ token_file = (shlex.split(v) or [''])[0]
+ token = _token_di(token_file)
+ progetto = os.path.dirname(os.path.dirname(os.path.abspath(client)))
+ spazio = spazio_di(url, token)
+ casa = os.path.abspath(os.path.expanduser(argv[3])) if len(argv) == 4 and argv[3] else os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'case', hashlib.sha256(spazio.encode()).hexdigest()[:12], agente)
+ vero = os.path.realpath(progetto)
+ if os.path.realpath(casa) == vero or os.path.realpath(casa).startswith(vero + os.sep) or vero.startswith(os.path.realpath(casa) + os.sep):
+ sys.stderr.write(F('casa_nel_progetto', agente=agente) + '\n')
+ return 1
+ try:
+ conf = json.loads(_get(f"{url.rstrip('/')}/api/porte/{urllib.parse.quote(ruolo)}/casa", token, timeout=15))
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ if os.path.isdir(casa):
+ sys.stderr.write(F('casa_non_detta', agente=agente, errore=e) + '\n')
+ print(casa)
+ return 0
+ sys.stderr.write(F('casa_senza_repo', agente=agente, errore=e) + '\n')
+ return 1
+ avvisi = _la_casa_e_un_repo(casa, conf.get('suo') or '', agente)
+ if len(argv) == 3:
+ os.chmod(casa, 448)
+ os.makedirs(os.path.join(casa, 'consegne'), exist_ok=True)
+ scelti = {r['nome']: r for r in conf.get('repo') or []}
+ novita = ['# ' + F('novita_titolo'), '']
+ if scelti:
+ base = os.path.join(casa, 'repo')
+ os.makedirs(base, exist_ok=True)
+ shutil.rmtree(os.path.join(casa, 'progetto'), ignore_errors=True)
+ for d in sorted(os.listdir(base)):
+ if d not in scelti and os.path.isdir(os.path.join(base, d, '.git')):
+ shutil.rmtree(os.path.join(base, d), ignore_errors=True)
+ novita += [f'## repo/{d}', '', F('novita_uscito'), '']
+ for nome, r in scelti.items():
+ dest, cartelle = (os.path.join(base, nome), r.get('cartelle') or [])
+ if os.path.isdir(os.path.join(dest, '.git')) and _chiave_repo(_origine(dest)) != _chiave_repo(r['chiave']):
+ shutil.rmtree(dest, ignore_errors=True)
+ novita += [f'## repo/{nome}', '']
+ if not os.path.isdir(os.path.join(dest, '.git')):
+ perche = _clona(r['chiave'], progetto, dest, cartelle)
+ novita += [F('novita_non_si_clona', repo=r['chiave'], perche=perche) if perche else F('novita_copia_repo'), '']
+ if perche:
+ avvisi.append(F('avviso_non_si_clona', repo=f'repo/{nome}', perche=perche))
+ continue
+ prima = _testa(dest)
+ perche = _aggiorna(dest, cartelle)
+ if perche:
+ avvisi.append(F('avviso_non_si_aggiorna', repo=f'repo/{nome}', perche=perche))
+ novita.append(F('novita_non_si_aggiorna', perche=perche))
+ righe = _uscito(dest, prima, cartelle) if prima and prima != _testa(dest) else []
+ novita += (righe or ([F('novita_niente')] if not perche else [])) + ['']
+ for nome in conf.get('usciti') or []:
+ novita += [F('novita_uscito_spazio', repo=nome), '']
+ else:
+ base = os.path.join(casa, 'repo')
+ if os.path.isdir(base):
+ shutil.rmtree(base, ignore_errors=True)
+ dest = os.path.join(casa, 'progetto')
+ if os.path.isdir(os.path.join(dest, '.git')):
+ prima = _testa(dest)
+ perche = _aggiorna(dest, [])
+ if perche:
+ avvisi.append(F('copia_progetto_ferma', perche=perche))
+ righe = _uscito(dest, prima, quanti=60) if prima != _testa(dest) else []
+ novita += righe or [F('novita_niente')]
+ else:
+ r = _git('clone', '-q', progetto, dest)
+ if r.returncode != 0:
+ sys.stderr.write(F('progetto_non_si_copia', agente=agente, casa=casa) + '\n')
+ return 1
+ novita.append(F('novita_copia_progetto'))
+ if avvisi:
+ novita += ['', '## ' + F('novita_al_tecnico'), ''] + [f'- {a}' for a in avvisi]
+ _scrivi_se_cambia(os.path.join(casa, 'NOVITA.md'), '\n'.join(novita).rstrip() + '\n')
+ _scrivi_se_cambia(os.path.join(casa, 'chiudi.sh'), CHIUDI_SH, 493)
+ ignorati = os.path.join(casa, '.gitignore')
+ try:
+ ci_sono = open(ignorati, encoding='utf-8').read().splitlines()
+ except OSError:
+ ci_sono = []
+ mancano = [x for x in _IGNORATI_DELLA_CASA if x not in ci_sono]
+ if mancano:
+ _scrivi_se_cambia(ignorati, '\n'.join(ci_sono + mancano).strip() + '\n')
+ for a in avvisi:
+ sys.stderr.write(f'⚠️ {agente}: {a}\n')
+ print(casa)
+ return 0
+
+def posta_ruolo(argv):
+ if len(argv) != 2 or argv[1] not in ('umano', 'volo', 'attesa'):
+ return 0
+ canale, momento = argv
+ try:
+ with open(canale, encoding='utf-8') as f:
+ srv = json.load(f)['mcpServers']
+ srv = srv.get(SERVER_RUOLO) or srv['delminio-ruolo']
+ base = srv['url'].rsplit('/mcp', 1)[0]
+ token = srv['headers']['Authorization'].split(' ', 1)[1]
+ except (OSError, ValueError, KeyError, IndexError):
+ return 0
+ evento = {}
+ if not sys.stdin.isatty():
+ try:
+ evento = json.loads(sys.stdin.read() or '{}')
+ except ValueError:
+ pass
+ if momento == 'volo' and evento.get('agent_id'):
+ return 0
+ cli = _pid_della_cli()
+ sid = re.sub('[^A-Za-z0-9_-]', '', str(evento.get('session_id') or cli))[:64]
+ stato = os.path.join(os.path.dirname(canale), 'posta')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ radice = os.path.join(stato, os.path.splitext(os.path.basename(canale))[0] + '-' + sid)
+ if momento == 'volo':
+ try:
+ if time.time() - os.path.getmtime(radice + '.volo') < 10:
+ return 0
+ except OSError:
+ pass
+ open(radice + '.volo', 'w').close()
+
+ def guarda(segna=True):
+ with open(radice + '.lock', 'w') as lk:
+ if fcntl is not None:
+ fcntl.flock(lk, fcntl.LOCK_EX)
+ try:
+ with open(radice + '.visto', encoding='utf-8') as f:
+ dopo = f.read().strip()
+ except OSError:
+ dopo = ''
+ q = urllib.parse.urlencode({'dopo': dopo, 'momento': momento})
+ try:
+ r = json.loads(_get(f'{base}/api/canale/ruolo?{q}', token, timeout=10))
+ except urllib.error.HTTPError as e:
+ if segna and e.code in (401, 403) and (not os.path.exists(radice + '.rifiutato')):
+ open(radice + '.rifiutato', 'w').close()
+ return F('posta_ruolo_rifiutata', codice=e.code)
+ return ''
+ except (OSError, ValueError, urllib.error.URLError):
+ return ''
+ if os.path.exists(radice + '.rifiutato'):
+ os.remove(radice + '.rifiutato')
+ if segna and r.get('ultimo') and (r['ultimo'] != dopo):
+ with open(radice + '.visto', 'w', encoding='utf-8') as f:
+ f.write(r['ultimo'])
+ if not segna and r.get('testo'):
+ return r.get('ultimo') or ''
+ return r.get('testo') or ''
+ if momento != 'attesa':
+ testo = guarda()
+ if momento == 'umano':
+ testo = '\n\n'.join((t for t in (_rito_del_messaggio(base, token, radice, evento), testo) if t))
+ if testo:
+ nome = 'UserPromptSubmit' if momento == 'umano' else 'PostToolUse'
+ print(json.dumps({'hookSpecificOutput': {'hookEventName': nome, 'additionalContext': testo}}))
+ return 0
+ posta_qwen = os.environ.get('DELMINIO_QWEN_POSTA') or ''
+ if posta_qwen:
+ m = re.search('-(\\d+)\\.jsonl$', posta_qwen)
+ if m:
+ cli = int(m.group(1))
+ if not os.path.isfile(posta_qwen) or os.fork():
+ return 0
+ os.setsid()
+ nulla = os.open(os.devnull, os.O_RDWR)
+ for fd in (0, 1, 2):
+ os.dup2(nulla, fd)
+ with open(radice + '.attesa', 'w', encoding='utf-8') as f:
+ f.write(str(os.getpid()))
+ giri = 0
+ while True:
+ testo = guarda(segna=not posta_qwen)
+ if testo and posta_qwen:
+ with open(radice + '.avviso.lock', 'w') as lk:
+ if fcntl is not None:
+ fcntl.flock(lk, fcntl.LOCK_EX)
+ mia, gia = (False, '')
+ try:
+ with open(radice + '.attesa', encoding='utf-8') as f:
+ mia = f.read().strip() == str(os.getpid())
+ except OSError:
+ pass
+ try:
+ with open(radice + '.avvisato', encoding='utf-8') as f:
+ gia = f.read().strip()
+ except OSError:
+ pass
+ if not mia:
+ return 0
+ if testo != gia:
+ with open(posta_qwen, 'a', encoding='utf-8') as f:
+ f.write(json.dumps({'type': 'submit', 'text': F('posta_arrivata')}, ensure_ascii=False) + '\n')
+ with open(radice + '.avvisato', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ return 0
+ elif testo:
+ sys.stderr.write(testo + '\n')
+ return 2
+ try:
+ os.kill(cli, 0)
+ with open(radice + '.attesa', encoding='utf-8') as f:
+ if f.read().strip() != str(os.getpid()):
+ return 0
+ except (OSError, ValueError):
+ return 0
+ giri += 1
+ time.sleep(3 if giri < 40 else 15 if giri < 80 else 30)
+GIORNI_DOPO_UN_CRASH = 3
+CONVERSAZIONI = ('subito', 'fine_sessione')
+
+def _pid_vivo(pid):
+ try:
+ os.kill(int(pid), 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except (PermissionError, ValueError, TypeError, OverflowError):
+ return True
+
+def _sessioni_vive(registro):
+ vive = set()
+ for f in glob_ordinato(os.path.join(registro, '*.json')):
+ try:
+ with open(f, encoding='utf-8') as h:
+ d = json.load(h)
+ if _pid_vivo(d.get('pid') or os.path.basename(f).split('.')[0]) and d.get('sessionId'):
+ vive.add(str(d['sessionId']))
+ except (OSError, ValueError, AttributeError):
+ continue
+ return vive
+
+def glob_ordinato(schema):
+ import glob
+ return sorted(glob.glob(schema))
+
+def _vecchia(percorsi, giorni):
+ if giorni <= 0:
+ return True
+ soglia = time.time() - giorni * 86400
+ for p in percorsi:
+ try:
+ if os.path.getmtime(p) >= soglia:
+ return False
+ except OSError:
+ continue
+ return True
+
+def _via(p):
+ try:
+ if os.path.isdir(p) and (not os.path.islink(p)):
+ shutil.rmtree(p, ignore_errors=True)
+ elif os.path.lexists(p):
+ os.unlink(p)
+ except OSError:
+ pass
+
+def _ancora_dopo(percorsi, secondi=15):
+ if not percorsi or os.fork():
+ return
+ try:
+ os.setsid()
+ nulla = os.open(os.devnull, os.O_RDWR)
+ for fd in (0, 1, 2):
+ os.dup2(nulla, fd)
+ time.sleep(secondi)
+ for p in percorsi:
+ _via(p)
+ finally:
+ os._exit(0)
+
+def _da_togliere(sessioni, vive, mia, fine, subito, giorni):
+ via = set()
+ for sid, percorsi in sessioni.items():
+ if sid == mia:
+ if fine or subito:
+ via.add(sid)
+ continue
+ if sid in vive:
+ continue
+ if _vecchia(percorsi, giorni):
+ via.add(sid)
+ return via
+
+def _pulisci_claude(evento, mia, fine, subito, giorni):
+ casa = os.path.realpath(os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude'))
+ progetti = os.path.join(casa, 'projects')
+ trascritto = str(evento.get('transcript_path') or '')
+ if trascritto:
+ cartella = os.path.dirname(os.path.realpath(trascritto))
+ else:
+ dove = os.environ.get('CLAUDE_PROJECT_DIR') or str(evento.get('cwd') or '')
+ if not dove:
+ return
+ cartella = os.path.join(progetti, re.sub('[^A-Za-z0-9]', '-', dove))
+ if os.path.dirname(cartella) != progetti or not os.path.isdir(cartella):
+ return
+ sessioni = {}
+ for nome in os.listdir(cartella):
+ sid = nome[:-6] if nome.endswith('.jsonl') else nome
+ if sid == 'memory' or not re.fullmatch('[0-9a-fA-F-]{8,}', sid):
+ continue
+ sessioni.setdefault(sid, []).append(os.path.join(cartella, nome))
+ via = _da_togliere(sessioni, _sessioni_vive(os.path.join(casa, 'sessions')), mia, fine, subito, giorni)
+ for sid in via:
+ for p in sessioni[sid]:
+ _via(p)
+ for p in (os.path.join(casa, 'file-history', sid), os.path.join(casa, 'session-env', sid), os.path.join(casa, 'tasks', sid), *glob_ordinato(os.path.join(casa, 'todos', sid + '*'))):
+ _via(p)
+ if via:
+ _togli_dalla_cronologia(os.path.join(casa, 'history.jsonl'), via)
+ if fine and mia in via:
+ _ancora_dopo([os.path.join(cartella, mia + '.jsonl'), os.path.join(cartella, mia)])
+
+def _togli_dalla_cronologia(f, via):
+ try:
+ with open(f, encoding='utf-8') as h:
+ righe = h.readlines()
+ except OSError:
+ return
+ tenute = []
+ for r in righe:
+ try:
+ if str(json.loads(r).get('sessionId') or '') in via:
+ continue
+ except (ValueError, AttributeError):
+ pass
+ tenute.append(r)
+ if len(tenute) == len(righe):
+ return
+ tmp = f + '.delminio'
+ try:
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as h:
+ h.writelines(tenute)
+ os.replace(tmp, f)
+ except OSError:
+ _via(tmp)
+
+def _casa_delminio(var, sotto):
+ h = os.environ.get(var)
+ if not h:
+ return None
+ casa = os.path.realpath(h)
+ base = os.path.realpath(os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', sotto))
+ return casa if os.path.dirname(casa) == base and os.path.isdir(casa) else None
+
+def _pulisci_qwen(mia, fine, subito, giorni):
+ casa = _casa_delminio('QWEN_HOME', 'qwen')
+ if not casa:
+ return
+ eta, tutto = ({}, {})
+ for p in glob_ordinato(os.path.join(casa, 'projects', '*', 'chats', '*')):
+ sid = os.path.basename(p).split('.', 1)[0]
+ eta.setdefault(sid, []).append(p)
+ tutto.setdefault(sid, []).append(p)
+ degli_agenti = {}
+ for d in glob_ordinato(os.path.join(casa, 'projects', '*', 'subagents', '*')):
+ sid = os.path.basename(d)
+ tutto.setdefault(sid, []).append(d)
+ degli_agenti.setdefault(sid, []).extend([d, *glob_ordinato(os.path.join(d, '*'))])
+ for sid, percorsi in degli_agenti.items():
+ eta.setdefault(sid, percorsi)
+ for p in [*glob_ordinato(os.path.join(casa, 'file-history', '*')), *glob_ordinato(os.path.join(casa, 'tmp', '*', 'background-shells', '*'))]:
+ tutto.setdefault(os.path.basename(p), []).append(p)
+ for sid, percorsi in tutto.items():
+ eta.setdefault(sid, percorsi)
+ vive = _sessioni_vive(os.path.join(casa, 'sessions'))
+ via = _da_togliere(eta, vive, mia, fine, subito, giorni)
+ for sid in via:
+ for p in tutto[sid]:
+ _via(p)
+ if fine and mia in via:
+ _ancora_dopo(tutto[mia])
+ for f in glob_ordinato(os.path.join(casa, 'sessions', '*.json')):
+ if not _pid_vivo(os.path.basename(f).split('.')[0]):
+ _via(f)
+ if not vive - ({mia} if fine else set()):
+ for d in glob_ordinato(os.path.join(casa, 'tmp', '*')):
+ for x in ('logs.json', 'tool-results', 'checkpoints'):
+ _via(os.path.join(d, x))
+
+def _pulisci_codex(mia, fine, giorni):
+ casa = _casa_delminio('CODEX_HOME', 'codex')
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if not casa or os.path.basename(cli) != 'codex' or (not os.path.isfile(cli)):
+ return
+ stato = os.path.join(casa, 'delminio-pulizia')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ if fine and re.fullmatch('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', mia):
+ open(os.path.join(stato, mia + '.pending'), 'a').close()
+ if not fine and giorni > 0:
+ return
+ env = {k: os.environ[k] for k in ('HOME', 'PATH', 'CODEX_HOME', 'DELMINIO_CLI', 'LANG', 'XDG_DATA_HOME', 'DELMINIO_CONVERSAZIONI') if k in os.environ}
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-codex', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
+
+def _codex_vivi(casa):
+ for p in glob_ordinato('/proc/[0-9]*'):
+ try:
+ if os.path.basename(os.path.realpath(os.path.join(p, 'exe'))) != 'codex':
+ continue
+ with open(os.path.join(p, 'environ'), 'rb') as h:
+ v = h.read().split(b'\x00')
+ c = next((x.split(b'=', 1)[1] for x in v if x.startswith(b'CODEX_HOME=')), None)
+ if c is None or os.path.realpath(os.fsdecode(c)) == casa:
+ return True
+ except FileNotFoundError:
+ continue
+ except OSError:
+ return True
+ return False
+
+def pulizia_codex(argv):
+ import fcntl, sqlite3, uuid
+ from contextlib import closing
+ casa = _casa_delminio('CODEX_HOME', 'codex')
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if not casa or os.path.basename(cli) != 'codex':
+ return 0
+ giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
+ stato = os.path.join(casa, 'delminio-pulizia')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ with open(os.path.join(stato, 'lock'), 'w') as lk:
+ try:
+ fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return 0
+ while _codex_vivi(casa):
+ time.sleep(3)
+ via = {os.path.basename(p)[:-8] for p in glob_ordinato(os.path.join(stato, '*.pending'))}
+ db = os.path.join(casa, 'state_5.sqlite')
+ if os.path.isfile(db) and glob_ordinato(os.path.join(casa, 'state_*.sqlite')) == [db]:
+ soglia = time.time() - giorni * 86400
+ with closing(sqlite3.connect('file:' + db + '?mode=ro', uri=True)) as c:
+ for sid, ultima in c.execute('SELECT id, updated_at FROM threads').fetchall():
+ if isinstance(ultima, (int, float)) and 0 < ultima < soglia:
+ via.add(str(sid))
+ tolte = []
+ for sid in sorted(via):
+ try:
+ sid = str(uuid.UUID(sid))
+ except ValueError:
+ continue
+ if _codex_vivi(casa):
+ return 0
+ r = subprocess.run([cli, 'delete', '--force', sid], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=120)
+ if r.returncode == 0:
+ tolte.append(sid)
+ _via(os.path.join(stato, sid + '.pending'))
+ for s in glob_ordinato(os.path.join(casa, 'shell_snapshots', sid + '.*.sh')):
+ _via(s)
+ if tolte and (not _codex_vivi(casa)):
+ for prefisso in ('state', 'thread_history', 'queue', 'logs', 'goals', 'memories'):
+ for p in glob_ordinato(os.path.join(casa, prefisso + '_*.sqlite')):
+ try:
+ with closing(sqlite3.connect(p, timeout=5)) as c:
+ if c.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]:
+ continue
+ c.execute('VACUUM')
+ c.execute('PRAGMA wal_checkpoint(TRUNCATE)')
+ except sqlite3.Error:
+ continue
+ return 0
+_SESSIONE_OPENCODE = re.compile('ses_[A-Za-z0-9]{8,64}')
+
+def _segni_opencode():
+ d = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'opencode', 'conversazioni')
+ os.makedirs(d, mode=448, exist_ok=True)
+ return d
+
+def _pulisci_opencode(mia, fine, giorni):
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if os.path.basename(cli) != 'opencode' or not os.path.isfile(cli) or (not _SESSIONE_OPENCODE.fullmatch(mia)):
+ return
+ stato = _segni_opencode()
+ pid = os.environ.get('DELMINIO_CLI_PID') or str(os.getppid())
+ with open(os.path.join(stato, mia + '.json'), 'w', encoding='utf-8') as h:
+ json.dump({'pid': pid, 'cli': cli, 'linea': '2'}, h)
+ if fine:
+ open(os.path.join(stato, mia + '.fine'), 'a').close()
+ env = {k: os.environ[k] for k in ('HOME', 'PATH', 'LANG', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME') if k in os.environ}
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-opencode', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
+
+def pulizia_opencode(argv):
+ import fcntl
+ giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
+ stato = _segni_opencode()
+ with open(os.path.join(stato, 'lock'), 'w') as lk:
+ try:
+ fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return 0
+ while True:
+ segnate, attese = ({}, False)
+ for f in glob_ordinato(os.path.join(stato, 'ses_*.json')):
+ sid = os.path.basename(f)[:-5]
+ try:
+ with open(f, encoding='utf-8') as h:
+ segnate[sid] = (json.load(h), f)
+ except (OSError, ValueError):
+ continue
+ via = []
+ for sid, (d, f) in segnate.items():
+ finita = os.path.exists(os.path.join(stato, sid + '.fine'))
+ if _pid_vivo(d.get('pid')):
+ attese = attese or finita
+ continue
+ if finita or _vecchia([f], giorni):
+ via.append((sid, d))
+ for sid, d in via:
+ cli = d.get('cli') if os.path.isfile(str(d.get('cli') or '')) else ''
+ if d.get('linea') != '2':
+ for x in ('.json', '.fine'):
+ _via(os.path.join(stato, sid + x))
+ continue
+ if not cli:
+ continue
+ cmd = [cli, 'session', 'delete', sid, '--standalone']
+ try:
+ r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=120)
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+ if r.returncode == 0 or b'Session not found' in r.stdout + r.stderr:
+ for x in ('.json', '.fine'):
+ _via(os.path.join(stato, sid + x))
+ if not attese:
+ return 0
+ time.sleep(3)
+
+def pulizia(argv):
+ modo = os.environ.get('DELMINIO_CONVERSAZIONI') or ''
+ if modo not in CONVERSAZIONI:
+ return 0
+ try:
+ evento = json.loads(sys.stdin.read() or '{}') if not sys.stdin.isatty() else {}
+ if not isinstance(evento, dict):
+ evento = {}
+ except ValueError:
+ evento = {}
+ fine = evento.get('hook_event_name') == 'SessionEnd' or argv[:1] == ['fine']
+ mia = str(evento.get('session_id') or '')
+ subito = modo == 'subito'
+ giorni = 0 if subito else GIORNI_DOPO_UN_CRASH
+ cli = os.environ.get('DELMINIO_CLI_NOME') or 'claude'
+ try:
+ if cli == 'qwen':
+ _pulisci_qwen(mia, fine, subito, giorni)
+ elif cli == 'codex':
+ _pulisci_codex(mia, fine, giorni)
+ elif cli == 'opencode':
+ _pulisci_opencode(mia, fine, giorni)
+ elif cli == 'claude':
+ _pulisci_claude(evento, mia, fine, subito, giorni)
+ except Exception:
+ pass
+ return 0
+ERRORI_TETTO_BYTE = 2000000
+ERRORI_RIGHE = 3
+ERRORI_CARATTERI = 300
+_USCITA = re.compile('^Exit code (\\d+)\\s*')
+_DICE_NO = {'grep', 'egrep', 'fgrep', 'rg', 'diff', 'cmp', 'test', '[', '[['}
+_SEGRETO = re.compile('(?i)\\b(token|password|passwd|secret|segreto|bearer|api[_-]?key|authorization)\\b(\\S*?)([=:]\\s*|\\s+)\\S+')
+_LUNGO = re.compile('[A-Za-z0-9_\\-+=]{24,}')
+_ESADECIMALE = re.compile('[0-9a-fA-F]{32,}')
+ENTROPIA_DI_UNA_CHIAVE = 4.3
+_FERMATO_CLI = re.compile('^blocked|isolated\\sin\\sthe\\sworktree|permission|denied|rejected')
+_TEMPO = re.compile('timed\\sout|timeout')
+
+def _registro_errori():
+ casa = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
+ return os.path.join(casa, 'delminio', 'errori-strumenti.jsonl')
+
+def _entropia(s):
+ return -sum((k / len(s) * math.log2(k / len(s)) for k in collections.Counter(s).values()))
+
+def _maschera(t):
+ t = _SEGRETO.sub(lambda m: m.group(1) + m.group(2) + m.group(3) + '…', t)
+ t = _ESADECIMALE.sub('…', t)
+ return _LUNGO.sub(lambda m: '…' if _entropia(m.group(0)) > ENTROPIA_DI_UNA_CHIAVE else m.group(0), t)
+
+def _programma(comando):
+ pezzi = [p for p in re.split('&&|\\|\\||;|\\||\\n', comando or '') if p.strip()]
+ if not pezzi:
+ return ''
+ for parola in pezzi[-1].split():
+ if re.match('^[A-Za-z_][A-Za-z0-9_]*=', parola) or parola in ('sudo', 'timeout', 'time', '!'):
+ continue
+ if re.fullmatch('\\d+[smh]?', parola):
+ continue
+ return os.path.basename(parola.strip('\'"()'))[:40]
+ return ''
+
+def _specie(evento, programma, errore):
+ if evento.get('is_interrupt'):
+ return ('interrotto', True)
+ m = _USCITA.match(errore)
+ if m:
+ resto = errore[m.end():].strip()
+ if m.group(1) == '1' and (not resto or programma in _DICE_NO):
+ return ('uscita_senza_errore', True)
+ return ('uscita', False)
+ basso = errore.lower()
+ if '<tool_use_error>' in basso or 'inputvalidationerror' in basso:
+ return ('tool', False)
+ if 'delminio' in basso or '🔒' in errore:
+ return ('fermato_da_delminio', False)
+ if _FERMATO_CLI.search(basso):
+ return ('fermato_dalla_cli', False)
+ if _TEMPO.search(basso):
+ return ('tempo', False)
+ return ('altro', False)
+
+def errori_registra(_argv):
+ try:
+ evento = json.loads(sys.stdin.read() or '{}')
+ tool = str(evento.get('tool_name') or '')[:60]
+ entrata = evento.get('tool_input') or {}
+ comando = entrata.get('command') if isinstance(entrata, dict) else ''
+ programma = _programma(comando) if isinstance(comando, str) else ''
+ errore = str(evento.get('error') or '').strip()
+ specie, non_errore = _specie(evento, programma, errore)
+ righe = [r for r in errore.splitlines() if r.strip()][:ERRORI_RIGHE]
+ voce = {'quando': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), 'sessione': os.environ.get('DELMINIO_SESSIONE_NOME') or '', 'cli': 'claude', 'cartella': str(evento.get('cwd') or '')[:200], 'tool': tool, 'programma': programma, 'specie': specie, 'non_errore': non_errore, 'errore': _maschera(' ⏎ '.join(righe))[:ERRORI_CARATTERI], 'ms': evento.get('duration_ms')}
+ dove = _registro_errori()
+ os.makedirs(os.path.dirname(dove), mode=448, exist_ok=True)
+ with open(dove, 'a', encoding='utf-8') as f:
+ f.write(json.dumps(voce, ensure_ascii=False) + '\n')
+ if os.path.getsize(dove) > ERRORI_TETTO_BYTE:
+ with open(dove, encoding='utf-8', errors='replace') as f:
+ tenute = f.readlines()
+ tenute = tenute[len(tenute) // 2:]
+ nuovo = dove + f'.{os.getpid()}.tmp'
+ with open(nuovo, 'w', encoding='utf-8') as f:
+ f.writelines(tenute)
+ os.replace(nuovo, dove)
+ except Exception:
+ pass
+ return 0
+
+def errori(argv):
+ tutti = '--tutti' in argv or '--all' in argv
+ numeri = [a for a in argv if a.isdigit()]
+ giorni = int(numeri[0]) if numeri else 7
+ dal = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=giorni)
+ dove = _registro_errori()
+ voci = []
+ try:
+ with open(dove, encoding='utf-8', errors='replace') as f:
+ for r in f:
+ try:
+ v = json.loads(r)
+ if datetime.datetime.fromisoformat(v['quando']) >= dal:
+ voci.append(v)
+ except (ValueError, KeyError, TypeError):
+ continue
+ except FileNotFoundError:
+ pass
+ nascoste = [v for v in voci if v.get('non_errore')]
+ mostrate = voci if tutti else [v for v in voci if not v.get('non_errore')]
+ print(F('errori_testa', giorni=giorni, n=len(mostrate), file=dove))
+ if nascoste and (not tutti):
+ print(F('errori_nascosti', n=len(nascoste)))
+ if not mostrate:
+ print(F('errori_nessuno'))
+ return 0
+ print(F('errori_per_specie'))
+ for specie, n in collections.Counter((v.get('specie', '') for v in mostrate)).most_common():
+ print(f' {n:4} {specie}')
+ print(F('errori_per_programma'))
+ for (tool, prog), n in collections.Counter(((v.get('tool', ''), v.get('programma', '')) for v in mostrate)).most_common(12):
+ print(f" {n:4} {tool}{(' ' + prog if prog else '')}")
+ print(F('errori_ultime'))
+ for v in mostrate[-15:]:
+ print(f" {v.get('quando', '')[:16].replace('T', ' ')} {v.get('sessione') or '—'} {v.get('tool', '')}{(' ' + v['programma'] if v.get('programma') else '')} · {v.get('specie', '')} · {v.get('errore', '')[:110]}")
+ return 0
+
+def _righe_del_prompt(riga, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ rotta = 'nascita' if riga.get('nascita') == 'intera' else 'sistema'
+ return [*_commento(F('commento_prompt')), 'D="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-eseguibili"', 'mkdir -p "$D" && chmod 700 "$D"', f'for f in "$D"/{nome}-*.txt; do', ' [ -e "$f" ] || continue; p=${f##*-}; p=${p%.txt}', ' kill -0 "$p" 2>/dev/null || rm -f "$f"', 'done', f'F="$D/{nome}-$$.txt"', f"""codice=$( (umask 077; printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -G -o "$F" -w "%{{http_code}}" -K - --data-urlencode {_q('ordine=' + porta)} """ + (f"--data-urlencode {_q('modello=' + riga['ordine'])} " if riga.get('ordine') and rotta == 'nascita' else '') + f"{_q(url.rstrip('/') + '/api/porte/' + rotta)}) 2>/dev/null)", 'if [ "$codice" != 200 ] || [ ! -s "$F" ]; then', ' ' + _printf(F('prompt_negato', nome='{nome}', porta='{porta}', codice='{codice}'), nome=_q(nome), porta=_q(porta), codice='"${codice:-000}"') + ' >&2', ' [ -s "$F" ] && head -c 400 "$F" >&2 && echo >&2', ' rm -f "$F"; exit 1', 'fi', *_commento(F('commento_hook_sistema')), 'export DELMINIO_SISTEMA="$F"']
+
+def _righe_al_lancio(modo, url, token_file):
+ if modo == 'kit':
+ chi = [' q=${r:-$(git rev-parse --show-toplevel 2>/dev/null)}', ' if [ -n "$q" ] && [ -f "$q/.claude/eseguibili.py" ]; then', ' python3 "$q/.claude/eseguibili.py" allinea --al-lancio --modo kit --da "$q/.claude/delminio.sh" >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi', ' fi']
+ else:
+ chi = [f' python3 {_q(os.path.abspath(__file__))} allinea --al-lancio --modo casa --url {_q(url)} --token-file {_q(token_file)} >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi']
+ return [*_commento(F('commento_al_lancio')), 'if [ -z "${DELMINIO_AL_LANCIO:-}" ]; then', *chi, 'fi', 'unset DELMINIO_AL_LANCIO']
+
+def _testa_del_wrapper(riga):
+ chi = ' '.join(str(riga.get('descrizione') or F('wrapper_descrizione_serie')).split())
+ return ['#!/bin/sh', f"# {riga['nome']} — {chi}", *_commento(F('wrapper_commento'))]
+
+def wrapper_codex(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ if personaggio(riga):
+ raise RuntimeError(F('codex_ruolo_solo'))
+ di_serie = [] if modo == 'kit' else ['--no-daemon', '-c', 'check_for_update_on_startup=false']
+ della_riga = []
+ if riga.get('modello'):
+ della_riga += ['-m', riga['modello']]
+ if riga.get('effort'):
+ della_riga += ['-c', f'''model_reasoning_effort="{riga['effort']}"''']
+ contesto = riga.get('_contesto') or {}
+ espliciti = riga.get('argomenti') or []
+ if contesto.get('massimo') and (not any((x.startswith('model_context_window=') for x in espliciti))):
+ di_serie += ['-c', f"model_context_window={int(contesto['massimo'])}"]
+ if contesto.get('compatta') and (not any((x.startswith('model_auto_compact_token_limit=') for x in espliciti))):
+ di_serie += ['-c', f"model_auto_compact_token_limit={int(contesto['compatta'])}"]
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ della_riga += delle_scelte + list(riga.get('argomenti') or [])
+ casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
+ righe = [*_testa_del_wrapper(riga), f'export CODEX_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/codex/{casa}"', 'export DELMINIO_CLI_NOME=codex', f"export DELMINIO_PERMESSI={_q((riga.get('scelte') or {}).get('permessi') or '')}", f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ righe += ['mkdir -p "$CODEX_HOME" && chmod 700 "$CODEX_HOME"', *_commento(F('commento_login_codex')), '[ -e "$CODEX_HOME/auth.json" ] || [ ! -f "$HOME/.codex/auth.json" ] || ln -s "$HOME/.codex/auth.json" "$CODEX_HOME/auth.json"']
+
+ def strato(client):
+ return [*_commento(F('commento_mie_codex')), f'DELMINIO_MIE=$(python3 {client} mie-codex "$CODEX_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := chiavi_della_riga('codex', della_riga)) else '') + ') || DELMINIO_MIE=""', 'export DELMINIO_MIE', *righe_dello_strato('codex', di_serie, della_riga, 'DELMINIO_MIE')]
+ if modo == 'kit' and porta:
+ righe += [*_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ if (tetto := (riga.get('_base') or {}).get('codex.tetto_uscite')):
+ righe.append(f'export DELMINIO_TETTO_USCITE={int(tetto)}')
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe += strato('"$r/.claude/eseguibili.py"')
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" codex', '"$@"'))
+ return '\n'.join(righe) + '\n'
+ if porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe.append(f'export DELMINIO_PORTA={_q(porta)}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ prompt = ' -c "model_instructions_file=\\"$F\\""' if porta else ''
+ righe += _righe_al_lancio(modo, url, token_file)
+ pacchetto = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugin.py')
+ righe += [*_commento(F('commento_plugin_codex')), f'[ -n "${{DELMINIO_SENZA_PLUGIN:-}}" ] || DELMINIO_CODEX={_q(cli)} python3 {_q(pacchetto)} codex "$CODEX_HOME" >/dev/null 2>&1 || true']
+ righe += strato(_q(os.path.abspath(__file__)))
+ righe.append(_riga_exec(_q(cli), prompt.strip(), '"$@"'))
+ return '\n'.join(righe) + '\n'
+MIE_QWEN = 'mie-qwen.json'
+MIE_CODEX = 'mie-codex.toml'
+QWEN_DI_DELMINIO = ('hooks', 'general.enableAutoUpdate', 'mcpServers.delminio', 'mcpServers.memoria')
+CODEX_DI_DELMINIO = (('hooks',), ('mcp_servers', 'delminio'), ('mcp_servers', 'memoria'), ('plugins', 'delminio@delminio'), ('marketplaces', 'delminio'), ('model_instructions_file',), ('check_for_update_on_startup',))
+OPZIONI_CHIAVE = {'codex': {'-m': 'model', '--model': 'model', '-s': 'sandbox_mode', '--sandbox': 'sandbox_mode', '-a': 'approval_policy', '--ask-for-approval': 'approval_policy'}, 'qwen': {'-m': 'model.name', '--model': 'model.name', '--approval-mode': 'tools.approvalMode', '--exclude-tools': 'tools.exclude'}}
+
+def cartella_mie():
+ return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio')
+
+def _percorsi_json(d, dove=()):
+ for k, v in d.items():
+ if isinstance(v, dict):
+ yield from _percorsi_json(v, dove + (k,))
+ else:
+ yield (dove + (k,))
+
+def _stampa_chiavi(percorsi):
+ print('|' + '|'.join(sorted({'.'.join(p) for p in percorsi})) + '|')
+
+def _della_riga(argomenti):
+ if '--della-riga' in argomenti:
+ i = argomenti.index('--della-riga')
+ return (argomenti[:i] + argomenti[i + 2:], [tuple(k.split('.')) for k in argomenti[i + 1].split(',') if k])
+ return (argomenti, [])
+
+def _sotto(percorso, chiavi):
+ return any((percorso[:len(k)] == k for k in chiavi))
+
+def _sopra(percorso, chiavi):
+ return [k for k in chiavi if len(k) > len(percorso) and k[:len(percorso)] == percorso]
+
+def unisci_mie_qwen(argomenti):
+ argomenti, della_riga = _della_riga(argomenti)
+ casa = argomenti[0]
+ base = json.load(open(os.path.join(casa, 'settings.json'), encoding='utf-8'))
+ scritte = []
+ di_delminio = [tuple(x.split('.')) for x in QWEN_DI_DELMINIO]
+
+ def unisci(a, b, dove=''):
+ for k, v in b.items():
+ if dove + k in QWEN_DI_DELMINIO:
+ print(F('mie_di_delminio', nome=dove + k), file=sys.stderr)
+ continue
+ percorso = tuple((dove + k).split('.'))
+ if _sotto(percorso, della_riga):
+ print(F('mie_della_riga', nome=dove + k), file=sys.stderr)
+ continue
+ dentro_d, dentro_r = (_sopra(percorso, di_delminio), _sopra(percorso, della_riga))
+ if isinstance(v, dict) and (isinstance(a.get(k), dict) or dentro_d or dentro_r):
+ if not isinstance(a.get(k), dict):
+ a[k] = {}
+ unisci(a[k], v, dove + k + '.')
+ elif dentro_d or dentro_r:
+ for x in dentro_d:
+ print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
+ for x in dentro_r:
+ print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
+ else:
+ a[k] = v
+ scritte.extend([percorso + p for p in _percorsi_json(v)] if isinstance(v, dict) else [percorso])
+ for file in (os.path.join(cartella_mie(), MIE_QWEN), os.path.join(casa, 'mie.json')):
+ if not os.path.isfile(file):
+ continue
+ try:
+ mie = json.load(open(file, encoding='utf-8'))
+ if not isinstance(mie, dict):
+ raise ValueError(type(mie).__name__)
+ except (OSError, ValueError) as e:
+ print(F('mie_qwen_illeggibili', file=file, errore=e), file=sys.stderr)
+ continue
+ unisci(base, mie)
+ with open(os.path.join(casa, 'settings.json'), 'w', encoding='utf-8') as h:
+ json.dump(base, h, indent=2, ensure_ascii=False)
+ _stampa_chiavi(scritte)
+ return 0
+
+def _toml_chiave(s, i):
+ parti = []
+ while True:
+ while i < len(s) and s[i] in ' \t':
+ i += 1
+ if i < len(s) and s[i] in '"\'':
+ q, j = (s[i], i + 1)
+ while j < len(s) and s[j] != q and (s[j] != '\n'):
+ j += 2 if q == '"' and s[j] == '\\' else 1
+ nome = s[i + 1:j]
+ if q == '"':
+ try:
+ nome = json.loads('"' + nome + '"')
+ except ValueError:
+ pass
+ parti.append(nome)
+ i = j + 1
+ else:
+ j = i
+ while j < len(s) and (s[j].isalnum() or s[j] in '_-'):
+ j += 1
+ if j == i:
+ raise ValueError(F('mie_toml_chiave', riga=s.count('\n', 0, i) + 1))
+ parti.append(s[i:j])
+ i = j
+ while i < len(s) and s[i] in ' \t':
+ i += 1
+ if s[i:i + 1] != '.':
+ return (tuple(parti), i)
+ i += 1
+
+def _toml_fine_valore(s, i):
+ profondo = 0
+ while i < len(s):
+ if s.startswith('"""', i) or s.startswith("'''", i):
+ q, j = (s[i:i + 3], i + 3)
+ while True:
+ k = s.find(q, j)
+ if k < 0:
+ raise ValueError(F('mie_toml_aperta', riga=s.count('\n', 0, i) + 1))
+ barre = len(s[:k]) - len(s[:k].rstrip('\\'))
+ if q == '"""' and barre % 2:
+ j = k + 1
+ continue
+ i = k + 3
+ while s[i:i + 1] == q[0]:
+ i += 1
+ break
+ continue
+ c = s[i]
+ if c in '"\'':
+ j = i + 1
+ while j < len(s) and s[j] != c and (s[j] != '\n'):
+ j += 2 if c == '"' and s[j] == '\\' else 1
+ i = j + 1
+ continue
+ if c == '#':
+ k = s.find('\n', i)
+ i = len(s) if k < 0 else k
+ continue
+ if c in '[{':
+ profondo += 1
+ elif c in ']}':
+ profondo -= 1
+ elif c == '\n' and profondo <= 0:
+ return i + 1
+ i += 1
+ return i
+
+def toml_pezzi(testo):
+ pezzi, i, tabella = ([], 0, ())
+ while i < len(testo):
+ j = i
+ while j < len(testo) and testo[j] in ' \t\r':
+ j += 1
+ if j >= len(testo) or testo[j] in '\n#':
+ k = testo.find('\n', j)
+ fine = len(testo) if k < 0 else k + 1
+ pezzi.append(('altro', None, testo[i:fine]))
+ i = fine
+ continue
+ if testo[j] == '[':
+ lista = testo.startswith('[[', j)
+ percorso, k = _toml_chiave(testo, j + (2 if lista else 1))
+ if not testo.startswith(']]' if lista else ']', k):
+ raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
+ k = testo.find('\n', k)
+ fine = len(testo) if k < 0 else k + 1
+ tabella = percorso
+ pezzi.append(('lista' if lista else 'tabella', percorso, testo[i:fine]))
+ i = fine
+ continue
+ percorso, k = _toml_chiave(testo, j)
+ if testo[k:k + 1] != '=':
+ raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
+ fine = _toml_fine_valore(testo, k + 1)
+ pezzi.append(('chiave', tabella + percorso, testo[i:fine]))
+ i = fine
+ return pezzi
+
+def _toml_parti(pezzi):
+ cima, sezioni = ([], [])
+ for p in pezzi:
+ if p[0] in ('tabella', 'lista'):
+ sezioni.append([p])
+ elif sezioni:
+ sezioni[-1].append(p)
+ else:
+ cima.append(p)
+ return (cima, sezioni)
+
+def _di_delminio_codex(percorso):
+ return any((percorso[:len(r)] == r for r in CODEX_DI_DELMINIO))
+SEGNO_MIE = '# delminio-strato:' + MIE_CODEX
+SEGNO_DA_PARTE = '# delminio-strato:da-parte'
+SEGNO_FINE = '# delminio-strato:fine'
+_TRATTO = re.compile('(?ms)^(' + re.escape(SEGNO_MIE) + '|' + re.escape(SEGNO_DA_PARTE) + ')[^\\n]*\\n(.*?)^' + re.escape(SEGNO_FINE) + '[^\\n]*\\n?')
+
+def _unito(pezzi):
+ t = ''.join((p[2] for p in pezzi))
+ return t if not t or t.endswith('\n') else t + '\n'
+
+def _tratto(segno, testo, prefisso=''):
+ if not testo.strip():
+ return ''
+ return segno + '\n' + ''.join((prefisso + r for r in testo.splitlines(keepends=True))) + SEGNO_FINE + '\n'
+
+def _casa_codex(testo):
+ da_parte = []
+
+ def via(m):
+ if m.group(1) == SEGNO_DA_PARTE:
+ da_parte.extend((r[3:] if r.startswith('#= ') else r[2:] if r.startswith('#=') else '' for r in m.group(2).splitlines(keepends=True)))
+ return ''
+ cima, sezioni = _toml_parti(toml_pezzi(_TRATTO.sub(via, testo)))
+ try:
+ cima_p, sezioni_p = _toml_parti(toml_pezzi(''.join(da_parte)))
+ except ValueError:
+ cima_p, sezioni_p = ([], [])
+ chiavi = {p[1] for p in cima + [x for s in sezioni for x in s] if p[0] == 'chiave'}
+ cima += [p for p in cima_p if p[0] == 'chiave' and p[1] not in chiavi]
+ for s in sezioni_p:
+ torna = [p for p in s[1:] if p[0] != 'chiave' or p[1] not in chiavi]
+ gemella = next((x for x in sezioni if x[0][0] == 'tabella' and x[0][1] == s[0][1]), None)
+ if gemella is None:
+ sezioni.append([s[0]] + torna)
+ else:
+ gemella.extend((p for p in torna if p[0] == 'chiave'))
+ return (cima, sezioni)
+
+def unisci_mie_codex(argomenti):
+ argomenti, della_riga = _della_riga(argomenti)
+ casa = argomenti[0]
+ conf, file = (os.path.join(casa, 'config.toml'), os.path.join(cartella_mie(), MIE_CODEX))
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except FileNotFoundError:
+ testo = ''
+ try:
+ cima_r, sezioni_r = _casa_codex(testo)
+ except ValueError as e:
+ print(F('mie_codex_casa_illeggibile', file=conf, errore=e), file=sys.stderr)
+ _stampa_chiavi([])
+ return 0
+ senza = _unito(cima_r) + _unito([p for s in sezioni_r for p in s])
+ nuovo, scritte = (senza, [])
+ pezzi = None
+ if os.path.isfile(file):
+ try:
+ with open(file, encoding='utf-8') as h:
+ pezzi = toml_pezzi(h.read())
+ except (OSError, ValueError, UnicodeDecodeError) as e:
+ print(F('mie_codex_illeggibili', file=file, errore=e), file=sys.stderr)
+ if pezzi:
+ cima_m, sezioni_m = _toml_parti(pezzi)
+
+ def fuori(percorso):
+ return _di_delminio_codex(percorso) or _sotto(percorso, della_riga)
+
+ def fuori_c(percorso):
+ return fuori(percorso) or bool(_sopra(percorso, CODEX_DI_DELMINIO) or _sopra(percorso, della_riga))
+
+ def dillo(percorso):
+ if fuori(percorso):
+ print(F('mie_di_delminio' if _di_delminio_codex(percorso) else 'mie_della_riga', nome='.'.join(percorso)), file=sys.stderr)
+ return
+ for x in _sopra(percorso, CODEX_DI_DELMINIO):
+ print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
+ for x in _sopra(percorso, della_riga):
+ print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
+ for p in [p for p in cima_m if p[0] == 'chiave' and fuori_c(p[1])] + [s[0] for s in sezioni_m if fuori(s[0][1])] + [p for s in sezioni_m if not fuori(s[0][1]) for p in s[1:] if p[0] == 'chiave' and fuori_c(p[1])]:
+ dillo(p[1])
+ cima_m = [p for p in cima_m if not (p[0] == 'chiave' and fuori_c(p[1]))]
+ sezioni_m = [[p for p in s if not (p[0] == 'chiave' and fuori_c(p[1]))] for s in sezioni_m if not fuori(s[0][1])]
+ scritte = [p[1] for p in cima_m + [x for s in sezioni_m for x in s] if p[0] == 'chiave']
+ tabelle_m = {s[0][1] for s in sezioni_m if s[0][0] == 'tabella'}
+ coppie_m = set(scritte) | tabelle_m
+
+ def coperta(p):
+ return p[0] == 'chiave' and (p[1] in coppie_m or any((p[1][:len(t)] == t for t in tabelle_m)))
+ fuori = [p for p in cima_r if coperta(p)]
+ cima_r = [p for p in cima_r if not coperta(p)]
+ dentro, fuori_sezioni = ([], [])
+ for s in sezioni_r:
+ if s[0][0] == 'tabella' and s[0][1] in tabelle_m:
+ fuori_sezioni.append(s)
+ elif s[0][0] == 'lista':
+ dentro.append(s)
+ else:
+ dentro.append([s[0]] + [p for p in s[1:] if not coperta(p)])
+ if any((coperta(p) for p in s[1:])):
+ fuori_sezioni.append([s[0]] + [p for p in s[1:] if coperta(p)])
+ fuori += [p for s in sorted(fuori_sezioni, key=lambda s: s[0][1]) for p in s]
+ nuovo = _tratto(SEGNO_MIE + ':chiavi', _unito(cima_m)) + _unito(cima_r) + _tratto(SEGNO_MIE + ':tabelle', _unito([p for s in sezioni_m for p in s])) + _unito([p for s in dentro for p in s]) + _tratto(SEGNO_DA_PARTE, _unito(fuori), '#= ')
+ try:
+ import tomllib
+ except ImportError:
+ tomllib = None
+ if tomllib:
+ try:
+ tomllib.loads(nuovo)
+ except tomllib.TOMLDecodeError as e:
+ print(F('mie_codex_scontro', file=file, errore=e), file=sys.stderr)
+ nuovo, scritte = (senza, [])
+ if nuovo != testo:
+ os.makedirs(casa, exist_ok=True)
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.chmod(conf + '.nuovo', 384)
+ os.replace(conf + '.nuovo', conf)
+ _stampa_chiavi(scritte)
+ return 0
+
+def opzioni_dello_strato(cli, args):
+ gruppi, i, chiavi = ([], 0, OPZIONI_CHIAVE.get(cli, {}))
+ while i < len(args):
+ a = args[i]
+ nome, _, valore = a.partition('=')
+ if cli == 'codex' and a in ('-c', '--config') and (i + 1 < len(args)):
+ gruppi.append((args[i + 1].split('=', 1)[0].strip(), args[i:i + 2]))
+ i += 2
+ elif nome in chiavi and valore:
+ gruppi.append((chiavi[nome], [a]))
+ i += 1
+ elif a in chiavi and i + 1 < len(args):
+ gruppi.append((chiavi[a], args[i:i + 2]))
+ i += 2
+ else:
+ gruppi.append((None, [a]))
+ i += 1
+ return gruppi
+
+def chiavi_della_riga(cli, della_riga):
+ return ','.join(sorted({k for k, _ in opzioni_dello_strato(cli, della_riga) if k}))
+
+def righe_dello_strato(cli, di_serie, della_riga, variabile):
+ righe = ['set -- ' + ' '.join((_q(a) for a in della_riga)) + ' "$@"'] if della_riga else []
+ for chiave, gruppo in reversed(opzioni_dello_strato(cli, di_serie)):
+ metti = 'set -- ' + ' '.join((_q(a) for a in gruppo)) + ' "$@"'
+ if not chiave:
+ righe.append(metti)
+ continue
+ parti = chiave.split('.')
+ casi = '|'.join(('*"|' + '.'.join(parti[:n]) + '|"*' for n in range(1, len(parti) + 1)))
+ righe.append(f'case "${{{variabile}:-}}" in {casi}) ;; *) {metti} ;; esac')
+ return righe
+
+def chiave_qwen(riga):
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ fisso = ((riga.get('_fornitori') or {}).get(tipo) or {}).get('chiave')
+ return fisso if fisso else re.sub('[^A-Z0-9]+', '_', riga['nome'].upper()).strip('_') + '_API_KEY'
+
+def impostazioni_qwen(riga):
+ f = riga.get('fornitore') or {}
+ info = (riga.get('_fornitori') or {}).get(f.get('tipo')) or {}
+ if not info:
+ raise RuntimeError(F('fornitore_ignoto', fornitore=f.get('tipo') or ''))
+ spente = {} if (riga.get('scelte') or {}).get('telemetria') == 'accesa' else {'privacy': {'usageStatisticsEnabled': False}, 'telemetry': {'enabled': False}}
+ auth, modello = (info['auth'], riga.get('modello') or '')
+ indirizzo = f.get('indirizzo') or info.get('indirizzo') or ''
+ fa = info.get('formato_anthropic') or {}
+ if fa.get('prefisso') and modello.startswith(fa['prefisso']):
+ auth, indirizzo = ('anthropic', fa['indirizzo'])
+ contesto = int(f.get('contesto') or 0)
+ memoria = (riga.get('scelte') or {}).get('memoria') == 'accesa'
+ base = riga.get('_base') or {}
+ attesa = int(base.get('qwen.prima_parola_ms') or QWEN_PRIMA_PAROLA_MS)
+ generazione = {'timeout': attesa, 'streamIdleTimeoutMs': attesa, **({'contextWindowSize': contesto} if contesto else {})}
+ compatta, voluto = ({}, int(f.get('compatta') or 0))
+ finestra = contesto or (1000000 if auth == 'anthropic' and QWEN_CLAUDE_1M.search(modello) else 0)
+ if finestra:
+ soglia = min(1.0, voluto / finestra) if voluto else min(0.85, int(base.get('qwen.compatta') or QWEN_SOGLIA) / finestra)
+ if voluto or soglia < 0.85:
+ generazione['contextWindowSize'] = finestra
+ compatta = {'context': {'autoCompactThreshold': round(soglia, 3)}}
+ if info.get('auth') == 'anthropic':
+ generazione['cacheRetention'] = '1h'
+ fornitori = {auth: [{'id': modello, 'name': modello, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo} if indirizzo else {}), **({'generationConfig': generazione} if generazione else {})}]}
+ veloce, extra = ((riga.get('scelte') or {}).get('classificatore') or '', {})
+ if veloce and veloce != modello:
+ auth_v, indirizzo_v = (info['auth'], f.get('indirizzo') or info.get('indirizzo') or '')
+ if fa.get('prefisso') and veloce.startswith(fa['prefisso']):
+ auth_v, indirizzo_v = ('anthropic', fa['indirizzo'])
+ fornitori.setdefault(auth_v, []).append({'id': veloce, 'name': veloce, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo_v} if indirizzo_v else {})})
+ extra = {'fastModel': veloce if auth_v == auth else f'{auth_v}:{veloce}'}
+ return {'modelProviders': fornitori, **extra, 'security': {'auth': {'selectedType': auth}}, 'model': {'name': modello}, **spente, **compatta, 'memory': {'enableManagedAutoMemory': memoria, 'enableManagedAutoDream': memoria, 'enableAutoSkill': False, 'enableTeamMemory': False}, 'general': {'enableAutoUpdate': False}, 'ui': {'enableFollowupSuggestions': False, 'showToolCallDetails': False}, 'tools': {'approvalMode': 'default', 'toolSearch': {'enabled': False}}, 'permissions': {'deny': list(QWEN_TOOL_FUORI + (QWEN_TOOL_LARGHI if 0 < contesto < 65536 else ())), 'ask': list(QWEN_CHIEDI)}, 'review': {**QWEN_REVIEW, **({'effort': base['qwen.review']} if base.get('qwen.review') else {})}, 'skills': skill_qwen(riga.get('_skill'))}
+
+def della_riga_qwen(riga):
+ sc, f = (riga.get('scelte') or {}, riga.get('fornitore') or {})
+ chiavi = ['modelProviders', 'model.name', 'security.auth']
+ if sc.get('classificatore'):
+ chiavi.append('fastModel')
+ if sc.get('telemetria'):
+ chiavi += ['privacy.usageStatisticsEnabled', 'telemetry.enabled']
+ if sc.get('memoria'):
+ chiavi += ['memory.enableManagedAutoMemory', 'memory.enableManagedAutoDream']
+ if f.get('compatta'):
+ chiavi.append('context.autoCompactThreshold')
+ if any(((x or {}).get('cli') == 'qwen' for x in riga.get('_skill') or [])):
+ chiavi.append('skills')
+ return ','.join(chiavi)
+
+def skill_qwen(scelte):
+ spente, a_scelta = (list(QWEN_SKILL_SPENTE), list(QWEN_SKILL_A_SCELTA))
+ for x in scelte or []:
+ nome = (x or {}).get('nome')
+ if (x or {}).get('cli') != 'qwen' or not nome:
+ continue
+ if x.get('stato') == 'accesa':
+ spente = [n for n in spente if n != nome]
+ a_scelta = [n for n in a_scelta if n != nome]
+ elif x.get('stato') == 'spenta' and nome not in spente and (nome not in a_scelta):
+ a_scelta.append(nome)
+ return {'disabled': spente, 'defaultDisabled': a_scelta}
+QWEN_TOOL_FUORI = ('artifact', 'autofix_pr', 'cron_create', 'cron_delete', 'cron_list', 'display_image', 'enter_worktree', 'exit_worktree', 'get_goal', 'list_agents', 'loop_wakeup', 'monitor', 'propose_goal', 'read_mcp_resource', 'record_artifact', 'report_findings', 'send_message', 'update_goal', 'zoom_image')
+QWEN_TOOL_LARGHI = ('agent', 'enter_plan_mode', 'exit_plan_mode')
+QWEN_SKILL_ACCESE = ('agent-delegation', 'batch', 'dataviz', 'extension-creator', 'new-app', 'review', 'simplify', 'stuck', 'zvec-grep-install')
+QWEN_SKILL_A_SCELTA = ()
+QWEN_SKILL_SPENTE = ('auto-memory', 'autofix-pr', 'batch-api', 'coordinate', 'goal-draft', 'loop', 'qc-helper', 'workflow-authoring', 'workflow-creator')
+QWEN_CHIEDI = ('agent', 'workflow')
+QWEN_REVIEW = {'effort': 'low'}
+QWEN_SOGLIA = 300000
+QWEN_PRIMA_PAROLA_MS = 60000
+QWEN_CLAUDE_1M = re.compile('claude-(opus|sonnet|fable)-(5|4-[6-9])')
+
+def explore_qwen():
+ return '\n'.join(['---', 'name: Explore', 'description: ' + json.dumps(F('explore_descrizione'), ensure_ascii=False), 'tools:', ' - read_file', ' - grep_search', ' - glob', '---', '', F('explore_prompt')])
+
+def _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file):
+ out = []
+ if (scelta := (riga.get('fornitore') or {}).get('chiave')):
+ if dal_repo:
+ leggi = 'python3 -c \'import shlex, sys\nfor l in open(sys.argv[1], encoding="utf-8"):\n k, _, x = l.strip().partition("=")\n if k == sys.argv[2] and x:\n print((shlex.split(x) or [""])[0])\n break\' "$r/.claude/delminio.sh"'
+ out += [f'T=$({leggi} FILE_TOKEN 2>/dev/null)', f'U=$({leggi} URL 2>/dev/null)']
+ dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$T")" | curl -sS -m 30 -K - "${{U%/}}"/api/eseguibili/{_q(urllib.parse.quote(nome))}/chiave"""
+ else:
+ dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -K - {_q(url.rstrip('/') + '/api/eseguibili/' + urllib.parse.quote(nome) + '/chiave')}"""
+ out += [*_commento(F('commento_chiave_dal_motore')), f'''K=$( ({dal_motore.replace('curl -sS', 'curl -sSf', 1)}) 2>/dev/null) || K=""''', 'if [ -z "$K" ]; then', ' echo ' + _sh(F('wrapper_chiave_negata', nome=nome, scelta=scelta)) + ' >&2', f' ({dal_motore}) 2>&1 | head -c 400 >&2; echo >&2', ' exit 1', 'fi', f'export {chiave}="$K"', 'unset K' + (' T U' if dal_repo else '')]
+ elif tipo == 'casa':
+ out.append(f'[ -n "${{{chiave}:-}}" ] || export {chiave}=nessuna')
+ else:
+ leggi = f"""python3 -c 'import json, os, sys\ntry:\n e = json.load(open(os.path.expanduser("~/.qwen/settings.json"), encoding="utf-8")).get("env") or {{}}\n print(e.get(sys.argv[1]) or "")\nexcept (OSError, ValueError, AttributeError):\n pass' {chiave}"""
+ out += [f'if [ -z "${{{chiave}:-}}" ]; then', *_commento(F('commento_chiave_di_qwen')), f' {chiave}=$({leggi} 2>/dev/null) || {chiave}=""', f' [ -n "${chiave}" ] && export {chiave}', 'fi', f'if [ -z "${{{chiave}:-}}" ]; then', ' echo ' + _sh(F('wrapper_senza_chiave', nome=nome, fornitore=riga['_fornitori'][tipo]['nome'], variabile=chiave)) + ' >&2', ' exit 1', 'fi']
+ return out
+
+def wrapper_qwen(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ impostazioni = impostazioni_qwen(riga)
+ canale = canale_del_ruolo(spazio_di(url, _token_di(token_file)), porta) if personaggio(riga) else ''
+ if canale:
+ impostazioni['hooks'] = ganci_della_posta(canale)
+ for g in impostazioni['hooks']['Stop'][0]['hooks']:
+ g.pop('asyncRewake', None)
+ g['timeout'] = 10
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ chiave = chiave_qwen(riga)
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
+ casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
+ node = os.path.join(node_di(os.path.dirname(os.path.dirname(os.path.dirname(cli)))), 'bin')
+ righe = [*_testa_del_wrapper(riga), f'export QWEN_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/qwen/{casa}-{nome}"', 'export DELMINIO_CLI_NOME=qwen', 'export QWEN_CODE_MODELS_DEV=off', 'export QWEN_CODE_DISABLE_ARTIFACT=1', 'export QWEN_CODE_LEGACY_MCP_BLOCKING=1', *([f"export DELMINIO_CONTESTO={int((riga.get('fornitore') or {}).get('contesto') or 0)}"] if int((riga.get('fornitore') or {}).get('contesto') or 0) > 0 else []), f'export PATH={_q(node)}:"$PATH"', f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ dal_repo = modo == 'kit' and bool(porta)
+ if dal_repo:
+ righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
+ righe += _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file)
+ righe += ['mkdir -p "$QWEN_HOME" && chmod 700 "$QWEN_HOME"', *_commento(F('commento_settings_qwen')), 'cat > "$QWEN_HOME/settings.json" <<\'IMPOSTAZIONI\'', json.dumps(impostazioni, indent=2, ensure_ascii=False), 'IMPOSTAZIONI', *_commento(F('commento_mie_qwen')), 'python3 ' + ('"$r/.claude/eseguibili.py"' if dal_repo else _q(os.path.abspath(__file__))) + ' mie-qwen "$QWEN_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := ','.join((x for x in (della_riga_qwen(riga), chiavi_della_riga('qwen', delle_scelte + list(riga.get('argomenti') or []))) if x))) else '') + ' >/dev/null', 'mkdir -p "$QWEN_HOME/agents"', 'cat > "$QWEN_HOME/agents/Explore.md" <<\'EXPLORE\'', explore_qwen(), 'EXPLORE']
+ if canale:
+ righe.append('mkdir -p "$QWEN_HOME/commands"')
+ for gesto, (descrizione, _corpo) in _SKILL_DEL_RITO.items():
+ righe += [f"""cat > "$QWEN_HOME/commands/{gesto}.md" <<'RITO'""", f'---\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\n---\n{gesto}', 'RITO']
+ righe += [f'export DELMINIO_CANALE_RUOLO={_q(canale)}']
+ if dal_repo:
+ righe += [f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}"]
+ if canale:
+ righe += _fuori_dal_suo_spazio(nome, spazio_di(url, _token_di(token_file)))
+ righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" qwen', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+ if porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe += [f'export DELMINIO_PORTA={_q(porta)}', 'export QWEN_SYSTEM_MD="$F"']
+ if canale:
+ righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec(_q(cli), fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+
+def opencode_v2(versione):
+ return str(versione).split('.', 1)[0] == '2'
+OPENCODE_SOGLIA = 300000
+OPENCODE_PRIMA_PAROLA_MS = 60000
+
+def config_opencode(riga, versione):
+ f = riga.get('fornitore') or {}
+ tipo = f.get('tipo')
+ info = (riga.get('_fornitori') or {}).get(tipo) or {}
+ if not info:
+ raise RuntimeError(F('fornitore_ignoto', fornitore=tipo or ''))
+ modello = riga.get('modello') or ''
+ anthropic = info.get('auth') == 'anthropic'
+ contesto = int(f.get('contesto') or 0)
+ finestra = contesto or (1000000 if anthropic and QWEN_CLAUDE_1M.search(modello) else 0)
+ base_spazio = riga.get('_base') or {}
+ voluto = int(f.get('compatta') or 0)
+ if finestra:
+ soglia = min(voluto, finestra) if voluto else min(int(finestra * 0.85), int(base_spazio.get('opencode.compatta') or OPENCODE_SOGLIA))
+ riserva = finestra - soglia
+ else:
+ riserva = '15%'
+ base = {'update': 'disable', 'share': 'disabled', 'compaction': {'background': False, 'buffer': riserva}}
+ if tipo == 'zen':
+ return {**base, 'model': f'opencode/{modello}'} if modello else base
+ chiave = chiave_qwen(riga)
+ indirizzo = '' if anthropic else f.get('indirizzo') or info.get('indirizzo') or ''
+ attesa = int(base_spazio.get('opencode.prima_parola_ms') or OPENCODE_PRIMA_PAROLA_MS)
+ impostazioni = {**({'baseURL': indirizzo} if indirizzo else {}), 'headerTimeout': attesa, 'chunkTimeout': attesa}
+ fornitore = {'name': info.get('nome') or tipo, 'env': [chiave], 'package': '@opencode/ai/providers/' + ('anthropic' if anthropic else 'openai-compatible'), 'settings': impostazioni, 'models': {modello: {'name': modello, **({'limit': {'context': finestra, 'output': min(32000, finestra // 4)}} if finestra else {})}}}
+ return {**base, 'providers': {'delminio': fornitore}, 'model': f'delminio/{modello}'}
+
+def wrapper_opencode(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ if modo != 'kit':
+ return '\n'.join([*_testa_del_wrapper(riga), 'echo ' + _sh(F('wrapper_opencode_solo_kit', nome=nome)) + ' >&2', 'exit 1']) + '\n'
+ versione = os.path.basename(os.path.dirname(os.path.dirname(cli)))
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
+ righe = [*_testa_del_wrapper(riga), 'export DELMINIO_CLI_NOME=opencode', 'export OPENCODE_DISABLE_AUTOUPDATE=1 # ' + F('commento_autoupdater'), *_commento(F('commento_config_opencode')), f'export DELMINIO_OPENCODE_CONFIG={_q(json.dumps(config_opencode(riga, versione), ensure_ascii=False, sort_keys=True))}', *([f'export DELMINIO_OPENCODE_GRATUITO={_q(nome)}'] if tipo == 'zen' and (not riga.get('modello')) else []), f'export DELMINIO_SQUADRA={hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]}', f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
+ if tipo != 'zen':
+ righe.append('export OPENCODE_DISABLE_MODELS_FETCH=1 # ' + F('commento_catalogo_opencode'))
+ righe += _righe_della_chiave(riga, chiave_qwen(riga), tipo, nome, True, url, token_file)
+ if porta:
+ righe.append(f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}")
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ elif riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" opencode', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+
+def _fuori_dal_suo_spazio(nome, spazio):
+ return ['qui=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null)', f'if [ -n "$qui" ] && [ "$qui" != {_q(spazio)} ]; then', ' echo ' + _sh(F('wrapper_altro_spazio', nome=nome, spazio=nome_spazio(spazio))) + ' >&2', ' exit 1', 'fi']
+
+def righe_della_casa(riga, nome, spazio):
+ if (riga.get('scelte') or {}).get('casa') != 'separata':
+ return [f"cd {_q(riga['cartella'])} || exit 1"] if riga.get('cartella') else []
+ dove = _q(riga['cartella']) if riga.get('cartella') else ''
+ return [*_commento(F('commento_casa')), f"""casa=$(python3 "$r/.claude/eseguibili.py" casa "$r/.claude/delminio.sh" {_q(riga['porta'])} {_q(nome)} {dove}) || exit 1""".rstrip(), 'cd "$casa" || exit 1']
+
+def wrapper(riga, cli, modo, url, token_file):
+ if riga.get('cli') == 'codex':
+ return wrapper_codex(riga, cli, modo, url, token_file)
+ if riga.get('cli') == 'qwen':
+ return wrapper_qwen(riga, cli, modo, url, token_file)
+ if riga.get('cli') == 'opencode':
+ return wrapper_opencode(riga, cli, modo, url, token_file)
+ nome = riga['nome']
+ args = []
+ if riga.get('modello'):
+ args += ['--model', riga['modello']]
+ if riga.get('effort'):
+ args += ['--effort', riga['effort']]
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ env_scelte = {**(riga.get('_promemoria') or {}), **env_scelte}
+ args += delle_scelte + list(riga.get('argomenti') or [])
+ if personaggio(riga):
+ spazio = spazio_di(url, _token_di(token_file))
+ canale = canale_del_ruolo(spazio, riga['porta'])
+ args = con_i_ganci(args, ganci_della_posta(canale))
+ args += ['--mcp-config', canale, '--allowedTools', f'mcp__{SERVER_RUOLO}__delminio,mcp__{SERVER_RUOLO}__delminio_write']
+ args += ['--plugin-dir', _rito_del_ruolo()]
+ fissi = ' '.join((_q(a) for a in args))
+ righe = [*_testa_del_wrapper(riga), 'export DISABLE_AUTOUPDATER=1 # ' + F('commento_autoupdater')]
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ porta = riga.get('porta')
+ if modo == 'kit':
+ if porta:
+ righe += [*_commento(F('commento_token_progetto')), *_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo_claude', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
+ if personaggio(riga):
+ righe += _fuori_dal_suo_spazio(nome, spazio)
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ if personaggio(riga):
+ righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" claude', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+ elif porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe.append(f'export DELMINIO_PORTA={_q(porta)}')
+ if personaggio(riga):
+ righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ prompt = ' --system-prompt-file "$F"' if porta and modo != 'kit' else ''
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec(_q(cli), fissi, prompt.strip(), '"$@"'))
+ return '\n'.join(righe) + '\n'
+PROMEMORIA_AMMESSI = frozenset({'CLAUDE_CODE_SILENT_TURN_REMINDER_TEXT', 'CLAUDE_CODE_SILENT_TURN_REMINDER'})
+
+def parte_libera(riga):
+ return {'cli': str(riga.get('cli') or 'claude'), 'argomenti': [str(x) for x in riga.get('argomenti') or []], 'ambiente': {str(k): str(v) for k, v in (riga.get('ambiente') or {}).items()}}
+
+def impronta_libera(riga):
+ return hashlib.sha256(json.dumps([str(riga.get('nome') or ''), parte_libera(riga)], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
+
+def da_accettare(riga, accettati):
+ p = parte_libera(riga)
+ return bool(p['argomenti'] or p['ambiente']) and impronta_libera(riga) not in accettati
+
+def _visibile_riga(v):
+ return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
+
+def accetta(registro):
+ mio = _leggi(registro)
+ fermi = [(url, x) for url, sp in (mio.get('spazi') or {}).items() for x in sp.get('fermi') or [] if isinstance(x, dict)]
+ if not fermi:
+ return 0
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ print(F('accetta_senza_terminale'), file=sys.stderr)
+ return 1
+ accettati, presi, restano = (set(mio.get('accettati') or []), set(), 0)
+ for url, x in fermi:
+ p = parte_libera(x)
+ tty.write(F('accetta_riga_domanda', nome=_visibile_riga(x.get('nome')), cli=_visibile_riga(p['cli']), spazio=_visibile_riga(come_si_chiama(url)), argomenti=_visibile_riga(shlex.join(p['argomenti']) or '—'), ambiente=_visibile_riga(' '.join((f'{k}={shlex.quote(v)}' for k, v in sorted(p['ambiente'].items()))) or '—')))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('accetta_si').split():
+ accettati.add(impronta_libera(x))
+ presi.add(url)
+ else:
+ restano += 1
+ mio = _leggi(registro)
+ mio['accettati'] = sorted(set(mio.get('accettati') or []) | accettati)
+ for url in presi:
+ (mio.get('spazi') or {}).get(url, {})['registro'] = ''
+ _scrivi(registro, mio)
+ print(F('accetta_righe_esito', nuovi=len(fermi) - restano, restano=restano))
+ return 0
+
+def _impronta(testo):
+ return hashlib.sha256(testo.encode('utf-8')).hexdigest()[:16]
+
+def _del_file(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return _impronta(f.read())
+ except (OSError, UnicodeDecodeError):
+ return None
+_DIARIO_MAX = 1000000
+
+def _nel_diario(registro, percorso, prima, dopo, vecchio, nuovo):
+ diario = os.path.join(os.path.dirname(registro) or '.', 'eseguibili-diario.log')
+ righe = [r for r in difflib.unified_diff((vecchio or '').splitlines(), nuovo.splitlines(), lineterm='', n=0) if not r.startswith(('---', '+++'))]
+ testa = f"── {time.strftime('%Y-%m-%d %H:%M:%S')} {percorso} · CLI {prima or '—'} → {dopo}"
+ try:
+ if os.path.exists(diario) and os.path.getsize(diario) > _DIARIO_MAX:
+ with open(diario, encoding='utf-8', errors='replace') as f:
+ resto = f.read()[-_DIARIO_MAX // 2:]
+ with open(diario, 'w', encoding='utf-8') as f:
+ f.write(resto[resto.find('\n── ') + 1:] if '\n── ' in resto else resto)
+ with open(os.open(diario, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384), 'a', encoding='utf-8') as f:
+ f.write('\n'.join([testa, *righe]) + '\n')
+ except OSError:
+ pass
+ return sum((1 for r in righe if r.startswith(('+', '-'))))
+_SEGNO_CASA = 'export DELMINIO_SISTEMA="$F"'
+
+def _di_casa(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return _SEGNO_CASA in f.read()
+ except (OSError, UnicodeDecodeError):
+ return False
+
+def _leggi(path):
+ try:
+ with open(path, encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return {}
+_CHIAVE_PER_SPAZIO = 1792090627
+
+def _spazio(mio, url):
+ spazi = mio.setdefault('spazi', {})
+ base = url.split('#', 1)[0]
+ if url not in spazi and url != base and (base in spazi) and ((spazi[base].get('quando') or 0) < _CHIAVE_PER_SPAZIO) and (not any((k.startswith(base + '#') for k in spazi))):
+ spazi[url] = spazi.pop(base)
+ for chi in mio.get('padroni', {}).values():
+ chi[:] = [url if u == base else u for u in chi]
+ if url not in spazi:
+ s = spazi[url] = {}
+ if len(spazi) == 1:
+ for k in ('registro', 'quando', 'rifiutato', 'cli'):
+ if k in mio:
+ s[k] = mio.pop(k)
+ for p in mio.get('eseguibili', {}):
+ mio.setdefault('padroni', {}).setdefault(p, [url])
+ return spazi[url]
+
+def _scrivi(path, dati):
+ os.makedirs(os.path.dirname(path), mode=448, exist_ok=True)
+ with open(path + '.nuovo', 'w', encoding='utf-8') as f:
+ json.dump(dati, f, ensure_ascii=False, indent=1)
+ os.replace(path + '.nuovo', path)
+
+def _cli_del_wrapper(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ testo = f.read()
+ except OSError:
+ return ''
+ m = re.search('/versions(?:-pinned)?/(\\d+\\.\\d+\\.\\d+)', testo)
+ return m.group(1) if m else '?'
+
+def sul_disco(versioni):
+ try:
+ return sorted((f for f in os.listdir(versioni) if _VERSIONE.match(f)), key=_v, reverse=True)
+ except OSError:
+ return []
+
+def nudo(bin_dir, versioni):
+ p = os.path.join(bin_dir, 'claude')
+ if not os.path.lexists(p):
+ return ''
+ vero = os.path.realpath(p)
+ if os.path.dirname(vero) == os.path.realpath(versioni) and _VERSIONE.match(os.path.basename(vero)):
+ return os.path.basename(vero)
+ return 'altro'
+
+def pulisci(bin_dir, versioni, scelte=None):
+ usate = set()
+ cartelle = {os.path.realpath(versioni), os.path.abspath(os.path.expanduser(versioni))}
+ voce = re.compile('(?:%s|/versions(?:-pinned)?)/(\\d+\\.\\d+\\.\\d+)' % '|'.join((re.escape(c) for c in cartelle)))
+ try:
+ nomi = [os.path.join(bin_dir, n) for n in os.listdir(bin_dir)]
+ except OSError:
+ nomi = []
+ for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
+ nomi += [os.path.join(radice, n) for n in file]
+ for p in nomi:
+ if os.path.islink(p):
+ vero = os.path.realpath(p)
+ if os.path.dirname(vero) == os.path.realpath(versioni):
+ usate.add(os.path.basename(vero))
+ continue
+ try:
+ if os.path.isfile(p) and os.path.getsize(p) < 200000:
+ with open(p, encoding='utf-8', errors='ignore') as f:
+ usate.update(voce.findall(f.read()))
+ except OSError:
+ pass
+ if (n := nudo(bin_dir, versioni)) and n != 'altro':
+ usate.add(n)
+ libere = [v for v in sul_disco(versioni) if v not in usate]
+ alta = max((v for v in usate if _VERSIONE.match(v)), key=_v, default=None)
+ prima = [v for v in libere if alta and _v(v) < _v(alta)]
+ riparo = (prima or libere)[:1]
+ if scelte is not None:
+ riparo = [v for v in libere if v not in scelte]
+ tolte, errori = ([], [])
+ for v in [x for x in libere if x not in riparo]:
+ try:
+ os.remove(os.path.join(versioni, v))
+ tolte.append(v)
+ except OSError as e:
+ errori.append(f'{v}: {e.strerror}')
+ esito = {'tolte': tolte, 'tenute': sorted(usate | set(riparo), key=_v, reverse=True)}
+ if scelte is not None:
+ riparo = []
+ if errori:
+ esito['errore'] = '; '.join(errori)[:300]
+ print(F('pulizia', n=len(tolte), tolte=', '.join(tolte) or F('nessuna'), tenute=', '.join(esito['tenute']) or F('nessuna'), riparo=F('al_riparo', versione=riparo[0]) if riparo else ''))
+ return esito
+
+def _cosa_lancia(bin_dir):
+ nomi = [os.path.join(bin_dir, n) for n in (os.listdir(bin_dir) if os.path.isdir(bin_dir) else ())]
+ for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
+ nomi += [os.path.join(radice, n) for n in file]
+ testi = []
+ for p in nomi:
+ try:
+ if os.path.islink(p):
+ testi.append(os.path.realpath(p))
+ elif os.path.isfile(p) and os.path.getsize(p) < 200000:
+ with open(p, encoding='utf-8', errors='ignore') as f:
+ testi.append(f.read())
+ except OSError:
+ pass
+ if os.path.isdir('/proc'):
+ for pid in os.listdir('/proc'):
+ if pid.isdigit():
+ try:
+ with open(f'/proc/{pid}/cmdline', 'rb') as f:
+ testi.append(f.read().replace(b'\x00', b' ').decode(errors='ignore'))
+ testi.append(os.readlink(f'/proc/{pid}/exe'))
+ except OSError:
+ pass
+ else:
+ try:
+ testi.append(subprocess.run(['ps', '-axww', '-o', 'comm=', '-o', 'command='], capture_output=True, text=True, errors='ignore', timeout=20, check=True).stdout)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return '\n'.join(testi)
+
+def pota(bin_dir, cartelle, nudo_claude=''):
+ testo, tolte = (_cosa_lancia(bin_dir), [])
+ if testo is None:
+ return tolte
+
+ def via(dove, nome):
+ try:
+ shutil.rmtree(dove) if os.path.isdir(dove) and (not os.path.islink(dove)) else os.remove(dove)
+ tolte.append(nome)
+ except OSError:
+ pass
+ for cartella in [c for c in cartelle if c and os.path.isdir(c)]:
+ radici = '|'.join((re.escape(c) for c in {os.path.realpath(cartella), os.path.abspath(cartella)}))
+ usate = set(re.findall('(?:%s)/(\\d+\\.\\d+\\.\\d+)' % radici, testo)) | {nudo_claude}
+ for v in sul_disco(cartella):
+ if v not in usate:
+ via(os.path.join(cartella, v), v)
+ sopra = os.path.realpath(os.path.dirname(os.path.normpath(cartella)))
+ nodi = set(re.findall('%s/(node-\\d[\\w.]*)' % re.escape(sopra), testo))
+ for n in os.listdir(sopra) if nodi else ():
+ if n.startswith('node-') and n not in nodi and os.path.isdir(os.path.join(sopra, n)):
+ via(os.path.join(sopra, n), n)
+ if tolte:
+ print(F('potate', tolte=', '.join(tolte)), flush=True)
+ return tolte
+
+def riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte=None, esito=None, senza_cli=()):
+ stato = []
+ for r in righe:
+ p = os.path.join(bin_dir, r['nome'])
+ ora = _del_file(p)
+ intatto = ora is not None and impronte.get(p) == ora
+ cli = (scritte or {}).get(p, '') if intatto else _cli_del_wrapper(p) if ora else ''
+ stato.append({'nome': r['nome'], 'cli': cli, 'stato': 'senza_cli' if ora is None and r['nome'] in senza_cli else 'manca' if ora is None else 'intatto' if intatto else 'toccato'})
+ corpo = {'host': socket.gethostname(), 'righe': stato, 'registro': registro, 'disco': sul_disco(versioni), 'nudo': nudo(bin_dir, versioni)}
+ if esito:
+ corpo['esito'] = esito
+ try:
+ return json.loads(_get(f'{base}/macchina', token, metodo='POST', corpo=corpo, timeout=10) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError):
+ return {}
+INSTALLABILI = tuple(CLI_NOMI)
+
+def richiesta(base, token, risposta, righe, impronte, bin_dir, versioni, registro, scritte, mio=None, file_mio=''):
+ r = (risposta or {}).get('richiesta') or {}
+ if r.get('pulizia'):
+ scelte = r.get('versioni')
+ esito = pulisci(bin_dir, versioni, scelte if isinstance(scelte, list) else None)
+ riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito=esito)
+ nuove = {c for c in r.get('installa') or [] if c in INSTALLABILI}
+ if nuove and mio is not None and file_mio:
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | nuove)
+ _scrivi(file_mio, mio)
+ print(F('installo_chiesta', cli=', '.join(sorted(nuove))), flush=True)
+ riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito={'installate': sorted(nuove)})
+ return True
+ return False
+SEGNO_SMISTA = '# delminio-più-spazi'
+_DIR_COMANDI = ['']
+
+def cartella_dei_comandi(registro):
+ return os.path.join(os.path.dirname(registro) or '.', 'comandi')
+
+def comando_dello_spazio(spazio, nome):
+ return os.path.join(_DIR_COMANDI[0], cartella_dello_spazio(spazio), nome)
+
+def cartella_dello_spazio(spazio):
+ return re.sub('[^A-Za-z0-9._-]', '_', spazio)
+
+def come_si_chiama(spazio):
+ if '#' in spazio:
+ return spazio.rsplit('#', 1)[1]
+ return urllib.parse.urlsplit(spazio).netloc or spazio
+
+def e_smistatore(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return SEGNO_SMISTA in f.read()
+ except (OSError, UnicodeDecodeError):
+ return False
+
+def smistatore(nome, spazi):
+ elenco = ', '.join((come_si_chiama(s) for s in spazi))
+ dove = _q(_DIR_COMANDI[0])
+ return '\n'.join(['#!/bin/sh', f'# {nome} — ' + F('smista_testa'), SEGNO_SMISTA, *_commento(F('wrapper_commento')), 'r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ] || [ ! -f "$r/.claude/eseguibili.py" ]; then', ' echo ' + _sh(F('smista_fuori', nome=nome, spazi=elenco)) + ' >&2', ' exit 1', 'fi', 's=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null) || s=""', 'd=$(printf %s "$s" | tr -c \'A-Za-z0-9._-\' \'_\')', f'f={dove}/"$d"/{_q(nome)}', 'if [ -n "$s" ] && [ -x "$f" ]; then', ' exec "$f" "$@"', 'fi', 'echo ' + _sh(F('smista_non_qui', nome=nome, spazi=elenco)) + ' >&2', 'exit 1']) + '\n'
+
+def _scrivi_eseguibile(p, testo):
+ os.makedirs(os.path.dirname(p), mode=448, exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+
+def dividi(p, url, testo, padroni, impronte):
+ chi = padroni.get(p) or []
+ nuovo = not e_smistatore(p)
+ if nuovo:
+ with open(p, encoding='utf-8') as f:
+ di_prima = f.read()
+ for u in chi:
+ if u != url:
+ q = comando_dello_spazio(u, os.path.basename(p))
+ _scrivi_eseguibile(q, di_prima)
+ impronte[q] = _impronta(di_prima)
+ q = comando_dello_spazio(url, os.path.basename(p))
+ _scrivi_eseguibile(q, testo)
+ impronte[q] = _impronta(testo)
+ if url not in chi:
+ chi.append(url)
+ padroni[p] = chi
+ rifai_smistatore(p, chi, impronte)
+ return nuovo
+
+def rifai_smistatore(p, chi, impronte):
+ t = smistatore(os.path.basename(p), chi)
+ if _del_file(p) != _impronta(t):
+ _scrivi_eseguibile(p, t)
+ impronte[p] = _impronta(t)
+
+def lascia_il_nome(p, url, padroni, impronte):
+ chi = padroni.get(p) or []
+ if url in chi:
+ chi.remove(url)
+ smista = e_smistatore(p) and impronte.get(p) == _del_file(p)
+ if smista:
+ q = comando_dello_spazio(url, os.path.basename(p))
+ if impronte.get(q) and _del_file(q) == impronte[q]:
+ os.remove(q)
+ impronte.pop(q, None)
+ if not chi:
+ tolto = os.path.exists(p) and _del_file(p) == impronte.get(p)
+ if tolto:
+ os.remove(p)
+ impronte.pop(p, None)
+ padroni.pop(p, None)
+ return 'tolto' if tolto else 'resta'
+ if not smista:
+ return 'altri'
+ if len(chi) > 1:
+ rifai_smistatore(p, chi, impronte)
+ return 'altri'
+ q = comando_dello_spazio(chi[0], os.path.basename(p))
+ if impronte.get(q) and _del_file(q) == impronte[q]:
+ with open(q, encoding='utf-8') as f:
+ suo = f.read()
+ _scrivi_eseguibile(p, suo)
+ impronte[p] = _impronta(suo)
+ os.remove(q)
+ impronte.pop(q, None)
+ return 'tornato'
+ rifai_smistatore(p, chi, impronte)
+ return 'altri'
+_SKILL_PROGETTO = (('.claude/skills', ('claude',)), ('.agents/skills', ('codex', 'qwen')), ('.qwen/skills', ('qwen',)))
+_SKILL_TETTO = 300
+
+def _skill_testa(percorso):
+ try:
+ with open(percorso, 'rb') as h:
+ crudo = h.read(200000)
+ except OSError:
+ return None
+ testo = crudo.decode('utf-8', errors='replace')
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(\\n|$)', testo, re.S)
+ testa = m.group(1) if m else ''
+
+ def campo(nome):
+ c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
+ if not c:
+ return ''
+ v = ' '.join(c.group(1).split())
+ if v[:1] in '"\'' and v[-1:] == v[:1]:
+ v = v[1:-1]
+ return '' if v in ('>', '|', '>-', '|-') else v
+ nome = campo('name') or os.path.basename(os.path.dirname(percorso))
+ return {'nome': nome, 'descrizione': campo('description')[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16]}
+
+def _skill_in(cartella):
+ if not os.path.isdir(cartella):
+ return []
+ out = []
+ for n in sorted(os.listdir(cartella)):
+ p = os.path.join(cartella, n, 'SKILL.md')
+ if not n.startswith('.') and os.path.isfile(p):
+ t = _skill_testa(p)
+ if t:
+ out.append((t, p))
+ return out
+
+def _da_leggere(p, radice):
+ casa = os.path.expanduser('~')
+ if radice and p.startswith(radice + os.sep):
+ return os.path.relpath(os.path.dirname(p), radice)
+ if p.startswith(casa + os.sep):
+ return '~/' + os.path.relpath(os.path.dirname(p), casa)
+ return os.path.dirname(p)
+
+def _case_codex():
+ base = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'codex')
+ return sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else []) if os.path.isfile(os.path.join(base, n, 'config.toml'))))
+
+def _blocchi_codex(testo):
+ out = {}
+ for b in re.split('(?m)^\\[\\[skills\\.config\\]\\]\\s*$', testo)[1:]:
+ corpo = re.split('(?m)^\\[', b, maxsplit=1)[0]
+ p = re.search('(?m)^path\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"', corpo)
+ e = re.search('(?m)^enabled\\s*=\\s*(true|false)', corpo)
+ if p:
+ out[json.loads('"' + p.group(1) + '"')] = not (e and e.group(1) == 'false')
+ return out
+
+def _claude_scelte(radice):
+ out = {}
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ for f in (os.path.join(cfg, 'settings.json'), os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')):
+ s = _leggi(f)
+ if isinstance(s.get('skillOverrides'), dict):
+ out.update(s['skillOverrides'])
+ return out
+_STATO_CLAUDE = {'on': 'accesa', 'name-only': 'accesa', 'user-invocable-only': 'a_mano', 'off': 'spenta'}
+
+def _qwen_stato(nome, livello, scelte):
+ voluta = scelte.get(('qwen', nome))
+ if voluta:
+ return 'accesa' if voluta == 'accesa' else 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano'
+ if livello != 'di_serie':
+ return 'accesa'
+ return 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano' if nome in QWEN_SKILL_A_SCELTA else 'accesa'
+
+def _progetto(radice):
+ remoto = ''
+ if radice:
+ try:
+ remoto = subprocess.run(['git', '-C', radice, 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ remoto = ''
+ return 'progetto:' + (re.sub('//[^/@]*@', '//', remoto) or os.path.basename(radice or ''))
+
+def raccogli_skill(radice, versioni_qwen, scelte=None):
+ scelte = scelte or {}
+ carte = []
+ progetto = _progetto(radice)
+ claude = _claude_scelte(radice) if radice else {}
+ case = _case_codex()
+ codex_blocchi = {}
+ for casa in case:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
+ codex_blocchi.update(_blocchi_codex(h.read()))
+
+ def stato(cli, nome, livello, percorsi):
+ out = {}
+ for c in cli:
+ if c == 'claude':
+ out[c] = _STATO_CLAUDE.get(claude.get(nome, 'on'), 'accesa')
+ elif c == 'codex':
+ out[c] = 'spenta' if any((codex_blocchi.get(p) is False for p in percorsi)) else 'accesa'
+ elif c == 'qwen':
+ out[c] = _qwen_stato(nome, livello, scelte)
+ return out
+
+ def metti(livello, dove, cartella, cli):
+ for t, p in _skill_in(cartella):
+ carte.append({**t, 'livello': livello, 'dove': dove, 'cartella': _da_leggere(p, radice), 'cli': list(cli), 'stato': stato(cli, t['nome'], livello, [p])})
+ if radice:
+ for rel, cli in _SKILL_PROGETTO:
+ metti('progetto', progetto, os.path.join(radice, rel), cli)
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ metti('personale', 'personale', os.path.join(cfg, 'skills'), ('claude',))
+ metti('personale', 'personale', os.path.expanduser('~/.agents/skills'), ('codex', 'qwen'))
+ metti('personale', 'personale', os.path.expanduser('~/.qwen/skills'), ('qwen',))
+ viste = set()
+ for casa in case:
+ for t, p in _skill_in(os.path.join(casa, 'skills', '.system')):
+ if t['nome'] not in viste:
+ viste.add(t['nome'])
+ carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'codex', 'cli': ['codex'], 'stato': stato(('codex',), t['nome'], 'di_serie', [os.path.join(c, 'skills', '.system', t['nome'], 'SKILL.md') for c in case])})
+ metti('personale', 'personale', os.path.join(casa, 'skills'), ('codex',))
+ qv = sorted((v for v in (os.listdir(versioni_qwen) if os.path.isdir(versioni_qwen) else []) if _VERSIONE.match(v)), key=lambda v: tuple((int(x) for x in v.split('.'))))
+ if qv:
+ for t, _p in _skill_in(os.path.join(versioni_qwen, qv[-1], 'lib', 'node_modules', '@qwen-code', 'qwen-code', 'bundled')):
+ carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'qwen ' + qv[-1], 'cli': ['qwen'], 'stato': stato(('qwen',), t['nome'], 'di_serie', [])})
+ pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
+ if radice and os.path.isfile(pacchetto) and shutil.which(os.environ.get('DELMINIO_CLI') or 'claude'):
+ try:
+ di_claude = runpy.run_path(pacchetto).get('SKILL_CLAUDE') or {}
+ except Exception:
+ di_claude = {}
+ for nome in sorted(di_claude):
+ carte.append({'nome': nome, 'descrizione': '', 'impronta': '', 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'claude', 'cli': ['claude'], 'stato': stato(('claude',), nome, 'di_serie', [])})
+ carte += raccogli_pezzi(radice, progetto)
+ return carte[:_SKILL_TETTO]
+_COMANDI = (('.claude/commands', 'claude'), ('.qwen/commands', 'qwen'))
+_AGENTI = (('.claude/agents', 'claude'), ('.qwen/agents', 'qwen'))
+_PEZZO_PESO = 100000
+_CHIAVE_FLAG = re.compile('^--?(?:[\\w-]*(?:token|key|secret|password|passwd|pass|auth|credential)[\\w-]*)$', re.I)
+_CHIAVE_VALORE = re.compile('(?:^(?:sk-|ghp_|gho_|ghs_|github_pat_|xox[abpr]-|glpat-|AKIA|AIza)\\S+)|(?:^(?=[^/.]*\\d)(?=[^/.]*[A-Za-z])[A-Za-z0-9_+=-]{24,}$)')
+NASCOSTO = '•••'
+
+def _testa_md(testo):
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
+ testa, corpo = (m.group(1), testo[m.end():]) if m else ('', testo)
+
+ def campo(nome):
+ c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
+ if not c:
+ return ''
+ v = ' '.join(c.group(1).split())
+ if v[:1] in '"\'' and v[-1:] == v[:1]:
+ v = v[1:-1]
+ return '' if v in ('>', '|', '>-', '|-') else v
+ return (campo, corpo)
+
+def _prima_riga(corpo):
+ for r in corpo.splitlines():
+ r = r.strip().lstrip('#').strip()
+ if r:
+ return r[:200]
+ return ''
+
+def _toml_stringa(testo, chiave):
+ m = re.search('(?m)^' + re.escape(chiave) + '\\s*=\\s*("""(.*?)"""|\\\'\\\'\\\'(.*?)\\\'\\\'\\\'|"((?:[^"\\\\\\n]|\\\\.)*)"|\\\'([^\\\'\\n]*)\\\')', testo, re.S)
+ if not m:
+ return ''
+ if m.group(4) is not None:
+ try:
+ return json.loads('"' + m.group(4) + '"')
+ except ValueError:
+ return m.group(4)
+ return next((g for g in (m.group(2), m.group(3), m.group(5)) if g is not None))
+
+def _scheda_file(p, rel_nome, cli, tipo):
+ try:
+ with open(p, 'rb') as h:
+ crudo = h.read(_PEZZO_PESO + 1)
+ except OSError:
+ return None
+ testo = crudo.decode('utf-8', errors='replace')
+ if p.endswith('.toml'):
+ descrizione, nome = (_toml_stringa(testo, 'description'), rel_nome)
+ else:
+ campo, corpo = _testa_md(testo)
+ nome = (campo('name') if tipo == 'agente' else '') or rel_nome
+ descrizione = campo('description') or (_prima_riga(corpo) if tipo == 'comando' else '')
+ return {'nome': nome, 'descrizione': descrizione[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16], 'tipo': tipo, 'cli': [cli], 'stato': {}}
+
+def _file_in(cartella, estensioni, ricorsivo):
+ if not os.path.isdir(cartella):
+ return []
+ out = []
+ for base, cartelle, nomi in os.walk(cartella):
+ cartelle[:] = sorted((c for c in cartelle if not c.startswith('.'))) if ricorsivo else []
+ for n in sorted(nomi):
+ p = os.path.join(base, n)
+ if n.startswith('.') or not n.endswith(estensioni) or (not os.path.isfile(p)):
+ continue
+ rel = os.path.relpath(p, cartella)
+ out.append((p, os.path.splitext(rel)[0].replace(os.sep, ':')))
+ return out
+
+def _cartella_da_leggere(p, radice):
+ casa = os.path.expanduser('~')
+ if radice and p.startswith(radice + os.sep):
+ return os.path.relpath(p, radice)
+ if p.startswith(casa + os.sep):
+ return '~/' + os.path.relpath(p, casa)
+ return p
+
+def _argomenti_puliti(argomenti):
+ out, dopo_flag = ([], False)
+ for a in argomenti or []:
+ a = str(a)
+ if '=' in a and _CHIAVE_FLAG.match(a.split('=', 1)[0]):
+ out.append(a.split('=', 1)[0] + '=' + NASCOSTO)
+ elif dopo_flag or _CHIAVE_VALORE.search(a) or '${' in a:
+ out.append(NASCOSTO)
+ else:
+ out.append(a[:500])
+ dopo_flag = bool(_CHIAVE_FLAG.match(a)) and '=' not in a
+ return out[:40]
+
+def _url_pulito(url):
+ try:
+ u = urllib.parse.urlsplit(str(url or ''))
+ except ValueError:
+ return ''
+ if u.scheme not in ('http', 'https') or not u.hostname:
+ return ''
+ host = u.netloc.rpartition('@')[2]
+ return urllib.parse.urlunsplit((u.scheme, host, u.path, '', ''))[:500]
+
+def _variabile_del_token(intestazioni):
+ for k, v in (intestazioni or {}).items():
+ m = re.fullmatch('(?:Bearer\\s+)?\\$\\{?([A-Za-z_][A-Za-z0-9_]{0,63})\\}?', str(v or '').strip())
+ if str(k).lower() == 'authorization' and m:
+ return m.group(1)
+ return ''
+
+def _server(nome, d, cli, livello, dove, cartella):
+ if not isinstance(d, dict):
+ return None
+ url = d.get('url') or d.get('httpUrl') or ''
+ intest = {}
+ for k in ('headers', 'http_headers', 'env_http_headers'):
+ if isinstance(d.get(k), dict):
+ intest.update(d[k])
+ if url:
+ token = str(d.get('bearer_token_env_var') or '') or _variabile_del_token(intest)
+ mcp = {'tipo': 'remoto', 'url': _url_pulito(url), 'intestazioni': sorted((str(k) for k in intest))[:20]}
+ if token:
+ mcp['token_variabile'] = token
+ elif d.get('command'):
+ variabili = set(d['env']) if isinstance(d.get('env'), dict) else set()
+ variabili |= {str(v) for v in d.get('env_vars') or [] if isinstance(v, str)}
+ mcp = {'tipo': 'locale', 'comando': str(d['command'])[:300], 'argomenti': _argomenti_puliti(d.get('args') if isinstance(d.get('args'), list) else []), 'variabili': sorted(variabili)[:20]}
+ else:
+ return None
+ return {'nome': str(nome), 'descrizione': str(d.get('description') or '')[:600], 'impronta': '', 'tipo': 'mcp', 'cli': [cli], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': cartella, 'mcp': mcp}
+
+def _toml_tabelle(testo, radice_tabella):
+ try:
+ import tomllib
+ d = tomllib.loads(testo).get(radice_tabella)
+ return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}
+ except ImportError:
+ pass
+ except ValueError:
+ return {}
+ out = {}
+ for m in re.finditer('(?m)^\\[' + re.escape(radice_tabella) + '\\.("[^"\\n]+"|[A-Za-z0-9_-]+)(\\.[A-Za-z_]+)?\\]\\s*$', testo):
+ nome = m.group(1).strip('"')
+ corpo = re.split('(?m)^\\[', testo[m.end():], maxsplit=1)[0]
+ campi = out.setdefault(nome, {})
+ if m.group(2):
+ campi[m.group(2)[1:]] = {k.strip('"'): '' for k in re.findall('(?m)^("[^"\\n]+"|[A-Za-z0-9_-]+)\\s*=', corpo)}
+ continue
+ for chiave, valore in re.findall('(?m)^([A-Za-z_]+)\\s*=\\s*(.+?)\\s*$', corpo):
+ if valore.startswith('{'):
+ campi[chiave] = {k.strip('"'): '' for k in re.findall('("[^"]+"|[A-Za-z0-9_-]+)\\s*=', valore)}
+ else:
+ try:
+ campi[chiave] = json.loads(valore)
+ except ValueError:
+ campi[chiave] = valore.strip("'")
+ return out
+
+def _codex_config(radice):
+ out = []
+ if radice:
+ out.append((os.path.join(radice, '.codex', 'config.toml'), 'progetto'))
+ casa = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
+ out.append((os.path.join(casa, 'config.toml'), 'personale'))
+ out += [(os.path.join(c, 'config.toml'), 'personale') for c in _case_codex()]
+ return [(p, l) for p, l in out if os.path.isfile(p)]
+
+def raccogli_pezzi(radice, progetto):
+ carte = []
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ casa_qwen = os.path.expanduser('~/.qwen')
+
+ def file_di(tipo, coppie_progetto, personali, estensioni, ricorsivo):
+ dove_cli = [(os.path.join(radice, rel), cli, 'progetto', progetto) for rel, cli in coppie_progetto] if radice else []
+ dove_cli += [(c, cli, 'personale', 'personale') for c, cli in personali]
+ for cartella, cli, livello, dove in dove_cli:
+ for p, rel_nome in _file_in(cartella, estensioni(cli), ricorsivo):
+ if (s := _scheda_file(p, rel_nome, cli, tipo)):
+ carte.append({**s, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(p, radice)})
+ file_di('comando', _COMANDI, [(os.path.join(cfg, 'commands'), 'claude'), (os.path.join(casa_qwen, 'commands'), 'qwen')], lambda cli: ('.md', '.toml') if cli == 'qwen' else ('.md',), True)
+ file_di('agente', _AGENTI, [(os.path.join(cfg, 'agents'), 'claude'), (os.path.join(casa_qwen, 'agents'), 'qwen')], lambda cli: ('.md',), False)
+
+ def server_json(percorso, chiavi, cli, livello, dove):
+ d = _leggi(percorso)
+ for k in chiavi:
+ d = d.get(k) if isinstance(d, dict) else None
+ for nome, s in (d or {}).items() if isinstance(d, dict) else []:
+ if (x := _server(nome, s, cli, livello, dove, _cartella_da_leggere(percorso, radice))):
+ carte.append(x)
+ stato_claude = os.path.join(os.environ['CLAUDE_CONFIG_DIR'], '.claude.json') if os.environ.get('CLAUDE_CONFIG_DIR') else os.path.expanduser('~/.claude.json')
+ if radice:
+ server_json(os.path.join(radice, '.mcp.json'), ['mcpServers'], 'claude', 'progetto', progetto)
+ server_json(os.path.join(radice, '.qwen', 'settings.json'), ['mcpServers'], 'qwen', 'progetto', progetto)
+ server_json(stato_claude, ['projects', radice, 'mcpServers'], 'claude', 'personale', 'personale')
+ server_json(stato_claude, ['mcpServers'], 'claude', 'personale', 'personale')
+ server_json(os.path.join(casa_qwen, 'settings.json'), ['mcpServers'], 'qwen', 'personale', 'personale')
+ visti = set()
+ for percorso, livello in _codex_config(radice):
+ try:
+ with open(percorso, encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ except OSError:
+ continue
+ dove = progetto if livello == 'progetto' else 'personale'
+ for nome, s in _toml_tabelle(testo, 'mcp_servers').items():
+ if (livello, 'mcp', nome) not in visti and (x := _server(nome, s, 'codex', livello, dove, _cartella_da_leggere(percorso, radice))):
+ visti.add((livello, 'mcp', nome))
+ carte.append(x)
+ for nome, s in _toml_tabelle(testo, 'agents').items():
+ if (livello, 'agente', nome) not in visti:
+ visti.add((livello, 'agente', nome))
+ carte.append({'nome': nome, 'descrizione': str(s.get('description') or '')[:600], 'impronta': '', 'tipo': 'agente', 'cli': ['codex'], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(percorso, radice)})
+ return carte
+
+def applica_skill(radice, scelte, fatte):
+ ora = {f'{c}:{n}': v for (c, n), v in scelte.items()}
+ via = [k for k in fatte or [] if k not in ora]
+ pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
+ try:
+ p = runpy.run_path(pacchetto) if os.path.isfile(pacchetto) else {}
+ except Exception:
+ p = {}
+ di_serie_claude, spente_codex = (p.get('SKILL_CLAUDE') or {}, set(p.get('SKILL_CODEX_SPENTE') or ()))
+ locale = os.path.join(radice or '', '.claude', 'settings.local.json')
+ if radice and os.path.isfile(locale):
+ s = _leggi(locale)
+ so = s.get('skillOverrides') if isinstance(s.get('skillOverrides'), dict) else {}
+ prima = dict(so)
+ for k, v in ora.items():
+ c, n = k.split(':', 1)
+ if c == 'claude':
+ so[n] = 'on' if v == 'accesa' else 'user-invocable-only'
+ for k in via:
+ c, n = k.split(':', 1)
+ if c == 'claude':
+ if n in di_serie_claude:
+ so[n] = di_serie_claude[n]
+ else:
+ so.pop(n, None)
+ if so != prima:
+ s['skillOverrides'] = so
+ if not so:
+ s.pop('skillOverrides', None)
+ _scrivi_se_cambia(locale, json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ for casa in _case_codex():
+ conf = os.path.join(casa, 'config.toml')
+ with open(conf, encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ nuovo = testo
+
+ def percorsi(n):
+ out = [os.path.join(casa, 'skills', '.system', n, 'SKILL.md'), os.path.join(casa, 'skills', n, 'SKILL.md'), os.path.expanduser(os.path.join('~/.agents/skills', n, 'SKILL.md'))]
+ if radice:
+ out.append(os.path.join(radice, '.agents', 'skills', n, 'SKILL.md'))
+ return [x for x in out if os.path.isfile(x)]
+
+ def blocco(t, percorso, acceso):
+ chiave = json.dumps(percorso)
+ schema = '(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(chiave) + '\\s*\\nenabled\\s*=\\s*(true|false)\\s*\\n?'
+ riga = f"[[skills.config]]\npath = {chiave}\nenabled = {('true' if acceso else 'false')}\n"
+ if acceso is None:
+ return re.sub(schema, '', t)
+ if re.search(schema, t):
+ return re.sub(schema, riga.replace('\\', '\\\\'), t)
+ return t.rstrip('\n') + '\n\n' + riga
+ for k, v in ora.items():
+ c, n = k.split(':', 1)
+ if c == 'codex':
+ for pp in percorsi(n):
+ nuovo = blocco(nuovo, pp, v == 'accesa')
+ for k in via:
+ c, n = k.split(':', 1)
+ if c == 'codex':
+ for pp in percorsi(n):
+ di_serie = '/skills/.system/' in pp.replace(os.sep, '/')
+ nuovo = blocco(nuovo, pp, False if n in spente_codex and di_serie else None)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.replace(conf + '.nuovo', conf)
+ return sorted(ora)
+_PORTO_FILE, _PORTO_PESO = (30, 512000)
+
+def _cartelle_di_skill(radice):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ out = [os.path.join(cfg, 'skills'), os.path.expanduser('~/.agents/skills'), os.path.expanduser('~/.qwen/skills')]
+ out += [os.path.join(c, 'skills') for c in _case_codex()]
+ if radice:
+ out += [os.path.join(radice, rel) for rel, _cli in _SKILL_PROGETTO]
+ return {os.path.realpath(x) for x in out}
+
+def _file_da_portare(radice, cartella):
+ if cartella.startswith('~/'):
+ d = os.path.expanduser(cartella)
+ elif os.path.isabs(cartella):
+ d = cartella
+ else:
+ d = os.path.join(radice or '', cartella)
+ vero = os.path.realpath(d)
+ if os.path.islink(d) or os.path.dirname(vero) not in _cartelle_di_skill(radice) or (not os.path.isfile(os.path.join(vero, 'SKILL.md'))):
+ return (None, F('porto_non_qui', cartella=cartella))
+ file, peso = ({}, 0)
+ for base, cartelle, nomi in os.walk(vero):
+ cartelle[:] = sorted((c for c in cartelle if not c.startswith('.') and (not os.path.islink(os.path.join(base, c)))))
+ for n in sorted(nomi):
+ p = os.path.join(base, n)
+ if n.startswith('.') or os.path.islink(p):
+ continue
+ try:
+ with open(p, 'rb') as h:
+ crudo = h.read(_PORTO_PESO + 1)
+ testo = crudo.decode('utf-8')
+ except (OSError, UnicodeDecodeError):
+ continue
+ peso += len(crudo)
+ if len(file) >= _PORTO_FILE or peso > _PORTO_PESO:
+ return (None, F('porto_troppo', cartella=cartella, file=_PORTO_FILE, peso=_PORTO_PESO))
+ file[os.path.relpath(p, vero).replace(os.sep, '/')] = testo
+ return (file, '')
+
+def _cartelle_di_pezzi(radice):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ out = [os.path.join(cfg, 'commands'), os.path.join(cfg, 'agents'), os.path.expanduser('~/.qwen/commands'), os.path.expanduser('~/.qwen/agents')]
+ if radice:
+ out += [os.path.join(radice, rel) for rel, _cli in _COMANDI + _AGENTI]
+ return [os.path.realpath(x) for x in out]
+
+def _pezzo_da_portare(radice, cartella):
+ if cartella.startswith('~/'):
+ p = os.path.expanduser(cartella)
+ elif os.path.isabs(cartella):
+ p = cartella
+ else:
+ p = os.path.join(radice or '', cartella)
+ vero = os.path.realpath(p)
+ dentro = any((vero.startswith(c + os.sep) for c in _cartelle_di_pezzi(radice)))
+ if os.path.islink(p) or not dentro or (not os.path.isfile(vero)) or (not vero.endswith(('.md', '.toml'))):
+ return (None, F('porto_non_qui', cartella=cartella))
+ try:
+ with open(vero, 'rb') as h:
+ crudo = h.read(_PEZZO_PESO + 1)
+ testo = crudo.decode('utf-8')
+ except (OSError, UnicodeDecodeError):
+ return (None, F('porto_non_qui', cartella=cartella))
+ if len(crudo) > _PEZZO_PESO:
+ return (None, F('porto_troppo', cartella=cartella, file=1, peso=_PEZZO_PESO))
+ return ({os.path.basename(vero): testo}, '')
+
+def _squadra(a, token, url, radice, impronta):
+ pacchetto = os.path.join(radice or '', '.claude', 'squadra.py')
+ if not radice or not os.path.isfile(pacchetto):
+ return ''
+ try:
+ p = runpy.run_path(pacchetto)
+ except Exception:
+ return ''
+ if 'squadra_scrivi' not in p:
+ return ''
+ chiave = hashlib.sha256(url.encode()).hexdigest()[:12]
+ if impronta != (p['squadra_di'](chiave) or {}).get('impronta', ''):
+ if impronta:
+ try:
+ pacco = json.loads(_get(a.url.rstrip('/') + '/api/skill/squadra', token, timeout=30) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ return F('squadra_muta', errore=e)
+ else:
+ pacco = {}
+ if isinstance(pacco, dict):
+ p['squadra_scrivi'](chiave, pacco)
+ p['squadra_claude'](radice, chiave)
+ if 'squadra_plugin_claude' in p:
+ try:
+ p['squadra_plugin_claude'](radice, chiave)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ sq = p['squadra_di'](chiave)
+ if not sq:
+ return ''
+ c = sq['ruoli'].get('conto') or {}
+ detto = F('squadra_qui', skill=c.get('skill', 0), comandi=c.get('comando', 0), agenti=c.get('agente', 0), mcp=c.get('mcp', 0), plugin=sq['plugin'])
+ try:
+ with open(os.path.join(sq['cartella'], '.plugin.json'), encoding='utf-8') as h:
+ plugin_sq = [x for x in json.load(h) if isinstance(x, dict)]
+ except (OSError, ValueError, TypeError):
+ plugin_sq = []
+ if plugin_sq:
+ fermi = sum((1 for x in plugin_sq if not x.get('accettato')))
+ detto += '\n' + F('squadra_plugin_qui', accettati=len(plugin_sq) - fermi, fermi=fermi)
+ return detto
+
+def gesto_skill(a, url, sp, registro, mio):
+ try:
+ radice = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ radice = ''
+ try:
+ token = open(os.path.expanduser(a.token_file)).read().strip()
+ except OSError as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ base = a.url.rstrip('/') + '/api/skill/macchina'
+ scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in sp.get('skill_scelte') or [] if isinstance(x, dict)}
+ carte = raccogli_skill(radice, os.path.expanduser(a.versioni_qwen), scelte)
+ try:
+ r = json.loads(_get(base, token, metodo='POST', timeout=20, corpo={'host': socket.gethostname(), 'skill': carte, 'plugin': raccogli_plugin(radice, _progetto(radice)), 'ganci': raccogli_ganci(radice, _progetto(radice))}) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ nuove = r.get('scelte') if isinstance(r.get('scelte'), list) else []
+ scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in nuove if isinstance(x, dict) and x.get('stato') in ('accesa', 'spenta') and _NOME_OK.fullmatch(str(x.get('nome') or ''))}
+ chiave = 'skill_applicate:' + (radice or '')
+ sp[chiave] = applica_skill(radice, scelte, sp.get(chiave) or [])
+ sp['skill_scelte'] = [{'cli': c, 'nome': n, 'stato': v} for (c, n), v in sorted(scelte.items())]
+ _scrivi(registro, mio)
+ print(F('skill_riferite', n=len(carte), scelte=len(scelte)))
+ for x in r.get('porta') if isinstance(r.get('porta'), list) else []:
+ cartella = str((x or {}).get('cartella') or '') if isinstance(x, dict) else ''
+ if not cartella:
+ continue
+ file, errore = _pezzo_da_portare(radice, cartella) if x.get('tipo') in ('comando', 'agente') else _file_da_portare(radice, cartella)
+ try:
+ e = json.loads(_get(a.url.rstrip('/') + '/api/skill/porto', token, metodo='POST', timeout=30, corpo={'cartella': cartella, **({'file': file} if file else {'errore': errore})}) or b'{}')
+ print(F('porto_fatto', nome=e.get('nome') or x.get('nome') or '') if e.get('entrata') else F('porto_no', cartella=cartella, errore=e.get('errore') or errore))
+ except (OSError, ValueError, urllib.error.URLError) as err:
+ print(F('registro_muto', url=a.url, errore=err), file=sys.stderr)
+ detto = _squadra(a, token, url, radice, str(r.get('squadra') or ''))
+ if detto:
+ print(detto)
+ return 0
+_PLUGIN_TETTO = 200
+
+def _origine_plugin(fonte):
+ if not isinstance(fonte, dict):
+ return ''
+ tipo = str(fonte.get('source') or fonte.get('source_type') or fonte.get('type') or '')
+ if tipo == 'github' and re.fullmatch('[\\w.-]+/[\\w.-]+', str(fonte.get('repo') or '')):
+ return 'github:' + str(fonte['repo'])
+ valore = str(fonte.get('url') or fonte.get('path') or fonte.get('source') or '')
+ if re.match('(?i)(https?|ssh|git)://', valore):
+ try:
+ u = urllib.parse.urlsplit(valore)
+ except ValueError:
+ return ''
+ return urllib.parse.urlunsplit((u.scheme, u.netloc.rpartition('@')[2], u.path, '', ''))[:300]
+ if re.fullmatch('[\\w.-]+@[\\w.-]+:[\\w./-]+', valore):
+ return valore.partition('@')[2][:300]
+ if valore.startswith(('/', '~')):
+ return 'cartella:' + _cartella_da_leggere(os.path.expanduser(valore), '')
+ return ''
+
+def _di_delminio(mercato, nome=''):
+ return mercato == 'delminio' or mercato.startswith('delminio-squadra-') or (not mercato and nome == 'delminio')
+
+def _carta_plugin(cli, nome, mercato, *, versione='', acceso=None, livello='personale', dove='personale', origine='', cartella=''):
+ return {'tipo': 'plugin', 'cli': cli, 'nome': nome, 'mercato': mercato, 'versione': str(versione or '')[:40], 'stato': '' if acceso is None else 'acceso' if acceso else 'spento', 'livello': livello, 'dove': dove, 'origine': origine, 'cartella': cartella, 'di_delminio': _di_delminio(mercato, nome)}
+
+def _plugin_claude(radice, progetto, carte):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ acceso = {}
+ impostazioni = [os.path.join(cfg, 'settings.json')]
+ if radice:
+ impostazioni += [os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')]
+ for p in impostazioni:
+ d = _leggi(p).get('enabledPlugins')
+ for k, v in d.items() if isinstance(d, dict) else []:
+ acceso[k] = v is True
+ installati = _leggi(os.path.join(cfg, 'plugins', 'installed_plugins.json')).get('plugins')
+ for pid, voci in installati.items() if isinstance(installati, dict) else []:
+ nome, _, mercato = str(pid).partition('@')
+ for v in voci if isinstance(voci, list) else []:
+ if not isinstance(v, dict):
+ continue
+ if v.get('scope') == 'user':
+ livello, dove = ('personale', 'personale')
+ elif v.get('scope') in ('project', 'local') and radice and (v.get('projectPath') == radice):
+ livello, dove = ('progetto', progetto)
+ else:
+ continue
+ carte.append(_carta_plugin('claude', nome, mercato, versione=v.get('version'), acceso=acceso.get(pid, False), livello=livello, dove=dove))
+ mercati = _leggi(os.path.join(cfg, 'plugins', 'known_marketplaces.json'))
+ for nome, m in mercati.items() if isinstance(mercati, dict) else []:
+ if isinstance(m, dict):
+ carte.append({'tipo': 'marketplace', 'cli': 'claude', 'nome': nome, 'origine': _origine_plugin(m.get('source')), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
+
+def _plugin_codex(carte):
+ casa_persona = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
+ for casa in dict.fromkeys([casa_persona] + _case_codex()):
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ except OSError:
+ continue
+ cartella = _cartella_da_leggere(casa, '')
+ for pid, campi in _toml_tabelle(testo, 'plugins').items():
+ nome, _, mercato = pid.partition('@')
+ cache = os.path.join(casa, 'plugins', 'cache', mercato, nome)
+ versioni = sorted(os.listdir(cache)) if mercato and os.path.isdir(cache) else []
+ carte.append(_carta_plugin('codex', nome, mercato, versione=versioni[-1] if versioni else '', acceso=campi.get('enabled') is not False, cartella=cartella))
+ for nome, campi in _toml_tabelle(testo, 'marketplaces').items():
+ carte.append({'tipo': 'marketplace', 'cli': 'codex', 'nome': nome, 'cartella': cartella, 'origine': _origine_plugin({'source_type': campi.get('source_type'), 'path': campi.get('source')} if campi.get('source_type') == 'local' else {'url': campi.get('source')}), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
+
+def _qwen_acceso(regole, qui):
+ acceso = True
+ for r in regole if isinstance(regole, list) else []:
+ r = str(r)
+ base = r.lstrip('!').rstrip('*').rstrip('/')
+ if not base or qui == base or qui.startswith(base + '/'):
+ acceso = not r.startswith('!')
+ return acceso
+
+def _plugin_qwen(radice, carte):
+ dati = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
+ base = os.path.join(dati, 'delminio', 'qwen')
+ case = [os.path.expanduser('~/.qwen')] + sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else [])))
+ qui = radice or os.path.expanduser('~')
+ for casa in case:
+ cartella_ext = os.path.join(casa, 'extensions')
+ if not os.path.isdir(cartella_ext):
+ continue
+ regole = _leggi(os.path.join(cartella_ext, 'extension-enablement.json'))
+ for nome in sorted(os.listdir(cartella_ext)):
+ d = os.path.join(cartella_ext, nome)
+ if not os.path.isdir(d):
+ continue
+ inst = _leggi(os.path.join(d, '.qwen-extension-install.json'))
+ sorgente = str(inst.get('source') or '')
+ manifesto = _leggi(os.path.join(d, 'qwen-extension.json')) or (_leggi(os.path.join(sorgente, 'qwen-extension.json')) if inst.get('type') == 'link' else {})
+ nome_vero = str(manifesto.get('name') or inst.get('pluginName') or nome)
+ origine = _origine_plugin({'path': sorgente} if inst.get('type') in ('link', 'local') else {'url': sorgente})
+ mercato = str((inst.get('marketplaceConfig') or {}).get('name') or '') if inst.get('pluginName') else ''
+ carta = _carta_plugin('qwen', nome_vero, mercato, versione=manifesto.get('version'), origine=origine, acceso=_qwen_acceso((regole.get(nome_vero) or {}).get('overrides'), qui), cartella=_cartella_da_leggere(casa, ''))
+ carta['di_delminio'] = nome_vero == 'delminio' or '/delminio/plugin/' in sorgente or '/delminio/squadre/' in sorgente
+ carte.append(carta)
+
+def _plugin_opencode(radice, progetto, carte):
+ casa = os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'opencode')
+ posti = [(casa, 'personale', 'personale')] + ([(radice, 'progetto', progetto)] if radice else [])
+ for cartella, livello, dove in posti:
+ sotto = os.path.join(cartella, 'plugins' if cartella == casa else os.path.join('.opencode', 'plugins'))
+ for f in sorted(os.listdir(sotto)) if os.path.isdir(sotto) else []:
+ nome, est = os.path.splitext(f)
+ if est in ('.js', '.ts', '.mjs') and os.path.isfile(os.path.join(sotto, f)):
+ carta = _carta_plugin('opencode', nome, '', acceso=True, livello=livello, dove=dove, origine='file', cartella=_cartella_da_leggere(sotto, radice))
+ carta['di_delminio'] = nome == 'delminio'
+ carte.append(carta)
+ for nome_conf in ('opencode.json', 'opencode.jsonc'):
+ conf = _leggi(os.path.join(cartella, nome_conf))
+ for pacchetto in conf.get('plugin') if isinstance(conf.get('plugin'), list) else []:
+ m = re.fullmatch('(@?[\\w.-]+(?:/[\\w.-]+)?)(?:@([\\w.^~<>=-]+))?', str(pacchetto))
+ if m:
+ carte.append(_carta_plugin('opencode', m.group(1), '', versione=m.group(2) or '', acceso=True, livello=livello, dove=dove, origine='npm:' + m.group(1)))
+
+def raccogli_plugin(radice, progetto):
+ carte = []
+ for leggi in (lambda: _plugin_claude(radice, progetto, carte), lambda: _plugin_codex(carte), lambda: _plugin_qwen(radice, carte), lambda: _plugin_opencode(radice, progetto, carte)):
+ try:
+ leggi()
+ except (OSError, ValueError, TypeError, AttributeError):
+ continue
+ return carte[:_PLUGIN_TETTO]
+_GANCI_MOMENTI = (('apertura', 'apertura'), ('opening', 'apertura'), ('dove-siamo', 'dove-siamo'), ('status', 'dove-siamo'))
+
+def _ganci_git(radice, *argomenti):
+ try:
+ return subprocess.run(['git', '-C', radice, *argomenti], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ return ''
+
+def _ganci_accettate(radice):
+ f = os.path.join(_ganci_git(radice, 'rev-parse', '--path-format=absolute', '--git-common-dir'), 'delminio-guardie-accettate')
+ try:
+ with open(f, encoding='utf-8') as h:
+ return sorted({x for x in h.read().split() if re.fullmatch('[0-9a-f]{64}', x)})[:500]
+ except OSError:
+ return []
+
+def _ganci_script(radice):
+ codice = os.environ.get('DELMINIO_FIDATI_PY') or ''
+ if not codice:
+ return []
+ fidati = {}
+ try:
+ exec(codice, fidati)
+ except Exception:
+ return []
+ gia = fidati['accettati'](radice)
+ voci = [(f, momento) for cartella, momento in _GANCI_MOMENTI for f in fidati['script_del_progetto'](radice, (cartella,))]
+ voci += [(f, 'lascito') for f in fidati['lascito_del_progetto'](radice)]
+ out = []
+ for f, momento in voci[:50]:
+ altro = fidati['di_chi'](radice, f)
+ out.append({'percorso': os.path.relpath(f, radice), 'momento': momento, 'gira': fidati['da_fidarsi'](radice, f, gia), 'di': altro[0] if altro else '', 'quando': altro[1] if altro else ''})
+ return out
+
+def raccogli_ganci(radice, progetto):
+ if not radice:
+ return {}
+ return {'dove': progetto, 'accettate': _ganci_accettate(radice), 'script': _ganci_script(radice)}
+PROVA_CONTESTO_MIN = 32768
+PROVA_CONTESTO_COMODO = 65536
+_PROVA_STRUMENTO = {'nome': 'conta_lettere', 'descrizione': F('prova_strumento'), 'parametri': {'type': 'object', 'properties': {'parola': {'type': 'string'}}, 'required': ['parola']}}
+_PROVA_CHIEDI = F('prova_chiedi')
+_PROVA_PREFISSO = ' '.join((F('prova_regola', i=i) for i in range(330)))
+
+def _prova_post(url, intestazioni, corpo, timeout=90):
+ req = urllib.request.Request(url, data=json.dumps(corpo).encode(), method='POST', headers={'Content-Type': 'application/json', **intestazioni})
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return json.loads(r.read())
+
+def _prova_cache_letta(formato, risposta):
+ u = risposta.get('usage') or {}
+ if formato == 'anthropic':
+ letti = u.get('cache_read_input_tokens')
+ totale = (u.get('input_tokens') or 0) + (letti or 0) + (u.get('cache_creation_input_tokens') or 0)
+ return (letti, totale)
+ totale = u.get('prompt_tokens') or 0
+ for chi in ((u.get('prompt_tokens_details') or {}).get('cached_tokens'), u.get('prompt_cache_hit_tokens'), u.get('cached_tokens'), (risposta.get('timings') or {}).get('cache_n')):
+ if isinstance(chi, int):
+ return (chi, totale)
+ return (None, totale)
+
+def _prova_contesto(riga, formato, base, intestazioni, modello):
+ f = riga.get('fornitore') or {}
+ if f.get('contesto'):
+ return int(f['contesto'])
+ elenco = 'https://openrouter.ai/api/v1/models' if f.get('tipo') == 'openrouter' else base.rstrip('/') + '/models' if formato == 'openai' else ''
+ if not elenco:
+ return None
+ h = {} if f.get('tipo') == 'openrouter' else intestazioni
+ try:
+ with urllib.request.urlopen(urllib.request.Request(elenco, headers=h), timeout=30) as r:
+ dati = json.loads(r.read())
+ except (OSError, ValueError):
+ return None
+ for m in dati.get('data') or dati.get('models') or []:
+ if m.get('id') == modello or m.get('name') == modello:
+ for k in ('context_length', 'context_window', 'max_model_len', 'max_context_length'):
+ if isinstance(m.get(k), int):
+ return m[k]
+ meta = m.get('meta') or {}
+ if isinstance(meta.get('n_ctx_train'), int):
+ return meta['n_ctx_train']
+ return None
+
+def prova_qwen(riga, dal_motore=''):
+ imp = impostazioni_qwen(riga)
+ formato = imp['security']['auth']['selectedType']
+ p = imp['modelProviders'][formato][0]
+ modello, base, variabile = (p['id'], p.get('baseUrl') or '', p['envKey'])
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ chiave = dal_motore or os.environ.get(variabile) or ('nessuna' if tipo == 'casa' else '')
+ if not chiave:
+ raise RuntimeError(F('prova_senza_chiave', variabile=variabile))
+ marca = formato == 'anthropic' or 'dashscope' in base
+ if formato == 'anthropic':
+ url, intest = (base.rstrip('/') + '/v1/messages', {'x-api-key': chiave, 'anthropic-version': '2023-06-01'})
+
+ def corpo(sistema, testo, strumenti=False):
+ s = {'type': 'text', 'text': sistema, **({'cache_control': {'type': 'ephemeral'}} if marca else {})}
+ c = {'model': modello, 'max_tokens': 200, 'system': [s], 'messages': [{'role': 'user', 'content': testo}]}
+ if strumenti:
+ c['tools'] = [{'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'input_schema': _PROVA_STRUMENTO['parametri']}]
+ return c
+
+ def chiamato(r):
+ return any((b.get('type') == 'tool_use' and b.get('name') == _PROVA_STRUMENTO['nome'] and ('delminio' in json.dumps(b.get('input') or {}).lower()) for b in r.get('content') or []))
+ else:
+ url, intest = (base.rstrip('/') + '/chat/completions', {'Authorization': f'Bearer {chiave}'})
+
+ def corpo(sistema, testo, strumenti=False):
+ s = [{'type': 'text', 'text': sistema, 'cache_control': {'type': 'ephemeral'}}] if marca else sistema
+ c = {'model': modello, 'max_tokens': 200, 'messages': [{'role': 'system', 'content': s}, {'role': 'user', 'content': testo}]}
+ if strumenti:
+ c['tools'] = [{'type': 'function', 'function': {'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'parameters': _PROVA_STRUMENTO['parametri']}}]
+ return c
+
+ def chiamato(r):
+ for c in ((r.get('choices') or [{}])[0].get('message') or {}).get('tool_calls') or []:
+ fn = c.get('function') or {}
+ if fn.get('name') == _PROVA_STRUMENTO['nome'] and 'delminio' in str(fn.get('arguments') or '').lower():
+ return True
+ return False
+ note = []
+ try:
+ tool = chiamato(_prova_post(url, intest, corpo(F('prova_sistema'), _PROVA_CHIEDI, True)))
+ except urllib.error.HTTPError as e:
+ testo = e.read()[:200].decode(errors='replace')
+ if e.code in (401, 403):
+ raise RuntimeError(F('prova_chiave_rifiutata', codice=e.code, testo=testo)) from None
+ tool = False
+ note.append(F('prova_strumento_errore', codice=e.code))
+ letti = totale = None
+ for attesa in (0, 3, 8):
+ time.sleep(attesa)
+ r = _prova_post(url, intest, corpo(_PROVA_PREFISSO, F('prova_ok')))
+ letti, totale = _prova_cache_letta(formato, r)
+ if attesa and (letti is None or letti > 0):
+ break
+ contesto = _prova_contesto(riga, formato, base, intest, modello)
+ if not tool:
+ note.append(F('prova_senza_strumento'))
+ if contesto is not None and contesto < PROVA_CONTESTO_COMODO:
+ note.append(F('prova_contesto_stretto', contesto=contesto))
+ if letti is None:
+ note.append(F('prova_cache_muta'))
+ esito = 'non_va' if not tool or (contesto is not None and contesto < PROVA_CONTESTO_MIN) else 'va' if letti else 'senza_cache'
+ return {'esito': esito, 'tool': tool, 'cache': {'letti': letti, 'totale': totale}, 'contesto': contesto, 'nota': '; '.join(note)}
+
+def comando_prova(a, righe, dati, base, token):
+ riga = next((r for r in righe if a.nomi and r.get('nome') == a.nomi[0]), None)
+ if riga is None or riga.get('cli') != 'qwen':
+ print(F('uso_prova'), file=sys.stderr)
+ return 2
+ riga = {**riga, '_fornitori': dati.get('fornitori_qwen') or {}}
+ locale = (riga.get('fornitore') or {}).get('tipo') == 'casa'
+ print(F('prova_inizio_locale', nome=riga['nome'], modello=riga.get('modello')) if locale else F('prova_inizio_fornitore', nome=riga['nome'], modello=riga.get('modello')))
+ dal_motore = ''
+ if (scelta := (riga.get('fornitore') or {}).get('chiave')):
+ try:
+ dal_motore = _get(base + '/' + urllib.parse.quote(riga['nome']) + '/chiave', token).decode().strip()
+ except urllib.error.HTTPError as e:
+ print(F('prova_chiave_negata', scelta=scelta, errore=e.read()[:400].decode(errors='replace')), file=sys.stderr)
+ return 1
+ except (OSError, urllib.error.URLError) as e:
+ print(F('prova_chiave_negata', scelta=scelta, errore=e), file=sys.stderr)
+ return 1
+ try:
+ v = prova_qwen(riga, dal_motore)
+ except (RuntimeError, OSError, ValueError) as e:
+ print(F('prova_non_fatta', errore=e), file=sys.stderr)
+ return 1
+ c = v['cache']
+ print(F('prova_riga_strumenti', valore=F('prova_si') if v['tool'] else F('prova_no')))
+ print(F('prova_riga_cache', valore=F('prova_cache_non_detta') if c['letti'] is None else F('prova_cache_letti', letti=c['letti'], totale=c['totale'])))
+ print(F('prova_riga_contesto', valore=v['contesto'] or F('prova_non_lo_dice')))
+ print(F('prova_riga_verdetto', valore={'va': F('prova_va'), 'senza_cache': F('prova_senza_cache'), 'non_va': F('prova_non_va')}[v['esito']], nota=f" ({v['nota']})" if v['nota'] else ''))
+ try:
+ _get(base + '/' + urllib.parse.quote(riga['nome']) + '/prova', token, metodo='POST', corpo=v)
+ except (OSError, urllib.error.URLError) as e:
+ print(F('verdetto_perso', errore=e), file=sys.stderr)
+ return 1
+ return 0 if v['esito'] != 'non_va' else 1
+
+def comando_rinomina(a, righe, base, token):
+ if len(a.nomi) != 2:
+ print(F('uso_rinomina'), file=sys.stderr)
+ return 2
+ vecchio, nuovo = a.nomi
+ riga = next((r for r in righe if r['nome'] == vecchio), None)
+ if riga is None:
+ print(F('rinomina_assente', nome=vecchio), file=sys.stderr)
+ return 1
+ try:
+ _get(f'{base}/{urllib.parse.quote(vecchio)}/rinomina', token, metodo='POST', corpo={'nuovo': nuovo})
+ except urllib.error.HTTPError as e:
+ print(F('rinomina_rifiutata', errore=e.read().decode('utf-8', 'replace')[:300]), file=sys.stderr)
+ return 1
+ print(F('rinominato', vecchio=vecchio, nuovo=nuovo))
+ return 0
+
+def comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro):
+ for r in righe:
+ p = os.path.join(bin_dir, r['nome'])
+ try:
+ voluta = versione_voluta(r, canali)
+ except Exception as e:
+ voluta = f'? ({e})'
+ ora = _del_file(p)
+ stato = F('stato_assente') if ora is None else F('stato_cambiato') if impronte.get(p) not in (None, ora) else F('stato_non_suo') if impronte.get(p) is None else F('stato_intatto') if url in padroni.get(p, [url]) else F('stato_altro_spazio', spazi=', '.join(padroni[p]))
+ cli = os.path.join(os.path.expanduser(a.versioni_codex), voluta, 'bin', 'codex') if r.get('cli') == 'codex' else os.path.join(os.path.expanduser(a.versioni_qwen), voluta, 'bin', 'qwen') if r.get('cli') == 'qwen' else os.path.join(os.path.expanduser(a.versioni_opencode), voluta, 'bin', 'opencode') if r.get('cli') == 'opencode' else os.path.join(versioni, voluta)
+ print(F('stato_riga', nome=r['nome'], versione=voluta, da_scaricare='' if os.path.isfile(cli) or prova else F('da_scaricare'), modello=r.get('modello') or F('modello_di_serie'), porta=r.get('porta') or '—', stato=stato))
+ if sp.get('rifiutato'):
+ print(F('stato_rifiutato'))
+ if not righe:
+ print(F('registro_vuoto'))
+ r = riferisci(base, token, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'))
+ richiesta(base, token, r, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'), mio=mio, file_mio=registro)
+ return 0
+
+def comando_lascia(a, url, padroni, impronte, mio, registro):
+ tolti = 0
+ for p in [x for x, chi in padroni.items() if url in chi]:
+ if lascia_il_nome(p, url, padroni, impronte) == 'tolto':
+ tolti += 1
+ mio['spazi'].pop(url, None)
+ _scrivi(registro, mio)
+ comando = os.path.join(os.path.expanduser(a.bin), 'delminio')
+ if not mio['spazi'] and os.path.isfile(comando):
+ with open(comando, encoding='utf-8', errors='replace') as h:
+ if '# delminio-comando\n' in h.read():
+ os.remove(comando)
+ print(F('lasciati', n=tolti))
+ return 0
+
+def scrivi_il_primo(a, dati, righe, bin_dir, impronte):
+ cli_voluta = a.vuoi or 'claude'
+ catalogo = (dati.get('modelli') or {}).get(cli_voluta) or []
+ ordine = [m.get('id') for m in catalogo]
+ consigliati = {m.get('id') for m in catalogo if m.get('consigliato')}
+ candidati = sorted((r for r in righe if (r.get('cli') or 'claude') == cli_voluta and (not personaggio(r))), key=lambda r: (r.get('modello') not in consigliati, ordine.index(r.get('modello')) if r.get('modello') in ordine else len(ordine)))
+ primo = next((p for p in (os.path.join(bin_dir, r['nome']) for r in candidati) if impronte.get(p) and _del_file(p) == impronte[p]), '')
+ if not candidati:
+ print(F('nessun_agente_di', cli=CLI_NOMI.get(cli_voluta, cli_voluta)))
+ with open(a.primo, 'w', encoding='utf-8') as f:
+ f.write(primo)
+
+def main():
+ if sys.argv[1:2] == ['posta-ruolo']:
+ return posta_ruolo(sys.argv[2:])
+ if sys.argv[1:2] == ['casa']:
+ return casa(sys.argv[2:])
+ if sys.argv[1:2] == ['mie-qwen']:
+ return unisci_mie_qwen(sys.argv[2:])
+ if sys.argv[1:2] == ['mie-codex']:
+ return unisci_mie_codex(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia']:
+ return pulizia(sys.argv[2:])
+ if sys.argv[1:2] == ['errori-registra']:
+ return errori_registra(sys.argv[2:])
+ if sys.argv[1:2] == ['errori']:
+ return errori(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia-codex']:
+ return pulizia_codex(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia-opencode']:
+ return pulizia_opencode(sys.argv[2:])
+ if sys.argv[1:2] == ['installa-agente']:
+ return installa_agente(sys.argv[2:])
+ if sys.argv[1:2] == ['modello-gratuito']:
+ return modello_gratuito(sys.argv[2:])
+ if sys.argv[1:2] == ['accetta']:
+ return accetta(os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json'))
+ ap = argparse.ArgumentParser(description=F('aiuto_descrizione'))
+ ap.add_argument('comando', nargs='?', default='allinea', choices=['allinea', 'stato', 'no', 'rinomina', 'lascia', 'spazio', 'prova', 'skill'])
+ ap.add_argument('nomi', nargs='*', help=F('aiuto_nomi'))
+ ap.add_argument('--url')
+ ap.add_argument('--token-file')
+ ap.add_argument('--da', help=F('aiuto_da'))
+ ap.add_argument('--modo', choices=['kit', 'casa'], default='kit')
+ ap.add_argument('--al-lancio', action='store_true', help=F('aiuto_al_lancio'))
+ ap.add_argument('--converti', action='store_true', help=F('aiuto_converti'))
+ ap.add_argument('--vuoi', choices=list(CLI_NOMI), help=F('aiuto_vuoi'))
+ ap.add_argument('--primo', help=F('aiuto_primo'))
+ ap.add_argument('--bin', default=os.environ.get('DELMINIO_BIN') or '~/.local/bin')
+ ap.add_argument('--versioni', default=os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions')
+ ap.add_argument('--versioni-codex', default=os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions')
+ ap.add_argument('--versioni-qwen', default=os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
+ ap.add_argument('--versioni-opencode', default=os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions')
+ ap.add_argument('--registro', default=os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
+ a = ap.parse_args()
+ if a.da:
+ for riga in open(a.da, encoding='utf-8'):
+ k, _, v = riga.strip().partition('=')
+ if k in ('URL', 'FILE_TOKEN') and v:
+ setattr(a, 'url' if k == 'URL' else 'token_file', (shlex.split(v) or [''])[0])
+ if not a.url or not a.token_file:
+ ap.error(F('servono_url_token'))
+ bin_dir, versioni, registro = (os.path.expanduser(x) for x in (a.bin, a.versioni, a.registro))
+ _DIR_COMANDI[0] = cartella_dei_comandi(registro)
+ prova = os.environ.get('DELMINIO_CLI_PROVA', '')
+ mio = _leggi(registro)
+ if a.vuoi and a.comando == 'allinea':
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {a.vuoi})
+ _scrivi(registro, mio)
+ letto = _del_file(registro)
+ impronte = mio.setdefault('eseguibili', {})
+ _ALIASI.update(mio.get('alias') or {})
+ url = spazio_di(a.url, _token_di(a.token_file))
+ if a.comando == 'spazio':
+ if url not in mio.get('spazi', {}) and mio.get('spazi'):
+ vero = _alias(mio, url, _istanza_di(a.url, _token_di(a.token_file)))
+ if vero != url:
+ _scrivi(registro, mio)
+ url = vero
+ print(url)
+ return 0
+ sp = _spazio(mio, url)
+ if a.comando == 'skill':
+ return gesto_skill(a, url, sp, registro, mio)
+ if a.comando == 'allinea' and a.modo == 'kit':
+ ricorda_il_progetto(url)
+ padroni = mio.setdefault('padroni', {})
+ if a.comando == 'no':
+ sp['rifiutato'] = True
+ _scrivi(registro, mio)
+ print(F('rifiutati'))
+ return 0
+ if a.comando == 'lascia':
+ return comando_lascia(a, url, padroni, impronte, mio, registro)
+ base = a.url.rstrip('/') + '/api/eseguibili'
+ try:
+ token = open(os.path.expanduser(a.token_file)).read().strip()
+ dati = json.loads(_get(base, token))
+ righe = dati['eseguibili']
+ except (OSError, ValueError, KeyError, urllib.error.URLError) as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ fuori = [str(r.get('nome')) for r in righe if not _NOME_OK.fullmatch(str(r.get('nome') or ''))]
+ if fuori:
+ print(F('nomi_fuori_forma', nomi=', '.join(map(repr, fuori))), file=sys.stderr)
+ righe = [r for r in righe if _NOME_OK.fullmatch(str(r.get('nome') or ''))]
+ istanza = dati.get('istanza') or ''
+ if (vero := _alias(mio, url, istanza)) != url:
+ url, sp = (vero, _spazio(mio, vero))
+ if istanza:
+ sp['istanza'] = istanza
+ al_lancio = a.comando == 'allinea' and a.al_lancio
+ if al_lancio and sp.get('registro') == dati.get('impronta'):
+ return 3 if os.environ.get('DELMINIO_AL_LANCIO_ATTESO') else 0
+ if al_lancio and (not os.environ.get('DELMINIO_AL_LANCIO_ATTESO')):
+ print(F('al_lancio'), file=sys.stderr)
+ if a.comando == 'prova':
+ return comando_prova(a, righe, dati, base, token)
+ if a.comando == 'rinomina':
+ return comando_rinomina(a, righe, base, token)
+ canali, esito = ({}, 0)
+ if a.comando == 'stato':
+ return comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro)
+ if fcntl is not None:
+ try:
+ os.makedirs(os.path.dirname(registro) or '.', exist_ok=True)
+ lucchetto = open(registro + '.lock', 'w')
+ fcntl.flock(lucchetto, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ if not al_lancio or os.environ.get('DELMINIO_AL_LANCIO_ATTESO') or 'lucchetto' not in locals():
+ print(F('allinea_in_corso'))
+ return 0
+ print(F('al_lancio_attesa'), file=sys.stderr)
+ fcntl.flock(lucchetto, fcntl.LOCK_EX)
+ lucchetto.close()
+ os.environ['DELMINIO_AL_LANCIO_ATTESO'] = '1'
+ sys.stderr.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ else:
+ if _del_file(registro) != letto and (not os.environ.get('DELMINIO_RILETTO')):
+ lucchetto.close()
+ os.environ['DELMINIO_RILETTO'] = '1'
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ os.makedirs(bin_dir, exist_ok=True)
+ nomi = set()
+ senza_cli = set()
+ detto = [0.0]
+
+ def avanza(percento, passo, subito=False):
+ if not subito and time.time() - detto[0] < 2:
+ return
+ detto[0] = time.time()
+ try:
+ _get(f'{base}/lavoro', token, metodo='POST', corpo={'host': socket.gethostname(), 'percento': int(percento), 'passo': passo[:120]}, timeout=5)
+ except (OSError, ValueError, urllib.error.URLError):
+ pass
+ nomi_cli = dati.get('cli') or {}
+ quante = max(1, len(righe))
+ prima_volta = 'accettati' not in mio
+ accettati, fermi = (set(mio.get('accettati') or []), [])
+ for i, r in enumerate(righe):
+ p = os.path.join(bin_dir, r['nome'])
+ nomi.add(p)
+ quota, nome_cli = (100.0 * i / quante, nomi_cli.get(r.get('cli') or 'claude', r.get('cli') or 'claude'))
+ if not cli_qui(r.get('cli') or 'claude', versioni, os.path.expanduser(a.versioni_codex), prova, os.path.expanduser(a.versioni_qwen), mio.get('cli_volute') or (), os.path.expanduser(a.versioni_opencode)):
+ senza_cli.add(r['nome'])
+ print(F('senza_cli_qui', nome=r['nome'], cli=r.get('cli') or 'claude'))
+ continue
+ if da_accettare(r, accettati):
+ if prima_volta and any((impronte.get(x) for x in (p, comando_dello_spazio(url, r['nome'])))):
+ accettati.add(impronta_libera(r))
+ else:
+ fermi.append({'nome': r['nome'], **parte_libera(r)})
+ print(F('riga_da_accettare', nome=r['nome']))
+ continue
+ try:
+ voluta = versione_voluta(r, canali)
+ avanza(quota, F('passo_controllo', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
+ su = lambda f, t, q=quota, n=nome_cli, vv=voluta, nn=r['nome']: avanza(q + 90.0 / quante * (f / t if t else 0), F('passo_scarico', nome=nn, cli=n, versione=vv, mb=f // 1000000) + (F('passo_di', mb=t // 1000000) if t else ''))
+ cli = assicura_codex(voluta, os.path.expanduser(a.versioni_codex), prova, su=su) if r.get('cli') == 'codex' else assicura_qwen(voluta, os.path.expanduser(a.versioni_qwen), prova, su=su) if r.get('cli') == 'qwen' else assicura_opencode(voluta, os.path.expanduser(a.versioni_opencode), prova, su=su) if r.get('cli') == 'opencode' else assicura_cli(voluta, versioni, prova, su=su)
+ if personaggio(r) and r.get('cli') in ('claude', 'qwen'):
+ assicura_canale(a.url, token, r['porta'])
+ if r.get('cli') == 'claude':
+ assicura_rito()
+ except Exception as e:
+ print(f"❌ {r['nome']}: {e}")
+ esito = 1
+ continue
+ modello = next((m for m in (dati.get('modelli') or {}).get(r.get('cli') or 'claude', []) if m['id'] == r.get('modello')), {})
+ promemoria = ((dati.get('promemoria') or {}).get('ambiente') or {}).get(r.get('cli') or 'claude') or {}
+ promemoria = {k: v for k, v in promemoria.items() if k in PROMEMORIA_AMMESSI}
+ da_lanciare = {**r, '_contesto': modello.get('contesto') or {}, '_promemoria': promemoria, '_fornitori': (dati.get('fornitori_opencode') if r.get('cli') == 'opencode' else dati.get('fornitori_qwen')) or {}, '_skill': dati.get('skill_scelte') or [], '_base': dati.get('parametri_base') or {}}
+ testo = wrapper(da_lanciare, cli, a.modo, a.url, os.path.expanduser(a.token_file))
+ ora = _del_file(p)
+ if ora is not None and p not in impronte:
+ print(F('non_di_delminio', percorso=p))
+ esito = 1
+ continue
+ if ora is not None and impronte.get(p) != ora:
+ print(F('toccato_resta', percorso=p))
+ continue
+ if a.modo == 'kit' and (not a.converti) and (ora != _impronta(testo)) and _di_casa(p):
+ testo = wrapper(da_lanciare, cli, 'casa', a.url, os.path.expanduser(a.token_file))
+ chi = padroni.get(p) or []
+ altri = [u for u in chi if u != url]
+ if ora is not None and altri and (not e_smistatore(p)) and (ora == _impronta(testo)):
+ if url not in chi:
+ chi.append(url)
+ sp.setdefault('cli', {})[p] = voluta
+ continue
+ if ora is not None and (altri or e_smistatore(p)):
+ q = comando_dello_spazio(url, r['nome'])
+ gia = _del_file(q)
+ if gia is not None and impronte.get(q) not in (None, gia):
+ print(F('toccato_resta', percorso=q))
+ continue
+ vecchio = None
+ if gia is not None:
+ with open(q, encoding='utf-8') as f:
+ vecchio = f.read()
+ prima = (sp.get('cli') or {}).get(p)
+ sp.setdefault('cli', {})[p] = voluta
+ if url in chi and gia == _impronta(testo) and e_smistatore(p):
+ continue
+ if dividi(p, url, testo, padroni, impronte):
+ print(F('smistato', nome=r['nome'], spazi=', '.join((come_si_chiama(u) for u in padroni[p]))))
+ cambiate = _nel_diario(registro, q, prima, voluta, vecchio, testo)
+ if gia is None:
+ print(F('scritto', percorso=q, versione=voluta))
+ elif gia != _impronta(testo):
+ print(F('rinfrescato', percorso=q, versione=voluta, righe=cambiate) if prima == voluta else F('aggiornato', percorso=q, prima=prima or '?', versione=voluta))
+ continue
+ padroni[p] = [url] + altri
+ prima = (sp.get('cli') or {}).get(p)
+ sp.setdefault('cli', {})[p] = voluta
+ if ora == _impronta(testo):
+ continue
+ vecchio = None
+ if ora is not None:
+ try:
+ with open(p, encoding='utf-8') as f:
+ vecchio = f.read()
+ except (OSError, UnicodeDecodeError):
+ pass
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+ impronte[p] = _impronta(testo)
+ cambiate = _nel_diario(registro, p, prima, voluta, vecchio, testo)
+ if ora is None:
+ print(F('scritto', percorso=p, versione=voluta))
+ elif prima == voluta:
+ print(F('rinfrescato', percorso=p, versione=voluta, righe=cambiate))
+ else:
+ print(F('aggiornato', percorso=p, prima=prima or '?', versione=voluta))
+ avanza(100.0 * (i + 1) / quante, F('passo_scritto', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
+ for p in [x for x in impronte if x not in nomi and os.path.dirname(x) == bin_dir]:
+ chi = padroni.get(p) or []
+ if url not in chi:
+ continue
+ sp.get('cli', {}).pop(p, None)
+ com_e = lascia_il_nome(p, url, padroni, impronte)
+ if com_e == 'tolto':
+ print(F('tolto', percorso=p))
+ elif com_e in ('altri', 'tornato'):
+ print(F('lasciato_ad_altri', percorso=p, spazi=', '.join(padroni.get(p) or [])))
+ if righe:
+ sp['rifiutato'] = False
+ mio['accettati'], sp['fermi'] = (sorted(accettati), fermi)
+ sp['registro'], sp['quando'] = (dati.get('impronta', ''), int(time.time()))
+ sp['skill_scelte'] = dati.get('skill_scelte') or []
+ _scrivi(registro, mio)
+ if esito == 0 and righe and (not prova):
+ pota(bin_dir, [versioni] + [os.path.expanduser(c) for c in (a.versioni_codex, a.versioni_qwen, a.versioni_opencode)], nudo(bin_dir, versioni))
+ r = riferisci(base, token, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), senza_cli=senza_cli)
+ if richiesta(base, token, r, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), mio=mio, file_mio=registro) and (not os.environ.get('DELMINIO_RIALLINEATO')):
+ os.environ['DELMINIO_RIALLINEATO'] = '1'
+ sys.stdout.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ cartelle = [os.path.realpath(os.path.expanduser(c)) for c in os.environ.get('PATH', '').split(os.pathsep) if c]
+ if righe and os.path.realpath(bin_dir) not in cartelle:
+ print(F('fuori_dal_path', cartella=bin_dir))
+ if a.primo:
+ scrivi_il_primo(a, dati, righe, bin_dir, impronte)
+ return 3 if al_lancio and esito == 0 else esito
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/kit/en/firme-client b/kit/en/firme-client
new file mode 100644
index 0000000..62aacad
--- /dev/null
+++ b/kit/en/firme-client
@@ -0,0 +1,1357 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Le firme delle modifiche da un terminale, dai ganci git e da una CI (B923)."""
+from __future__ import annotations
+import base64
+import datetime
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import urllib.error
+import urllib.request
+CMD = 'delminio firme'
+URL = os.environ.get('DELMINIO_URL', '').rstrip('/')
+TOKEN = os.environ.get('DELMINIO_TOKEN', '')
+STATO = os.environ.get('DELMINIO_STATO', '')
+MASSIMO = 20000
+COMMIT_MAX = 500
+RAMO_MAX = 200
+APP_ANDROID = ('jG9UXQXhlWwgZvpNwGNDmhcDbR_94LnCQOAcyOOgJqg',)
+PROVE_TEMPO = 900
+COMANDI = {
+ "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"
+ }
+}
+FRASI = {
+ "ci_gitlab_passi": "Then, once: Settings \u2192 CI/CD \u2192 Variables, a DELMINIO_FIRME variable (masked) with the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key; and Settings \u2192 Merge requests \u2192 \u201cPipelines must succeed\u201d, or merging stays possible even with the check red.",
+ "ci_gitlab": "With GitLab there is a single file for the whole repo ({file}), and I won't touch it: add this job.",
+ "ci_passi_forgejo": "On Forgejo (or Gitea), three steps to do by hand, once:\n 1. A runner: Actions only run if the service has one (in the repo, Settings \u2192 Actions \u2192 Runners). The file asks for a runner labelled docker: if yours has another label, change \u201cruns-on\u201d in the file.\n 2. The secret: Settings \u2192 Actions \u2192 Secrets, name DELMINIO_FIRME, value the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.\n 3. The gate: Settings \u2192 Branches \u2192 a protection rule on branch {ramo}, with three things: the required status check \u201cdelminio-firme / controlla (pull_request)\u201d (on Forgejo the name carries the file and the event: \u201ccontrolla\u201d alone matches nothing, and merging stays blocked even with the sign-offs); direct push turned off, so the branch is entered only through a pull request; the rule applied to administrators too. Without this rule the CI goes red, but merging stays possible.\nOn pull requests from a fork there are no secrets: there the check can't run.",
+ "ci_gh_manca": "The GitHub CLI (gh) is not on this computer: the secret and the branch rule are still to be done by hand.",
+ "ci_gh_non_collegato": "The GitHub CLI is here, but not signed in to an account (gh auth login): the secret and the branch rule are still to be done by hand.",
+ "ci_gh_quale_repo": "The GitHub CLI does not recognise the repository in this folder ({errore}): the secret and the branch rule are still to be done by hand.",
+ "ci_gh_permessi": "On {repo} your GitHub account is not an admin: the secret and the branch rule are set by someone who is, by hand or by running this command again.",
+ "ci_gh_privato": "\u274c GitHub does not enforce branch rules on private repositories of a free account: on {repo} the check will be red, but merging will still be possible. You need a GitHub plan that enforces them (Team, or Pro for a personal account), or a git service of your own.",
+ "ci_gh_regola_no": "\u274c The rule on the {ramo} branch was not set ({errore}). By hand: Settings \u2192 Branches \u2192 a rule on the {ramo} branch with the \u201ccontrolla\u201d check required and \u201cDo not allow bypassing the above settings\u201d.",
+ "ci_gh_regole_altre": "The {ramo} branch already has its own rules: I leave them as they are and only add what is missing.",
+ "ci_gh_regola_ok": "\u2705 On {repo}, the {ramo} branch requires the \u201ccontrolla\u201d check before every merge, and the rule applies to admins too.",
+ "ci_gh_segreto_c_e": "\u2705 The DELMINIO_FIRME secret is already on {repo}. GitHub shows its value to no one: if the CI says the key is not valid, set it again.",
+ "ci_gh_segreto_tu": "The DELMINIO_FIRME secret is missing, and a person sets it, not an agent: in their own terminal, in this repository, they type {cmd} and paste the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.",
+ "ci_gh_segreto_incolla": "Now the DELMINIO_FIRME secret: paste the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key. It is not shown while you paste it, and it goes only to GitHub.",
+ "ci_gh_segreto_fatto": "\u2705 The DELMINIO_FIRME secret is on {repo}.",
+ "ci_gh_segreto_no": "\u274c The secret was not set ({errore}): in the repository, Settings \u2192 Secrets and variables \u2192 Actions, name DELMINIO_FIRME.",
+ "ci_passi_github": "On GitHub, two steps to do by hand, once:\n 1. The secret: in the repo, Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret. Name DELMINIO_FIRME, value the key the administrator creates in Delminio, under Sign-offs \u2192 The CI key.\n 2. The gate: Settings \u2192 Branches (or Rules) \u2192 a rule on branch {ramo} that requires the \u201ccontrolla\u201d check before merging, for admins too (\u201cDo not allow bypassing the above settings\u201d). The check shows up in the list after the first pull request. Without this rule the CI goes red, but merging stays possible.\nOn pull requests from a fork GitHub doesn't hand out secrets: there the check can't run.",
+ "ci_esiste_diverso": "\u26a0\ufe0f {file} is already there and differs from what I'd write: I'm leaving it alone. If you changed it yourselves, that's fine; if not, remove it and run me again.",
+ "ci_gia_pronto": "\u2705 {file} is already there, and it's the right one.",
+ "ci_scritto": "\u2705 Wrote {file}: commit it and push it like any other file.",
+ "ci_commento": "Delminio change sign-off: each pull request checks the sign-offs of its branch, each push to the main branch that nothing got in without them. Written by \u201cdelminio signoffs ci\u201d; the key lives in the service's secrets, named DELMINIO_FIRME.",
+ "ci_dentro_casa": "\u26a0\ufe0f This Delminio lives at {url}, an address on your network: the machines of a CI on the internet (GitHub, GitLab.com) can't reach it. The check only works with a CI running inside your network (a runner of your own), or with a Delminio reachable from outside.",
+ "ci_quale": "I can't tell this repo's git service. Tell me which: delminio signoffs ci github, forgejo (Gitea too) or gitlab.",
+ "dell_autore": "by the author: it does not count",
+ "chi_non_detto": "another session",
+ "revisione_dell_autore": "The review of {commit} is recorded, but you are the author: what counts is the reviewer's, with their agent.",
+ "uso": "usage: {cmd} check [<range>] \xb7 {cmd} description [<range>] \xb7 {cmd} report [<range>] [<file>] \xb7 {cmd} export [<file>] \xb7 {cmd} chain <file> [<earlier copy>] \xb7 {cmd} review <commit|range> clean|findings [N] \xb7 {cmd} checks \xb7 {cmd} ci [github|forgejo|gitlab]",
+ "senza_motore": "\u274c Delminio's address or the key is missing: in a CI you need DELMINIO_URL and DELMINIO_TOKEN (the read key the administrator creates in Sign-offs).",
+ "non_risponde": "\u274c Delminio does not answer ({url}): {errore}",
+ "assenti": "Change sign-off is not available in this space: the licence does not include it.",
+ "intestazione": "The person's words to the agent, recorded by Delminio (change sign-off):",
+ "non_registrata": "not recorded in Delminio",
+ "controlli": "The checks before the commit:",
+ "zona": "\u26a0\ufe0f This change touches a sign-off zone ({zone}): it must be signed in the Delminio app, under Sign-offs, before it goes ahead.",
+ "nascosto": "[hidden]",
+ "troncata": "[\u2026 {n} more characters not copied here]",
+ "nessun_commit": "No commits in {intervallo}.",
+ "intervallo_illeggibile": "\u274c I can't read the commits in {intervallo}: git can't find it ({errore}). With nothing to check this isn't a pass: the CI needs the whole history (fetch-depth: 0), and after a force push the previous commit is gone.",
+ "firmata": " \u2705 {commit} signed \u2014 {soggetto}",
+ "da_firmare": " \u274c {commit} to sign ({zone}): still missing {manca} \u2014 {soggetto}",
+ "respinta": " \u274c {commit} rejected \u2014 {soggetto}",
+ "libera": " \xb7 {commit} outside the sign-off zones \u2014 {soggetto}",
+ "senza": " \u274c {commit} with no recorded sign-off: nobody answers for it in Delminio. It was made on a computer not connected to Delminio, skipping its checks, with sign-off switched off, or the network dropped at the commit: make it again on a connected computer (git commit --amend --no-edit) \u2014 {soggetto}",
+ "senza_in_zona": " \u274c {commit} touches a sign-off zone ({zone}) with no recorded sign-off: it was made on a computer not connected to Delminio, skipping its checks, with sign-off switched off, or the network dropped at the commit. Make it again on a connected computer (git commit --amend --no-edit) \u2014 {soggetto}",
+ "merge_pulito": " \xb7 {commit} merge with no changes of its own \u2014 {soggetto}",
+ "unita": " \u2705 {commit} comes from branch {ramo}: its {n} changes are signed \u2014 {soggetto}",
+ "unita_da_firmare": " \u274c {commit} comes from branch {ramo}: {n} of its changes still need signing \u2014 {soggetto}",
+ "unita_mancano": " \u274c {commit} comes from branch {ramo}, but {n} of its commits have no recorded sign-off \u2014 {soggetto}",
+ "unita_scoperta": " \u274c {commit} comes from branch {ramo} and touches a sign-off zone ({zone}) that its recorded changes do not carry: the recorded files are not the commit's. Redo the commits from a connected computer \u2014 {soggetto}",
+ "parole_non_tornano": " \u274c {commit}: the words of request {id} do not match its fingerprint \u2014 the message was changed",
+ "parole_ignote": " \u274c {commit}: request {id} is not the one Delminio recorded",
+ "esito": "{firmate} signed \xb7 {da_firmare} to sign \xb7 {libere} outside the zones \xb7 {senza} with no recorded sign-off \xb7 {rotte} with changed words \xb7 {urgenti} let in as urgent.",
+ "urgente": " \u26a1 {commit} let in as urgent \u2014 {soggetto} (let through by {da} on {quando}: \u201c{perche}\u201d; sign-offs are given afterwards)",
+ "gov_urgenza": "{quando} \u2014 {chi} lets commit {commit} into {repo} as urgent: \u201c{perche}\u201d",
+ "esportata": "The chain is in {file}: {anelli} links, {esito}.",
+ "catena_rotta": "broken at link {anello}",
+ "revisione_registrata": "Your review of {commit} is recorded: you can now sign it from the app, under Sign-offs.",
+ "revisione_senza_sessione": "Your agent records the review, from its session: ask it to review the commit and to run \u201c{cmd} review <commit> clean\u201d itself (or \u201cfindings N\u201d). From a terminal outside a session it isn't recorded, because the review is yours and the model's you chose.",
+ "descr_parole": "### What the person asked for",
+ "descr_nessuna_parola": "_No recorded request: changes made by hand._",
+ "descr_fatti": "### The facts",
+ "descr_commit": "{n} commits, {file} files",
+ "descr_assistito": "With the agent: {con}",
+ "descr_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures, reviewed by {chi}",
+ "descr_chiunque": "anyone in the space",
+ "descr_controllo": "Check {codice} `{comando}` \u2192 exit {uscita}",
+ "descr_revisione": "Review by {chi}, with {revisore}: {esito}, {rilievi} findings ({indipendente})",
+ "indipendente": "independent",
+ "stessa_sessione": "from the session that wrote it: does not count",
+ "indipendente_stesso_modello": "independent, same model as the author",
+ "descr_stati": "Sign-off: {stati}",
+ "stato_firmata": "signed",
+ "stato_unita": "signed on the branch",
+ "stato_libera": "outside the zones",
+ "stato_pulito": "merges",
+ "stato_senza": "with no recorded sign-off",
+ "stato_da_firmare": "to sign",
+ "stato_respinta": "rejected",
+ "stato_zona": "in a zone with no recorded sign-off",
+ "res_titolo": "# Change sign-off \u2014 {remoto} \u2014 {intervallo}",
+ "res_generato": "Written on {quando} by Delminio. The sign-off chain: {anelli} links, {esito}.",
+ "res_stato": "Status: {riga}",
+ "res_unita": "Merged into the main branch from branch {ramo}: the signatures are on its {n} commits.",
+ "res_autore": "Accountable: {autore} \xb7 with {con} \xb7 {quando}",
+ "res_a_mano": "no agent (by hand)",
+ "res_zona": "Sign-off zone {codice} \u201c{cosa}\u201d: {servono} signatures",
+ "res_firma": "Signed by {persona}, {significato}, {quando}{parole}",
+ "significato_autore": "as author",
+ "significato_revisione": "as reviewer",
+ "significato_respinta": "rejected",
+ "res_nessuna_firma": "No signatures yet.",
+ "res_richiesta": "Request {id} (fingerprint {impronta}\u2026): {torna}",
+ "res_torna": "the words match the recorded fingerprint",
+ "res_non_torna": "the words do NOT match the fingerprint: the message was changed",
+ "res_file": "{n} files: {elenco}",
+ "res_come_verificare": "The chain can be checked without Delminio: \u201cdelminio signoffs export\u201d, then, inside the repository, \u201cdelminio signoffs chain <file> [<earlier copy>]\u201d, which also checks the anchors written in the commits and that the earlier copy is still its beginning. The words of each request are in the commit message, and their fingerprint (sha256) is the one Delminio recorded when the person wrote them.",
+ "res_scritto": "The report is in {file}: {commit} commits.",
+ "ripresa": " \u2705 {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), with its signatures \u2014 {soggetto}",
+ "ripresa_da_firmare": " \u274c {commit} is a change from branch {ramo}, redone (rebase or cherry-pick), still to sign \u2014 {soggetto}",
+ "repo_senza_firme": "This repository has no change sign-off: nothing to check. The administrator turns it on per repository, from Sign-offs.",
+ "repo_sconosciuto": "\u274c Delminio doesn't know this repository ({remoto}): the check doesn't know what to look at, so it won't say green. In a CI the variable DELMINIO_FIRME_REPO gives the repository as it is connected to Delminio: \u201cdelminio signoffs ci\u201d writes it in the file. Run it again from a connected computer (if the file is already there, remove it first) and commit the new one.",
+ "scartata": " \u274c {commit} discarded: it is no longer signed \u2014 {soggetto}",
+ "manca_prove": "the zone's checks on this commit",
+ "manca_autore": "the author's signature",
+ "manca_persone": "the reviewer's review, with their agent, and their signature",
+ "parole_tolte": " \u274c {commit}: request {id}, which Delminio linked to this commit, is not in the message \u2014 the words were removed",
+ "ancora_rotta": "\u274c REWRITTEN: link {anello} is no longer the one commit {commit} anchored (anchors that don't match: {n}). The people who hold Delminio's database changed the chain after that commit",
+ "catena_ancorata": "intact, and anchored in {n} commits of this repository",
+ "catena_non_ancorata": "intact, but no commit in this copy of the repository anchors it: until the first one, the people who hold the database could rewrite it without it showing",
+ "gov_accese": "{quando} \u2014 {chi} switches sign-off on in the space",
+ "gov_spente": "{quando} \u2014 {chi} switches sign-off off in the space: nothing is recorded until it is switched back on",
+ "gov_repo_si": "{quando} \u2014 {chi} switches sign-off on in repository {repo}",
+ "gov_repo_no": "{quando} \u2014 {chi} switches sign-off off in repository {repo}: nothing is recorded there until it is switched back on",
+ "gov_chiave_si": "{quando} \u2014 {chi} creates the read key \u201c{etichetta}\u201d",
+ "gov_chiave_no": "{quando} \u2014 {chi} revokes the read key \u201c{etichetta}\u201d",
+ "gov_zona_nata": "{quando} \u2014 {chi} creates zone {codice}: {zona}",
+ "gov_zona_ritirata": "{quando} \u2014 {chi} withdraws zone {codice}",
+ "gov_zona_cambiata": "{quando} \u2014 {chi} changes zone {codice}: from {prima} to {dopo}",
+ "gov_zona_detta": "{dove}, {servono} signatures, reviewed by {chi}, checks `{comando}`",
+ "res_governo": "## Who governed sign-off",
+ "res_unito_da": "Into the main branch by {chi}, on {quando} (git says so: the person who merges doesn't go through Delminio)",
+ "res_git_dice": "Git says the author is {autore}: not verified, Delminio did not see this commit being made",
+ "res_non_in_catena": "\u274c this change is not in the chain: Delminio's database says things the chain does not",
+ "res_zona_dopo": "{quando}: zone {zone} was created after the commit, and applies to it too",
+ "res_prova_mancante": "Check {codice} `{comando}` \u2192 not run on this commit",
+ "res_firme_diverse": "\u274c Delminio's database shows different signatures ({motore}): the chain is what counts, and the database has been changed",
+ "res_scartata": "Discarded on {quando}: {perche}",
+ "res_parole_altrove": "The words are in commit {commit} of branch {ramo}, which this copy of the repository doesn't have: git fetch origin {ramo} (on GitHub they also stay in refs/pull/*/head)",
+ "copia_diversa": "\u274c {file} is not the beginning of this chain: link {anello} is different. The chain was rewritten after that copy",
+ "copia_uguale": "{file}: its {anelli} links are the beginning of this chain, unchanged",
+ "prova_non_accettata": "\u26a0\ufe0f the check for sign-off zone {codice} is new or changed, and nobody on this machine has accepted it yet \u2014 I didn't run it:\n {comando}\n Read it and, if you trust it, from your own terminal: delminio accept. Then: delminio signoffs checks\n Without the check having run, this commit can't be signed.",
+ "prova_fallita": "\u274c the check for sign-off zone {codice} did not pass on this commit (exit {uscita}): it can't be signed until it passes on a redone commit.\n {comando}",
+ "prova_passata": "\u2705 the check for sign-off zone {codice} passed on this commit.",
+ "prove_albero_diverso": "\u26a0\ufe0f the checks of the sign-off zone ({zone}) did not run: the files here are not the same as commit {commit}, and would test something else. When they are: delminio signoffs checks",
+ "prove_solo_testa": "Checks run on the commit that is here now (HEAD), with the files equal to the commit. For an earlier commit: git rebase --exec \"delminio signoffs checks\" <base>",
+ "prove_registrate": "The checks of {commit} are recorded: {esito}.",
+ "prove_nessuna": "No sign-off zone asks for checks on {commit}.",
+ "res_passkey": "with {persona}'s passkey \u201c{nome}\u201d, added on {quando} (confirmed with {come}): the device signature matches",
+ "res_passkey_non_torna": "\u274c the device signature does NOT match ({perche}): this sign-off wasn't given by {persona}'s passkey",
+ "res_passkey_cieca": "\u26a0\ufe0f the device signature can't be checked here: it needs Python's cryptography module or the openssl command",
+ "res_senza_passkey_prima": "signed in the app before sign-offs required a passkey",
+ "res_senza_passkey_dopo": "\u274c signed without a passkey after sign-offs require one: no device gave this sign-off",
+ "res_persona": "{persona} has been in the space since {quando}, {da}",
+ "res_persona_invitata": "invited by {chi}",
+ "res_persona_da_sempre": "from before who invites was recorded",
+ "res_passkey_mail": "email",
+ "res_passkey_password": "password",
+ "gov_passkey": "{quando} \u2014 from here every sign-off requires the passkey of the signer's device",
+ "gov_persona_entrata": "{quando} \u2014 {persona} joins the space as {ruolo}, invited by {chi}",
+ "gov_persona_spenta": "{quando} \u2014 {persona} leaves the space (account turned off)",
+ "gov_persona_riaccesa": "{quando} \u2014 {persona} is back in the space (account turned on)",
+ "gov_passkey_nuova": "{quando} \u2014 {persona} adds the passkey \u201c{nome}\u201d for {rp}, confirmed with {come}",
+ "gov_passkey_revocata": "{quando} \u2014 {chi} revokes {persona}'s passkey \u201c{nome}\u201d",
+ "perche_chiave": "the passkey isn't in the chain, or isn't the signer's",
+ "perche_revocata": "the passkey was revoked",
+ "perche_commit": "the device signed other commits",
+ "perche_sfida": "the device signed other words, another meaning or another person",
+ "perche_origine": "signed from another address",
+ "perche_persona": "without the person's fingerprint or PIN",
+ "perche_firma": "the cryptographic signature doesn't match the public key"
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+class Rifiuto(Exception):
+
+ def __init__(self, messaggio: str, codice: int=0):
+ super().__init__(messaggio)
+ self.codice = codice
+
+def forma(testo: str) -> str:
+ return '\n'.join((r.rstrip() for r in (testo or '').strip().splitlines())).strip()
+
+def impronta(testo: str) -> str:
+ return hashlib.sha256(forma(testo).encode('utf-8')).hexdigest()
+
+def verifica_catena(anelli: list) -> object:
+ prima = ''
+ for i, a in enumerate(anelli):
+ atteso = hashlib.sha256((prima + '\n' + a.get('tipo', '') + '\n' + a.get('contenuto', '')).encode('utf-8')).hexdigest()
+ if a.get('prima', '') != prima or a.get('impronta') != atteso:
+ return a.get('seq', i + 1)
+ prima = atteso
+ return None
+
+def git(*a: str) -> str:
+ r = subprocess.run(['git', *a], capture_output=True, text=True, encoding='utf-8', errors='replace')
+ return r.stdout.strip() if r.returncode == 0 else ''
+
+def chiedi(metodo: str, percorso: str, corpo=None, attesa: int=30) -> dict:
+ if not URL or not TOKEN:
+ raise Rifiuto(F('senza_motore'))
+ req = urllib.request.Request(URL + percorso, method=metodo, data=json.dumps(corpo).encode() if corpo is not None else None, headers={'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json'})
+ try:
+ return json.loads(urllib.request.urlopen(req, timeout=attesa).read())
+ except urllib.error.HTTPError as e:
+ try:
+ perche = json.loads(e.read()).get('error') or str(e)
+ except Exception:
+ perche = str(e)
+ raise Rifiuto(F('assenti') if e.code == 404 and perche == 'Not Found' else '❌ ' + perche, e.code) from None
+ except Exception as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
+_VUOTO = []
+
+def _albero_vuoto() -> str:
+ if not _VUOTO:
+ r = subprocess.run(['git', 'hash-object', '-t', 'tree', '--stdin'], input=b'', capture_output=True)
+ _VUOTO.append(r.stdout.decode().strip())
+ return _VUOTO[0]
+
+def _patch(da: str, a: str) -> str:
+ d = subprocess.run(['git', '-c', 'diff.noprefix=false', '-c', 'diff.mnemonicPrefix=false', 'diff', '--no-color', '--no-ext-diff', '--binary', da, a], capture_output=True)
+ if d.returncode or not d.stdout.strip():
+ return ''
+ p = subprocess.run(['git', 'patch-id', '--stable'], input=d.stdout, capture_output=True)
+ return (p.stdout.split() or [b''])[0].decode()
+
+def _genitori(h: str) -> list:
+ return git('rev-list', '--parents', '-n', '1', h).split()[1:]
+
+def _principale() -> str:
+ r = git('symbolic-ref', '-q', 'refs/remotes/origin/HEAD')
+ if r:
+ return r
+ for n in ('refs/remotes/origin/main', 'refs/remotes/origin/master'):
+ if git('rev-parse', '-q', '--verify', n):
+ return n
+ return ''
+
+def _ramo(h: str, nome: str='') -> dict | None:
+ principale = _principale()
+ base = git('merge-base', principale, h) if principale else ''
+ if not base:
+ return None
+ commit = git('rev-list', '--no-merges', '--reverse', f'{base}..{h}').split()[-RAMO_MAX:]
+ return {'nome': nome, 'patch': _patch(base, h) if commit else '', 'commit': commit}
+
+def _file(h: str) -> list:
+ file = git('diff-tree', '--no-commit-id', '--name-only', '-r', '-z', '--root', h).split('\x00')
+ return [f for f in file if f.strip()][:400]
+
+def segni(h: str) -> dict:
+ gen = _genitori(h)
+ return {'albero': git('rev-parse', h + '^{tree}'), 'patch': _patch(gen[0] if gen else _albero_vuoto(), h), 'file': _file(h)}
+
+def _parole_nel_messaggio(msg: str) -> tuple[dict, dict]:
+ dette = dict(re.findall('^Delminio-(?:Request|Richiesta): (\\d+) ([0-9a-f]{64})\\s*$', msg, re.M))
+ testi, corrente = ({}, None)
+ for r in msg.splitlines():
+ m = re.match('^\\[(\\d+)\\] ', r)
+ if m:
+ corrente = m.group(1)
+ testi[corrente] = []
+ elif corrente and (r == '>' or r.startswith('> ')):
+ testi[corrente].append(r[2:] if r.startswith('> ') else '')
+ else:
+ corrente = None
+ return (dette, {k: '\n'.join(v) for k, v in testi.items()})
+
+def _parole_rotte(h: str, msg: str, carta: dict | None) -> list:
+ dette, testi = _parole_nel_messaggio(msg)
+ registrate = {x['impronta']: x for x in (carta or {}).get('richieste') or []}
+ rotte = []
+ for rid, imp in dette.items():
+ if impronta(testi.get(rid) or '') != imp:
+ rotte.append((rid, 'non_tornano'))
+ elif carta is not None and imp not in registrate:
+ rotte.append((rid, 'ignote'))
+ scritte = set(dette.values())
+ for imp, x in registrate.items():
+ if imp not in scritte:
+ rotte.append((str(x.get('id') or '?'), 'tolte'))
+ return rotte
+
+def intervallo_di(a: list) -> str:
+ if a:
+ return a[0]
+ if git('rev-parse', '-q', '--verify', '@{upstream}'):
+ return '@{upstream}..HEAD'
+ p = _principale()
+ return f'{p}..HEAD' if p else 'HEAD~1..HEAD'
+
+def _merge_pulito(h: str) -> bool:
+ return len(_genitori(h)) > 1 and (not git('diff-tree', '--cc', '--no-commit-id', '--name-only', '-r', h))
+
+class SenzaFirme(Exception):
+
+ def __init__(self, sconosciuto: bool=False):
+ super().__init__()
+ self.sconosciuto = sconosciuto
+
+def leggi(intervallo: str, promuovi: bool=False) -> list:
+ r = subprocess.run(['git', 'rev-list', '--reverse', intervallo], capture_output=True, text=True, encoding='utf-8', errors='replace')
+ if r.returncode != 0:
+ raise Rifiuto(F('intervallo_illeggibile', intervallo=intervallo, errore=(r.stderr.strip().splitlines() or ['?'])[0][:200]))
+ voluti = r.stdout.split()[-COMMIT_MAX:]
+ if not voluti:
+ return []
+ remoto = _remoto()
+ puliti = {h for h in voluti if _merge_pulito(h)}
+ da_chiedere = [h for h in voluti if h not in puliti]
+ d = chiedi('POST', '/api/carta/commit', {'hash': da_chiedere or voluti[:1], 'remoto': remoto, 'promuovi': promuovi, 'segni': {h: {'file': _file(h)} for h in da_chiedere} if promuovi else {}})
+ if d.get('repo_senza_firme'):
+ raise SenzaFirme(bool(d.get('repo_sconosciuto')))
+ carte = d.get('carte') or {} if da_chiedere else {}
+ urgenze = dict(d.get('urgenze') or {}) if da_chiedere else {}
+ senza = [h for h in da_chiedere if carte.get(h) is None]
+ fuori = {}
+ if senza:
+ d2 = chiedi('POST', '/api/carta/commit', {'hash': senza, 'segni': {h: segni(h) for h in senza}, 'remoto': remoto, 'promuovi': promuovi})
+ fuori = d2.get('fuori') or {}
+ urgenze.update(d2.get('urgenze') or {})
+ out = []
+ for h in voluti:
+ msg = git('log', '-1', '--format=%B', h)
+ out.append({'hash': h, 'msg': msg, 'soggetto': (msg.strip().splitlines() or [''])[0][:70], 'pulito': h in puliti, 'carta': carte.get(h), 'fuori': fuori.get(h) or {}, 'urgenza': urgenze.get(h)})
+ return out
+PASSANO = ('firmata', 'libera', 'unita', 'pulito', 'urgente')
+
+def _mancano(k: dict) -> str:
+ nomi = {'prove': F('manca_prove'), 'autore': F('manca_autore'), 'persone': F('manca_persone')}
+ return ', '.join((nomi.get(m, m) for m in k.get('mancano') or []))
+
+def esito(c: dict) -> tuple[str, str]:
+ st, riga = _esito(c)
+ u = c.get('urgenza')
+ if u and st in ('da_firmare', 'zona', 'senza'):
+ return ('urgente', F('urgente', commit=c['hash'][:10], soggetto=c['soggetto'], da=u.get('da') or '?', quando=_quando(u.get('quando') or ''), perche=u.get('perche') or ''))
+ return (st, riga)
+
+def _esito(c: dict) -> tuple[str, str]:
+ corto, sogg = (c['hash'][:10], c['soggetto'])
+ if c['pulito']:
+ return ('pulito', F('merge_pulito', commit=corto, soggetto=sogg))
+ k = c['carta']
+ if k is not None:
+ st = k['stato']
+ if st == 'firmata':
+ return (st, F('firmata', commit=corto, soggetto=sogg))
+ if st == 'libera':
+ return (st, F('libera', commit=corto, soggetto=sogg))
+ if st == 'respinta':
+ return (st, F('respinta', commit=corto, soggetto=sogg))
+ if st == 'scartata':
+ return (st, F('scartata', commit=corto, soggetto=sogg))
+ return ('da_firmare', F('da_firmare', commit=corto, soggetto=sogg, manca=_mancano(k), zone=', '.join((z['codice'] for z in k.get('zone') or []))))
+ fu = c['fuori']
+ lg = fu.get('legame')
+ zone = ', '.join((z['codice'] for z in fu.get('zone') or []))
+ if lg:
+ ramo = lg.get('ramo') or '?'
+ if lg.get('mancano'):
+ return ('zona', F('unita_mancano', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg['mancano'])))
+ if lg.get('scoperte'):
+ return ('zona', F('unita_scoperta', commit=corto, soggetto=sogg, ramo=ramo, zone=', '.join((z['codice'] for z in lg['scoperte']))))
+ aperte = [x for x in lg.get('carte') or [] if x['stato'] not in ('firmata', 'libera')]
+ if lg.get('via') == 'ripreso':
+ return ('da_firmare', F('ripresa_da_firmare', commit=corto, soggetto=sogg, ramo=ramo)) if aperte else ('unita', F('ripresa', commit=corto, soggetto=sogg, ramo=ramo))
+ if aperte:
+ return ('da_firmare', F('unita_da_firmare', commit=corto, soggetto=sogg, ramo=ramo, n=len(aperte)))
+ return ('unita', F('unita', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg.get('carte') or [])))
+ if zone:
+ return ('zona', F('senza_in_zona', commit=corto, soggetto=sogg, zone=zone))
+ return ('senza', F('senza', commit=corto, soggetto=sogg))
+
+def _dice_rotta(h: str, rid: str, perche: str) -> str:
+ return {'non_tornano': F('parole_non_tornano', commit=h[:10], id=rid), 'tolte': F('parole_tolte', commit=h[:10], id=rid)}.get(perche) or F('parole_ignote', commit=h[:10], id=rid)
+
+def controlla(a: list) -> int:
+ intervallo = intervallo_di(a)
+ commit = leggi(intervallo, promuovi=True)
+ if not commit:
+ print(F('nessun_commit', intervallo=intervallo))
+ return 0
+ conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
+ for c in commit:
+ for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
+ print(_dice_rotta(c['hash'], rid, perche))
+ conti['rotte'] += 1
+ st, riga = esito(c)
+ print(riga)
+ if st in ('firmata', 'unita'):
+ conti['firmate'] += 1
+ elif st in ('libera', 'pulito'):
+ conti['libere'] += 1
+ elif st == 'urgente':
+ conti['urgenti'] += 1
+ elif st in ('senza', 'zona'):
+ conti['senza'] += 1
+ else:
+ conti['da_firmare'] += 1
+ print(F('esito', **conti))
+ return 1 if conti['da_firmare'] or conti['rotte'] or conti['senza'] else 0
+
+def _remoto() -> str:
+ remoto = os.environ.get('DELMINIO_FIRME_REPO', '').strip() or git('remote', 'get-url', 'origin')
+ return re.sub('^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@', '\\1', remoto)
+
+def _quando(iso: str) -> str:
+ return (iso or '')[:16].replace('T', ' ') + ' UTC' if iso else ''
+
+def _richieste(c: dict) -> list:
+ dette, testi = _parole_nel_messaggio(c['msg'])
+ return [(rid, testi.get(rid) or '', imp, impronta(testi.get(rid) or '') == imp) for rid, imp in dette.items()]
+
+def _nome_stato(st: str) -> str:
+ return {'firmata': F('stato_firmata'), 'unita': F('stato_unita'), 'libera': F('stato_libera'), 'pulito': F('stato_pulito'), 'senza': F('stato_senza'), 'da_firmare': F('stato_da_firmare'), 'respinta': F('stato_respinta'), 'zona': F('stato_zona')}.get(st, st)
+
+def _nome_firma(significato: str) -> str:
+ return {'autore': F('significato_autore'), 'revisione': F('significato_revisione'), 'respinta': F('significato_respinta')}.get(significato, significato)
+
+def descrizione(a: list) -> int:
+ intervallo = intervallo_di(a)
+ commit = [c for c in leggi(intervallo) if not c['pulito']]
+ if not commit:
+ print(F('nessun_commit', intervallo=intervallo))
+ return 0
+ out, viste = ([F('descr_parole'), ''], set())
+ for c in commit:
+ for rid, testo, imp, _torna in _richieste(c):
+ if imp in viste:
+ continue
+ viste.add(imp)
+ out += ['> ' + r if r else '>' for r in testo.split('\n')] + ['']
+ if not viste:
+ out += [F('descr_nessuna_parola'), '']
+ file, assistiti, zone, controlli, revisioni = (set(), set(), {}, {}, [])
+ for c in commit:
+ k = c['carta'] or {}
+ file |= set(k.get('file') or _file(c['hash']))
+ if k.get('assistito'):
+ assistiti.add(k['assistito'])
+ for z in k.get('zone') or c['fuori'].get('zone') or []:
+ zone[z['codice']] = z
+ for x in k.get('controlli') or []:
+ controlli[x['codice'], x['comando']] = x['uscita']
+ revisioni += k.get('revisioni') or []
+ stati = {}
+ for c in commit:
+ st, _ = esito(c)
+ stati[st] = stati.get(st, 0) + 1
+ out += [F('descr_fatti'), '', '- ' + F('descr_commit', n=len(commit), file=len(file))]
+ if assistiti:
+ out.append('- ' + F('descr_assistito', con=', '.join(sorted(assistiti))))
+ for z in zone.values():
+ chi = ', '.join(z['firme'].get('persone') or []) or F('descr_chiunque')
+ out.append('- ' + F('descr_zona', codice=z['codice'], cosa=z['cosa'], servono=z['firme']['servono'], chi=chi))
+ for (codice, comando), uscita in controlli.items():
+ out.append('- ' + F('descr_controllo', codice=codice, comando=comando, uscita=uscita))
+ for r in revisioni:
+ out.append('- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r)))
+ out.append('- ' + F('descr_stati', stati=', '.join((f'{_nome_stato(k)} {v}' for k, v in sorted(stati.items())))))
+ print('\n'.join(out))
+ return 0
+
+def _ancore() -> list:
+ out = []
+ for riga in git('log', '--all', '-n', '20000', '--format=%H%x09%(trailers:key=Delminio-Chain,valueonly,separator=%x2C)%x2C%(trailers:key=Delminio-Catena,valueonly,separator=%x2C)').splitlines():
+ h, _, valori = riga.partition('\t')
+ for v in valori.split(','):
+ m = re.fullmatch('\\s*(\\d+) ([0-9a-f]{64})\\s*', v)
+ if m:
+ out.append((h, int(m.group(1)), m.group(2)))
+ return out
+
+def _ancore_rotte(anelli: list) -> tuple:
+ per_seq = {a.get('seq'): a.get('impronta') for a in anelli}
+ ancore = _ancore()
+ return (len(ancore), [(h, seq) for h, seq, imp in ancore if per_seq.get(seq) != imp])
+
+def _dalla_catena(anelli: list) -> dict:
+ d = {'carte': {}, 'firme': {}, 'revisioni': {}, 'zone_dopo': {}, 'scartate': {}, 'prove': {}, 'governo': [], 'chiavi': {}, 'revocate': {}, 'persone': {}, 'regola': None}
+ for a in anelli:
+ try:
+ x = json.loads(a.get('contenuto') or '{}')
+ except ValueError:
+ continue
+ tipo = a.get('tipo')
+ if tipo == 'carta':
+ d['carte'][x.get('id')] = x
+ elif tipo == 'firma':
+ d['firme'].setdefault(x.get('carta'), []).append({**x, '_seq': a.get('seq')})
+ elif tipo == 'revisione':
+ d['revisioni'].setdefault(x.get('carta'), []).append(x)
+ elif tipo == 'zona_dopo':
+ d['zone_dopo'].setdefault(x.get('carta'), []).append(x)
+ elif tipo == 'scartata':
+ d['scartate'][x.get('carta')] = x
+ elif tipo == 'prove':
+ fatte = d['prove'].setdefault(x.get('carta'), {})
+ for p in x.get('controlli') or []:
+ fatte[p.get('codice')] = p
+ elif tipo in ('funzione', 'repo', 'zona', 'lettore', 'urgenza'):
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'chiave':
+ if x.get('creata'):
+ d['chiavi'][x.get('id')] = {**x, '_seq': a.get('seq')}
+ else:
+ d['revocate'].setdefault(x.get('id'), a.get('seq'))
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'persona':
+ if x.get('gesto') == 'entrata':
+ d['persone'].setdefault(x.get('persona'), x)
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'regola' and x.get('passkey') and (d['regola'] is None):
+ d['regola'] = a.get('seq')
+ d['governo'].append({'tipo': tipo, **x})
+ return d
+
+def _canonico(d: dict) -> str:
+ return json.dumps(d, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
+
+def _da_b64u(s: str) -> bytes:
+ s = str(s or '')
+ return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
+
+def _sfida(cosa: dict, nonce: str) -> str:
+ h = hashlib.sha256((_canonico(cosa) + '\n' + nonce).encode('utf-8')).digest()
+ return base64.urlsafe_b64encode(h).rstrip(b'=').decode()
+
+def _firma_valida(alg: int, pem: str, firma: bytes, dati: bytes):
+ try:
+ from cryptography.exceptions import InvalidSignature
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
+ k = serialization.load_pem_public_key(pem.encode())
+ try:
+ if isinstance(k, ec.EllipticCurvePublicKey):
+ k.verify(firma, dati, ec.ECDSA(hashes.SHA256()))
+ elif isinstance(k, rsa.RSAPublicKey):
+ k.verify(firma, dati, padding.PKCS1v15(), hashes.SHA256())
+ elif isinstance(k, ed25519.Ed25519PublicKey):
+ k.verify(firma, dati)
+ else:
+ return False
+ return True
+ except (InvalidSignature, ValueError):
+ return False
+ except ImportError:
+ pass
+ if not shutil.which('openssl'):
+ return None
+ with tempfile.TemporaryDirectory() as cartella:
+ percorsi = {}
+ for nome, contenuto in (('chiave.pem', pem.encode()), ('firma', firma), ('dati', dati)):
+ percorsi[nome] = os.path.join(cartella, nome)
+ with open(percorsi[nome], 'wb') as h:
+ h.write(contenuto)
+ if alg == -8:
+ cmd = ['openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', percorsi['chiave.pem'], '-rawin', '-in', percorsi['dati'], '-sigfile', percorsi['firma']]
+ else:
+ cmd = ['openssl', 'dgst', '-sha256', '-verify', percorsi['chiave.pem'], '-signature', percorsi['firma'], percorsi['dati']]
+ return subprocess.run(cmd, capture_output=True).returncode == 0
+
+def _origine_sua(origine: str, rp: str) -> bool:
+ from urllib.parse import urlparse
+ if origine.startswith('android:apk-key-hash:'):
+ return origine[len('android:apk-key-hash:'):] in APP_ANDROID
+ return urlparse(origine).hostname == rp
+
+def _dispositivo(f: dict, k: dict, fatti: dict) -> tuple:
+ d = f.get('dispositivo')
+ if not d:
+ if fatti['regola'] is not None and (f.get('_seq') or 0) > fatti['regola']:
+ return (F('res_senza_passkey_dopo'), False)
+ return (F('res_senza_passkey_prima'), True)
+ persona = f.get('persona') or '?'
+ chiave = fatti['chiavi'].get(d.get('chiave'))
+ perche = ''
+ if chiave is None or chiave.get('persona') != persona or (chiave.get('_seq') or 0) > (f.get('_seq') or 0):
+ perche = F('perche_chiave')
+ elif (rev := fatti['revocate'].get(d.get('chiave'))) is not None and rev < (f.get('_seq') or 0):
+ perche = F('perche_revocata')
+ elif {'id': k.get('id'), 'hash': k.get('hash')} not in (d.get('carte') or []):
+ perche = F('perche_commit')
+ if not perche:
+ cosa = {'persona': persona, 'significato': f.get('significato'), 'parole': f.get('parole') or '', 'carte': d.get('carte') or []}
+ try:
+ cdj = _da_b64u(d.get('client'))
+ cd, ad = (json.loads(cdj), _da_b64u(d.get('autenticatore')))
+ except ValueError:
+ cd, ad, cdj = ({}, b'', b'')
+ rp = chiave.get('rp') or ''
+ if cd.get('type') != 'webauthn.get' or cd.get('challenge') != _sfida(cosa, d.get('nonce') or ''):
+ perche = F('perche_sfida')
+ elif not _origine_sua(cd.get('origin') or '', rp) or ad[:32] != hashlib.sha256(rp.encode()).digest():
+ perche = F('perche_origine')
+ elif len(ad) < 37 or ad[32] & 5 != 5:
+ perche = F('perche_persona')
+ else:
+ esito = _firma_valida(int(chiave.get('alg') or 0), chiave.get('pem') or '', _da_b64u(d.get('firma')), ad + hashlib.sha256(cdj).digest())
+ if esito is None:
+ return (F('res_passkey_cieca'), False)
+ if not esito:
+ perche = F('perche_firma')
+ if perche:
+ return (F('res_passkey_non_torna', perche=perche, persona=persona), False)
+ come = F('res_passkey_mail') if chiave.get('provata') == 'mail' else F('res_passkey_password')
+ return (F('res_passkey', nome=chiave.get('nome') or '—', persona=persona, quando=_quando(chiave.get('quando')), come=come), True)
+
+def _chi_e_entrato(persona: str, fatti: dict) -> str:
+ e = fatti['persone'].get(persona) or {}
+ k = next((x for x in fatti['chiavi'].values() if x.get('persona') == persona), {})
+ quando = e.get('quando') or k.get('entrata') or ''
+ da = e.get('invitata_da') or k.get('invitata_da') or ''
+ if not quando:
+ return ''
+ return F('res_persona', persona=persona, quando=_quando(quando), da=F('res_persona_invitata', chi=da) if da else F('res_persona_da_sempre'))
+
+def _verifica(anelli: list) -> tuple:
+ rotto = verifica_catena(anelli)
+ if rotto is not None:
+ return (F('catena_rotta', anello=rotto), False)
+ n, rotte = _ancore_rotte(anelli)
+ if rotte:
+ h, seq = rotte[0]
+ return (F('ancora_rotta', commit=h[:10], anello=seq, n=len(rotte)), False)
+ return (F('catena_ancorata', n=n) if n else F('catena_non_ancorata'), True)
+
+def _governo(g: dict) -> str:
+ quando, chi = (_quando(g.get('quando')), g.get('chi') or '?')
+ if g['tipo'] == 'funzione':
+ if g.get('accesa'):
+ return F('gov_accese', quando=quando, chi=chi)
+ return F('gov_spente', quando=quando, chi=chi)
+ if g['tipo'] == 'repo':
+ if g.get('firme'):
+ return F('gov_repo_si', quando=quando, chi=chi, repo=g.get('repo') or '?')
+ return F('gov_repo_no', quando=quando, chi=chi, repo=g.get('repo') or '?')
+ if g['tipo'] == 'regola':
+ return F('gov_passkey', quando=quando)
+ if g['tipo'] == 'persona':
+ if g.get('gesto') == 'entrata':
+ return F('gov_persona_entrata', quando=quando, persona=g.get('persona') or '?', ruolo=g.get('ruolo') or '?', chi=g.get('invitata_da') or '?')
+ if g.get('gesto') == 'spenta':
+ return F('gov_persona_spenta', quando=quando, persona=g.get('persona') or '?')
+ return F('gov_persona_riaccesa', quando=quando, persona=g.get('persona') or '?')
+ if g['tipo'] == 'chiave':
+ if g.get('creata'):
+ come = F('res_passkey_mail') if g.get('provata') == 'mail' else F('res_passkey_password')
+ return F('gov_passkey_nuova', quando=quando, persona=g.get('persona') or '?', nome=g.get('nome') or '—', rp=g.get('rp') or '?', come=come)
+ return F('gov_passkey_revocata', quando=quando, chi=chi, persona=g.get('persona') or '?', nome=g.get('nome') or '—')
+ if g['tipo'] == 'urgenza':
+ return F('gov_urgenza', quando=quando, chi=chi, commit=(g.get('hash') or '?')[:10], repo=g.get('remoto') or '?', perche=g.get('perche') or '')
+ if g['tipo'] == 'lettore':
+ if g.get('creata'):
+ return F('gov_chiave_si', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
+ return F('gov_chiave_no', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
+ prima, dopo = (g.get('prima'), g.get('dopo'))
+
+ def detta(z):
+ f = z['firme']
+ return F('gov_zona_detta', dove=', '.join(z.get('dove') or []), servono=f.get('servono'), chi=', '.join(f.get('persone') or []) or F('descr_chiunque'), comando=z.get('comando') or '-')
+ if not prima:
+ return F('gov_zona_nata', quando=quando, chi=chi, codice=g.get('codice') or '?', zona=detta(dopo))
+ if not dopo:
+ return F('gov_zona_ritirata', quando=quando, chi=chi, codice=g.get('codice') or '?')
+ return F('gov_zona_cambiata', quando=quando, chi=chi, codice=g.get('codice') or '?', prima=detta(prima), dopo=detta(dopo))
+
+def _parole_dal_git(k: dict) -> list:
+ if subprocess.run(['git', 'cat-file', '-e', k['hash'] + '^{commit}'], capture_output=True).returncode:
+ return None
+ registrate = {x['impronta'] for x in k.get('richieste') or []}
+ return [(rid, testo, imp, torna, imp in registrate) for rid, testo, imp, torna in _richieste({'msg': git('log', '-1', '--format=%B', k['hash'])})]
+
+def _scrivi_parole(out: list, righe, rientro: str) -> None:
+ for rid, testo, imp, torna, *registrata in righe:
+ ok = torna and (not registrata or registrata[0])
+ out.append(rientro + '- ' + F('res_richiesta', id=rid, impronta=imp[:16], torna=F('res_torna') if ok else F('res_non_torna')))
+ out += [rientro + ' > ' + r if r else rientro + ' >' for r in testo.split('\n')]
+
+def resoconto(a: list) -> int:
+ intervallo = intervallo_di(a[:1])
+ dove = a[1] if len(a) > 1 else ''
+ commit = leggi(intervallo)
+ anelli = chiedi('GET', '/api/carta/catena').get('anelli') or []
+ verdetto, ok = _verifica(anelli)
+ fatti = _dalla_catena(anelli)
+ out = [F('res_titolo', remoto=_remoto() or '?', intervallo=intervallo), '', F('res_generato', quando=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC'), anelli=len(anelli), esito=verdetto), '']
+ for c in commit:
+ st, riga = esito(c)
+ out += [f"## {c['hash'][:10]} — {c['soggetto']}", '', '- ' + F('res_stato', riga=riga.strip())]
+ if c['pulito']:
+ out.append('')
+ continue
+ carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
+ if not c['carta'] and carte:
+ out.append('- ' + F('res_unita', n=len(carte), ramo=c['fuori']['legame'].get('ramo') or '?'))
+ ct = git('log', '-1', '--format=%ct', c['hash'])
+ quando = datetime.datetime.fromtimestamp(int(ct), datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC') if ct.isdigit() else ''
+ out.append('- ' + F('res_unito_da', chi=git('log', '-1', '--format=%cn', c['hash']), quando=quando))
+ if not carte:
+ out.append('- ' + F('res_git_dice', autore=git('log', '-1', '--format=%an <%ae>', c['hash'])))
+ for k in carte:
+ dentro = ' ' if not c['carta'] else ''
+ if not c['carta']:
+ out.append(f"- `{k['hash'][:10]}` {k.get('soggetto') or ''}")
+ dalla = fatti['carte'].get(k['id'])
+ if dalla is None:
+ out.append(dentro + '- ' + F('res_non_in_catena'))
+ ok = False
+ out.append(dentro + '- ' + F('res_autore', autore=(dalla or k)['autore'], con=(dalla or k).get('assistito') or F('res_a_mano'), quando=_quando((dalla or k).get('quando'))))
+ for z in (dalla or k).get('zone') or []:
+ out.append(dentro + '- ' + F('res_zona', codice=z['codice'], cosa=z['cosa'], servono=max(int(z['firme'].get('servono') or 0), 2)))
+ for zd in fatti['zone_dopo'].get(k['id']) or []:
+ out.append(dentro + '- ' + F('res_zona_dopo', quando=_quando(zd.get('quando')), zone=', '.join((z['codice'] for z in zd.get('zone') or []))))
+ dopo = fatti['prove'].get(k['id']) or {}
+ for p in (dalla or k).get('prove') or []:
+ fatta = next((x for x in [dopo.get(p['codice'])] + list((dalla or k).get('controlli') or []) if x and x['codice'] == p['codice'] and (x['comando'] == p['comando'])), None)
+ out.append(dentro + '- ' + (F('descr_controllo', codice=p['codice'], comando=p['comando'], uscita=fatta['uscita']) if fatta else F('res_prova_mancante', codice=p['codice'], comando=p['comando'])))
+ for r in fatti['revisioni'].get(k['id']) or []:
+ out.append(dentro + '- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r, k.get('autore', ''))))
+ firme_catena = fatti['firme'].get(k['id']) or []
+ for f in firme_catena:
+ out.append(dentro + '- ' + F('res_firma', persona=f['persona'], significato=_nome_firma(f['significato']), quando=_quando(f['quando']), parole=' — «' + f['parole'] + '»' if f.get('parole') else ''))
+ riga, buona = _dispositivo(f, k, fatti)
+ out.append(dentro + ' - ' + riga)
+ if (chi_e := _chi_e_entrato(f['persona'], fatti)):
+ out.append(dentro + ' - ' + chi_e)
+ ok = ok and buona
+ if {(f['persona'], f['significato']) for f in firme_catena} != {(f['persona'], f['significato']) for f in k.get('firme') or []}:
+ out.append(dentro + '- ' + F('res_firme_diverse', motore=', '.join((f"{f['persona']} ({_nome_firma(f['significato'])})" for f in k.get('firme') or [])) or '-'))
+ ok = False
+ if not firme_catena and (k.get('zone') or []):
+ out.append(dentro + '- ' + F('res_nessuna_firma'))
+ if (sc := fatti['scartate'].get(k['id'])):
+ out.append(dentro + '- ' + F('res_scartata', quando=_quando(sc.get('quando')), perche=sc.get('perche') or ''))
+ if not c['carta']:
+ parole = _parole_dal_git(k)
+ if parole is None:
+ out.append(dentro + '- ' + F('res_parole_altrove', commit=k['hash'][:10], ramo=k.get('ramo') or '?'))
+ else:
+ _scrivi_parole(out, parole, dentro)
+ if c['carta'] or not carte:
+ _scrivi_parole(out, _richieste(c), '')
+ for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
+ if perche == 'tolte':
+ out.append('- ' + _dice_rotta(c['hash'], rid, perche).strip())
+ file = (c['carta'] or {}).get('file') or _file(c['hash'])
+ out.append('- ' + F('res_file', n=len(file), elenco=', '.join((f'`{x}`' for x in file[:30])) + (f' (+{len(file) - 30})' if len(file) > 30 else '')))
+ out.append('')
+ if fatti['governo']:
+ out += [F('res_governo'), ''] + ['- ' + _governo(g) for g in fatti['governo']] + ['']
+ out += [F('res_come_verificare'), '']
+ testo = '\n'.join(out) + '\n'
+ if dove.lower().endswith(('.html', '.htm')):
+ conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
+ for c in commit:
+ st = esito(c)[0]
+ chiave = {'firmata': 'firmate', 'unita': 'firmate', 'libera': 'libere', 'pulito': 'libere', 'urgente': 'urgenti', 'senza': 'senza', 'zona': 'senza'}.get(st, 'da_firmare')
+ conti[chiave] += 1
+ testo = _html(testo, F('esito', **conti), ok)
+ elif dove.lower().endswith('.csv'):
+ testo = _csv(commit, fatti, ok)
+ if dove:
+ with open(dove, 'w', encoding='utf-8') as h:
+ h.write(testo)
+ print(F('res_scritto', file=dove, commit=len(commit)))
+ else:
+ sys.stdout.write(testo)
+ return 0 if ok else 1
+_STILE = '\n:root{--fondo:#f6f4ef;--carta:#fff;--testo:#1d1b18;--piano:#6b665c;--oro:#a77d1c;--verde:#2f7d4f;--rosso:#b3362c;--ambra:#b7791f}\n*{box-sizing:border-box}body{margin:0;background:var(--fondo);color:var(--testo);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}\nmain{max-width:980px;margin:0 auto;padding:32px 20px 60px}h1{font:600 26px/1.25 Georgia,serif;margin:0 0 6px}\n.sotto{color:var(--piano);margin:0 0 18px}.conto{background:var(--carta);border-radius:10px;padding:14px 18px;margin:0 0 22px;\nborder-left:5px solid var(--oro);font-weight:600}.catena-ok{border-left-color:var(--verde)}.catena-no{border-left-color:var(--rosso)}\nsection{background:var(--carta);border-radius:10px;padding:16px 20px;margin:0 0 14px;border-left:5px solid #ccc;box-shadow:0 1px 2px #0001}\nsection.ok{border-left-color:var(--verde)}section.no{border-left-color:var(--rosso)}section.urgente{border-left-color:var(--ambra)}\nh2{font:600 17px/1.3 Georgia,serif;margin:0 0 8px}ul{margin:4px 0;padding-left:20px}li{margin:2px 0}\ncode{font:13px ui-monospace,Menlo,Consolas,monospace;background:#efece4;padding:1px 5px;border-radius:4px}\nli.parole{list-style:none}blockquote{margin:2px 0 8px 0;padding:4px 12px;border-left:3px solid var(--oro);background:#faf7ef;font-style:italic}\n@media print{body{background:#fff}section,.conto{box-shadow:none;break-inside:avoid}main{padding:0}}\n'
+
+def _inline_html(t: str) -> str:
+ import html
+ pezzi = re.split('(`[^`]+`)', t)
+ out = []
+ for p in pezzi:
+ if len(p) > 1 and p.startswith('`') and p.endswith('`'):
+ out.append('<code>' + html.escape(p[1:-1]) + '</code>')
+ else:
+ out.append(re.sub('\\*\\*(.+?)\\*\\*', '<b>\\1</b>', html.escape(p)))
+ return ''.join(out)
+
+def _html(testo: str, conto: str, catena_ok: bool) -> str:
+ import html
+ righe, corpo, livello, sezione = (testo.splitlines(), [], 0, False)
+ titolo = next((r[2:] for r in righe if r.startswith('# ')), '')
+
+ def chiudi_liste(fino: int=0) -> None:
+ nonlocal livello
+ while livello > fino:
+ corpo.append('</ul>')
+ livello -= 1
+ for i, r in enumerate(righe):
+ if r.startswith('# '):
+ continue
+ if r.startswith('## '):
+ chiudi_liste()
+ if sezione:
+ corpo.append('</section>')
+ stato = next((x for x in righe[i + 1:i + 4] if x.startswith('- ')), '')
+ classe = 'ok' if '✅' in stato else 'urgente' if '⚡' in stato else 'no' if '❌' in stato else ''
+ corpo.append(f'<section class="{classe}"><h2>{_inline_html(r[3:])}</h2>')
+ sezione = True
+ continue
+ m = re.match('^( *)- (.*)$', r)
+ if m:
+ voluto = len(m.group(1)) // 2 + 1
+ if voluto > livello:
+ while livello < voluto:
+ corpo.append('<ul>')
+ livello += 1
+ else:
+ chiudi_liste(voluto)
+ corpo.append(f'<li>{_inline_html(m.group(2))}</li>')
+ continue
+ q = r.lstrip()
+ if q == '>' or q.startswith('> '):
+ corpo.append(f'<li class="parole"><blockquote>{_inline_html(q[2:])}</blockquote></li>' if livello else f'<blockquote>{_inline_html(q[2:])}</blockquote>')
+ continue
+ chiudi_liste()
+ if r.strip():
+ if sezione:
+ corpo.append('</section>')
+ sezione = False
+ corpo.append(f'<p class="sotto">{_inline_html(r)}</p>')
+ chiudi_liste()
+ if sezione:
+ corpo.append('</section>')
+ return f"""<!doctype html>\n<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{html.escape(titolo)}</title><style>{_STILE}</style></head><body><main><h1>{_inline_html(titolo)}</h1><div class="conto {('catena-ok' if catena_ok else 'catena-no')}">{_inline_html(conto)}</div>""" + '\n'.join(corpo) + '</main></body></html>\n'
+COLONNE_CSV = ('commit', 'committed_at', 'subject', 'status', 'author', 'agent', 'zones', 'checks', 'reviews', 'signoffs', 'signoff_devices_verified', 'urgent_by', 'urgent_at', 'urgent_reason', 'chain_verified')
+
+def _cella(x) -> str:
+ x = '' if x is None else str(x)
+ return "'" + x if x[:1] in ('=', '+', '-', '@', '\t', '\r') else x
+
+def _csv(commit: list, fatti: dict, catena_ok: bool) -> str:
+ import csv
+ import io
+ buf = io.StringIO()
+ w = csv.writer(buf, lineterminator='\n')
+ w.writerow(COLONNE_CSV)
+ for c in commit:
+ st, _riga = esito(c)
+ carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
+ autori, agenti, zone, prove, rev, firme, buone = ([], [], [], [], [], [], [])
+ for k in carte:
+ dalla = fatti['carte'].get(k['id']) or k
+ autori.append(dalla['autore'])
+ agenti.append(dalla.get('assistito') or '')
+ zone += [z['codice'] for z in dalla.get('zone') or []]
+ fatte = {**{x['codice']: x for x in dalla.get('controlli') or []}, **(fatti['prove'].get(k['id']) or {})}
+ prove += [f"{p['codice']}:{(fatte[p['codice']]['uscita'] if p['codice'] in fatte else '?')}" for p in dalla.get('prove') or []]
+ rev += [f"{r.get('persona') or '?'}:{r['esito']}" for r in fatti['revisioni'].get(k['id']) or []]
+ for f in fatti['firme'].get(k['id']) or []:
+ firme.append(f"{f['persona']}:{f['significato']}@{(f.get('quando') or '')[:19]}")
+ buone.append(_dispositivo(f, k, fatti)[1])
+ ct = git('log', '-1', '--format=%cI', c['hash'])
+ u = c.get('urgenza') or {}
+ w.writerow([_cella(x) for x in (c['hash'], ct, c['soggetto'], st, ' '.join(dict.fromkeys(autori)) or git('log', '-1', '--format=%ae', c['hash']), ' '.join(dict.fromkeys((a for a in agenti if a))), ' '.join(dict.fromkeys(zone)), ' '.join(dict.fromkeys(prove)), ' '.join(dict.fromkeys(rev)), ' '.join(firme), ('yes' if all(buone) else 'no') if buone else '', u.get('da') or '', (u.get('quando') or '')[:19], u.get('perche') or '', 'yes' if catena_ok else 'no')])
+ return buf.getvalue()
+
+def esporta(a: list) -> int:
+ d = chiedi('GET', '/api/carta/catena')
+ dove = a[0] if a else 'delminio-signoff-' + datetime.date.today().isoformat() + '.json'
+ with open(dove, 'w', encoding='utf-8') as h:
+ json.dump({'anelli': d.get('anelli') or []}, h, ensure_ascii=False, indent=1)
+ verdetto, ok = _verifica(d.get('anelli') or [])
+ print(F('esportata', file=dove, anelli=len(d.get('anelli') or []), esito=verdetto))
+ return 0 if ok else 1
+
+def catena(a: list) -> int:
+ if not a:
+ raise Rifiuto(F('uso', cmd=CMD))
+ anelli = json.load(open(a[0], encoding='utf-8')).get('anelli') or []
+ verdetto, ok = _verifica(anelli)
+ print(F('esportata', file=a[0], anelli=len(anelli), esito=verdetto))
+ if len(a) > 1:
+ vecchi = json.load(open(a[1], encoding='utf-8')).get('anelli') or []
+ per_seq = {x.get('seq'): x.get('impronta') for x in anelli}
+ diverso = next((x.get('seq') for x in vecchi if per_seq.get(x.get('seq')) != x.get('impronta')), None)
+ if verifica_catena(vecchi) is not None or diverso is not None:
+ print(F('copia_diversa', file=a[1], anello=diverso if diverso is not None else verifica_catena(vecchi)))
+ ok = False
+ else:
+ print(F('copia_uguale', file=a[1], anelli=len(vecchi)))
+ return 0 if ok else 1
+
+def _indipendente(r: dict, autore: str='') -> str:
+ if not r.get('indipendente'):
+ return F('stessa_sessione')
+ if autore and r.get('persona') == autore:
+ return F('dell_autore')
+ return F('indipendente_stesso_modello') if r.get('stesso_modello') else F('indipendente')
+
+def revisione(a: list) -> int:
+ if len(a) > 1:
+ a[1] = {'clean': 'pulita', 'findings': 'rilievi'}.get(a[1], a[1])
+ sess = os.environ.get('DELMINIO_SESSIONE', '')
+ if len(a) < 2 or a[1] not in ('pulita', 'rilievi'):
+ raise Rifiuto(F('uso', cmd=CMD))
+ if not sess:
+ raise Rifiuto(F('revisione_senza_sessione', cmd=CMD))
+ rilievi = int(a[2]) if len(a) > 2 and a[2].isdigit() else 0
+ voluti = git('rev-list', '--no-merges', '--reverse', a[0]).split() if '..' in a[0] else [git('rev-parse', a[0]) or a[0]]
+ for h in voluti[-COMMIT_MAX:]:
+ try:
+ r = chiedi('POST', '/api/carta/revisione', {'hash': h, 'esito': a[1], 'rilievi': rilievi, 'sessione': sess})
+ except Rifiuto as e:
+ print(f' {h[:10]} {e}', file=sys.stderr)
+ continue
+ ultima = (r.get('revisioni') or [{}])[-1]
+ print(F('revisione_dell_autore', commit=h[:10]) if ultima.get('persona') == r.get('autore') else F('revisione_registrata', commit=h[:10]))
+ return 0
+
+def _stato(nome: str) -> str:
+ return os.path.join(STATO, nome)
+
+def _richiesta(a: list) -> int:
+ sess = a[0] if a else ''
+ try:
+ testo = json.load(sys.stdin).get('prompt') or ''
+ except Exception:
+ return 0
+ if not sess or not isinstance(testo, str) or (not testo.strip()):
+ return 0
+ nascosto = F('nascosto')
+ for r in ('-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]+?-----END [A-Z ]*PRIVATE KEY-----', 'eyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{16,}', '\\bsk-[A-Za-z0-9_-]{20,}', '\\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{20,}', '\\bAKIA[0-9A-Z]{16}\\b', '\\bxox[abprs]-[A-Za-z0-9-]{10,}', '\\bAIza[0-9A-Za-z_-]{35}\\b', '\\bglpat-[A-Za-z0-9_-]{20,}'):
+ testo = re.sub(r, nascosto, testo)
+ testo = re.sub('(?i)\\b(password|passwd|pwd|secret|token|api[_-]?key)(\\s*[:=]\\s*)\\S+', '\\1\\2' + nascosto, testo)
+ testo = forma(testo)
+ if len(testo) > MASSIMO:
+ testo = forma(testo[:MASSIMO] + '\n' + F('troncata', n=len(testo) - MASSIMO))
+ voce = {'impronta': impronta(testo), 'testo': testo}
+ try:
+ r = chiedi('POST', '/api/carta/richiesta', {'sessione': sess, 'impronta': voce['impronta'], 'remoto': _remoto()}, attesa=3)
+ voce.update(id=r['id'], quando=r['quando'])
+ _segno(True)
+ except Rifiuto as e:
+ if e.codice == 409:
+ return 0
+ if e.codice in (403, 404):
+ _segno(False)
+ return 0
+ voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
+ except Exception:
+ voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
+ fd = os.open(_stato(f'carta-{sess}.jsonl'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384)
+ with os.fdopen(fd, 'a', encoding='utf-8') as h:
+ h.write(json.dumps(voce, ensure_ascii=False) + '\n')
+ return 0
+
+def _segno(accese: bool) -> None:
+ si, no = (_stato('carta'), _stato('carta-no'))
+ try:
+ open(si if accese else no, 'a').close()
+ os.remove(no if accese else si)
+ except OSError:
+ pass
+
+def _voci(sess: str) -> list:
+ voci = []
+ if not sess:
+ return voci
+ try:
+ for riga in open(_stato(f'carta-{sess}.jsonl'), encoding='utf-8'):
+ try:
+ voci.append(json.loads(riga))
+ except ValueError:
+ pass
+ except OSError:
+ pass
+ return voci
+
+def _messaggio(a: list) -> int:
+ file, sess, controlli_f = (a + ['', '', ''])[:3]
+ carta = json.loads(os.environ.get('DELMINIO_DURI') or '{}').get('carta') or {}
+ try:
+ controlli = json.load(open(controlli_f, encoding='utf-8'))
+ except (OSError, ValueError):
+ controlli = []
+ voci = _voci(sess)
+ blocco = []
+ if voci:
+ blocco.append(F('intestazione'))
+ for v in voci:
+ blocco.append(f"[{v.get('id') or '-'}] {_quando(v.get('quando'))}" + ('' if v.get('id') else ' · ' + F('non_registrata')))
+ blocco += ['> ' + r if r else '>' for r in v['testo'].split('\n')]
+ blocco.append('')
+ if controlli:
+ blocco.append(F('controlli'))
+ blocco += [f" {c['codice']} `{c['comando']}` → {c['uscita']}" for c in controlli]
+ blocco.append('')
+ testo = open(file, encoding='utf-8').read()
+ if blocco:
+ righe = testo.rstrip('\n').split('\n')
+ fine = len(righe)
+ while fine > 0 and righe[fine - 1].startswith('#'):
+ fine -= 1
+ inizio = fine
+ while inizio > 0 and righe[inizio - 1].strip():
+ inizio -= 1
+ trailer = inizio > 0 and all((re.match('^[A-Za-z0-9-]+: ', r) for r in righe[inizio:fine]))
+ punto = inizio if trailer else fine
+ nuove = righe[:punto] + ([''] if punto and righe[punto - 1].strip() else []) + blocco + righe[punto:]
+ with open(file, 'w', encoding='utf-8') as h:
+ h.write('\n'.join(nuove).rstrip('\n') + '\n')
+ aggiunti = ['Assisted-by: ' + carta['assistito']] if carta.get('assistito') else []
+ aggiunti += [f"Delminio-Request: {v['id']} {v['impronta']}" for v in voci if v.get('id')]
+ testa = carta.get('catena') or {}
+ if isinstance(testa.get('seq'), int) and re.fullmatch('[0-9a-f]{64}', str(testa.get('impronta') or '')):
+ aggiunti.append(f"Delminio-Chain: {testa['seq']} {testa['impronta']}")
+ gia = open(file, encoding='utf-8').read()
+ for t in aggiunti:
+ if t.replace('Delminio-Request:', 'Delminio-Richiesta:').replace('Delminio-Chain:', 'Delminio-Catena:') in gia.splitlines():
+ continue
+ subprocess.run(['git', 'interpret-trailers', '--in-place', '--if-exists', 'addIfDifferent', '--trailer', t, file], check=False)
+ with open(_stato(f"carta-incluse-{sess or 'mano'}.json"), 'w', encoding='utf-8') as h:
+ json.dump({'impronte': [v['impronta'] for v in voci], 'richieste': [v['id'] for v in voci if v.get('id')], 'controlli': controlli}, h)
+ zone = carta.get('zone') or []
+ if zone:
+ print(F('zona', zone=', '.join((f"{z['codice']} «{z['cosa']}»" for z in zone))), file=sys.stderr)
+ return 0
+
+def _commit(a: list) -> int:
+ sess = a[0] if a else ''
+ incl = _stato(f"carta-incluse-{sess or 'mano'}.json")
+ try:
+ d = json.load(open(incl, encoding='utf-8'))
+ except (OSError, ValueError):
+ return 0
+ try:
+ os.remove(incl)
+ except OSError:
+ pass
+ file = [f for f in git('show', '--name-only', '--format=', '-z', 'HEAD').split('\x00') if f.strip()]
+ controlli = list(d.get('controlli') or [])
+ fatte = _gira_prove(git('rev-parse', 'HEAD'), file)
+ if fatte:
+ gia = {x['codice'] for x in fatte}
+ controlli = [x for x in controlli if x.get('codice') not in gia] + fatte
+ dette = list(_parole_nel_messaggio(git('log', '-1', '--format=%B', 'HEAD'))[0])
+ richieste = list(dict.fromkeys([str(x) for x in d.get('richieste') or []] + dette))
+ print(json.dumps({'file': file[:400], 'richieste': [int(x) for x in richieste if x.isdigit()], 'controlli': controlli}))
+ scritte = set(d.get('impronte') or [])
+ if scritte and sess:
+ p = _stato(f'carta-{sess}.jsonl')
+ try:
+ resta = [r for r in open(p, encoding='utf-8') if json.loads(r).get('impronta') not in scritte]
+ with open(p, 'w', encoding='utf-8') as h:
+ h.writelines(resta)
+ except (OSError, ValueError):
+ pass
+ return 0
+
+def _segni(a: list) -> int:
+ h = git('rev-parse', a[0] if a else 'HEAD')
+ if not h:
+ return 0
+ sg = segni(h)
+ nome = git('rev-parse', '--abbrev-ref', 'HEAD')
+ print(json.dumps({'albero': sg['albero'], 'patch': sg['patch'], 'ramo': _ramo(h, '' if nome == 'HEAD' else nome)}))
+ return 0
+
+def _prove_chieste(h: str, file: list) -> list:
+ if not file or not URL or (not TOKEN):
+ return []
+ try:
+ r = chiedi('POST', '/api/lock/commit', {'staged': file, 'sessione': '', 'remoto': os.environ.get('DELMINIO_REMOTO') or _remoto()}, attesa=8)
+ except Rifiuto:
+ return []
+ return (r.get('carta') or {}).get('prove') or []
+
+def _gira_prove(h: str, file: list) -> list | None:
+ prove = _prove_chieste(h, file)
+ if not prove:
+ return []
+ uguale = git('rev-parse', 'HEAD') == h and subprocess.run(['git', 'diff', '--quiet', 'HEAD'], capture_output=True).returncode == 0 and (subprocess.run(['git', 'diff', '--cached', '--quiet', 'HEAD'], capture_output=True).returncode == 0)
+ if not uguale:
+ print(F('prove_albero_diverso', zone=', '.join((p['codice'] for p in prove)), commit=h[:10]), file=sys.stderr)
+ return None
+ try:
+ accettate = set(open(os.environ.get('DELMINIO_ACCETTATE') or git('rev-parse', '--git-path', 'delminio-guardie-accettate'), encoding='utf-8').read().split())
+ except OSError:
+ accettate = set()
+ radice = git('rev-parse', '--show-toplevel') or '.'
+ fatte = []
+ for p in prove:
+ if hashlib.sha256((p['codice'] + '\x00' + p['comando']).encode()).hexdigest() not in accettate:
+ print(F('prova_non_accettata', codice=p['codice'], comando=p['comando']), file=sys.stderr)
+ continue
+ try:
+ e = subprocess.run(p['comando'], shell=True, cwd=radice, capture_output=True, text=True, timeout=PROVE_TEMPO)
+ rc, uscita = (e.returncode, (e.stdout or '') + (e.stderr or ''))
+ except subprocess.TimeoutExpired:
+ rc, uscita = (124, '')
+ fatte.append({'codice': p['codice'], 'comando': p['comando'], 'uscita': rc})
+ if rc == 0:
+ print(F('prova_passata', codice=p['codice']), file=sys.stderr)
+ else:
+ print(F('prova_fallita', codice=p['codice'], comando=p['comando'], uscita=rc), file=sys.stderr)
+ for riga in uscita.strip().splitlines()[-15:]:
+ print(' ' + riga, file=sys.stderr)
+ return fatte
+
+def prove(a: list) -> int:
+ h = git('rev-parse', 'HEAD')
+ if a and git('rev-parse', a[0]) != h:
+ print(F('prove_solo_testa'))
+ return 2
+ fatte = _gira_prove(h, _file(h))
+ if fatte is None:
+ return 1
+ if not fatte:
+ print(F('prove_nessuna', commit=h[:10]))
+ return 0
+ chiedi('POST', '/api/carta/prove', {'hash': h, 'controlli': fatte})
+ esito = ', '.join((f"{x['codice']} → {x['uscita']}" for x in fatte))
+ print(F('prove_registrate', commit=h[:10], esito=esito))
+ return 0 if all((x['uscita'] == 0 for x in fatte)) else 1
+
+def _riscritti(a: list) -> int:
+ coppie = [r.split()[:2] for r in sys.stdin.read().splitlines() if len(r.split()) >= 2 and r.split()[0] != r.split()[1]]
+ sg = {}
+ if a and a[0] == 'segni':
+ for _vecchio, nuovo in coppie:
+ s = segni(nuovo)
+ sg[nuovo] = {'albero': s['albero'], 'patch': s['patch'], 'ramo': _ramo(nuovo)}
+ print(json.dumps({'vecchi': [v for v, _ in coppie], 'coppie': coppie, 'segni': sg}))
+ return 0
+_CI_GITHUB = '# {commento}\nname: delminio-firme\non:\n pull_request:\n push:\n branches: [{ramo}]\njobs:\n controlla:\n runs-on: {macchina}\n steps:\n - uses: actions/checkout@v7\n with:\n fetch-depth: 0\n - name: delminio-firme\n env:\n DELMINIO_URL: {url}\n DELMINIO_FIRME_REPO: {repo}\n DELMINIO_TOKEN: ${{{{ secrets.DELMINIO_FIRME }}}}\n BASE: ${{{{ github.base_ref }}}}\n PRIMA: ${{{{ github.event.before }}}}\n run: |\n curl -fsS -H "Authorization: Bearer $DELMINIO_TOKEN" "$DELMINIO_URL/static/kit/signoff-client" -o "$RUNNER_TEMP/signoff.py"\n if [ -n "$BASE" ]; then\n python3 "$RUNNER_TEMP/signoff.py" controlla "origin/$BASE..HEAD"\n else\n case "$PRIMA" in ""|0000000000000000000000000000000000000000) PRIMA=HEAD~1 ;; esac\n python3 "$RUNNER_TEMP/signoff.py" controlla "$PRIMA..HEAD"\n fi\n'
+_CI_GITLAB = 'delminio-firme:\n image: python:3\n variables:\n GIT_DEPTH: "0"\n DELMINIO_URL: {url}\n DELMINIO_FIRME_REPO: {repo}\n rules:\n - if: $CI_PIPELINE_SOURCE == "merge_request_event"\n script:\n - git fetch -q origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"\n - curl -fsS -H "Authorization: Bearer $DELMINIO_FIRME" "$DELMINIO_URL/static/kit/signoff-client" -o signoff.py\n - DELMINIO_TOKEN="$DELMINIO_FIRME" python3 signoff.py controlla "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME..HEAD"\n'
+
+def _servizio(a: list) -> str:
+ if a and a[0] in ('github', 'forgejo', 'gitea', 'gitlab'):
+ return 'forgejo' if a[0] == 'gitea' else a[0]
+ host = re.sub('^[a-z][a-z0-9+.-]*://', '', _remoto().lower()).split('@')[-1].split('/')[0].split(':')[0]
+ if host == 'github.com' or host.endswith('.github.com'):
+ return 'github'
+ if 'gitlab' in host:
+ return 'gitlab'
+ if os.path.isdir('.forgejo') or os.path.isdir('.gitea'):
+ return 'forgejo'
+ return ''
+
+def _da_fuori(url: str) -> bool:
+ import ipaddress
+ import urllib.parse
+ host = (urllib.parse.urlparse(url).hostname or '').lower()
+ if not host or host == 'localhost' or '.' not in host or host.endswith(('.local', '.lan', '.home.arpa', '.internal')):
+ return False
+ try:
+ ip = ipaddress.ip_address(host)
+ return not (ip.is_private or ip.is_loopback or ip.is_link_local)
+ except ValueError:
+ return True
+
+def ci(a: list) -> int:
+ servizio = _servizio(a)
+ if not servizio:
+ print(F('ci_quale'))
+ return 2
+ url = os.environ.get('DELMINIO_URL', '').rstrip('/')
+ radice = git('rev-parse', '--show-toplevel') or '.'
+ repo = json.dumps(_remoto())
+ ramo = (git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD') or 'origin/main').split('/', 1)[-1]
+ if not _da_fuori(url):
+ print(F('ci_dentro_casa', url=url))
+ if servizio == 'gitlab':
+ print(F('ci_gitlab', file='.gitlab-ci.yml'))
+ print(_CI_GITLAB.format(url=url, repo=repo))
+ print(F('ci_gitlab_passi'))
+ return 0
+ cartella = '.github' if servizio == 'github' else '.forgejo'
+ file = os.path.join(cartella, 'workflows', 'delminio-firme.yml')
+ testo = _CI_GITHUB.format(commento=F('ci_commento'), ramo=ramo, url=url, repo=repo, macchina='ubuntu-latest' if servizio == 'github' else 'docker')
+ dove = os.path.join(radice, file)
+ if os.path.exists(dove):
+ if open(dove, encoding='utf-8').read() == testo:
+ print(F('ci_gia_pronto', file=file))
+ else:
+ print(F('ci_esiste_diverso', file=file))
+ else:
+ os.makedirs(os.path.dirname(dove), exist_ok=True)
+ with open(dove, 'w', encoding='utf-8') as f:
+ f.write(testo)
+ print(F('ci_scritto', file=file))
+ if servizio == 'github':
+ return _github(ramo)
+ print(F('ci_passi_forgejo', ramo=ramo))
+ return 0
+_CONTROLLO = 'controlla'
+
+def _gh(*a: str, entrata: str | None=None) -> tuple[int, str]:
+ try:
+ r = subprocess.run(['gh', *a], capture_output=True, text=True, input=entrata, timeout=60)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return (1, str(e))
+ return (r.returncode, (r.stdout if r.returncode == 0 else r.stderr or r.stdout).strip())
+
+def _gh_errore(out: str) -> str:
+ righe = [r for r in out.splitlines() if r.strip()]
+ return righe[-1][:300] if righe else '?'
+
+def _github(ramo: str) -> int:
+ if not shutil.which('gh'):
+ print(F('ci_gh_manca'))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ if _gh('auth', 'status')[0] != 0:
+ print(F('ci_gh_non_collegato'))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ rc, out = _gh('repo', 'view', '--json', 'nameWithOwner,viewerPermission')
+ try:
+ r = json.loads(out) if rc == 0 else {}
+ except ValueError:
+ r = {}
+ nwo = r.get('nameWithOwner') or ''
+ if not nwo:
+ print(F('ci_gh_quale_repo', errore=_gh_errore(out)))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ if r.get('viewerPermission') != 'ADMIN':
+ print(F('ci_gh_permessi', repo=nwo))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ regola = _gh_regola(nwo, ramo)
+ segreto = _gh_segreto(nwo)
+ return 0 if regola and segreto else 1
+
+def _gh_regola(nwo: str, ramo: str) -> bool:
+ base = f'repos/{nwo}/branches/{ramo}/protection'
+ rc, out = _gh('api', base)
+ if rc != 0 and 'HTTP 404' not in out:
+ print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ if rc != 0:
+ corpo = {'required_status_checks': {'strict': False, 'contexts': [_CONTROLLO]}, 'enforce_admins': True, 'required_pull_request_reviews': None, 'restrictions': None}
+ rc, out = _gh('api', '-X', 'PUT', base, '--input', '-', entrata=json.dumps(corpo))
+ if rc != 0:
+ print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ else:
+ d = json.loads(out)
+ rsc = d.get('required_status_checks') or {}
+ if _CONTROLLO not in _gh_controlli(rsc):
+ print(F('ci_gh_regole_altre', ramo=ramo))
+ rc, out = _gh('api', '-X', 'POST', base + '/required_status_checks/contexts', '--input', '-', entrata=json.dumps([_CONTROLLO])) if rsc else _gh('api', '-X', 'PATCH', base + '/required_status_checks', '--input', '-', entrata=json.dumps({'strict': False, 'contexts': [_CONTROLLO]}))
+ if rc != 0:
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ if not (d.get('enforce_admins') or {}).get('enabled'):
+ rc, out = _gh('api', '-X', 'POST', base + '/enforce_admins')
+ if rc != 0:
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ rc, out = _gh('api', base)
+ d = json.loads(out) if rc == 0 else {}
+ if _CONTROLLO in _gh_controlli(d.get('required_status_checks') or {}) and (d.get('enforce_admins') or {}).get('enabled'):
+ print(F('ci_gh_regola_ok', ramo=ramo, repo=nwo))
+ return True
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out) if rc else '?'))
+ return False
+
+def _gh_controlli(rsc: dict) -> set:
+ return set(rsc.get('contexts') or []) | {c.get('context') for c in rsc.get('checks') or [] if isinstance(c, dict)}
+
+def _gh_segreto(nwo: str) -> bool:
+ rc, out = _gh('secret', 'list', '--repo', nwo, '--json', 'name')
+ try:
+ nomi = {x.get('name') for x in json.loads(out)} if rc == 0 else set()
+ except ValueError:
+ nomi = set()
+ if rc != 0:
+ print(F('ci_gh_segreto_no', errore=_gh_errore(out)))
+ return False
+ if 'DELMINIO_FIRME' in nomi:
+ print(F('ci_gh_segreto_c_e', repo=nwo))
+ return True
+ imposta = ['gh', 'secret', 'set', 'DELMINIO_FIRME', '--repo', nwo]
+ cmd = ' '.join(imposta)
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
+ print(F('ci_gh_segreto_tu', cmd=cmd))
+ return False
+ print(F('ci_gh_segreto_incolla'))
+ esito = subprocess.run(imposta).returncode
+ if esito != 0:
+ print(F('ci_gh_segreto_no', errore=esito))
+ return False
+ print(F('ci_gh_segreto_fatto', repo=nwo))
+ return True
+VERBI = {'controlla': controlla, 'descrizione': descrizione, 'resoconto': resoconto, 'esporta': esporta, 'catena': catena, 'revisione': revisione, 'prove': prove, 'ci': ci, '_richiesta': _richiesta, '_messaggio': _messaggio, '_commit': _commit, '_segni': _segni, '_riscritti': _riscritti}
+
+def main(argv: list) -> int:
+ verbo = argv[0] if argv else 'controlla'
+ verbo = COMANDI['carta'].get(verbo, verbo)
+ fai = VERBI.get(verbo)
+ if fai is None:
+ print(F('uso', cmd=CMD), file=sys.stderr if verbo not in ('-h', '--help') else sys.stdout)
+ return 0 if verbo in ('-h', '--help') else 2
+ try:
+ return fai(argv[1:])
+ except SenzaFirme as e:
+ if e.sconosciuto:
+ print(F('repo_sconosciuto', remoto=_remoto()), file=sys.stderr)
+ return 2
+ print(F('repo_senza_firme'))
+ return 0
+ except Rifiuto as e:
+ if verbo.startswith('_'):
+ return 0
+ print(str(e), file=sys.stderr)
+ return 2
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/en/ganci-git-client b/kit/en/ganci-git-client
new file mode 100644
index 0000000..2daf4af
--- /dev/null
+++ b/kit/en/ganci-git-client
@@ -0,0 +1,224 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+e_un_close() { grep -qE "^($P_CLOSE) S[0-9]+" <<<"$1"; }
+case "${1:-}" in
+ commit-msg)
+ file="${2:-}"; [ -f "$file" ] || exit 0
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ if [ -n "$sess" ] && ! { f=$(_segno_pubblico) && [ -e "$f" ]; }; then
+ git interpret-trailers --in-place --if-exists doNothing --trailer "Delminio-Sessione: $sess" "$file" 2>/dev/null || true
+ fi
+ staged=$(git diff --cached --name-only -z | python3 -c 'import json,sys; print(json.dumps({"staged": [x for x in sys.stdin.read().split("\0") if x], "sessione": sys.argv[1], "remoto": sys.argv[2]}))' "$sess" "$(_remoto)")
+ controlli_f="$STATO/carta-controlli-$$"; rm -f "$controlli_f"
+ if duri=$(chiedi POST /api/lock/commit "$staged"); then
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ DELMINIO_DURI="$duri" DELMINIO_U="$URL" DELMINIO_T="$TOKEN" DELMINIO_ACCETTATE="$(accettate_file)" \
+ DELMINIO_CONTROLLI_F="$controlli_f" python3 - "$nome" <<'DURI' || exit 1
+import hashlib, json, os, subprocess, sys, urllib.error, urllib.request
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+duri = json.loads(os.environ["DELMINIO_DURI"]).get("duri") or []
+radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip() or "."
+try:
+ accettate = set(open(os.environ["DELMINIO_ACCETTATE"], encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+fermo = False
+fatti = [] # B923: il comando e la sua uscita, le prove nella carta del commit
+GUARDIA_SECONDI = 120 # il controllo del commit ha il suo tempo: ci girano anche i test
+
+
+def manda(percorso, dati):
+ req = urllib.request.Request(os.environ["DELMINIO_U"] + percorso, data=json.dumps(dati).encode(), method="POST",
+ headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"],
+ "Content-Type": "application/json"})
+ return json.loads(urllib.request.urlopen(req, timeout=8).read())
+
+
+def cieco(lk, motivo):
+ """B938 — il controllo non ha detto niente: si conta, e il commit si ferma come per una
+ violazione (le guardie del commit sono tutte di decisioni che bloccano)."""
+ try:
+ manda("/api/lock/cieco", {"codice": lk["codice"], "motivo": motivo, "sessione": sys.argv[1],
+ "comando": lk["comando"]})
+ except Exception:
+ pass # un conto non ferma un commit
+for lk in duri:
+ impronta = hashlib.sha256((lk["codice"] + "\0" + lk["comando"]).encode()).hexdigest()
+ if impronta not in accettate:
+ print(F("guardia_non_accettata", codice=lk["codice"], comando=lk["comando"]), file=sys.stderr)
+ continue
+ fermo_cieco = ""
+ try:
+ p = subprocess.run(lk["comando"], shell=True, cwd=radice, capture_output=True, text=True,
+ timeout=GUARDIA_SECONDI)
+ rc, uscita = p.returncode, p.stdout + p.stderr
+ except subprocess.TimeoutExpired:
+ rc, uscita = 124, F("controllo_lento_breve", comando=lk["comando"], secondi=GUARDIA_SECONDI)
+ fermo_cieco = F("guardia_lento_fermo", codice=lk["codice"], comando=lk["comando"], secondi=GUARDIA_SECONDI)
+ cieco(lk, "lento")
+ except OSError:
+ rc, uscita = 127, ""
+ fatti.append({"codice": lk["codice"], "comando": lk["comando"], "uscita": rc})
+ if rc == 0:
+ continue
+ if rc in (126, 127) and not fermo_cieco:
+ uscita = F("controllo_non_parte_breve", comando=lk["comando"])
+ fermo_cieco = F("guardia_non_parte_fermo", codice=lk["codice"], comando=lk["comando"])
+ cieco(lk, "non_parte")
+ try:
+ r = manda("/api/lock/violazione", {"codice": lk["codice"], "uscita": uscita[-4000:], "sessione": sys.argv[1]})
+ except urllib.error.HTTPError as e:
+ print(F("lock_grida_errore", codice=lk["codice"], codice_http=e.code), file=sys.stderr)
+ r = {"esito": "avviso"}
+ except Exception:
+ print(F("lock_grida_muto", codice=lk["codice"]), file=sys.stderr)
+ r = {"esito": "avviso"}
+ if fermo_cieco and r.get("esito") == "ferma":
+ print(fermo_cieco, file=sys.stderr)
+ print(("❌ " if r.get("esito") == "ferma" else "⚠️ ") + (r.get("messaggio") or lk["cosa"]), file=sys.stderr)
+ if fermo_cieco and r.get("esito") != "ferma":
+ print(" " + uscita.strip(), file=sys.stderr)
+ elif not fermo_cieco:
+ print(F("guardia_dice"), file=sys.stderr)
+ for riga in uscita.strip().splitlines()[-15:]:
+ print(" " + riga, file=sys.stderr)
+ fermo = fermo or r.get("esito") == "ferma"
+with open(os.environ["DELMINIO_CONTROLLI_F"], "w", encoding="utf-8") as h:
+ json.dump(fatti, h)
+sys.exit(1 if fermo else 0)
+DURI
+ case "$duri" in
+ *'"carta":{'*)
+ : > "$STATO/carta"; rm -f "$STATO/carta-no"
+ [ -f "$(dirname "$0")/firme.py" ] && DELMINIO_DURI="$duri" DELMINIO_STATO="$STATO" \
+ python3 "$(dirname "$0")/firme.py" _messaggio "$file" "$sess" "$controlli_f" || true ;;
+ esac
+ rm -f "$controlli_f"
+ else
+ _f "$M_lock_duri_sono" perche "$(perche_no)" >&2
+ fi
+ soggetto=$(grep -v '^#' "$file" | sed -n '/[^[:space:]]/{p;q;}')
+ e_un_close "$soggetto" || exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ corpo=$(python3 - "$file" "$nome" <<'GIUDIZIO'
+import json, subprocess, sys
+messaggio = open(sys.argv[1], encoding="utf-8").read()
+staged = subprocess.run(["git", "diff", "--cached", "--name-only"],
+ capture_output=True, text=True).stdout.split()
+head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
+print(json.dumps({"messaggio": messaggio, "staged": staged, "sessione": sys.argv[2], "head": head}))
+GIUDIZIO
+)
+ if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/giudica "$corpo"); then
+ _f "$M_chiusura_passa_senza" perche "$(perche_no)" >&2
+ exit 0
+ fi
+ DELMINIO_VERDETTO="$r" python3 - "$file" <<'VERDETTO'
+import json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+r = json.loads(os.environ["DELMINIO_VERDETTO"])
+if not r.get("ok", True):
+ print(F("chiusura_rifiutata"), file=sys.stderr)
+ for m in r.get("motivi", []):
+ print(f" • {m}", file=sys.stderr)
+ sys.exit(1)
+perche = {"P_TRAILER_TORNATA": F("perche_tornata"), "P_TRAILER_MEMORIA": F("perche_memoria")}
+for k, v in (r.get("aggiungi") or {}).items():
+ subprocess.run(["git", "interpret-trailers", "--in-place", "--trailer", f"{k}: {v}", sys.argv[1]], check=True)
+ spiega = next((x for var, x in perche.items() if k.lower() in os.environ[var].lower().split("|")), "")
+ print(F("aggiunge_trailer_perche", trailer=f"{k}: {v}", perche=spiega) if spiega
+ else F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
+for a in r.get("avvisi") or []:
+ print(f"⚠️ {a}", file=sys.stderr)
+VERDETTO
+ ;;
+ post-rewrite)
+ coppie=$(awk '$1 != $2 { print $1, $2 }')
+ [ -n "$coppie" ] || exit 0
+ segni=""; [ -f "$STATO/carta" ] && segni=segni
+ f="$STATO/riscritti-$$"; printf '%s\n' "$coppie" > "$f"
+ _staccato bash "$0" post-rewrite-dopo "$f" "$(_remoto)" $segni >/dev/null 2>&1 < /dev/null &
+ ;;
+ post-rewrite-dopo)
+ f=$2
+ corpo=$(python3 "$(dirname "$0")/firme.py" _riscritti ${4:-} < "$f" 2>/dev/null \
+ | python3 -c 'import json, sys; d = json.load(sys.stdin); d["remoto"] = sys.argv[1]; print(json.dumps(d))' "$3") \
+ && chiedi POST /api/repo/riscritti "$corpo" >/dev/null 2>&1
+ rm -f "$f"
+ ;;
+ post-commit)
+ soggetto=$(git log -1 --format=%s 2>/dev/null)
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ righe=""
+ [ -z "$(git rev-parse -q --verify HEAD^2 2>/dev/null)" ] && righe=$(git show --numstat --format= --diff-filter=d HEAD 2>/dev/null)
+ carta=""
+ [ -f "$(dirname "$0")/firme.py" ] && carta=$(DELMINIO_STATO="$STATO" DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" \
+ DELMINIO_ACCETTATE="$(accettate_file)" DELMINIO_REMOTO="$(_remoto)" python3 "$(dirname "$0")/firme.py" _commit "$sess")
+ corpo=$(DELMINIO_RIGHE="$righe" DELMINIO_CARTA="$carta" python3 -c '
+import json, os, sys
+d = dict(zip(("remoto", "hash", "sessione", "soggetto"), sys.argv[1:]))
+file = []
+for r in os.environ.get("DELMINIO_RIGHE", "").splitlines():
+ p = r.split("\t", 2)
+ if len(p) == 3 and p[0].isdigit() and p[1].isdigit():
+ file.append((p[2].split("/")[:-1], int(p[0]) + int(p[1])))
+for livelli in (3, 2, 1):
+ righe = {}
+ for cartelle, n in file:
+ k = "/".join(cartelle[:livelli]) or "."
+ righe[k] = righe.get(k, 0) + n
+ if len(righe) <= 150:
+ break
+d["righe"] = righe
+if os.environ.get("DELMINIO_CARTA"):
+ d["carta"] = json.loads(os.environ["DELMINIO_CARTA"])
+print(json.dumps(d))' \
+ "$(_remoto)" "$(git rev-parse HEAD 2>/dev/null)" "$sess" "$soggetto")
+ clone=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd)
+ testa=$(git rev-parse HEAD 2>/dev/null)
+ f="$STATO/commit-$testa.json"; printf '%s' "$corpo" > "$f"
+ _staccato bash "$0" post-commit-dopo "$f" "$testa" "$clone" ${carta:+carta} >/dev/null 2>&1 < /dev/null &
+ e_un_close "$soggetto" || exit 0
+ n=$(printf '%s' "$soggetto" | grep -oE 'S[0-9]+' | head -1)
+ corpo=$(python3 - "$n" "$(_remoto)" <<'CLOSE'
+import json, os, subprocess, sys
+def g(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+remoto = sys.argv[2]
+repo = os.path.basename(remoto.rstrip("/"))[:-4] if remoto.rstrip("/").endswith(".git") \
+ else os.path.basename(remoto.rstrip("/"))
+if not repo:
+ repo = os.path.basename(os.path.dirname(os.path.abspath(g("rev-parse", "--git-common-dir"))))
+print(json.dumps({"sessione": sys.argv[1], "close": True, "commit": {
+ "hash": g("rev-parse", "--short=10", "HEAD"), "remoto": remoto, "repo": repo,
+ "tornata": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)"),
+ "audit": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly)").strip(),
+ "testo": g("--no-replace-objects", "log", "-1", "--format=%B")}}))
+CLOSE
+)
+ if r=$(chiedi POST /api/canale/sessioni/chiudi "$corpo"); then
+ _f "$M_delminio_chiusa_chi" n "$n" >&2
+ m=$(printf '%s' "$r" | python3 -c 'import json,sys
+try: print(", ".join(json.load(sys.stdin).get("mollate") or []))
+except Exception: print("")')
+ [ -z "$m" ] || _f "$M_opere_avevi_mano" m "$m" >&2
+ else
+ _f "$M_risultera_morta_senza" perche "$(perche_no)" n "$n" >&2
+ fi
+ ;;
+ post-commit-dopo)
+ f=$2; corpo=$(cat "$f" 2>/dev/null); rm -f "$f"
+ [ -n "$corpo" ] || exit 0
+ if [ "${5:-}" = carta ]; then
+ segni=$(python3 "$(dirname "$0")/firme.py" _segni "$3" 2>/dev/null) && con=$(DELMINIO_SEGNI="$segni" python3 -c '
+import json, os, sys
+d = json.loads(sys.stdin.read())
+d["carta"].update(json.loads(os.environ["DELMINIO_SEGNI"]))
+print(json.dumps(d))' <<<"$corpo") && corpo=$con
+ fi
+ r=$(chiedi POST /api/repo/commit "$corpo" 2>/dev/null) \
+ && riaggancia "$(printf '%s' "$r" | campo versione)" "$4" presto
+ ;;
+esac
diff --git a/kit/en/lanciatori-client b/kit/en/lanciatori-client
new file mode 100644
index 0000000..f063f42
--- /dev/null
+++ b/kit/en/lanciatori-client
@@ -0,0 +1,230 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+sonda_sandbox_codex() {
+ python3 - "${DELMINIO_CLI:-codex}" <<'CODEX_SONDA'
+import subprocess, sys
+if sys.platform != 'linux':
+ sys.exit(0)
+cli = sys.argv[1]
+try:
+ r = subprocess.run([cli, 'sandbox', '-c', 'sandbox_mode="read-only"', '--', 'true'],
+ capture_output=True, text=True, timeout=5)
+ print('ok' if r.returncode == 0 else 'rotta')
+except (OSError, subprocess.TimeoutExpired):
+ print('non_verificata')
+CODEX_SONDA
+}
+porta_del_lancio() { # porta_del_lancio <rotta> <frase per chi resta senza agente>
+ local v p
+ f="$STATO/sistema-$$.txt"
+ codice=$( (umask 077; curl -sS -m 30 -G -o "$f" -w '%{http_code}' -K <(_chiave "$TOKEN") \
+ --data-urlencode "ordine=$porta" --data-urlencode "modello=${DELMINIO_MODELLO:-}" \
+ "$URL/api/porte/$1") 2>/dev/null || true)
+ if [ "$codice" != 200 ] || [ ! -s "$f" ]; then
+ _f "$M_delminio_dato_system" url "$URL" porta "$porta" codice "${codice:-000}" >&2
+ [ -s "$f" ] && { head -c 400 "$f" >&2; echo >&2; }
+ echo "$2" >&2
+ rm -f "$f"
+ exit 1
+ fi
+ for v in "$STATO"/sistema-*.txt "$STATO"/qwen-posta-*.jsonl "$STATO"/qwen-mcp-*.json; do
+ [ -e "$v" ] || continue
+ p=${v##*/sistema-}; p=${p##*/qwen-posta-}; p=${p##*/qwen-mcp-}; p=${p%.txt}; p=${p%.jsonl}; p=${p%.json}
+ [ "$p" = "$$" ] || kill -0 "$p" 2>/dev/null || rm -f "$v"
+ done
+}
+case "${1:-}" in
+ claude)
+ shift
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ rotta=nascita; [ "${DELMINIO_NASCITA:-intera}" = porta ] && rotta=sistema
+ porta_del_lancio "$rotta" "$M_agente_parte_meta"
+ export DELMINIO_SISTEMA=1
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/plugin.py" ] \
+ && [ "$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" \
+ = "$(git -C "$(dirname "$0")/.." rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" ]; then
+ DELMINIO_CLAUDE="${DELMINIO_CLI:-claude}" python3 "$(dirname "$0")/plugin.py" claude-al-lancio \
+ "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" >/dev/null 2>&1 || true
+ fi
+ squadra=()
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ while IFS= read -r x; do [ -n "$x" ] && squadra+=("$x"); done < <(python3 "$(dirname "$0")/squadra.py" \
+ lancio claude "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" 2>/dev/null)
+ fi
+ exec "${DELMINIO_CLI:-claude}" --system-prompt-file "$f" ${squadra[@]+"${squadra[@]}"} "$@"
+ ;;
+ codex)
+ shift
+ export DELMINIO_CLI_NOME=codex
+ DELMINIO_SANDBOX_LINUX=$(sonda_sandbox_codex); export DELMINIO_SANDBOX_LINUX
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ [ "${DELMINIO_NASCITA:-intera}" = porta ] && {
+ echo "$M_ruolo_sola_sua" >&2
+ exit 1; }
+ porta_del_lancio nascita "$M_agente_parte_meta_2"
+ export DELMINIO_SISTEMA=1
+ mcp=()
+ if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || [ -z "${CODEX_HOME:-}" ] \
+ || ! DELMINIO_CODEX="${DELMINIO_CLI:-codex}" python3 "$(dirname "$0")/plugin.py" codex "$CODEX_HOME" >/dev/null 2>&1; then
+ [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && echo "$M_codex_senza_plugin" >&2
+ export DELMINIO_MCP_TOKEN="$TOKEN"
+ mcp=(-c "mcp_servers.memoria.url=\"$URL/mcp\"" -c 'mcp_servers.memoria.bearer_token_env_var="DELMINIO_MCP_TOKEN"'
+ -c 'mcp_servers.memoria.env_http_headers={"X-Delminio-Modello"="DELMINIO_MODELLO"}'
+ -c 'mcp_servers.memoria.tools.delminio.approval_mode="approve"'
+ -c 'mcp_servers.memoria.tools.delminio_write.approval_mode="approve"')
+ fi
+ squadra=()
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -n "${CODEX_HOME:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ while IFS= read -r x; do [ -n "$x" ] && squadra+=("$x"); done < <(python3 "$(dirname "$0")/squadra.py" \
+ lancio codex "$CODEX_HOME" 2>/dev/null)
+ fi
+ case "${DELMINIO_TETTO_USCITE:-}" in ''|*[!0-9]*) DELMINIO_TETTO_USCITE=25000 ;; esac
+ tetto=(-c "tool_output_token_limit=$DELMINIO_TETTO_USCITE")
+ case "${DELMINIO_MIE:-}" in *"|tool_output_token_limit|"*) tetto=() ;; esac
+ gesto=(-c check_for_update_on_startup=false ${mcp[@]+"${mcp[@]}"} ${squadra[@]+"${squadra[@]}"}
+ ${tetto[@]+"${tetto[@]}"}
+ -c "model_instructions_file=\"$f\"")
+ tutti=()
+ while IFS= read -r -d '' x; do tutti+=("$x"); done < <(python3 -c 'import sys
+n = int(sys.argv[1]); g, a = sys.argv[2:2 + n], sys.argv[2 + n:]
+CON_VALORE = {"-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a",
+ "--ask-for-approval", "-C", "--cd", "--add-dir", "-i", "--image", "--enable", "--disable",
+ "--remote", "--remote-auth-token-env", "--local-provider"}
+i, sub = 0, None
+while i < len(a):
+ x = a[i]
+ if x == "--": break
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-"): i += 1; continue
+ if x in ("exec", "e", "review", "resume", "fork"): sub = i
+ break
+if sub is None:
+ out = g + a
+else:
+ resto, c, j = [], [], 0
+ while j < sub:
+ if a[j] in ("-c", "--config") and j + 1 < sub: c += a[j:j + 2]; j += 2
+ else: resto.append(a[j]); j += 1
+ out = resto + [a[sub]] + g + c + a[sub + 1:]
+sys.stdout.write("".join(x + "\0" for x in out))' "${#gesto[@]}" "${gesto[@]}" "$@")
+ [ ${#tutti[@]} -ge ${#gesto[@]} ] || { echo "$M_delminio_argomenti_codex" >&2; exit 1; }
+ exec "${DELMINIO_CLI:-codex}" --no-daemon "${tutti[@]}"
+ ;;
+ app-codex)
+ shift
+ p="$(dirname "$0")/plugin.py"
+ case "${1:-}" in
+ "") python3 "$p" app-codex; e=$?
+ case $e in 0) echo "$M_app_codex_fatto" ;; 4) echo "$M_app_codex_assente" ;; *) echo "$M_app_codex_non_riuscito" >&2; exit 1 ;; esac ;;
+ via) python3 "$p" app-codex via && echo "$M_app_codex_tolto" ;;
+ no) python3 "$p" app-codex no && echo "$M_app_codex_no" ;;
+ stato) python3 "$p" app-codex stato ;;
+ *) echo "$M_app_codex_uso" >&2; exit 2 ;;
+ esac
+ ;;
+ qwen)
+ shift
+ export DELMINIO_CLI_NOME=qwen
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ rotta=nascita; mcp_token="$TOKEN"
+ if [ "${DELMINIO_NASCITA:-intera}" = porta ]; then
+ rotta=sistema
+ mcp_token=$(python3 -c 'import json,sys
+s = json.load(open(sys.argv[1]))["mcpServers"]
+print((s.get("memoria-ruolo") or s["delminio-ruolo"])["headers"]["Authorization"].split(" ", 1)[1])' \
+ "${DELMINIO_CANALE_RUOLO:-}" 2>/dev/null) || mcp_token=""
+ [ -n "$mcp_token" ] || { echo "$M_ruolo_sola_sua_2" >&2; exit 1; }
+ fi
+ posta="$STATO/qwen-posta-$$.jsonl"
+ (umask 077; : > "$posta")
+ porta_del_lancio "$rotta" "$M_agente_parte_meta_2"
+ export QWEN_SYSTEM_MD="$f" DELMINIO_SISTEMA=1 DELMINIO_QWEN_POSTA="$posta"
+ radice=$(git rev-parse --show-toplevel 2>/dev/null || true)
+ if [ -n "$radice" ] && [ ! -e "$radice/.qwen/.env" ]; then
+ (umask 077; mkdir -p "$radice/.qwen" && echo "# delminio" > "$radice/.qwen/.env") 2>/dev/null || true
+ escludi=$(cd "$radice" && git rev-parse --path-format=absolute --git-path info/exclude 2>/dev/null) || escludi=""
+ [ -n "$escludi" ] && { grep -qxF ".qwen/.env" "$escludi" 2>/dev/null || echo ".qwen/.env" >> "$escludi"; } 2>/dev/null
+ fi
+ if [ -n "${QWEN_HOME:-}" ] && [ -f "$(dirname "$0")/plugin.py" ]; then
+ if [ "$rotta" = nascita ] && [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] \
+ && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" python3 "$(dirname "$0")/plugin.py" qwen "$QWEN_HOME" >/dev/null 2>&1; then
+ exec "${DELMINIO_CLI:-qwen}" --input-file "$posta" "$@"
+ fi
+ DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" python3 "$(dirname "$0")/plugin.py" qwen-via "$QWEN_HOME" >/dev/null 2>&1 || true
+ [ "$rotta" = nascita ] && [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && echo "$M_qwen_senza_plugin" >&2
+ fi
+ mcp="$STATO/qwen-mcp-$$.json"
+ (umask 077; DELMINIO_T="$mcp_token" python3 -c 'import json,os,sys
+print(json.dumps({"mcpServers": {"memoria": {
+ "command": "bash", "args": [sys.argv[2], "ponte-mcp", sys.argv[1]],
+ "env": {"DELMINIO_T": os.environ["DELMINIO_T"],
+ "DELMINIO_MODELLO": os.environ.get("DELMINIO_MODELLO", "")},
+ "timeout": 60000, "trust": True, "alwaysLoadTools": True}}}))' "$URL" "$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" > "$mcp") && [ -s "$mcp" ] \
+ || { echo "$M_delminio_mcp_qwen" >&2; rm -f "$mcp"; exit 1; }
+ exec "${DELMINIO_CLI:-qwen}" --input-file "$posta" --mcp-config "$mcp" "$@"
+ ;;
+ opencode)
+ shift
+ export DELMINIO_CLI_NOME=opencode
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ porta_del_lancio nascita "$M_agente_parte_meta_2"
+ export DELMINIO_SISTEMA=1
+ radice=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
+ [ -f "$radice/.opencode/plugins/delminio.js" ] || python3 "$(dirname "$0")/plugin.py" opencode "$radice" >/dev/null 2>&1 || true
+ squadra="{}"
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ squadra=$(python3 "$(dirname "$0")/squadra.py" lancio opencode "$radice" 2>/dev/null) || squadra="{}"
+ fi
+ gratuito=""
+ if [ -n "${DELMINIO_OPENCODE_GRATUITO:-}" ]; then
+ ricordo="${XDG_STATE_HOME:-$HOME/.local/state}/delminio/opencode-gratuito"
+ oggi=$(date +%F)
+ giorno=""; [ -f "$ricordo" ] && read -r giorno gratuito < "$ricordo"
+ if [ "${giorno:-}" != "$oggi" ] || [ -z "$gratuito" ]; then
+ echo "$M_opencode_gratuito_scelgo" >&2
+ gratuito=$(python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" modello-gratuito "${DELMINIO_CLI:-$(command -v opencode)}" 2>/dev/null) || gratuito=""
+ if [ -n "$gratuito" ]; then
+ mkdir -p "$(dirname "$ricordo")" && printf '%s %s\n' "$oggi" "$gratuito" > "$ricordo"
+ else
+ _f "$M_opencode_gratuito_nessuno" nome "$DELMINIO_OPENCODE_GRATUITO" >&2
+ fi
+ fi
+ fi
+ OPENCODE_CONFIG_CONTENT=$(DELMINIO_F="$f" DELMINIO_OPENCODE_SQUADRA="$squadra" DELMINIO_GRATUITO_SCELTO="$gratuito" python3 -c 'import json, os
+c = json.loads(os.environ.get("DELMINIO_OPENCODE_CONFIG") or "{}")
+if os.environ.get("DELMINIO_GRATUITO_SCELTO"):
+ c["model"] = os.environ["DELMINIO_GRATUITO_SCELTO"]
+porta = "{file:" + os.environ["DELMINIO_F"] + "}"
+c.setdefault("agents", {}).setdefault("build", {})["system"] = porta
+def unisci(a, b):
+ for k, v in b.items():
+ if isinstance(v, dict) and isinstance(a.get(k), dict):
+ unisci(a[k], v)
+ elif isinstance(v, list) and isinstance(a.get(k), list):
+ a[k] += [x for x in v if x not in a[k]]
+ else:
+ a.setdefault(k, v)
+try:
+ sq = json.loads(os.environ.get("DELMINIO_OPENCODE_SQUADRA") or "{}")
+except ValueError:
+ sq = {}
+if isinstance(sq, dict):
+ unisci(c, sq)
+print(json.dumps(c))') || { echo "$M_agente_parte_meta_2" >&2; exit 1; }
+ export OPENCODE_CONFIG_CONTENT OPENCODE_DISABLE_AUTOUPDATE=1 OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1
+ exec "${DELMINIO_CLI:-opencode}" --standalone "$@"
+ ;;
+esac
diff --git a/kit/en/opencode-client.js b/kit/en/opencode-client.js
new file mode 100644
index 0000000..cb9cf6a
--- /dev/null
+++ b/kit/en/opencode-client.js
@@ -0,0 +1,174 @@
+/*! © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite. */
+import{spawn}from"node:child_process"
+import fs from"node:fs"
+import os from"node:os"
+import path from"node:path"
+const RITI={"apertura":"apertura","chiusura":"chiusura"}
+const FRASI={"apertura":"","chiusura":"","ciclo":"","fermo":"","v1":"","permesso":"","ammessi":""}
+const nome_server=(ha)=>{const c=ha("memoria")
+return c&&!JSON.stringify(c.command??"").includes("ponte")?"delminio":"memoria"}
+const file=(a)=>a.path
+const COME_CLAUDE={read:["Read",(a)=>({file_path:file(a)})],edit:["Edit",(a)=>({file_path:file(a),old_string:a.oldString,new_string:a.newString})],write:["Write",(a)=>({file_path:file(a),content:a.content})],shell:["Bash",(a)=>({command:a.command,description:a.description})],grep:["Grep",(a)=>({pattern:a.pattern,path:a.path})],glob:["Glob",(a)=>({pattern:a.pattern,path:a.path})],apply_patch:["apply_patch",(a)=>({command:a.patchText})],patch:["apply_patch",(a)=>({command:a.patchText})],opencode_worktree_remove:["Bash",(a)=>({command:`git worktree remove ${a.force ? "--force " : ""}${JSON.stringify(a.directory || "")}`})],opencode_worktree_create:["Bash",(a)=>({command:`git worktree add ${JSON.stringify(a.name || "")}`})],}
+const conMotivo=(errore)=>{const b=errore?.error
+if(b?._tag!=="Permission.BlockedError"||!Array.isArray(b.rules))return null
+const tocca=(schema,testo)=>new RegExp("^"+String(schema).split("*").map((x)=>x.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","s").test(String(testo))
+const regola=(r)=>b.rules.findLast((x)=>tocca(x.action,b.permission)&&tocca(x.resource,r))
+const tutti=(b.resources||[]).map(String)
+const vietati=tutti.filter((r)=>regola(r)?.effect!=="allow")
+const ammessi=[...new Set(b.rules.filter((x)=>x.action===b.permission&&x.effect==="allow"&&x.resource!=="*").map((x)=>x.resource))].slice(0,20)
+const elenco=(xs)=>xs.map((x)=>`«${x}»`).join(", ")
+return FRASI.permesso.replace("{permesso}",b.permission||"").replace("{rifiutati}",elenco(vietati.length?vietati:tutti)).replace("{ammessi}",ammessi.length?FRASI.ammessi.replace("{elenco}",elenco(ammessi)):"")}
+const PRIMA=[["tocco",["Write","Edit","apply_patch"]],["guardia",["Read","Grep","Glob","Write","Edit","apply_patch","Bash"]],["condiviso",["Bash"]],["gesto",["*"]],]
+const nucleo=(radice,{ferma=null}={})=>{const gancio=path.join(radice,".claude","delminio.sh")
+if(!fs.existsSync(gancio))return null
+const ancore=new Map()
+const ancora=(id)=>{if(!id)return""
+let a=ancore.get(id)
+if(!a||a.exitCode!==null||a.signalCode){a=spawn("bash",["-c",'while kill -0 "$1" 2>/dev/null; do sleep 20; done',"delminio-opencode",String(process.pid)],{stdio:"ignore"})
+a.on("error",()=>{})
+ancore.set(id,a)}
+return a.pid?String(a.pid):""}
+const chiudi=()=>{for(const a of ancore.values())try{a.kill()}catch{}ancore.clear()}
+const gesto=(nome,evento,argomenti=[],tempo=30000,id=evento?.session_id)=>new Promise((fine)=>{let out="",err="",finito=false
+const pid=ancora(id)
+const p=spawn("bash",[gancio,nome,...argomenti],{cwd:radice,env:{...process.env,DELMINIO_CLI_NOME:"opencode",...(pid?{DELMINIO_CLI_PID:pid}:{})},stdio:["pipe","pipe","pipe"],})
+const basta=(codice)=>{if(!finito){finito=true;clearTimeout(t);fine({codice,out,err})}}
+const t=tempo?setTimeout(()=>{p.kill("SIGTERM");basta(124)},tempo):null
+p.stdout.on("data",(d)=>(out+=d))
+p.stderr.on("data",(d)=>(err+=d))
+p.on("error",()=>basta(127))
+p.on("close",(c)=>basta(c??1))
+p.stdin.on("error",()=>{})
+p.stdin.end(evento===undefined?"":JSON.stringify(evento))})
+const contesto=(r)=>{try{return JSON.parse(r.out).hookSpecificOutput?.additionalContext||""}catch{return""}}
+const rifiuto=(r)=>{if(r.codice===2)return r.err.trim()||"Delminio"
+try{const h=JSON.parse(r.out).hookSpecificOutput||{}
+if(h.permissionDecision==="deny")return h.permissionDecisionReason||"Delminio"}catch{}
+return""}
+const sessioni=new Map()
+const di=(id)=>{if(!sessioni.has(id))sessioni.set(id,{detti:{}});return sessioni.get(id)}
+const CICLO=12
+const FERMATE=3
+const ripete=(s,firma)=>{const uguali=(s.storia||[]).filter((x)=>x.firma===firma)
+return uguali.length>=2&&uguali[uguali.length-1].esito===uguali[uguali.length-2].esito}
+const evento=(id,nome,piu={})=>({session_id:id,hook_event_name:nome,cwd:radice,...piu})
+const nasci=(id,origine)=>{const s=di(id)
+if(s.figlia)return Promise.resolve("")
+if(!s.nascita)
+s.nascita=gesto("apertura",evento(id,"SessionStart",{source:origine}),[],90000).then((r)=>{s.apertura=contesto(r)
+return s.apertura})
+return s.nascita}
+const messaggio=async(id,testo)=>{const s=di(id)
+s.fermate=0
+await nasci(id,"resume")
+const e=evento(id,"UserPromptSubmit",{prompt:testo,model:s.modello||"",coda:(s.coda||"").slice(-1200)})
+const no=rifiuto(await gesto("segreto",e,[],5000))
+if(no)return{no}
+const aggiunte=[]
+for(const[nome,tempo]of[["umano",30000],["memorie",5000]]){const c=contesto(await gesto(nome,e,[],tempo))
+if(c)aggiunte.push(c)}
+return{aggiunte}}
+const rito=async(canonico,dopo,id)=>{dopo=(dopo||"").replace(/^"(.*)"$/s,"$1").trim()
+const r=canonico==="apertura"?await gesto("prompt",undefined,[],30000,id):await gesto("chiusura",undefined,dopo?[dopo]:[],30000,id)
+if(canonico==="chiusura")pulisci(id,true)
+return[r.out.trim(),canonico==="apertura"?dopo:""].filter((x)=>x).join("\n\n")}
+const primaDelTool=async(id,strumento,a,chiamata)=>{const voce=COME_CLAUDE[strumento]||[strumento,(x)=>x]
+const[nome,argomenti]=voce
+a=a||{}
+const firma=`${strumento} ${JSON.stringify(a)}`
+const st=di(id)
+st.firme={...(st.firme||{}),[chiamata]:firma}
+if(ripete(st,firma)){st.fermate=(st.fermate||0)+1
+if(ferma&&st.fermate>=FERMATE){st.fermate=0
+setTimeout(()=>Promise.resolve(ferma(id)).catch(()=>{}),0)
+throw new Error(FRASI.fermo||FRASI.ciclo||"Delminio")}
+throw new Error(FRASI.ciclo||"Delminio")}
+const cwd=nome==="Bash"&&a.workdir?path.resolve(radice,a.workdir):radice
+const e={...evento(id,"PreToolUse"),cwd,tool_name:nome,tool_input:argomenti(a)}
+const s=di(id)
+if(s.figlia)e.agent_id=id
+const detti=[]
+for(const[g,quali]of PRIMA){if(!quali.includes("*")&&!quali.includes(nome))continue
+const r=await gesto(g,e,[],10000)
+const no=rifiuto(r)
+if(no)throw new Error(no)
+const c=contesto(r)
+if(c)detti.push(c)}
+if(detti.length)s.detti[chiamata]=detti.join("\n\n")}
+const db=path.join(process.env.XDG_DATA_HOME||path.join(os.homedir(),".local","share"),"opencode","opencode.db")
+const consumi=(id,nome)=>{if(di(id).figlia||!fs.existsSync(db))return
+gesto(nome,{...evento(id,nome==="consumi"?"Stop":"PostToolUse"),transcript_path:db,cli:"opencode"},[],10000,id)}
+const dopoIlTool=async(id,strumento,chiamata,esito)=>{const s=di(id)
+const firma=(s.firme||{})[chiamata]
+if(firma!==undefined){delete s.firme[chiamata]
+s.storia=[...(s.storia||[]),{firma,esito:String(esito??"").slice(0,4000)}].slice(-CICLO)}
+const prima=s.detti[chiamata]
+delete s.detti[chiamata]
+const e={...evento(id,"PostToolUse"),tool_name:strumento}
+const posta=s.figlia?"":contesto(await gesto("volo",e,[],10000))
+consumi(id,"consumi-tool")
+return[prima,posta].filter((x)=>x).join("\n\n")}
+const conversazioni=process.env.DELMINIO_CONVERSAZIONI||""
+const pulisci=(id,finita)=>{if(conversazioni&&!di(id).figlia)gesto("pulizia",evento(id,finita?"SessionEnd":"Stop"),[],10000,id)}
+const aspetta=(id,sveglia)=>{const s=di(id)
+consumi(id,"consumi")
+pulisci(id,conversazioni==="subito")
+if(s.figlia||s.attesa)return
+s.attesa=gesto("attesa-codex",undefined,[ancora(id)||String(process.pid),id],0,id).then((r)=>{s.attesa=null
+const avviso=r.out.trim()
+if(r.codice===0&&avviso)return Promise.resolve(sveglia(avviso)).catch(()=>{})})}
+return{gancio,di,nasci,messaggio,rito,primaDelTool,dopoIlTool,aspetta,chiudi}}
+const v1=async({client,directory,worktree})=>{const radice=worktree||directory
+if(!fs.existsSync(path.join(radice,".claude","delminio.sh")))return{}
+const detto=new Set()
+const avviso=FRASI.v1||"Delminio: OpenCode 1 is not supported. opencode upgrade --major"
+const mostra=()=>client.tui.showToast({body:{message:avviso,variant:"error",duration:30000}}).catch(()=>{})
+mostra()
+return{"chat.message":async(input,output)=>{if(detto.has(input.sessionID))return
+detto.add(input.sessionID)
+mostra()
+const accanto=(output.parts||[]).find((x)=>x.type==="text")
+if(accanto)
+output.parts.push({id:`${accanto.id}z`,sessionID:accanto.sessionID,messageID:accanto.messageID,type:"text",text:avviso,synthetic:true})},}}
+const v2=async(ctx)=>{const n=nucleo(ctx.location?.directory||ctx.location?.project?.directory||"",{ferma:(id)=>ctx.session.interrupt({sessionID:id}),})
+if(!n)return
+const agente=Boolean(process.env.DELMINIO_PORTA)
+if(agente)
+await ctx.skill.transform((ed)=>{for(const x of ed.list())if(String(x?.path||"").startsWith("skill://"))ed.remove(x.id)}).catch(()=>{})
+const figlia=async(id)=>{const s=n.di(id)
+if(s.figlia===undefined){try{const info=await ctx.session.get({sessionID:id})
+s.figlia=Boolean(info?.parentID??info?.data?.parentID)}catch{s.figlia=false}}
+return s.figlia}
+await ctx.mcp.transform((mcp)=>{const k=nome_server((x)=>mcp.get(x))
+if(!mcp.get(k))
+mcp.set(k,{type:"local",command:["bash",n.gancio,"ponte"],codemode:false,timeout:{execution:120000}})})
+await ctx.command.transform((comandi)=>{for(const[nome,canonico]of Object.entries(RITI))
+comandi.add({name:nome,description:FRASI[canonico]||nome,execute:async({sessionID,prompt})=>{const testo=await n.rito(canonico,prompt?.text,sessionID)
+if(testo)await ctx.session.prompt({sessionID,text:testo})},})})
+await ctx.session.hook("prompt",async(ev)=>{const testo=(ev.prompt?.text||"").trim()
+if(!testo||(await figlia(ev.sessionID)))return
+const r=await n.messaggio(ev.sessionID,testo)
+if(r.no){ev.prompt.text=r.no;return}
+for(const c of r.aggiunte)
+await ctx.session.synthetic({sessionID:ev.sessionID,text:c,delivery:"steer",resume:false})})
+await ctx.session.hook("context",async(ev)=>{if(agente){if(ev.tools?.skill){let elenco=null
+try{const r=await ctx.skill.list();elenco=Array.isArray(r)?r:r?.data}catch{}
+if(Array.isArray(elenco)&&!elenco.some((x)=>!String(x?.path||"").startsWith("skill://")))
+delete ev.tools.skill}
+ev.system=(ev.system||[]).map((x)=>x?.type==="text"&&x.text?.includes("/tmp/opencode")?{...x,text:x.text.split("\n").filter((r)=>!r.includes("/tmp/opencode")).join("\n")}:x)}
+if(await figlia(ev.sessionID))return
+const s=n.di(ev.sessionID)
+if(ev.model)s.modello=`${ev.model.providerID}/${ev.model.id}`
+const apertura=s.apertura??(await n.nasci(ev.sessionID,"resume"))
+if(apertura)ev.system.push({type:"text",text:apertura})})
+await ctx.session.hook("experimental.idle",async(ev)=>{if(await figlia(ev.sessionID))return
+n.aspetta(ev.sessionID,(avviso)=>ctx.session.prompt({sessionID:ev.sessionID,text:avviso}))})
+await ctx.tool.hook("execute.before",async(ev)=>{await figlia(ev.sessionID)
+await n.primaDelTool(ev.sessionID,ev.tool,ev.input,ev.id)})
+await ctx.tool.hook("execute.after",async(ev)=>{const motivo=ev.status==="error"&&FRASI.permesso?conMotivo(ev.error):null
+if(motivo)try{ev.error=new ev.error.constructor({message:motivo})}catch{}
+const piu=await n.dopoIlTool(ev.sessionID,ev.tool,ev.id,JSON.stringify(ev.result?.content??ev.error??""))
+if(piu&&ev.status==="completed")ev.result.content=[...(ev.result.content||[]),{type:"text",text:piu}]});(async()=>{try{for await(const e of ctx.event.subscribe()){const p=e.properties||e.data||{}
+if(e.type==="session.created"&&p.sessionID&&!p.parentID)n.nasci(p.sessionID,"startup")}}catch{}})()
+return()=>n.chiudi()}
+export default{id:"delminio",server:v1,setup:v2}
\ No newline at end of file
diff --git a/kit/en/plugin-client b/kit/en/plugin-client
new file mode 100644
index 0000000..7f9ba19
--- /dev/null
+++ b/kit/en/plugin-client
@@ -0,0 +1,474 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Il pacchetto di Delminio per le CLI degli agenti (F776): i ganci, /apertura e"""
+from __future__ import annotations
+import hashlib
+import json
+import os
+import re
+import runpy
+import shlex
+import shutil
+import subprocess
+import sys
+NOME = 'delminio'
+ID = f'{NOME}@{NOME}'
+SERVER = 'memoria'
+SERVER_DI_PRIMA = ('delminio', 'delminio-ruolo')
+TOOL = ('delminio', 'delminio_write')
+TOOLS_CLAUDE = tuple((f'mcp__plugin_{NOME}_{SERVER}__{t}' for t in TOOL))
+TOOLS_CLAUDE_PROGETTO = tuple((f'mcp__{SERVER}__{t}' for t in TOOL))
+TOOLS_CLAUDE_DI_PRIMA = tuple((f'mcp__plugin_{NOME}_delminio__{t}' for t in TOOL)) + tuple((f'mcp__{s}__{t}' for s in SERVER_DI_PRIMA for t in TOOL))
+SKILL_CLAUDE = {'dataviz': 'on', 'keybindings-help': 'on', 'update-config': 'on', 'claude-api': 'name-only', 'code-review': 'name-only', 'fewer-permission-prompts': 'name-only', 'init': 'name-only', 'plugin-authoring': 'name-only', 'run': 'name-only', 'security-review': 'name-only', 'simplify': 'name-only', 'workflow-authoring': 'name-only', 'loop': 'name-only', 'schedule': 'name-only'}
+SKILL_CLAUDE_F811 = {**{n: 'user-invocable-only' for n in ('claude-api', 'code-review', 'fewer-permission-prompts', 'init', 'plugin-authoring', 'run', 'security-review', 'simplify')}, 'loop': 'off', 'schedule': 'off'}
+CHIEDI_CLAUDE = ('Agent', 'Workflow')
+SKILL_CODEX_SPENTE = ()
+SKILL_CODEX_F811 = ('imagegen', 'skill-creator', 'skill-installer')
+COMANDI = {
+ "riti": {
+ "apertura": "apertura",
+ "chiusura": "chiusura",
+ "closing": "chiusura",
+ "handoff": "chiusura",
+ "opening": "apertura",
+ "start": "apertura"
+ }
+}
+FRASI = {
+ "descrizione": "Delminio: the project's memory, opening and closing sessions, messages between agents and the checks before an action",
+ "apertura": "Delminio: open the session with your role's briefing \u2014 what you write after the command goes as your message",
+ "apertura_suggerimento": "[what you want to tell it right away]",
+ "chiusura": "Delminio: close the session \u2014 what you write after the command goes as your message",
+ "chiusura_suggerimento": "[what to do before closing]",
+ "ciclo_opencode": "Delminio: this is the third time you have made exactly this call, and the last two got the same answer: a fourth will change nothing. Take another route, or stop and tell the person who gave you the work what is blocking you.",
+ "fermo_opencode": "Delminio stopped this run: the model made the same call with the same answer again even after three warnings. Read what it was trying to do and tell it again what you want, or change model.",
+ "permesso_opencode": "Delminio: this agent's rules do not let {rifiutati} through ({permesso}). In a chain (|, ;, &&) each command is checked on its own, and one outside the rules stops the whole chain; redirections pass.{ammessi} Do not retry the same command: run the ones the rules allow on their own, or tell the person who gave you the work what you need.",
+ "ammessi_opencode": " The rules allow: {elenco}.",
+ "opencode_v1": "Delminio does not work with OpenCode 1: the project memory and the checks are not here. Exit and update to OpenCode 2 with \u201copencode upgrade --major\u201d, then reopen OpenCode in this project. To the model: tell the person to update, before working.",
+ "uso": "usage: python3 .claude/plugin.py claude|rimuovi|opencode <repo root> \xb7 codex|qwen <CLI folder> \xb7 app-codex [stato|allinea|via|no|lascia]"
+}
+
+def F(chiave: str, **valori) -> str:
+ testo = FRASI[chiave]
+ for k, v in valori.items():
+ testo = testo.replace('{' + k + '}', str(v))
+ return testo
+
+def cartella() -> str:
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'plugin')
+GANCI_CLAUDE = (('SessionStart', 'apertura', {}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, 'Write|Edit|MultiEdit|NotebookEdit'), ('PreToolUse', 'guardia', {'timeout': 5}, 'Read|Grep|Glob|Write|Edit|MultiEdit|NotebookEdit|Bash'), ('PreToolUse', 'condiviso', {'timeout': 10}, 'Bash'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('PostToolUseFailure', 'errore', {'timeout': 5}, ''), ('Stop', 'attesa', {'asyncRewake': True, 'timeout': 43200}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
+LUNGO = {'additionalContextLimit': 16000}
+FINE_CODEX = {'timeout': 3}
+GANCI_CODEX = (('SessionStart', 'apertura', LUNGO, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(apply_patch|Edit|Write)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(apply_patch|Edit|Write|Bash)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^Bash$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10, **LUNGO}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', FINE_CODEX, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', FINE_CODEX, ''))
+GANCI_QWEN = (('SessionStart', 'apertura', {'timeout': 60}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(edit|write_file|notebook_edit)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(read_file|grep_search|edit|write_file|notebook_edit|run_shell_command)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^run_shell_command$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
+QWEN = NOME + '-qwen'
+PERMESSI_CODEX = tuple((f'[plugins."{ID}".mcp_servers.{SERVER}.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
+PERMESSI_CODEX_DI_PRIMA = tuple((f'[plugins."{ID}".mcp_servers.delminio.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
+
+def _permessi_codex(conf: str) -> None:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ nuovo = testo
+ for b in PERMESSI_CODEX_DI_PRIMA:
+ nuovo = nuovo.replace('\n' + b, '').replace(b, '')
+ if (mancano := [b for b in PERMESSI_CODEX if b not in nuovo]):
+ nuovo = nuovo.rstrip('\n') + '\n\n' + '\n'.join(mancano)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.replace(conf + '.nuovo', conf)
+LANCIATORE = '#!/usr/bin/env bash\nd=${CLAUDE_PROJECT_DIR:-$PWD}\nr=$(cd "$d" 2>/dev/null && git rev-parse --show-toplevel 2>/dev/null) || exit 0\n[ -f "$r/.claude/delminio.sh" ] || exit 0\nexec bash "$r/.claude/delminio.sh" "$@"\n'
+
+def _skill(nome: str, descrizione: str, suggerimento: str, comando: str) -> str:
+ return f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\nargument-hint: {json.dumps(suggerimento, ensure_ascii=False)}\ndisable-model-invocation: true\nallowed-tools: Bash(bash:*)\n---\n!`{comando}`\n\n$ARGUMENTS\n'
+
+def ganci(chiama: str, lista, matcher_sempre: bool=False) -> dict:
+ g: dict = {}
+ for evento, gesto, extra, matcher in lista:
+ g.setdefault(evento, []).append({**({'matcher': matcher} if matcher or matcher_sempre else {}), 'hooks': [{'type': 'command', 'command': f'{chiama} {gesto}', **extra}]})
+ return g
+
+def contenuti(radice_pacchetto: str) -> dict[str, str]:
+ lanciatore = os.path.join(radice_pacchetto, NOME, 'bin', 'delminio')
+ chiama = 'bash ' + shlex.quote(lanciatore)
+ server = {'command': 'bash', 'args': [lanciatore, 'ponte']}
+ f = {os.path.join(NOME, 'bin', 'delminio'): LANCIATORE, os.path.join(NOME, 'hooks', 'hooks.json'): json.dumps({'hooks': ganci(chiama, GANCI_CLAUDE)}, indent=2) + '\n', os.path.join(NOME, '.mcp.json'): json.dumps({'mcpServers': {SERVER: server}}, indent=2) + '\n', os.path.join(NOME, 'hooks', 'codex.json'): json.dumps({'hooks': ganci(chiama, GANCI_CODEX)}, indent=2) + '\n', os.path.join(NOME, 'mcp-codex.json'): json.dumps({'mcpServers': {SERVER: {**server, 'env_vars': ['DELMINIO_MODELLO', 'DELMINIO_CLI_NOME']}}}, indent=2) + '\n'}
+ riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
+ for nome, rito in sorted(riti.items()):
+ f[os.path.join(QWEN, 'commands', nome + '.md')] = f"---\ndescription: {json.dumps(F('apertura') if rito == 'apertura' else F('chiusura'), ensure_ascii=False)}\n---\n{nome}\n"
+ qwen_server = {**server, 'timeout': 60000, 'trust': True, 'alwaysLoadTools': True}
+ apre = (F('apertura'), F('apertura_suggerimento'), f'{chiama} prompt')
+ chiude = (F('chiusura'), F('chiusura_suggerimento'), f'{chiama} chiusura')
+ for nome, rito in sorted(riti.items()):
+ f[os.path.join(NOME, 'skills', nome, 'SKILL.md')] = _skill(nome, *(apre if rito == 'apertura' else chiude))
+ impronta = hashlib.sha256(''.join((k + v for k, v in sorted(f.items()))).encode()).hexdigest()
+ versione = f'1.0.{int(impronta[:7], 16)}'
+ f[os.path.join(NOME, '.claude-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione')}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(QWEN, 'qwen-extension.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'mcpServers': {SERVER: qwen_server}, 'hooks': ganci(chiama, GANCI_QWEN, matcher_sempre=True)}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(NOME, 'skills-codex', '.vuota')] = ''
+ f[os.path.join(NOME, '.codex-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'skills': './skills-codex/', 'hooks': './hooks/codex.json', 'mcpServers': './mcp-codex.json'}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': NOME, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': NOME, 'source': {'source': 'local', 'path': './' + NOME}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': NOME, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': NOME, 'source': './' + NOME, 'description': F('descrizione'), 'version': versione}]}, ensure_ascii=False, indent=2) + '\n'
+ return f
+
+def scrivi() -> str:
+ radice = cartella()
+ for rel, testo in contenuti(radice).items():
+ p = os.path.join(radice, rel)
+ try:
+ with open(p, encoding='utf-8') as h:
+ if h.read() == testo:
+ continue
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ if rel.endswith(os.path.join('bin', 'delminio')):
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+ return radice
+
+def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _acceso(radice: str) -> bool:
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ return (json.load(h).get('enabledPlugins') or {}).get(ID) is True
+ except (OSError, ValueError, AttributeError):
+ return False
+
+def claude(radice: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ return 3
+ try:
+ if _claude('--help', cwd=radice).returncode != 0:
+ return 3
+ pacchetto = scrivi()
+ _claude('marketplace', 'add', pacchetto, '--scope', 'local', cwd=radice)
+ _claude('install', ID, '--scope', 'local', cwd=radice)
+ if not _acceso(radice):
+ _claude('enable', ID, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _acceso(radice) else 3
+
+def _versione() -> str:
+ return json.loads(contenuti(cartella())[os.path.join(NOME, '.codex-plugin', 'plugin.json')])['version']
+
+def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _codex_pronto(casa: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ return False
+ acceso = re.search('^\\[plugins\\."' + re.escape(ID) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
+ return bool(acceso) and all((b in conf for b in PERMESSI_CODEX)) and (not any((b in conf for b in PERMESSI_CODEX_DI_PRIMA))) and os.path.isdir(os.path.join(casa, 'plugins', 'cache', NOME, NOME, _versione()))
+
+def _skill_codex(casa: str) -> None:
+ conf = os.path.join(casa, 'config.toml')
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except FileNotFoundError:
+ testo = ''
+ except OSError:
+ return
+ prima = testo
+ segno = os.path.join(casa, 'delminio-skill-f844')
+ if testo and (not os.path.exists(segno)):
+ for nome in SKILL_CODEX_F811:
+ percorso = json.dumps(os.path.join(casa, 'skills', '.system', nome, 'SKILL.md'))
+ testo = re.sub('(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(percorso) + '\\s*\\nenabled\\s*=\\s*false\\s*\\n?\\n?', '', testo)
+ blocchi = []
+ for nome in SKILL_CODEX_SPENTE:
+ percorso = os.path.join(casa, 'skills', '.system', nome, 'SKILL.md')
+ if json.dumps(percorso) not in testo:
+ blocchi.append(f'[[skills.config]]\npath = {json.dumps(percorso)}\nenabled = false\n')
+ try:
+ os.makedirs(casa, exist_ok=True)
+ if blocchi or testo != prima:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write((testo.rstrip('\n') + '\n\n' if testo.strip() else '') + '\n'.join(blocchi) if blocchi else testo)
+ os.replace(conf + '.nuovo', conf)
+ if not os.path.exists(segno):
+ open(segno, 'w').close()
+ except OSError:
+ pass
+
+def codex(casa: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_CODEX') or 'codex'):
+ return 3
+ pacchetto = scrivi()
+ _skill_codex(casa)
+ _squadra('codex', casa)
+ if _codex_pronto(casa):
+ return 0
+ try:
+ os.makedirs(casa, exist_ok=True)
+ _codex(casa, 'marketplace', 'add', pacchetto)
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'add', ID)
+ _permessi_codex(os.path.join(casa, 'config.toml'))
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _codex_pronto(casa) else 3
+APP_CODEX = ('/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '~/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '/usr/lib/chatgpt/resources/codex')
+
+def app_codex_cli() -> str:
+ return next((p for p in map(os.path.expanduser, APP_CODEX) if os.access(p, os.X_OK)), '')
+
+def _casa_app() -> str:
+ return os.path.expanduser('~/.codex')
+
+def _no_app() -> str:
+ return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio', 'app-codex-no')
+
+def _app_scelta(casa: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ return bool(re.search('^\\[marketplaces\\.' + re.escape(NOME) + '\\]', h.read(), re.M))
+ except OSError:
+ return False
+
+def app_codex_stato() -> str:
+ if not app_codex_cli():
+ return ''
+ if _app_scelta(_casa_app()):
+ return 'dentro'
+ return 'no' if os.path.exists(_no_app()) else 'manca'
+
+def app_codex() -> int:
+ cli = app_codex_cli()
+ if not cli:
+ return 4
+ casa = _casa_app()
+ vecchio = os.environ.get('DELMINIO_CODEX')
+ os.environ['DELMINIO_CODEX'] = cli
+ try:
+ pacchetto = scrivi()
+ if not _codex_pronto(casa):
+ os.makedirs(casa, exist_ok=True)
+ _codex(casa, 'marketplace', 'add', pacchetto)
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'add', ID)
+ _permessi_codex(os.path.join(casa, 'config.toml'))
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ finally:
+ if vecchio is None:
+ os.environ.pop('DELMINIO_CODEX', None)
+ else:
+ os.environ['DELMINIO_CODEX'] = vecchio
+ try:
+ os.remove(_no_app())
+ except OSError:
+ pass
+ return 0 if _codex_pronto(casa) else 3
+
+def app_codex_allinea() -> int:
+ if app_codex_cli() and _app_scelta(_casa_app()) and (not _codex_pronto(_casa_app())):
+ return app_codex()
+ return 0
+
+def app_codex_via() -> int:
+ casa = _casa_app()
+ cli = app_codex_cli() or shutil.which('codex') or ''
+ if cli:
+ vecchio = os.environ.get('DELMINIO_CODEX')
+ os.environ['DELMINIO_CODEX'] = cli
+ try:
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'marketplace', 'remove', NOME)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ finally:
+ if vecchio is None:
+ os.environ.pop('DELMINIO_CODEX', None)
+ else:
+ os.environ['DELMINIO_CODEX'] = vecchio
+ conf = os.path.join(casa, 'config.toml')
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except OSError:
+ return 0
+ nuovo = testo
+ for b in PERMESSI_CODEX + PERMESSI_CODEX_DI_PRIMA:
+ nuovo = nuovo.replace('\n' + b, '').replace(b, '')
+ for intestazione in (f'[plugins."{ID}"]', f'[marketplaces.{NOME}]'):
+ nuovo = re.sub('(?ms)^' + re.escape(intestazione) + '\\n.*?(?=^\\[|\\Z)', '', nuovo)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo.rstrip('\n') + '\n')
+ os.replace(conf + '.nuovo', conf)
+ return 0 if not _app_scelta(casa) else 3
+
+def app_codex_lascia() -> int:
+ try:
+ os.remove(_no_app())
+ except OSError:
+ pass
+ if not _app_scelta(_casa_app()):
+ return 0
+ return 2 if app_codex_via() == 0 else 3
+
+def app_codex_no() -> int:
+ os.makedirs(os.path.dirname(_no_app()), exist_ok=True)
+ with open(_no_app(), 'w', encoding='utf-8') as h:
+ h.write('no\n')
+ return 0
+
+def _qwen_pronto(casa: str, estensione: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'extensions', NOME, '.qwen-extension-install.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ except (OSError, ValueError):
+ return False
+ return d.get('type') == 'link' and os.path.realpath(d.get('source') or '') == os.path.realpath(estensione)
+
+def qwen(casa: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
+ return 3
+ estensione = os.path.join(scrivi(), QWEN)
+ _squadra('qwen', casa)
+ if _qwen_pronto(casa, estensione):
+ return 0
+ try:
+ os.makedirs(casa, exist_ok=True)
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ subprocess.run([q, 'extensions', 'uninstall', NOME], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _qwen_pronto(casa, estensione) else 3
+
+def qwen_via(casa: str) -> int:
+ if os.path.exists(os.path.join(casa, 'extensions', NOME)) and shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
+ try:
+ subprocess.run([os.environ.get('DELMINIO_QWEN') or 'qwen', 'extensions', 'uninstall', NOME], env={**os.environ, 'QWEN_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 1 if os.path.exists(os.path.join(casa, 'extensions', NOME)) else 0
+
+def claude_al_lancio(radice: str) -> int:
+ if _acceso(radice):
+ scrivi()
+ return 0
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ ganci = json.load(h).get('hooks') or {}
+ if any(('delminio.sh' in x.get('command', '') for l in ganci.values() for b in l for x in b.get('hooks', []))):
+ return 0
+ except (OSError, ValueError, AttributeError):
+ pass
+ return claude(radice)
+
+def _squadra(gesto: str, dove: str) -> None:
+ p = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'squadra.py')
+ if not os.path.isfile(p):
+ return
+ try:
+ runpy.run_path(p)[gesto](dove)
+ except Exception:
+ pass
+
+def rimuovi(radice: str) -> int:
+ _squadra('stacca', radice)
+ opencode_via(radice)
+ if shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ try:
+ _claude('uninstall', ID, '--scope', 'local', cwd=radice)
+ _claude('marketplace', 'remove', NOME, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ return 0
+ cambiato = False
+ if isinstance(s.get('enabledPlugins'), dict) and ID in s['enabledPlugins']:
+ del s['enabledPlugins'][ID]
+ cambiato = True
+ if not s['enabledPlugins']:
+ del s['enabledPlugins']
+ mercati = s.get('extraKnownMarketplaces')
+ for m in [m for m in mercati or {} if m == NOME] if isinstance(mercati, dict) else []:
+ del mercati[m]
+ cambiato = True
+ if isinstance(mercati, dict) and (not mercati):
+ del s['extraKnownMarketplaces']
+ if cambiato:
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ os.replace(p + '.nuovo', p)
+ return 0
+OPENCODE_PLUGIN = os.path.join('.opencode', 'plugins', 'delminio.js')
+OPENCODE_SORGENTE = os.path.join('.claude', 'opencode.js')
+
+def _nostro_opencode(testo: str) -> bool:
+ return 'delminio.sh' in testo and 'attesa-codex' in testo
+
+def opencode(radice: str) -> int:
+ try:
+ with open(os.path.join(radice, OPENCODE_SORGENTE), encoding='utf-8') as h:
+ testo = h.read()
+ except OSError:
+ return 3
+ riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
+ frasi = {'apertura': F('apertura'), 'chiusura': F('chiusura'), 'ciclo': F('ciclo_opencode'), 'fermo': F('fermo_opencode'), 'v1': F('opencode_v1'), 'permesso': F('permesso_opencode', rifiutati='{rifiutati}', permesso='{permesso}', ammessi='{ammessi}'), 'ammessi': F('ammessi_opencode', elenco='{elenco}')}
+ testo = re.sub('const RITI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const RITI = ' + json.dumps(riti, ensure_ascii=False), testo, count=1)
+ testo = re.sub('const FRASI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const FRASI = ' + json.dumps(frasi, ensure_ascii=False), testo, count=1)
+ dove = os.path.join(radice, OPENCODE_PLUGIN)
+ try:
+ with open(dove, encoding='utf-8') as h:
+ prima = h.read()
+ except OSError:
+ prima = None
+ if prima == testo:
+ return 0
+ if prima is not None and (not _nostro_opencode(prima)):
+ return 3
+ os.makedirs(os.path.dirname(dove), exist_ok=True)
+ with open(dove + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ os.replace(dove + '.nuovo', dove)
+ return 0
+
+def opencode_via(radice: str) -> None:
+ dove = os.path.join(radice, OPENCODE_PLUGIN)
+ try:
+ with open(dove, encoding='utf-8') as h:
+ if not _nostro_opencode(h.read()):
+ return
+ os.remove(dove)
+ os.rmdir(os.path.dirname(dove))
+ os.rmdir(os.path.dirname(os.path.dirname(dove)))
+ except OSError:
+ pass
+
+def main(argv: list[str]) -> int:
+ if argv[:1] == ['app-codex'] and len(argv) <= 2:
+ quale = argv[1] if len(argv) == 2 else ''
+ if quale == 'stato':
+ print(app_codex_stato())
+ return 0
+ gesti = {'': app_codex, 'allinea': app_codex_allinea, 'via': app_codex_via, 'no': app_codex_no, 'lascia': app_codex_lascia}
+ if quale in gesti:
+ return gesti[quale]()
+ if len(argv) != 2 or argv[0] not in ('claude', 'claude-al-lancio', 'codex', 'qwen', 'qwen-via', 'rimuovi', 'opencode'):
+ print(F('uso'), file=sys.stderr)
+ return 1
+ if argv[0] in ('codex', 'qwen', 'qwen-via'):
+ return {'codex': codex, 'qwen': qwen, 'qwen-via': qwen_via}[argv[0]](os.path.realpath(argv[1]))
+ radice = os.path.realpath(argv[1])
+ return {'claude': claude, 'claude-al-lancio': claude_al_lancio, 'rimuovi': rimuovi, 'opencode': opencode}[argv[0]](radice)
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/en/squadra-client b/kit/en/squadra-client
new file mode 100644
index 0000000..bddba2a
--- /dev/null
+++ b/kit/en/squadra-client
@@ -0,0 +1,753 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La squadra di Delminio su questo computer (F810, F867): ciò che lo spazio dà a ogni suo"""
+from __future__ import annotations
+import hashlib
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+NOME = 'delminio'
+FRASI = {
+ "uso": "usage: python3 .claude/squadra.py accetta \xb7 lancio <cli> <where> \xb7 codex|qwen <CLI folder> \xb7 stacca <repo root>",
+ "squadra_descrizione": "The team's skills, from Delminio",
+ "squadra_mcp_domanda": "\nThe team MCP server \u201c{nome}\u201d of this space:\n {cosa}\n\nIt will run on this computer, with your permissions, every time an agent starts. Accept it? [y/N] ",
+ "squadra_mcp_locale": "the command that starts here: {comando}\n the environment variables it receives: {variabili}",
+ "squadra_mcp_remoto": "the address it calls: {url}\n the environment variable it is sent as a key: {variabile}",
+ "squadra_mcp_si": "y yes",
+ "squadra_mcp_accettati": "\u2705 team MCP servers and plugins: {nuovi} accepted now \xb7 {restano} stay stopped (if one changes, I ask again)",
+ "squadra_plugin_domanda": "\nThe team plugin \u201c{nome}\u201d of this space:\n from the {mercato} marketplace ({origine}), for {cli}\n\nA plugin can bring commands, hooks and servers that run on this computer with your permissions. Install it? [y/N] "
+}
+
+def F(chiave: str, **valori) -> str:
+ testo = FRASI[chiave]
+ for k, v in valori.items():
+ testo = testo.replace('{' + k + '}', str(v))
+ return testo
+
+def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+SQUADRA_MKT = NOME + '-squadra-'
+NOME_PLUGIN_OK = re.compile('[a-z0-9]+(?:-[a-z0-9]+)*')
+
+def cartella_squadre() -> str:
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'squadre')
+
+def _chiave_ok(chiave: str) -> bool:
+ return bool(re.fullmatch('[0-9a-f]{12}', chiave or ''))
+
+def squadra_di(chiave: str) -> dict:
+ d = os.path.join(cartella_squadre(), chiave)
+ try:
+ with open(os.path.join(d, '.claude-plugin', 'marketplace.json'), encoding='utf-8') as h:
+ m = json.load(h)
+ p = m['plugins'][0]
+ with open(os.path.join(d, '.impronta'), encoding='utf-8') as h:
+ impronta = h.read().strip()
+ except (OSError, ValueError, KeyError, IndexError, TypeError):
+ return {}
+ if not _chiave_ok(chiave) or not NOME_PLUGIN_OK.fullmatch(str(p.get('name') or '')):
+ return {}
+ try:
+ with open(os.path.join(d, '.ruoli.json'), encoding='utf-8') as h:
+ di_chi = json.load(h)
+ except (OSError, ValueError):
+ di_chi = {}
+ return {'cartella': d, 'plugin': p['name'], 'versione': str(p.get('version') or ''), 'marketplace': m.get('name') or '', 'impronta': impronta, 'ruoli': di_chi if isinstance(di_chi, dict) else {}}
+
+def _norm_ruolo(nome: str) -> str:
+ return ''.join((c for c in (nome or '').lower() if c.isalnum()))
+
+def _testa(testo: str) -> tuple[dict, str]:
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
+ if not m:
+ return ({}, testo)
+ campi = {}
+ for riga in m.group(1).splitlines():
+ k, _, v = riga.partition(':')
+ v = v.strip()
+ if v[:1] == '"':
+ try:
+ v = json.loads(v)
+ except ValueError:
+ v = v.strip('"')
+ campi[k.strip()] = v
+ return (campi, testo[m.end():])
+
+def _col_nome(testo: str, nome: str) -> str:
+ m = re.match('^---[ \\t]*\\n(.*?)\\n---[ \\t]*(?:\\n|$)', testo, re.S)
+ if not m:
+ return f'---\nname: {nome}\n---\n' + testo
+ righe = [r for r in m.group(1).splitlines() if not re.match('name[ \\t]*:', r)]
+ return '---\n' + '\n'.join([f'name: {nome}', *righe]) + '\n---\n' + testo[m.end():]
+
+def _mcp_claude(spec: dict) -> dict:
+ if spec.get('tipo') == 'remoto':
+ t = spec.get('token_variabile')
+ return {'type': 'http', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
+ return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})}
+
+def _mcp_qwen(spec: dict) -> dict:
+ if spec.get('tipo') == 'remoto':
+ t = spec.get('token_variabile')
+ return {'httpUrl': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
+ return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})}
+_TESTA_AMMESSA = frozenset({'name', 'description', 'argument-hint', 'when_to_use', 'disable-model-invocation', 'user-invocable', 'model', 'color', 'tools', 'modelConfig', 'runConfig'})
+_CHIAVE_TESTA = re.compile('([A-Za-z_][\\w-]*)[ \\t]*:(?:[ \\t]|$)')
+
+def _testa_ripulita(testo: str) -> str:
+ m = re.match('^(\\ufeff?\\s*---[ \\t]*\\r?\\n)(.*?)(\\r?\\n---[ \\t]*(?:\\r?\\n|$))', testo, re.S)
+ if not m:
+ return testo
+ tenute, tieni = ([], False)
+ for riga in re.split('\\r\\n|\\r|\\n', m.group(2)):
+ if riga[:1] not in (' ', '\t'):
+ k = _CHIAVE_TESTA.match(riga)
+ tieni = bool(k) and k.group(1) in _TESTA_AMMESSA
+ if tieni:
+ tenute.append(riga)
+ return '---\n' + ''.join((r + '\n' for r in tenute)) + '---\n' + testo[m.end():]
+
+def _stampabile(v) -> bool:
+ if isinstance(v, str):
+ return v.isprintable()
+ if isinstance(v, dict):
+ return all((_stampabile(k) and _stampabile(x) for k, x in v.items()))
+ if isinstance(v, list):
+ return all((_stampabile(x) for x in v))
+ return True
+
+def _visibile(v) -> str:
+ return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
+
+def _mcp_impronta(nome: str, spec: dict) -> str:
+ return hashlib.sha256(json.dumps([nome, spec], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
+
+def _accettati_file(chiave: str) -> str:
+ return os.path.join(cartella_squadre(), chiave + '.mcp-accettati')
+
+def mcp_accettati(chiave: str) -> set[str]:
+ try:
+ with open(_accettati_file(chiave), encoding='utf-8') as h:
+ return set(h.read().split())
+ except OSError:
+ return set()
+
+def _squadra_contenuti(chiave: str, pacco: dict) -> dict[str, str]:
+ plugin = str(pacco.get('plugin') or 'squadra')
+ if not NOME_PLUGIN_OK.fullmatch(plugin):
+ plugin = 'squadra'
+ impronta = str(pacco.get('impronta') or '')
+ descrizione = F('squadra_descrizione')
+ mkt = SQUADRA_MKT + chiave
+ pezzi = pacco.get('pezzi') if isinstance(pacco.get('pezzi'), list) else [{**x, 'tipo': 'skill'} for x in pacco.get('skill') or [] if isinstance(x, dict)]
+ tutti, plugin_squadra = ([], [])
+ for x in pezzi:
+ tipo, nome = (str(x.get('tipo') or ''), str(x.get('nome') or ''))
+ if tipo == 'plugin' and NOME_PLUGIN_OK.fullmatch(nome) and (len(nome) <= 64):
+ if (spec := _plugin_spec((x.get('file') or {}).get('plugin.json'))):
+ plugin_squadra.append({'nome': nome, 'spec': spec, 'impronta': _mcp_impronta(nome, spec), 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})})
+ continue
+ if tipo not in ('skill', 'comando', 'agente', 'mcp') or not NOME_PLUGIN_OK.fullmatch(nome) or len(nome) > 64:
+ continue
+ file = {}
+ for rel, testo in (x.get('file') or {}).items():
+ pezzi_rel = str(rel).replace('\\', '/').split('/')
+ if isinstance(testo, str) and (not any((not q or q.startswith('.') for q in pezzi_rel))):
+ file[os.path.join(*pezzi_rel)] = testo
+ principale = {'skill': 'SKILL.md', 'comando': 'comando.md', 'agente': 'agente.md', 'mcp': 'mcp.json'}[tipo]
+ if principale not in file:
+ continue
+ if tipo != 'mcp':
+ file[principale] = _testa_ripulita(file[principale])
+ spec = {}
+ if tipo == 'mcp':
+ try:
+ spec = json.loads(file[principale])
+ spec = {k: v for k, v in spec.items() if k != 'descrizione'}
+ _mcp_claude(spec)
+ except (ValueError, KeyError, TypeError, AttributeError):
+ continue
+ if not _stampabile(spec):
+ continue
+ tutti.append({'tipo': tipo, 'nome': nome, 'file': file, 'principale': principale, 'spec': spec, 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})})
+ accettati = mcp_accettati(chiave)
+ fermi = [{'nome': x['nome'], 'spec': x['spec'], 'impronta': _mcp_impronta(x['nome'], x['spec'])} for x in tutti if x['tipo'] == 'mcp' and _mcp_impronta(x['nome'], x['spec']) not in accettati]
+ via = {x['nome'] for x in fermi}
+ tutti = [x for x in tutti if not (x['tipo'] == 'mcp' and x['nome'] in via)]
+ dentro = sorted((_mcp_impronta(x['nome'], x['spec']) for x in tutti if x['tipo'] == 'mcp'))
+ minore = int(hashlib.sha256(' '.join(dentro).encode()).hexdigest()[:5], 16) + 1 if dentro else 0
+ versione = f"1.{minore}.{int((impronta or '0')[:7], 16)}"
+ f: dict[str, str] = {}
+ manifesto = {'name': plugin, 'version': versione, 'description': descrizione}
+
+ def un_plugin(dove: str, scelti) -> None:
+ mcp_claude, mcp_qwen = ({}, {})
+ for x in scelti:
+ n = x['nome']
+ if x['tipo'] == 'skill':
+ for rel, testo in x['file'].items():
+ f[os.path.join(dove, 'skills', n, rel)] = testo
+ elif x['tipo'] == 'comando':
+ f[os.path.join(dove, 'commands', n + '.md')] = x['file']['comando.md']
+ elif x['tipo'] == 'agente':
+ f[os.path.join(dove, 'agents', n + '.md')] = x['file']['agente.md']
+ else:
+ mcp_claude[n] = _mcp_claude(x['spec'])
+ mcp_qwen[plugin + '-' + n] = _mcp_qwen(x['spec'])
+ f[os.path.join(dove, '.claude-plugin', 'plugin.json')] = json.dumps(manifesto, ensure_ascii=False, indent=2) + '\n'
+ if mcp_claude:
+ f[os.path.join(dove, '.mcp.json')] = json.dumps({'mcpServers': mcp_claude}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(dove, 'qwen-extension.json')] = json.dumps({**manifesto, **({'mcpServers': mcp_qwen} if mcp_qwen else {})}, ensure_ascii=False, indent=2) + '\n'
+ per_tutti = [x for x in tutti if not x['ruoli']]
+ un_plugin(plugin, per_tutti)
+ for r in sorted({r for x in tutti for r in x['ruoli']}):
+ un_plugin(os.path.join('ruoli', r, plugin), per_tutti + [x for x in tutti if r in x['ruoli']])
+ lancio = {'skill': {}, 'agente': {}, 'mcp': {}}
+ for x in tutti:
+ n = x['nome']
+ if x['tipo'] == 'skill':
+ for rel, testo in x['file'].items():
+ f[os.path.join('codex', plugin, 'skills', n, rel)] = testo
+ lancio['skill'][n] = x['ruoli']
+ if len(plugin) + 1 + len(n) <= 64:
+ for rel, testo in x['file'].items():
+ f[os.path.join('opencode', 'skills', f'{plugin}-{n}', rel)] = _col_nome(testo, f'{plugin}-{n}') if rel == 'SKILL.md' else testo
+ elif x['tipo'] == 'comando':
+ campi, corpo = _testa(x['file']['comando.md'])
+ f[os.path.join('codex', plugin, 'skills', n, 'SKILL.md')] = f"---\nname: {n}\ndescription: {json.dumps(str(campi.get('description') or ''), ensure_ascii=False)}\n---\n" + corpo.lstrip('\n')
+ lancio['skill'][n] = x['ruoli']
+ elif x['tipo'] == 'agente':
+ campi, corpo = _testa(x['file']['agente.md'])
+ f[os.path.join('codex', 'agenti', n + '.toml')] = f'name = {json.dumps(n)}\ndeveloper_instructions = {json.dumps(corpo.strip(), ensure_ascii=False)}\n'
+ lancio['agente'][n] = {'ruoli': x['ruoli'], 'descrizione': str(campi.get('description') or '')}
+ else:
+ lancio['mcp'][n] = {'ruoli': x['ruoli'], 'spec': x['spec']}
+ f[os.path.join('codex', plugin, '.codex-plugin', 'plugin.json')] = json.dumps({**manifesto, 'skills': './skills/'}, ensure_ascii=False, indent=2) + '\n'
+ lancio['conto'] = {t: sum((1 for x in tutti if x['tipo'] == t)) for t in ('skill', 'comando', 'agente', 'mcp')}
+ lancio['conto']['mcp_fermi'] = len(fermi)
+ f['.ruoli.json'] = json.dumps(lancio, indent=2, sort_keys=True, ensure_ascii=False) + '\n'
+ f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': mkt, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': plugin, 'source': './' + plugin, 'description': descrizione, 'version': versione}]}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': mkt, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': plugin, 'source': {'source': 'local', 'path': './codex/' + plugin}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n'
+ f['.impronta'] = impronta + '\n'
+ f['.pacco.json'] = json.dumps(pacco, ensure_ascii=False, sort_keys=True) + '\n'
+ if fermi:
+ f['.mcp-fermi.json'] = json.dumps(fermi, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ if plugin_squadra:
+ presi = plugin_accettati(chiave)
+ for x in plugin_squadra:
+ x['accettato'] = x['impronta'] in presi
+ f['.plugin.json'] = json.dumps(plugin_squadra, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ if (fermi_p := [x for x in plugin_squadra if not x['accettato']]):
+ f['.plugin-fermi.json'] = json.dumps(fermi_p, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ return f
+
+def squadra_accetta_dal_terminale() -> int:
+ radice = cartella_squadre()
+ try:
+ chiavi = sorted((c for c in os.listdir(radice) if _chiave_ok(c)))
+ except OSError:
+ return 0
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ return 1
+ nuovi = restano = 0
+ for chiave in chiavi:
+ d = os.path.join(radice, chiave)
+ try:
+ with open(os.path.join(d, '.pacco.json'), encoding='utf-8') as h:
+ pacco = json.load(h)
+ except (OSError, ValueError):
+ continue
+ try:
+ with open(os.path.join(d, '.mcp-fermi.json'), encoding='utf-8') as h:
+ fermi = json.load(h)
+ except (OSError, ValueError):
+ fermi = []
+ accettati, presi = (mcp_accettati(chiave), 0)
+ for x in fermi if isinstance(fermi, list) else []:
+ spec, nome = (x.get('spec') or {}, str(x.get('nome') or ''))
+ if not isinstance(spec, dict) or not _stampabile(spec):
+ restano += 1
+ continue
+ if spec.get('tipo') == 'remoto':
+ cosa = F('squadra_mcp_remoto', url=_visibile(spec.get('url') or ''), variabile=_visibile(spec.get('token_variabile') or '—'))
+ else:
+ cosa = F('squadra_mcp_locale', comando=_visibile(shlex.join([str(spec.get('comando') or '')] + [str(a) for a in spec.get('argomenti') or []])), variabili=_visibile(', '.join((str(v) for v in spec.get('variabili') or [])) or '—'))
+ tty.write(F('squadra_mcp_domanda', nome=_visibile(nome), cosa=cosa))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
+ accettati.add(_mcp_impronta(nome, spec))
+ presi += 1
+ else:
+ restano += 1
+ try:
+ with open(os.path.join(d, '.plugin-fermi.json'), encoding='utf-8') as h:
+ plugin_fermi = json.load(h)
+ except (OSError, ValueError):
+ plugin_fermi = []
+ presi_p, plugin_presi = (0, plugin_accettati(chiave))
+ for x in plugin_fermi if isinstance(plugin_fermi, list) else []:
+ spec, nome = (_plugin_spec(json.dumps((x or {}).get('spec'))), str((x or {}).get('nome') or ''))
+ if not spec or not NOME_PLUGIN_OK.fullmatch(nome):
+ restano += 1
+ continue
+ tty.write(F('squadra_plugin_domanda', nome=_visibile(nome), mercato=_visibile(spec['mercato']), origine=_visibile(spec['origine']), cli=', '.join(spec['cli'])))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
+ plugin_presi.add(_mcp_impronta(nome, spec))
+ presi_p += 1
+ else:
+ restano += 1
+ if presi_p:
+ os.makedirs(radice, exist_ok=True)
+ with open(_plugin_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(''.join((i + '\n' for i in sorted(plugin_presi))))
+ os.replace(_plugin_accettati_file(chiave) + '.nuovo', _plugin_accettati_file(chiave))
+ presi += presi_p
+ if presi:
+ os.makedirs(radice, exist_ok=True)
+ with open(_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(''.join((i + '\n' for i in sorted(accettati))))
+ os.replace(_accettati_file(chiave) + '.nuovo', _accettati_file(chiave))
+ squadra_scrivi(chiave, pacco)
+ nuovi += presi
+ if nuovi or restano:
+ print(F('squadra_mcp_accettati', nuovi=nuovi, restano=restano))
+ return 0
+
+def squadra_scrivi(chiave: str, pacco: dict) -> dict:
+ if not _chiave_ok(chiave):
+ return {}
+ d = os.path.join(cartella_squadre(), chiave)
+ if not (pacco.get('pezzi') or pacco.get('skill')):
+ shutil.rmtree(d, ignore_errors=True)
+ return {}
+ voluti = _squadra_contenuti(chiave, pacco)
+ for rel, testo in voluti.items():
+ p = os.path.join(d, rel)
+ try:
+ with open(p, encoding='utf-8') as h:
+ if h.read() == testo:
+ continue
+ except (OSError, UnicodeDecodeError):
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ os.replace(p + '.nuovo', p)
+ for radice, cartelle, nomi in os.walk(d, topdown=False):
+ for n in nomi:
+ rel = os.path.relpath(os.path.join(radice, n), d)
+ if rel not in voluti:
+ os.remove(os.path.join(radice, n))
+ if radice != d and (not os.listdir(radice)):
+ os.rmdir(radice)
+ return squadra_di(chiave)
+
+def _squadra_id(sq: dict) -> str:
+ return f"{sq['plugin']}@{sq['marketplace']}"
+
+def squadra_claude(radice: str, chiave: str) -> int:
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ s = {}
+ accesi = s.get('enabledPlugins') if isinstance(s.get('enabledPlugins'), dict) else {}
+ mkt = SQUADRA_MKT + chiave
+ sq = squadra_di(chiave)
+ voluto = _squadra_id(sq) if sq else ''
+ vecchi = [k for k in accesi if k.endswith('@' + mkt) and k != voluto]
+ if (not voluto or accesi.get(voluto) is True) and (not vecchi):
+ return 0
+ if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ return 3
+ try:
+ for k in vecchi:
+ _claude('uninstall', k, '--scope', 'local', cwd=radice)
+ if voluto:
+ _claude('marketplace', 'add', sq['cartella'], '--scope', 'local', cwd=radice)
+ _claude('install', voluto, '--scope', 'local', cwd=radice)
+ else:
+ _claude('marketplace', 'remove', mkt, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0
+
+def _squadra_codex(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa))
+ if not _chiave_ok(chiave):
+ return
+ sq = squadra_di(chiave)
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ conf = ''
+ mkt = SQUADRA_MKT + chiave
+ if not sq:
+ for m in re.finditer('^\\[plugins\\."([a-z0-9-]+@' + re.escape(mkt) + ')"\\]', conf, re.M):
+ _codex(casa, 'remove', m.group(1))
+ if mkt in conf:
+ _codex(casa, 'marketplace', 'remove', mkt)
+ return
+ pid = _squadra_id(sq)
+ acceso = re.search('^\\[plugins\\."' + re.escape(pid) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
+ if acceso and os.path.isdir(os.path.join(casa, 'plugins', 'cache', mkt, sq['plugin'], sq['versione'])):
+ return
+ _codex(casa, 'marketplace', 'add', sq['cartella'])
+ _codex(casa, 'add', pid)
+
+def _squadra_qwen(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
+ if not _chiave_ok(chiave):
+ return
+ sq = squadra_di(chiave)
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ via = [n for n in (os.listdir(os.path.join(casa, 'extensions')) if os.path.isdir(os.path.join(casa, 'extensions')) else []) if n != NOME and _collegata_a(casa, n, cartella_squadre()) and (not sq or n != sq['plugin'])]
+ for n in via:
+ subprocess.run([q, 'extensions', 'uninstall', n], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ if not sq:
+ return
+ del_ruolo = os.path.join(sq['cartella'], 'ruoli', _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')), sq['plugin'])
+ estensione = del_ruolo if _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')) and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], sq['plugin'])
+ if _collegata_a(casa, sq['plugin'], estensione):
+ return
+ subprocess.run([q, 'extensions', 'uninstall', sq['plugin']], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
+_PLUGIN_ORIGINE = re.compile('(github:[A-Za-z0-9][\\w.-]*/[\\w.-]+|https://[^\\s@?#]{3,300})')
+
+def _plugin_spec(testo) -> dict:
+ try:
+ d = json.loads(testo) if isinstance(testo, str) else {}
+ except ValueError:
+ return {}
+ if not isinstance(d, dict):
+ return {}
+ mercato, origine = (str(d.get('mercato') or ''), str(d.get('origine') or ''))
+ cli = [c for c in ('claude', 'codex', 'qwen') if c in (d.get('cli') or [])]
+ if not re.fullmatch('[\\w.-]{1,100}', mercato) or not _PLUGIN_ORIGINE.fullmatch(origine) or (not cli) or (not _stampabile({'m': mercato, 'o': origine})):
+ return {}
+ return {'mercato': mercato, 'origine': origine, 'cli': cli}
+
+def _plugin_accettati_file(chiave: str) -> str:
+ return os.path.join(cartella_squadre(), chiave + '.plugin-accettati')
+
+def plugin_accettati(chiave: str) -> set[str]:
+ try:
+ with open(_plugin_accettati_file(chiave), encoding='utf-8') as h:
+ return set(h.read().split())
+ except OSError:
+ return set()
+
+def plugin_squadra(chiave: str, cli: str) -> list[dict]:
+ try:
+ with open(os.path.join(cartella_squadre(), chiave, '.plugin.json'), encoding='utf-8') as h:
+ tutti = json.load(h)
+ except (OSError, ValueError):
+ return []
+ presi = plugin_accettati(chiave)
+ return [x for x in tutti if isinstance(x, dict) and x.get('impronta') in presi and (cli in (x.get('spec') or {}).get('cli', [])) and NOME_PLUGIN_OK.fullmatch(str(x.get('nome') or '')) and _plugin_spec(json.dumps(x.get('spec')))]
+
+def _installati(chiave: str) -> dict:
+ try:
+ with open(os.path.join(cartella_squadre(), chiave + '.plugin-installati.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ return d if isinstance(d, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+def _installati_scrivi(chiave: str, d: dict) -> None:
+ p = os.path.join(cartella_squadre(), chiave + '.plugin-installati.json')
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ json.dump(d, h, indent=2, sort_keys=True)
+ os.replace(p + '.nuovo', p)
+
+def _sorgente(origine: str, cli: str) -> str:
+ if origine.startswith('github:'):
+ return origine[7:] if cli != 'qwen' else 'https://github.com/' + origine[7:]
+ return origine
+
+def _claude_installati(radice: str) -> dict:
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ try:
+ with open(os.path.join(cfg, 'plugins', 'installed_plugins.json'), encoding='utf-8') as h:
+ d = json.load(h).get('plugins') or {}
+ except (OSError, ValueError, AttributeError):
+ return {}
+ return {pid: str(v.get('installPath') or '') for pid, voci in d.items() if isinstance(voci, list) for v in voci if isinstance(v, dict) and v.get('scope') in ('local', 'project') and (v.get('projectPath') == radice)}
+
+def squadra_plugin_claude(radice: str, chiave: str) -> int:
+ if not radice or not _chiave_ok(chiave) or (not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude')):
+ return 3
+ voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'claude')}
+ stato = _installati(chiave)
+ miei = stato.get('claude:' + radice) or {}
+ c_e = _claude_installati(radice)
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ accesi = json.load(h).get('enabledPlugins') or {}
+ except (OSError, ValueError, AttributeError):
+ accesi = {}
+ for pid, x in voluti.items():
+ if pid not in c_e:
+ _claude('marketplace', 'add', _sorgente(x['spec']['origine'], 'claude'), '--scope', 'local', cwd=radice)
+ if _claude('install', pid, '--scope', 'local', cwd=radice).returncode != 0:
+ continue
+ miei[pid] = True
+ elif pid not in miei:
+ continue
+ per_tutti = not x['ruoli']
+ if per_tutti and accesi.get(pid) is not True:
+ _claude('enable', pid, '--scope', 'local', cwd=radice)
+ elif not per_tutti and accesi.get(pid) is not False:
+ _claude('disable', pid, '--scope', 'local', cwd=radice)
+ for pid in [k for k in miei if k not in voluti]:
+ _claude('uninstall', pid, '--scope', 'local', cwd=radice)
+ miei.pop(pid)
+ stato['claude:' + radice] = miei
+ _installati_scrivi(chiave, stato)
+ return 0
+
+def _squadra_plugin_codex(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa))
+ if not _chiave_ok(chiave):
+ return
+ voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'codex') if not x['ruoli']}
+ stato = _installati(chiave)
+ miei = stato.get('codex:' + casa) or {}
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ conf = ''
+ for pid, x in voluti.items():
+ if f'[plugins."{pid}"]' in conf:
+ continue
+ if f"[marketplaces.{x['spec']['mercato']}]" not in conf:
+ _codex(casa, 'marketplace', 'add', _sorgente(x['spec']['origine'], 'codex'))
+ if _codex(casa, 'add', pid).returncode == 0:
+ miei[pid] = True
+ for pid in [k for k in miei if k not in voluti]:
+ _codex(casa, 'remove', pid)
+ miei.pop(pid)
+ stato['codex:' + casa] = miei
+ _installati_scrivi(chiave, stato)
+
+def _squadra_plugin_qwen(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
+ if not _chiave_ok(chiave):
+ return
+ ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
+ voluti = {x['nome']: x for x in plugin_squadra(chiave, 'qwen') if not x['ruoli'] or ruolo in x['ruoli']}
+ stato = _installati(chiave)
+ miei = stato.get('qwen:' + casa) or {}
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ for nome, x in voluti.items():
+ if os.path.isdir(os.path.join(casa, 'extensions', nome)):
+ continue
+ r = subprocess.run([q, 'extensions', 'install', f"{_sorgente(x['spec']['origine'], 'qwen')}:{nome}", '--consent'], env=ambiente, capture_output=True, text=True, timeout=300, stdin=subprocess.DEVNULL)
+ if r.returncode == 0:
+ miei[nome] = True
+ for nome in [k for k in miei if k not in voluti]:
+ subprocess.run([q, 'extensions', 'uninstall', nome], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ miei.pop(nome)
+ stato['qwen:' + casa] = miei
+ _installati_scrivi(chiave, stato)
+
+def squadra_lancio(cli: str, dove: str) -> list[str]:
+ ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
+ if cli == 'claude':
+ try:
+ with open(os.path.join(dove, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ accesi = json.load(h).get('enabledPlugins') or {}
+ except (OSError, ValueError, AttributeError):
+ return []
+ chiavi = [m.group(1) for k, v in accesi.items() if v is True for m in [re.search('@' + re.escape(SQUADRA_MKT) + '([0-9a-f]{12})$', k)] if m]
+ sq = squadra_di(chiavi[0]) if chiavi else {}
+ d = os.path.join(sq['cartella'], 'ruoli', ruolo, sq['plugin']) if sq and ruolo else ''
+ out = ['--plugin-dir', d] if d and os.path.isdir(d) else []
+ if chiavi and ruolo:
+ c_e = _claude_installati(dove)
+ for x in plugin_squadra(chiavi[0], 'claude'):
+ cartella = c_e.get(f"{x['nome']}@{x['spec']['mercato']}", '')
+ if ruolo in x['ruoli'] and cartella and os.path.isdir(cartella):
+ out += ['--plugin-dir', cartella]
+ return out
+ if cli == 'codex':
+ chiave = os.path.basename(os.path.normpath(dove))
+ sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
+ if not sq:
+ return []
+ lancio = sq['ruoli']
+ per_me = lambda r: not r or ruolo in r
+ out = []
+ base = os.path.join(dove, 'plugins', 'cache', sq['marketplace'], sq['plugin'], sq['versione'], 'skills')
+ via = [n for n, r in sorted((lancio.get('skill') or {}).items()) if not per_me(r) and NOME_PLUGIN_OK.fullmatch(n)]
+ if via:
+ voci = ','.join(('{path=' + json.dumps(os.path.join(base, n, 'SKILL.md')) + ',enabled=false}' for n in via))
+ out += ['-c', f'skills.config=[{voci}]']
+ for n, a in sorted((lancio.get('agente') or {}).items()):
+ toml = os.path.join(sq['cartella'], 'codex', 'agenti', n + '.toml')
+ if NOME_PLUGIN_OK.fullmatch(n) and per_me(a.get('ruoli')) and os.path.isfile(toml):
+ out += ['-c', f"agents.{n}.description={json.dumps(a.get('descrizione') or n, ensure_ascii=False)}", '-c', f'agents.{n}.config_file={json.dumps(toml)}']
+ for n, m in sorted((lancio.get('mcp') or {}).items()):
+ spec, k = (m.get('spec') or {}, f"{sq['plugin']}-{n}")
+ if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
+ continue
+ if spec.get('tipo') == 'remoto' and spec.get('url'):
+ out += ['-c', f"mcp_servers.{k}.url={json.dumps(spec['url'])}"]
+ if spec.get('token_variabile'):
+ out += ['-c', f"mcp_servers.{k}.bearer_token_env_var={json.dumps(spec['token_variabile'])}"]
+ elif spec.get('comando'):
+ out += ['-c', f"mcp_servers.{k}.command={json.dumps(spec['comando'])}", '-c', f"mcp_servers.{k}.args={json.dumps(list(spec.get('argomenti') or []))}"]
+ if spec.get('variabili'):
+ out += ['-c', f"mcp_servers.{k}.env_vars={json.dumps(list(spec['variabili']))}"]
+ return out
+ if cli == 'opencode':
+ return [json.dumps(_squadra_opencode(ruolo), ensure_ascii=False)]
+ return []
+
+def _squadra_opencode(ruolo: str) -> dict:
+ chiave = os.environ.get('DELMINIO_SQUADRA', '')
+ sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
+ if not sq:
+ return {}
+ lancio, plugin = (sq['ruoli'], sq['plugin'])
+ per_me = lambda r: not r or ruolo in r
+ skill = [os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}') for n, r in sorted((lancio.get('skill') or {}).items()) if per_me(r) and NOME_PLUGIN_OK.fullmatch(n) and os.path.isfile(os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}', 'SKILL.md'))]
+ del_ruolo = os.path.join(sq['cartella'], 'ruoli', ruolo, plugin)
+ base = del_ruolo if ruolo and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], plugin)
+ comandi, agenti = ({}, {})
+ for cartella, dove in (('commands', comandi), ('agents', agenti)):
+ try:
+ nomi = sorted(os.listdir(os.path.join(base, cartella)))
+ except OSError:
+ nomi = []
+ for x in nomi:
+ n = x[:-3] if x.endswith('.md') else ''
+ if not NOME_PLUGIN_OK.fullmatch(n):
+ continue
+ try:
+ with open(os.path.join(base, cartella, x), encoding='utf-8') as h:
+ campi, corpo = _testa(h.read())
+ except OSError:
+ continue
+ descrizione = str(campi.get('description') or n)
+ if cartella == 'commands':
+ dove[f'{plugin}:{n}'] = {'template': corpo.strip() or '$ARGUMENTS', 'description': descrizione}
+ else:
+ dove[f'{plugin}-{n}'] = {'mode': 'subagent', 'description': descrizione, 'system': corpo.strip()}
+ server = {}
+ for n, m in sorted((lancio.get('mcp') or {}).items()):
+ spec = m.get('spec') or {}
+ if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
+ continue
+ if spec.get('tipo') == 'remoto' and spec.get('url'):
+ t = spec.get('token_variabile')
+ s = {'type': 'remote', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer {env:' + t + '}'}} if t else {})}
+ elif spec.get('comando'):
+ s = {'type': 'local', 'command': [str(spec['comando'])] + [str(a) for a in spec.get('argomenti') or []], **({'environment': {v: '{env:' + v + '}' for v in spec['variabili']}} if spec.get('variabili') else {})}
+ else:
+ continue
+ server[f'{plugin}-{n}'] = s
+ out: dict = {}
+ if skill:
+ out['skills'] = skill
+ if comandi:
+ out['commands'] = comandi
+ if agenti:
+ out['agents'] = agenti
+ if server:
+ out['mcp'] = {'servers': server}
+ return out
+
+def _collegata_a(casa: str, nome: str, dove: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'extensions', nome, '.qwen-extension-install.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ except (OSError, ValueError):
+ return False
+ sorgente = os.path.realpath(d.get('source') or '')
+ dove = os.path.realpath(dove)
+ return d.get('type') == 'link' and (sorgente == dove or sorgente.startswith(dove + os.sep))
+
+def codex(casa: str) -> int:
+ try:
+ _squadra_codex(casa)
+ _squadra_plugin_codex(casa)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 0
+
+def qwen(casa: str) -> int:
+ try:
+ _squadra_qwen(casa)
+ _squadra_plugin_qwen(casa)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 0
+
+def stacca(radice: str) -> int:
+ d = cartella_squadre()
+ for nome in sorted(os.listdir(d)) if os.path.isdir(d) else []:
+ if nome.endswith('.plugin-installati.json') and _chiave_ok(nome.split('.', 1)[0]):
+ chiave = nome.split('.', 1)[0]
+ stato = _installati(chiave)
+ miei = stato.pop('claude:' + radice, None) or {}
+ for pid in miei:
+ try:
+ _claude('uninstall', pid, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ if miei:
+ _installati_scrivi(chiave, stato)
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ return 0
+ cambiato = False
+ for k in [k for k in s.get('enabledPlugins') or {} if k.split('@', 1)[-1].startswith(SQUADRA_MKT)]:
+ del s['enabledPlugins'][k]
+ cambiato = True
+ if isinstance(s.get('enabledPlugins'), dict) and (not s['enabledPlugins']):
+ del s['enabledPlugins']
+ mercati = s.get('extraKnownMarketplaces')
+ for m in [m for m in mercati or {} if m.startswith(SQUADRA_MKT)] if isinstance(mercati, dict) else []:
+ del mercati[m]
+ cambiato = True
+ if isinstance(mercati, dict) and (not mercati):
+ del s['extraKnownMarketplaces']
+ if cambiato:
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ os.replace(p + '.nuovo', p)
+ return 0
+
+def main(argv: list[str]) -> int:
+ if argv == ['accetta']:
+ return squadra_accetta_dal_terminale()
+ if len(argv) == 3 and argv[0] == 'lancio':
+ for x in squadra_lancio(argv[1], os.path.realpath(argv[2])):
+ print(x)
+ return 0
+ if len(argv) == 2 and argv[0] in ('codex', 'qwen', 'stacca'):
+ return {'codex': codex, 'qwen': qwen, 'stacca': stacca}[argv[0]](os.path.realpath(argv[1]))
+ print(F('uso'), file=sys.stderr)
+ return 1
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/en/worktree-client b/kit/en/worktree-client
new file mode 100644
index 0000000..b20c45c
--- /dev/null
+++ b/kit/en/worktree-client
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+case "${1:-}" in
+ nuovo|merge|smonta)
+ principale=$(cd "$(dirname "$(_assoluto "$0")")/.." && pwd)
+ if f=$(chiedi GET /api/funzioni); then
+ perche=$(printf '%s' "$f" | python3 -c 'import json,sys
+x = next((x for x in json.load(sys.stdin)["funzioni"] if x["id"] == "agenti"), {})
+print("" if x.get("accesa", True) else "licenza" if x.get("concessa") is False else "spenta")' 2>/dev/null || true)
+ case "$perche" in
+ licenza) echo "$M_piu_agenti_non_concessa" >&2; exit 1 ;;
+ spenta) echo "$M_piu_agenti_insieme" >&2; exit 1 ;;
+ esac
+ fi
+ remoto=$(git -C "$principale" remote get-url origin 2>/dev/null || true)
+ pid=$(cli_pid || true); nome="${2:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { _f "$M_chi_sei_bash" gesto "$1" >&2; exit 1; }
+ qui=$(git rev-parse --show-toplevel 2>/dev/null || echo "$principale")
+ if [ -z "${DELMINIO_WORKTREE_DEL_PROGETTO:-}" ] && [ -x "$qui/.delminio/worktree" ]; then
+ DELMINIO_WORKTREE_DEL_PROGETTO=1 exec "$qui/.delminio/worktree" "$1" "$nome"
+ fi
+ ramo="sessione/$nome"; wt="$(dirname "$principale")/$(basename "$principale")-$nome"
+ case "$1" in
+ nuovo)
+ [ -e "$wt" ] && { _f "$M_gia_entraci_smontalo" wt "$wt" >&2; exit 1; }
+ [ -z "$remoto" ] || git -C "$principale" pull -q --ff-only 2>/dev/null || echo "$M_principale_aggiorna_remoto" >&2
+ git -C "$principale" worktree add -q "$wt" -b "$ramo" || exit 1
+ for f in $KIT_FILE; do
+ [ -e "$principale/$f" ] && mkdir -p "$wt/$(dirname "$f")" && ln -sfn "$principale/$f" "$wt/$f"
+ done
+ _f "$M_ramo" wt "$wt" ramo "$ramo"
+ case "$( [ -n "$pid" ] && cli_di "$pid")" in
+ codex)
+ _f "$M_codex_resta_dov" wt "$wt" ;;
+ claude)
+ echo "$M_entraci_col_tool"
+ echo "$M_lavoro_tocca_altro" ;;
+ *)
+ _f "$M_tua_cli_modo" wt "$wt" ;;
+ esac
+ ;;
+ merge)
+ dove=$(git rev-parse --show-toplevel)
+ [ "$dove" = "$wt" ] || { _f "$M_merge_lancia_tuo" wt "$wt" dove "$dove" >&2; exit 1; }
+ [ -z "$(git status --porcelain --untracked-files=no)" ] || { echo "$M_hai_lavoro_committato" >&2; git status --short | head -10 >&2; exit 1; }
+ exec 9>"$(git rev-parse --git-common-dir)/delminio-merge.lock"
+ _lucchetto 600 || { echo "$M_altro_merge_corso" >&2; exit 1; }
+ staged=$(git -C "$principale" diff --cached --name-only)
+ [ -z "$staged" ] || { echo "$M_principale_lavoro_staging" >&2; echo "$staged" | head -10 >&2; exit 1; }
+ [ -z "$remoto" ] || git -C "$principale" pull -q --ff-only 2>/dev/null || { echo "$M_principale_aggiorna_remoto_2" >&2; exit 1; }
+ collisione=$(comm -12 <(git -C "$principale" diff --name-only | sort -u) <(git diff --name-only "$(git merge-base HEAD "$(git -C "$principale" rev-parse HEAD)")" HEAD | sort -u))
+ [ -z "$collisione" ] || { echo "$M_merge_toccherebbe_file" >&2; echo "$collisione" | head -10 >&2; exit 1; }
+ git -C "$principale" merge -q --no-edit "$ramo" || { git -C "$principale" merge --abort 2>/dev/null; ramo_principale=$(git -C "$principale" rev-parse --abbrev-ref HEAD); _f "$M_merge_non_pulito" ramo "$ramo_principale" >&2; exit 1; }
+ if [ -z "$remoto" ]; then
+ _f "$M_principale_senza_remoto" ramo "$ramo"
+ else
+ git -C "$principale" push -q origin HEAD || { echo "$M_mergiato_locale_push" >&2; exit 1; }
+ _f "$M_principale_remoto" ramo "$ramo"
+ fi
+ ;;
+ smonta)
+ [ -d "$wt" ] || { _f "$M_nessun_worktree" wt "$wt"; exit 0; }
+ sporchi=$(git -C "$wt" status --porcelain 2>/dev/null)
+ [ -z "$sporchi" ] || { _f "$M_file_committati_smonta" wt "$wt" >&2; exit 1; }
+ git -C "$principale" merge-base --is-ancestor "$ramo" HEAD \
+ || { _f "$M_principale_prima_merge" ramo "$ramo" >&2; exit 1; }
+ git -C "$principale" worktree remove "$wt" && git -C "$principale" branch -q -d "$ramo" && _f "$M_smontato_tolto" wt "$wt" ramo "$ramo"
+ ;;
+ esac
+ ;;
+esac
diff --git a/kit/it/aggancia.sh b/kit/it/aggancia.sh
new file mode 100644
index 0000000..5739a4a
--- /dev/null
+++ b/kit/it/aggancia.sh
@@ -0,0 +1,1131 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+set -euo pipefail
+
+URL="${DELMINIO_URL:-__DELMINIO_URL__}"
+URL="${URL%/}"
+
+muori() { printf '❌ %s\n' "$*" >&2; exit 1; }
+_no_del_motore() {
+ local c=${1##*$'\n'} e
+ case "$c" in
+ 200) return 0 ;;
+ ''|000) [ -n "${2:-}" ] || return 0
+ e=$(_f "$M_non_risponde" url "$URL"); muori "$(_f "$M_rifiutato" motivo "$e")" ;;
+ *) e=$(printf '%s' "${1%$'\n'*}" | campo error); muori "$(_f "$M_rifiutato" motivo "HTTP $c${e:+: $e}")" ;;
+ esac
+}
+
+: '⟦frasi: aggancia⟧'
+M_agente_opencode_domanda='
+ OpenCode lavora coi modelli di un fornitore. Hai la sua chiave? [c] la metto adesso — oppure [g] provo coi modelli gratuiti di OpenCode, senza chiave: '
+M_agente_opencode_gratuito=' Il modello gratuito che risponde adesso è {modello}: va bene per provare; per lavorare davvero serve la chiave di un fornitore.'
+M_agente_opencode_nessuno='nessun modello gratuito di OpenCode risponde adesso: rilancia questo comando e scegli la chiave di un fornitore'
+M_agente_opencode_chiave_no='la chiave non è stata messa: rilancia questo comando, o scegli i modelli gratuiti'
+M_agente_opencode_senza_terminale=' OpenCode è installato. Per partire serve un terminale: rilancia questo comando da lì, e scegli la chiave o i modelli gratuiti.'
+M_agente_non_installato='{cli} non si è installato (il perché è nelle righe sopra): rilancia questo comando, e se si ferma di nuovo mostra quelle righe a chi ti ha dato Delminio'
+M_agente_quale='«--agente» vuole claude, codex, qwen o opencode e la versione (hai scritto «{cli} {versione}»)'
+M_agente_frase='Leggi con curl -fsSL {url}/aggancia.md e segui quel testo parola per parola.'
+M_agente_entra_account='la prima volta ti chiede di entrare col tuo account (si apre il browser) e se fidarti di questa cartella: di'"'"' di sì.'
+M_agente_entra_qwen='la prima volta ti chiede a quale modello collegarsi: l'"'"'account Qwen, o un fornitore con la sua chiave (lo scegli dall'"'"'elenco e incolli la chiave). Poi, se te lo chiede, di'"'"' che ti fidi di questa cartella.'
+M_agente_entra_opencode='con la chiave o il modello gratuito che hai scelto.'
+M_agente_parte='
+ Fatto: {cli} è su questo computer. Adesso parte: {entra}
+ Gli abbiamo già dato la frase: legge la guida di Delminio e ti porta per tutti i passi — il git, il progetto, la copia delle memorie, il collegamento. Quello che sai già fare, diglielo e lo salta.
+ Se si chiude a metà, rilancia lo stesso comando: non riscarica niente, e lo riapre già con la frase.
+'
+M_manca='manca «{c}»: installalo e rilancia questo comando (su Ubuntu e Debian: sudo apt install {c})'
+M_non_parte='«{c}» c'"'"'è ({dove}) ma non parte: {perche}. Sistemalo e rilancia questo comando.'
+M_mac_strumenti='Su questo Mac git e python3 sono quelli di Apple, che partono solo con gli strumenti da riga di comando di Apple (circa 1 GB, un clic).
+ Ho chiesto al Mac di installarli: nella finestra di Apple premi «Installa», aspetta che finisca e rilancia questo comando.
+ Se la finestra non si è aperta, lancia tu: xcode-select --install'
+M_argomento_ignoto='non conosco «{arg}»: gli argomenti sono --installa claude, codex o qwen, e --agente claude, codex, qwen o opencode con la versione'
+M_installa_quale='«--installa» vuole claude, codex o qwen (hai scritto «{cli}»)'
+M_chi_sei_nome='git non sa ancora chi sei. Il nome che firmerà il tuo lavoro (per esempio Maria Rossi): '
+M_chi_sei_mail='La tua email: '
+M_installo_cli=' Installo {cli} su questa macchina, nella versione scelta in Delminio: la prima volta qualche minuto.'
+M_installa_non_riuscita='il computer è collegato, ma {cli} non si è installato (il perché è nelle righe sopra): rilancia questo comando, e se si ferma di nuovo mostra quelle righe all'"'"'amministratore'
+M_parto_codex=' Con Codex, dopo la cartella: scrivi /hooks e scegli «Trust all», una volta sola. Senza, Codex parte ma non sente Delminio.
+'
+M_parto_qwen=' Con Qwen Code il modello e il fornitore sono quelli dell'"'"'agente nella vista Agenti, e la chiave del fornitore la legge dal tuo ambiente.
+'
+M_fuori_dal_clone='lancialo dentro il clone del repo che vuoi collegare'
+M_progetto_nome='Qui ({dove}) non c'"'"'è un progetto git. Ne creo uno nuovo, in una cartella nuova qui dentro, con un git solo su questo computer.
+Come la chiamo? [progetto] '
+M_progetto_nome_no='«{nome}» non va bene come nome di cartella: usa lettere senza accenti, numeri, «-» e «_», e non cominciare con un punto'
+M_progetto_esiste='{cartella} c'"'"'è già e non la tocco: rilancia scegliendo un altro nome, o entra lì dentro e rilancia se è già il tuo progetto'
+M_progetto_creato=' Il progetto è nella cartella {cartella}, con un git solo su questo computer. Quando vorrai metterlo anche su GitHub o su un altro git host, te lo spiega l'"'"'agente.'
+M_progetto_primo_commit='Il progetto comincia'
+M_parto='
+ Fatto. Parte {nome}. La prima volta ti chiede di entrare col tuo account (si apre il browser) e se fidarti di questa cartella: di'"'"' di sì.
+ Quando è pronto scrivi {apertura}: da lì l'"'"'agente ti guida. Le volte dopo apri il terminale in {cartella} e scrivi {dopo}.
+'
+M_rito_apertura=/apertura
+M_rito_apertura_codex=apertura
+M_comando_occupato='{file} c'"'"'è già e non è di Delminio: non lo tocco. Senza il comando «delminio», i comandi si scrivono per intero, dalla cartella del progetto: bash .claude/delminio.sh …'
+M_comando_fuori='delminio: qui non c'"'"'è un progetto collegato a Delminio. Entra nella cartella del progetto, o in una sua sottocartella, e riprova.'
+M_chi_sei='git non sa chi sei: git config --global user.name "Nome" && git config --global user.email tu@esempio.it'
+M_senza_origin='questo repo non ha un remoto «origin»: la chiusura e il merge restano su questa macchina, e chi lavora da un'"'"'altra non li vede'
+M_non_pusha='non puoi pushare su {origine} (git: {errore}): la chiusura e il merge resteranno su questa macchina finché non sistemi le credenziali'
+M_codice_apri=' Apri questo indirizzo e premi Approva:'
+M_codice_oppure=' (oppure: Delminio → Accesso, scrivi il codice {codice} e premi Approva)'
+M_codice_vale=' Vale 10 minuti. Questa macchina si presenta come «{macchina}».
+ Aspetto l'"'"'approvazione…'
+M_approvato=' ✅ approvato'
+M_scaduto=' ❌ il codice è scaduto: rilancia il comando'
+M_senza_terminale='nessun terminale per chiedere il token: passalo in DELMINIO_TOKEN'
+M_domanda_token='Il token di Delminio (UI → Accesso → Collegare un repo): '
+M_nessun_token='nessun token'
+M_non_risponde='Delminio non risponde a {url}'
+M_token_rifiutato='Delminio a {url} rifiuta questo token (HTTP {codice})'
+M_rifiutato='non collegato: {motivo}'
+M_tiene_gia='⚠️ In questo spazio di Delminio sono già collegati altri repo: {altri}.
+ Uno spazio contiene un solo progetto: più repo vanno bene se fanno parte dello stesso
+ lavoro, con la stessa squadra. Un progetto diverso va in un altro spazio.'
+M_stessa_storia=' {repo} fa parte dello stesso progetto? [s/N] '
+M_altra_storia='non collegato: se è un altro progetto, crea un altro spazio (nell'"'"'app, «Spazi») e collegalo lì; se è lo stesso, rilancia il comando e rispondi sì'
+M_app_codex_domanda=' Su questo computer c'"'"'è l'"'"'app di Codex: ci metto anche Delminio? Aggiungo a ~/.codex/config.toml solo il plugin di Delminio e il permesso dei suoi due strumenti. [s/N] '
+M_clone_fermo='il clone delle memorie in {cartella} non si aggiorna: si riprova a ogni apertura'
+M_clone_https=' memorie: l'"'"'ssh di {remoto} non passa da qui, clonate in https ({https})'
+M_clonate=' memorie: clonate da {remoto} in {cartella} — la CLI ci trova l'"'"'indice'
+M_memorie_vuote='il repo delle memorie ({remoto}) è ancora vuoto: Delminio ci mette la base appena il suo push passa (Impostazioni → «Le memorie su git»: la chiave di deploy, con scrittura). Il clone in {cartella} si aggiorna da sé; finché è vuoto l'"'"'agente si avvia senza l'"'"'indice, e glielo si dice'
+M_clone_negato='il repo delle memorie ({remoto}) non si legge da questo computer con le tue credenziali git: va bene così, l'"'"'agente riceve l'"'"'indice delle memorie da Delminio all'"'"'apertura. Se vuoi anche la copia locale, chiedi l'"'"'accesso in lettura a chi ha il repo e rilancia il collegamento'
+M_codex_indice=' Codex e Qwen Code ricevono l’indice delle memorie nell’apertura di Delminio: non serve un clone git locale né una chiamata iniziale a list.'
+M_senza_embedder='Delminio non ha un embedder: finché l'"'"'amministratore non lo configura (Impostazioni → Embedder) le memorie si cercano per parole, non per senso'
+M_embedder_muto='l'"'"'embedder configurato in Delminio non risponde ({risposta}): finché non torna si cerca per parole'
+M_note_sue='📦 La tua CLI tiene le sue note in {cartella} (lo dice {fonte}).
+ Da adesso le terrebbe Delminio e quella cartella non si leggerebbe più. Prima ne faccio una copia di
+ sicurezza fuori dal repo, l'"'"'agente ti propone le note come memorie, e con
+ «delminio stacca» torna tutto com'"'"'era.'
+M_va_bene=' Va bene? [s/N] '
+M_memoria_sua_resta='non collegato: la tua memoria resta dov'"'"'è. Se va bene, rilancia e rispondi sì (o DELMINIO_MEMORIA_SUA=si)'
+M_prima_non_salva='non riesco a fare la copia di sicurezza di ciò che c'"'"'era prima: non ho toccato niente'
+M_prima_copia_diversa='la copia di {file} non è uguale all'"'"'originale: mi fermo prima di toccare qualunque cosa'
+M_mcp_fallito='claude mcp add è fallito'
+M_mcp_senza_claude='Claude Code non è nel PATH di questa shell: il tool di Delminio non è registrato, e un Claude che parte qui non avrebbe la memoria. Con Claude Code installato (e `claude` nel PATH), rilancia questo collegamento: rifà solo ciò che manca.'
+M_senza_client='Delminio non dà il client ({indirizzo})'
+M_comando_tuo='{file} è un tuo /{c}, e vince su quello di Delminio in ogni progetto: qui /{c} non sarà quello di Delminio. Se vuoi quello, rinomina il tuo (per esempio in /{c}-mio)'
+M_mcp_col_nome_nostro='{file} ha un suo server MCP che si chiama «memoria», come quello di Delminio: in {cli} prende il suo posto, e l'"'"'agente resta senza memoria. Dagli un altro nome.'
+M_json_non_valido='{file} non è JSON valido: correggilo e rilancia'
+M_codex_sotto_git='.codex/hooks.json è sotto git: Codex qui si avvia senza gli hook di Delminio. Rimuovi il file da git (resta tuo), o aggiungi a mano gli hook di .claude/settings.local.json, e rilancia il collegamento'
+M_qwen_sotto_git='.qwen/settings.json è sotto git: Qwen Code qui si avvia senza gli hook di Delminio. Rimuovi il file da git (resta tuo), o aggiungi a mano gli hook di .claude/settings.local.json, e rilancia il collegamento'
+M_senza_client_cantiere='Delminio non dà il client del Backlog ({indirizzo})'
+M_senza_client_eseguibili='Delminio non dà il client degli eseguibili ({indirizzo})'
+M_senza_client_cassaforte='Delminio non dà il client della cassaforte ({indirizzo})'
+M_apertura_muta='l'"'"'hook d'"'"'apertura non riceve risposta da Delminio: guarda delminio apertura'
+M_nello_spazio=' nello spazio «{spazio}»'
+M_collegato='✅ {repo} è collegato a Delminio ({url}){dove} come {chi}.'
+M_sempre_nello_spazio=' Chi apre l'"'"'agente in questa cartella lavora sempre{dove}: per un altro spazio, un altro clone collegato da lì.'
+M_prima_al_sicuro='📦 Ciò che c'"'"'era prima è al sicuro in {cartella}, fuori dal repo (il LEGGIMI.md lì dentro dice cosa).
+ L'"'"'agente lo rivede con te alla prima sessione. Tornare com'"'"'era: delminio stacca'
+M_apri_eseguibile=' Apri l'"'"'agente qui dentro col tuo eseguibile di Delminio, e scrivi /apertura.'
+M_scrivi_eseguibile=' L'"'"'agente si avvia meglio dal comando di Delminio, con le regole in cima:
+ delminio eseguibili lo scrive su questa macchina (il nome nella vista Agenti); poi /apertura.'
+M_path_nuovo=' ℹ️ Il comando «delminio» sta in {cartella}, che questo terminale non ha nel PATH: finché non c'"'"'è, scrivilo intero,
+ {comando}. Su Linux di solito un terminale nuovo lo trova già col nome.'
+M_con_codex=' Con Codex: se è già aperto, chiudilo e rilancialo dal comando di Delminio (quello che scrive «eseguibili»):
+ un Codex aperto prima del collegamento non vede Delminio. Al primo avvio Codex chiede se fidarsi della
+ cartella e degli hook (/hooks → Trust all): di'"'"' di sì, poi scrivi apertura, senza la barra.'
+M_senza_cli=' Su questa macchina non c'"'"'è ancora la CLI di un agente (claude, codex, qwen o opencode). Per installarne
+ una, rilancia il collegamento con quella che vuoi: il comando giusto sta in Delminio → Agenti →
+ «Collega un altro computer» → «Non ho un agente».'
+M_con_qwen=' Con Qwen Code: lancialo dal comando di Delminio (quello che scrive «delminio eseguibili»), che gli dà il modello
+ scelto nella vista Agenti e la sua chiave dall'"'"'ambiente; un Qwen aperto prima del collegamento non vede
+ Delminio. Poi scrivi /apertura.'
+M_con_opencode=' Con OpenCode: aprilo in questa cartella (uno già aperto va rilanciato): la memoria, /apertura e /chiusura
+ li porta il plugin di Delminio in .opencode/plugins. Poi scrivi /apertura.'
+M_qwen_ripiego='L'"'"'estensione di Delminio non si è collegata in Qwen Code ({agente}): gli hook e /apertura e /chiusura restano nel progetto, come prima del pacchetto.'
+M_solo_claude=' Col solo claude, o dall'"'"'app desktop, si avvia col prompt di serie: /apertura gli porta le regole.'
+M_gancio_tuo='⚠️ {file} c'"'"'è già e non è di Delminio: aggiungici tu {riga}'
+M_gancio_globale='⚠️ gli hook di git qui vengono da {dir}, che non è di questo repo (core.hooksPath globale): vale per tutti i tuoi repo, e Delminio non ci scrive. Aggiungi tu a {file} {riga}'
+M_prima_questo_progetto='questo progetto'
+M_prima_claude_md='le istruzioni del progetto per Claude'
+M_prima_claude_local='le tue istruzioni personali per questo progetto'
+M_prima_settings='le impostazioni locali della CLI per questo progetto, com'"'"'erano'
+M_prima_hook_codex='gli hook di Codex per questo progetto, com'"'"'erano'
+M_prima_qwen='le impostazioni di Qwen Code per questo progetto, com'"'"'erano'
+M_prima_apertura='il tuo comando /apertura: da adesso è quello di Delminio, e i suoi passi l'"'"'agente te li propone dentro quello nuovo'
+M_prima_chiusura='il tuo comando /chiusura: da adesso è quello di Delminio, e i suoi passi l'"'"'agente te li propone dentro quello nuovo'
+M_prima_mcp='il server MCP «{nome}» che avevi prima (contiene il suo token)'
+M_prima_note='- `memoria/` — le {n} note che la CLI si era scritta da sé, da `{cartella}`'
+M_prima_configurazioni='- le tue configurazioni della CLI (hook, comandi, agenti, server MCP, plugin): **non si toccano**, restano dove sono; i file di impostazioni sono anche in questa copia, in `fatti.json` c'"'"'è l'"'"'elenco, e l'"'"'agente ti dice cosa funziona insieme a Delminio e cosa no'
+M_prima_altri='- le istruzioni che hai scritto per altri strumenti e le memorie che altri strumenti si tengono ({elenco}): **copiate qui e non toccate**, gli originali restano dove sono; in `fatti.json` c'"'"'è cosa sono, e l'"'"'agente te le propone con le note'
+M_prima_chiesti='- ciò che hai chiesto di mettere al sicuro prima del collegamento ({elenco})'
+M_prima_tutti='- in tutto {n} file, ognuno con la sua impronta in `fatti.json`: così si controlla che la copia sia uguale all'"'"'originale'
+M_prima_non_copiato='- `{file}`: non copiato ({perche})'
+M_prima_perche_credenziali='contiene credenziali: resta solo dov'"'"'è, e il collegamento non lo tocca'
+M_prima_perche_grande='troppo grande per la copia: resta dov'"'"'è, e il collegamento non lo tocca'
+M_prima_perche_fuori='sta fuori dal repo e dalla tua cartella personale'
+M_prima_perche_assente='non c'"'"'è'
+M_prima_niente_da_ripassare='niente di tuo da rivedere: la copia c'"'"'è lo stesso'
+M_prima_leggimi_titolo='Ciò che c'"'"'era prima di Delminio'
+M_prima_leggimi_testa='Il collegamento a Delminio ha copiato qui, prima di toccare qualunque cosa, ciò che questo progetto aveva su questa macchina. Niente è stato eliminato: gli originali sono ancora al loro posto.'
+M_prima_leggimi_note='Le note della CLI da adesso non si leggono più: la CLI legge l'"'"'indice di Delminio. L'"'"'agente te le propone come memorie, una per una, e si crea solo ciò che approvi; i CLAUDE.md li puoi tenere come sono, o passarli a Delminio.'
+M_prima_leggimi_tornare='Tornare com'"'"'era: `delminio stacca`. Rimette le impostazioni, i comandi e il server MCP di prima, e la CLI torna a leggere le sue note; ciò che è stato creato in Delminio resta in Delminio.'
+M_qwen_comando_apertura='Delminio: apri la sessione col briefing del tuo ruolo — ciò che scrivi dopo il comando parte come tuo messaggio'
+M_qwen_comando_chiusura='Delminio: chiudi la sessione — ciò che scrivi dopo il comando parte come tuo messaggio'
+M_senza_client_plugin='Delminio non dà il client del pacchetto per le CLI ({indirizzo})'
+M_senza_client_squadra='Delminio non dà il client della squadra ({indirizzo})'
+M_kit_non_firmato='{file} da {url} non porta la firma dei rilasci di Delminio, o non è il file firmato: non lo installo. Se questo Delminio è una versione di sviluppo, e lo sai, rilancia con DELMINIO_KIT_SENZA_FIRMA=1.'
+: '⟦fine frasi⟧'
+export ${!M_@} # anche ai python (F, fra gli aiutanti qui sotto)
+
+
+PORTABILI=$(cat <<'PORTABILI'
+ha_terminale() { { : </dev/tty; } 2>/dev/null; }
+_f() { # _f "$M_<chiave>" [segnaposto valore]... → la frase coi {segnaposto} riempiti
+ local t=$1 k v fuori
+ shift
+ while [ $# -ge 2 ]; do
+ k="{$1}"; v=$2; fuori=""
+ while [ "${t#*"$k"}" != "$t" ]; do fuori=$fuori${t%%"$k"*}$v; t=${t#*"$k"}; done
+ t=$fuori$t; shift 2
+ done
+ printf '%s\n' "$t"
+}
+export DELMINIO_F_PY='def F(chiave, **s):
+ t = __import__("os").environ.get("M_" + chiave, chiave)
+ for k, v in s.items():
+ t = t.replace("{" + k + "}", str(v))
+ return t'
+_sha16() { # stdin → i primi 16 dello sha256 (il nome del file del token: uguale ovunque)
+ if command -v sha256sum >/dev/null 2>&1; then sha256sum
+ elif command -v shasum >/dev/null 2>&1; then shasum -a 256
+ else python3 -c 'import hashlib, sys; print(hashlib.sha256(sys.stdin.buffer.read()).hexdigest())'
+ fi | cut -c1-16
+}
+_tempo() { # _tempo <secondi> <comando…> — come timeout: 124 se scade
+ if command -v timeout >/dev/null 2>&1; then timeout "$@"
+ elif command -v gtimeout >/dev/null 2>&1; then gtimeout "$@"
+ else python3 -c 'import subprocess, sys
+try: sys.exit(subprocess.run(sys.argv[2:], timeout=float(sys.argv[1])).returncode)
+except subprocess.TimeoutExpired: sys.exit(124)
+except OSError: sys.exit(127)' "$@"
+ fi
+}
+_staccato() { # _staccato <comando…> — in una sessione sua: la CLI che esce non se lo porta via
+ if command -v setsid >/dev/null 2>&1; then setsid nohup "$@"
+ else nohup python3 -c 'import os, sys
+try: os.setsid()
+except OSError: pass
+os.execvp(sys.argv[1], sys.argv[1:])' "$@"
+ fi
+}
+_mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || echo 0; }
+_lucchetto() { # _lucchetto <secondi> — esclusivo sull'fd 9, come flock -w
+ if command -v flock >/dev/null 2>&1; then flock -w "$1" 9
+ else python3 -c 'import fcntl, sys, time
+fine = time.time() + float(sys.argv[1])
+while True:
+ try:
+ fcntl.flock(9, fcntl.LOCK_EX | fcntl.LOCK_NB); break
+ except BlockingIOError:
+ if time.time() > fine: sys.exit(1)
+ time.sleep(0.5)' "$1"
+ fi
+}
+_assoluto() { python3 -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' "$1"; }
+_args() { # _args <pid> → gli argomenti del processo, uno per riga, coi loro confini
+ if [ -r "/proc/$1/cmdline" ]; then tr '\0' '\n' < "/proc/$1/cmdline"; return; fi
+ python3 -c 'import ctypes, ctypes.util, struct, sys
+pid = int(sys.argv[1]); libc = ctypes.CDLL(ctypes.util.find_library("c"))
+def leggi(mib):
+ m = (ctypes.c_int * len(mib))(*mib); n = ctypes.c_size_t(0)
+ if libc.sysctl(m, len(mib), None, ctypes.byref(n), None, 0): sys.exit(1)
+ b = ctypes.create_string_buffer(n.value)
+ if libc.sysctl(m, len(mib), b, ctypes.byref(n), None, 0): sys.exit(1)
+ return b.raw[:n.value]
+if sys.platform == "darwin":
+ r = leggi([1, 49, pid]) # KERN_PROCARGS2: argc, il percorso, NUL, gli argomenti
+ argc = struct.unpack("i", r[:4])[0]; r = r[4:]
+ args = r[r.index(b"\0"):].lstrip(b"\0").split(b"\0")[:argc]
+else:
+ args = leggi([1, 14, 7, pid]).rstrip(b"\0").split(b"\0") # KERN_PROC_ARGS
+print("\n".join(a.decode(errors="replace") for a in args))' "$1" 2>/dev/null \
+ || ps -o args= -p "$1" 2>/dev/null | tr ' ' '\n'
+}
+_chiave() { printf 'header = "Authorization: Bearer %s"\n' "$1"; }
+KIT_FIRMA='ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOpJpAP6o9ATpruI8Stf85bQMwgmrVlsmY3JSvkDDwl0'
+_firmato() { # _firmato <indirizzo> <nome servito> <file> → 0 se il file sta nella firma del kit
+ [ -n "${DELMINIO_KIT_SENZA_FIRMA:-}" ] && return 0
+ local d r=1
+ d=$(mktemp -d) || return 1
+ if curl -fsS -m 30 "$1/static/kit/FIRMA" -o "$d/f" 2>/dev/null \
+ && curl -fsS -m 30 "$1/static/kit/FIRMA.sig" -o "$d/f.sig" 2>/dev/null \
+ && printf 'rilasci@delminio.com %s\n' "$KIT_FIRMA" > "$d/chi" \
+ && ssh-keygen -Y verify -f "$d/chi" -I rilasci@delminio.com -n delminio-kit -s "$d/f.sig" < "$d/f" >/dev/null 2>&1 \
+ && python3 -c 'import hashlib, sys
+i = hashlib.sha256(open(sys.argv[3], "rb").read()).hexdigest()
+righe = open(sys.argv[1], encoding="utf-8").read().splitlines()
+sys.exit(0 if righe[:1] and righe[0].startswith("delminio-kit ") and i + " " + sys.argv[2] in righe[1:] else 1)' \
+ "$d/f" "$2" "$3"; then
+ r=0
+ fi
+ rm -rf "$d"
+ return $r
+}
+campo() { # campo <chiave> < json → il valore, o "" (anche su un corpo che non è JSON)
+ python3 -c 'import json,sys
+try: print(json.load(sys.stdin).get(sys.argv[1]) or "")
+except Exception: print("")' "$1"
+}
+json_stringa() { python3 -c 'import json,sys; print(json.dumps(sys.argv[1]))' "$1"; } # una stringa JSON
+export DELMINIO_GANCI_PY='def nostro(h, cosa=None):
+ c = h.get("command", "")
+ return ".claude/mneme.sh" in c or ("delminio.sh" in c and (cosa is None or c.endswith(" " + cosa)))
+def togli_ganci(s, cosa=None):
+ for evento, lista in list((s.get("hooks") or {}).items()):
+ for b in lista:
+ b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
+ lista[:] = [b for b in lista if b.get("hooks")]
+ if not lista:
+ del s["hooks"][evento]
+ if not s.get("hooks"):
+ s.pop("hooks", None)
+def metti_ganci(s, comando, gesti, matcher_sempre=False):
+ for evento, cosa, extra, matcher in gesti:
+ lista = s.setdefault("hooks", {}).setdefault(evento, [])
+ for b in lista:
+ b["hooks"] = [h for h in b.get("hooks", []) if not nostro(h, cosa)]
+ lista[:] = [b for b in lista if b.get("hooks")]
+ lista.append({**({"matcher": matcher} if matcher or matcher_sempre else {}),
+ "hooks": [{"type": "command", "command": comando + " " + cosa, **extra}]})'
+KIT_FILE=".claude/delminio.sh .claude/lanciatori.sh .claude/ganci-git.sh .claude/worktree.sh .claude/consumi.py .claude/cantiere.py .claude/backlog.py .claude/eseguibili.py .claude/cassaforte.py .claude/firme.py .claude/plugin.py .claude/squadra.py .claude/settings.local.json .claude/commands/apertura.md .claude/commands/chiusura.md .claude/commands/start.md .claude/commands/handoff.md .claude/commands/opening.md .claude/commands/closing.md .claude/rules/delminio.md .codex/hooks.json .qwen/settings.json .qwen/commands/apertura.md .qwen/commands/chiusura.md .qwen/commands/start.md .qwen/commands/handoff.md .qwen/commands/opening.md .qwen/commands/closing.md .claude/opencode.js .opencode/plugins/delminio.js"
+KIT_DI_PRIMA=".claude/guardia.py .claude/commands/risveglio.md"
+PORTABILI
+)
+eval "$PORTABILI"
+
+installa=""
+agente_cli=""; agente_versione=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --installa) installa=${2:-}; [ $# -ge 2 ] && shift; shift ;;
+ --agente) agente_cli=${2:-}; agente_versione=${3:-}; shift; [ $# -gt 0 ] && shift; [ $# -gt 0 ] && shift ;;
+ *) muori "$(_f "$M_argomento_ignoto" arg "$1")" ;;
+ esac
+done
+case "$installa" in ''|claude|codex|qwen) ;; *) muori "$(_f "$M_installa_quale" cli "$installa")" ;; esac
+if [ -n "$agente_cli" ]; then
+ case "$agente_cli" in claude|codex|qwen|opencode) ;; *) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
+ case "$agente_versione" in ''|*[!A-Za-z0-9.]*) muori "$(_f "$M_agente_quale" cli "$agente_cli" versione "$agente_versione")" ;; esac
+fi
+
+segnaposto_apple() {
+ local d
+ [ "$(uname -s)" = Darwin ] || return 1
+ case "$1" in git|python3) ;; *) return 1 ;; esac # curl di /usr/bin è vero
+ case "$(command -v "$1")" in /usr/bin/*) ;; *) return 1 ;; esac
+ d=$(xcode-select -p 2>/dev/null) && [ -d "$d" ] && return 1
+ return 0
+}
+for c in curl git python3; do
+ command -v "$c" >/dev/null || muori "$(_f "$M_manca" c "$c")"
+ if segnaposto_apple "$c"; then
+ xcode-select --install >/dev/null 2>&1 || true
+ muori "$M_mac_strumenti"
+ fi
+ case $c in
+ curl) perche=$(curl --version 2>&1 >/dev/null) ;;
+ git) perche=$(git --version 2>&1 >/dev/null) ;;
+ python3) perche=$(python3 -c 'import json, ssl, urllib.request' 2>&1) ;;
+ esac || {
+ dove_c=$(command -v "$c"); perche=$(printf '%s' "${perche:-?}" | tail -1)
+ muori "$(_f "$M_non_parte" c "$c" dove "$dove_c" perche "$perche")"
+ }
+done
+if [ -n "$agente_cli" ]; then
+ cartella_agente=$(mktemp -d) || muori "$(_f "$M_installa_non_riuscita" cli "$agente_cli")"
+ curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
+ || muori "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
+ _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
+ || muori "$(_f "$M_kit_non_firmato" file eseguibili-client url "$URL")"
+ case $agente_cli in claude) nome_cli="Claude Code" ;; codex) nome_cli=Codex ;; qwen) nome_cli="Qwen Code" ;; *) nome_cli=OpenCode ;; esac
+ _f "$M_installo_cli" cli "$nome_cli"
+ uscita=$(python3 "$cartella_agente/eseguibili.py" installa-agente "$agente_cli" "$agente_versione") \
+ && lancia=$(printf '%s\n' "$uscita" | tail -1) && [ -x "$lancia" ] \
+ || { rm -rf "$cartella_agente"; muori "$(_f "$M_agente_non_installato" cli "$nome_cli")"; }
+ rm -rf "$cartella_agente"
+ nodo=$(printf '%s\n' "$uscita" | sed -n 's/^DELMINIO_NODE=//p' | tail -1)
+ [ -n "$nodo" ] && PATH="$nodo:$PATH" && export PATH
+ case $0 in /dev/fd/*|/proc/self/fd/*) cat "$0" >/dev/null 2>&1 || true ;; esac
+ frase=$(_f "$M_agente_frase" url "$URL")
+ primo=("$frase"); entra=$M_agente_entra_account
+ [ "$agente_cli" = qwen ] && primo=(-i "$frase") && entra=$M_agente_entra_qwen
+ export QWEN_CODE_SKIP_UPDATE_CHECK_ONCE=true OPENCODE_DISABLE_AUTOUPDATE=1
+ if [ "$agente_cli" = opencode ]; then
+ primo=(--standalone)
+ entra=$M_agente_entra_opencode
+ ha_terminale || { echo "$M_agente_opencode_senza_terminale"; exit 0; }
+ risposta=""; read -rp "$M_agente_opencode_domanda" risposta </dev/tty || true
+ case "$risposta" in
+ g|G)
+ cartella_agente=$(mktemp -d)
+ curl -fsS "$URL/static/kit/eseguibili-client" -o "$cartella_agente/eseguibili.py" \
+ && _firmato "$URL" eseguibili-client "$cartella_agente/eseguibili.py" \
+ && modello=$(python3 "$cartella_agente/eseguibili.py" modello-gratuito "$lancia") || modello=""
+ rm -rf "$cartella_agente"
+ [ -n "$modello" ] || muori "$M_agente_opencode_nessuno"
+ _f "$M_agente_opencode_gratuito" modello "$modello"
+ OPENCODE_CONFIG_CONTENT=$(DELMINIO_M="$modello" python3 -c 'import json, os; print(json.dumps({"model": os.environ["DELMINIO_M"]}))')
+ export OPENCODE_CONFIG_CONTENT
+ primo+=(--prompt "$frase") ;;
+ *)
+ "$lancia" auth login </dev/tty || muori "$M_agente_opencode_chiave_no"
+ primo+=(--prompt "$frase") ;;
+ esac
+ fi
+ _f "$M_agente_parte" cli "$nome_cli" entra "$entra"
+ ha_terminale || exit 0
+ if [ -t 0 ]; then exec "$lancia" "${primo[@]}"; fi
+ exec "$lancia" "${primo[@]}" </dev/tty
+fi
+cli_presente() {
+ local d
+ case $1 in
+ claude) d=${DELMINIO_VERSIONI:-$HOME/.local/share/claude/versions} ;;
+ codex) d=${DELMINIO_VERSIONI_CODEX:-$HOME/.local/share/codex/versions} ;;
+ qwen) d=${DELMINIO_VERSIONI_QWEN:-$HOME/.local/share/qwen-code/versions} ;;
+ opencode) d=${DELMINIO_OPENCODE_BIN:-$HOME/.opencode/bin} ;;
+ esac
+ command -v "$1" >/dev/null || [ -n "$(ls -A "$d" 2>/dev/null)" ] \
+ || { [ "$1" = opencode ] && [ -n "$(ls -A "${DELMINIO_VERSIONI_OPENCODE:-$HOME/.local/share/delminio/opencode/versions}" 2>/dev/null)" ]; }
+}
+senza_cli=""
+cli_presente claude || cli_presente codex || cli_presente qwen || cli_presente opencode || senza_cli=1
+chiedi_una_riga() { # chiedi_una_riga <domanda> → la risposta, richiesta finché è vuota (tre volte)
+ local r="" giri=0
+ while [ -z "$r" ] && [ $giri -lt 3 ]; do read -rp "$1" r </dev/tty; giri=$((giri + 1)); done
+ printf '%s' "$r"
+}
+if [ -n "$installa" ] && ha_terminale && { [ -z "$(git config user.name)" ] || [ -z "$(git config user.email)" ]; }; then
+ chi_nome=$(git config user.name || true); [ -n "$chi_nome" ] || chi_nome=$(chiedi_una_riga "$M_chi_sei_nome")
+ chi_mail=$(git config user.email || true); [ -n "$chi_mail" ] || chi_mail=$(chiedi_una_riga "$M_chi_sei_mail")
+ [ -n "$chi_nome" ] && [ -n "$chi_mail" ] || muori "$M_chi_sei"
+ git config --global user.name "$chi_nome"
+ git config --global user.email "$chi_mail"
+fi
+progetto_nuovo=""
+if ! radice=$(git rev-parse --show-toplevel 2>/dev/null); then
+ [ -n "$installa" ] && ha_terminale || muori "$M_fuori_dal_clone"
+ domanda=$(_f "$M_progetto_nome" dove "$PWD")
+ read -rp "$domanda" nome_progetto </dev/tty
+ nome_progetto=${nome_progetto:-progetto}
+ case "$nome_progetto" in
+ .*|*[!A-Za-z0-9._-]*) muori "$(_f "$M_progetto_nome_no" nome "$nome_progetto")" ;;
+ esac
+ [ -e "$nome_progetto" ] && muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
+ mkdir "$nome_progetto" && git -C "$nome_progetto" init -q || muori "$(_f "$M_progetto_esiste" cartella "$PWD/$nome_progetto")"
+ radice=$(cd "$nome_progetto" && pwd)
+ progetto_nuovo=1
+fi
+cd "$radice"
+
+avvisa() { printf '⚠️ %s\n' "$*" >&2; }
+senza_credenziali() { sed -E 's#([A-Za-z][A-Za-z0-9+.-]*://)[^/[:space:]]*@#\1#g'; }
+[ -n "$(git config user.name)" ] && [ -n "$(git config user.email)" ] || muori "$M_chi_sei"
+if [ -n "$progetto_nuovo" ]; then
+ git commit -q --allow-empty -m "$M_progetto_primo_commit"
+ _f "$M_progetto_creato" cartella "$radice"
+fi
+if ! git remote get-url origin >/dev/null 2>&1; then
+ avvisa "$M_senza_origin"
+elif ! perche=$(GIT_TERMINAL_PROMPT=0 git push --dry-run -q origin "HEAD:refs/heads/delminio-prova-del-push-$$" 2>&1); then
+ origine=$(git remote get-url origin | senza_credenziali)
+ errore_git=$(printf '%s' "$perche" | tail -1 | senza_credenziali)
+ avvisa "$(_f "$M_non_pusha" origine "$origine" errore "$errore_git")"
+fi
+
+aggancio_col_codice() {
+ local r codice disp c giri=0 macchina
+ macchina=$(hostname 2>/dev/null || echo "?")
+ r=$(python3 -c 'import json,sys; print(json.dumps({"macchina": sys.argv[1]}))' "$macchina" \
+ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
+ "$URL/api/aggancio/inizia" 2>/dev/null) || return 1
+ [ "${r##*$'\n'}" = 200 ] || return 1
+ r=${r%$'\n'*}
+ codice=$(printf '%s' "$r" | campo codice)
+ disp=$(printf '%s' "$r" | campo dispositivo)
+ [ -n "$codice" ] && [ -n "$disp" ] || return 1
+ {
+ echo
+ echo "$M_codice_apri"
+ echo
+ echo " $URL/?aggancio=$codice"
+ echo
+ _f "$M_codice_oppure" codice "$codice"
+ echo
+ _f "$M_codice_vale" macchina "$macchina"
+ } >&2
+ while [ $giri -lt 220 ]; do
+ sleep 3; giri=$((giri + 1))
+ r=$(python3 -c 'import json,sys; print(json.dumps({"dispositivo": sys.argv[1]}))' "$disp" \
+ | curl -sS -m 10 -w '\n%{http_code}' -X POST -H "Content-Type: application/json" --data-binary @- \
+ "$URL/api/aggancio/ritira" 2>/dev/null) || continue
+ c=${r##*$'\n'}
+ case "$c" in
+ 200) printf '%s' "${r%$'\n'*}" | campo token
+ echo "$M_approvato" >&2; return 0 ;;
+ 410) echo "$M_scaduto" >&2; return 1 ;;
+ esac
+ done
+ return 1
+}
+
+token="${DELMINIO_TOKEN:-}"
+[ -n "$token" ] || token=$(aggancio_col_codice) || token=""
+if [ -z "$token" ]; then
+ ha_terminale || muori "$M_senza_terminale"
+ read -rsp "$M_domanda_token" token </dev/tty
+ echo
+fi
+[ -n "$token" ] || muori "$M_nessun_token"
+
+risposta=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/auth/check" 2>&1) \
+ || muori "$(_f "$M_non_risponde" url "$URL")"
+codice=${risposta##*$'\n'}
+[ "$codice" = 200 ] || muori "$(_f "$M_token_rifiutato" url "$URL" codice "$codice")"
+if frasi=$(curl -fsS -m 10 -K <(_chiave "$token") "$URL/aggancia.sh" 2>/dev/null | python3 -c '
+import re, shlex, sys
+m = re.search(r"^: .⟦frasi: aggancia⟧.\n(.*?)^: .⟦fine frasi⟧.\n", sys.stdin.read(), re.S | re.M)
+voci = shlex.split(m.group(1), comments=True) if m else []
+if voci and all(re.fullmatch(r"M_\w+=.*", v, re.S) for v in voci):
+ print("".join("%s=%s\n" % (k, shlex.quote(v)) for k, _, v in (x.partition("=") for x in voci)))
+') && [ -n "$frasi" ]; then
+ eval "$frasi"; export ${!M_@}
+fi
+chi=$(python3 -c 'import json,sys; u=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("utente") or {}; print((u.get("mostrato") or u.get("nome") or "?") + " (" + (u.get("ruolo_detto") or u.get("ruolo") or "?") + ")")' <<<"$risposta")
+etichetta=$(python3 -c 'import json,sys; print(json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]).get("etichetta") or "")' <<<"$risposta" 2>/dev/null)
+remoto_repo=$(git remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#' || true)
+conferma=false
+{ [ -f .claude/delminio.sh ] || [ "${DELMINIO_STESSA_STORIA:-}" = si ]; } && conferma=true
+remoto_prima=$(sed -n 's/^REMOTO=//p' .claude/delminio.sh 2>/dev/null | head -1 | sed 's/\\\(.\)/\1/g' || true)
+corpo_repo=$(python3 -c 'import json,sys; print(json.dumps({"remoto": sys.argv[1], "nome": sys.argv[2], "conferma": sys.argv[3] == "true", "prima": sys.argv[4]}))' "$remoto_repo" "$(basename "$radice")" "$conferma" "$remoto_prima")
+repo=$(curl -sS -m 10 -w '\n%{http_code}' -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" 2>/dev/null) || repo=""
+_no_del_motore "$repo"; repo=${repo%$'\n'*}
+no=$(printf '%s' "$repo" | campo rifiuta)
+[ -z "$no" ] || muori "$(_f "$M_rifiutato" motivo "$no")"
+if [ -n "$repo" ] \
+ && altri=$(printf '%s' "$repo" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(", ".join(d.get("altri") or []) if d.get("chiede") else "")' 2>/dev/null) \
+ && [ -n "$altri" ]; then
+ _f "$M_tiene_gia" altri "$altri"
+ risposta_storia="${DELMINIO_STESSA_STORIA:-}"
+ if [ -z "$risposta_storia" ] && ha_terminale; then
+ nome_repo=$(basename "$radice")
+ read -rp "$(_f "$M_stessa_storia" repo "$nome_repo")" risposta_storia </dev/tty
+ fi
+ case "$risposta_storia" in
+ s|S|si|sì|y|yes) corpo_repo=$(python3 -c 'import json,sys; d=json.loads(sys.argv[1]); d["conferma"]=True; print(json.dumps(d))' "$corpo_repo")
+ curl -sS -m 10 -X POST -K <(_chiave "$token") -H "Content-Type: application/json" --data-binary "$corpo_repo" "$URL/api/repo" >/dev/null 2>&1 || true ;;
+ *) muori "$M_altra_storia" ;;
+ esac
+fi
+
+imp=$(curl -sS -m 10 -w '\n%{http_code}' -K <(_chiave "$token") "$URL/api/impostazioni" 2>/dev/null || true)
+_no_del_motore "$imp" si; imp=${imp%$'\n'*}
+emb=$(printf '%s' "$imp" | python3 -c 'import json,sys
+try: e = json.load(sys.stdin).get("embedder") or {}
+except Exception: e = {}
+print(json.dumps({"url": e.get("url") or "", "modello": e.get("modello") or ""}) if not e.get("di_delminio") else "di_delminio")')
+memoria=$(printf '%s' "$imp" | campo memoria_sul_disco)
+kit=$(printf '%s' "$imp" | campo versione)
+[ -n "$memoria" ] && [ ! -d "$memoria" ] && memoria=""
+clone=""
+if [ -z "$memoria" ]; then
+ remoto_memorie=$(printf '%s' "$imp" | campo memorie_remoto)
+ dest="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$radice" | _sha16)/memoria"
+ ssh_muto=${GIT_SSH_COMMAND:-ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new}
+ if [ -d "$dest/.git" ]; then
+ GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 30 git -C "$dest" pull -q --ff-only >/dev/null 2>&1 \
+ || avvisa "$(_f "$M_clone_fermo" cartella "$dest")"
+ memoria=$dest; clone=si
+ elif [ -n "$remoto_memorie" ] && command -v claude >/dev/null; then
+ mkdir -p "$(dirname "$dest")"
+ in_https=$(python3 -c 'import sys
+r = sys.argv[1].strip()
+if r.startswith("ssh://"):
+ host, _, p = r[6:].split("@", 1)[-1].partition("/")
+ host = host.split(":", 1)[0]
+elif "://" not in r and "@" in r and ":" in r.split("@", 1)[1]:
+ host, _, p = r.split("@", 1)[1].partition(":")
+else:
+ sys.exit(1)
+print("https://" + host + "/" + p.lstrip("/"))' "$remoto_memorie" 2>/dev/null || true)
+ if GIT_SSH_COMMAND=$ssh_muto GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$remoto_memorie" "$dest" 2>/dev/null \
+ || { [ -n "$in_https" ] && rm -rf "$dest" && GIT_TERMINAL_PROMPT=0 _tempo 60 git clone -q "$in_https" "$dest" 2>/dev/null \
+ && _f "$M_clone_https" remoto "$remoto_memorie" https "$in_https"; }; then
+ memoria=$dest; clone=si
+ if [ -f "$dest/MEMORY.md" ]; then
+ _f "$M_clonate" remoto "$remoto_memorie" cartella "$dest"
+ else
+ avvisa "$(_f "$M_memorie_vuote" remoto "$remoto_memorie" cartella "$dest")"
+ fi
+ else
+ _f "$M_clone_negato" remoto "$remoto_memorie"
+ fi
+ elif ! command -v claude >/dev/null && { cli_presente codex || cli_presente qwen; }; then
+ echo "$M_codex_indice"
+ fi
+fi
+if [ "$emb" != di_delminio ]; then
+ case "$emb" in *'"url": ""'*)
+ avvisa "$M_senza_embedder" ;;
+ esac
+ prova=$(curl -sS -m 30 -w '\n%{http_code}' -X POST -K <(_chiave "$token") \
+ -H "Content-Type: application/json" --data-binary "$emb" "$URL/api/impostazioni/embedder/prova" 2>/dev/null || true)
+ if [ "${prova##*$'\n'}" = 200 ] && ! printf '%s' "${prova%$'\n'*}" | grep -q '"ok": *true'; then
+ risposta_emb="${prova%$'\n'*}"
+ avvisa "$(_f "$M_embedder_muto" risposta "$risposta_emb")"
+ fi
+fi
+
+scarica_client() { # nome, destinazione, errore già composto nella lingua dello spazio
+ local nuovo indirizzo="$URL/static/kit/$1"
+ case $1 in *.*) ;; *) indirizzo+=-client ;; esac
+ nuovo=$(mktemp "$2.XXXXXX") || muori "$3"
+ if ! curl -fsS -K <(_chiave "$token") "$indirizzo" -o "$nuovo"; then
+ rm -f "$nuovo"
+ muori "$3"
+ fi
+ if ! _firmato "$URL" "${indirizzo##*/}" "$nuovo"; then
+ rm -f "$nuovo"
+ muori "$(_f "$M_kit_non_firmato" file "${indirizzo##*/}" url "$URL")"
+ fi
+ mv -f "$nuovo" "$2"
+}
+cartella_copia=$(mktemp -d) || muori "$M_prima_non_salva"
+scarica_client copia "$cartella_copia/copia.py" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/copia-client")"
+prima_volta=si; [ -f .claude/delminio.sh ] && prima_volta=""
+gitdir=$(_assoluto "$(git rev-parse --git-common-dir)")
+comune=$(dirname "$gitdir")
+if [ -n "$prima_volta" ]; then
+ sua=$(python3 "$cartella_copia/copia.py" controlla "$radice" "$memoria" "$comune" "$URL" "$gitdir")
+ if [ -n "$sua" ]; then
+ cartella_sua="${sua%%$'\t'*}"; chi_lo_dice="${sua#*$'\t'}"
+ _f "$M_note_sue" cartella "$cartella_sua" fonte "$chi_lo_dice"
+ risposta_sua="${DELMINIO_MEMORIA_SUA:-}"
+ if [ -z "$risposta_sua" ] && ha_terminale; then
+ read -rp "$M_va_bene" risposta_sua </dev/tty
+ fi
+ case "$risposta_sua" in
+ s|S|si|sì|y|yes) ;;
+ *) muori "$M_memoria_sua_resta" ;;
+ esac
+ fi
+fi
+salvato=$(umask 077; DELMINIO_PRIMA_VOLTA="${prima_volta:+si}" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" \
+ DELMINIO_GANCI="$(git config --local core.hooksPath || git rev-parse --git-path hooks)" \
+ python3 "$cartella_copia/copia.py" salva "$radice" "$memoria" "$comune" "$URL" "$gitdir") \
+ || muori "$M_prima_non_salva"
+rm -rf "$cartella_copia"
+
+
+mkdir -p .claude
+rm -f .claude/mneme.sh # il client di prima della rinomina (0cfdde7): i suoi hook li toglie il passo 2
+cartella_token="${XDG_CONFIG_HOME:-$HOME/.config}/delminio"
+mkdir -p "$cartella_token" && chmod 700 "$cartella_token"
+file_token="$cartella_token/$(printf '%s' "$radice" | _sha16).token"
+( umask 077; printf '%s' "$token" > "$file_token" )
+
+scarica_client plugin .claude/plugin.py "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/plugin-client")"
+scarica_client squadra .claude/squadra.py "$(_f "$M_senza_client_squadra" indirizzo "$URL/static/kit/squadra-client")"
+mcp_locali() { # mcp_locali togli|da-parte
+ python3 - "$1" "${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json" "$radice" "$URL" \
+ "$(_assoluto "$(git rev-parse --git-common-dir)")/delminio-backup" <<'MCP_LOCALI' || true
+import glob, json, os, subprocess, sys
+gesto, cj, radice, url, segno = sys.argv[1:6]
+try:
+ server = json.load(open(cj, encoding="utf-8"))["projects"][radice]["mcpServers"] or {}
+except (OSError, ValueError, KeyError, TypeError):
+ server = {}
+for nome in ("memoria", "delminio"):
+ s = server.get(nome)
+ if not isinstance(s, dict):
+ continue
+ if str(s.get("url", "")).startswith(url):
+ if gesto == "togli":
+ subprocess.run(["claude", "mcp", "remove", nome, "-s", "local"], capture_output=True, timeout=60)
+ elif gesto == "da-parte" and nome == "memoria":
+ try:
+ prime = sorted(glob.glob(os.path.join(open(segno, encoding="utf-8").read().strip(), "*", "fatti.json")))
+ except OSError:
+ prime = []
+ dest = os.path.join(os.path.dirname(prime[-1]), "mcp-memoria.json") if prime else ""
+ if dest and not os.path.exists(dest):
+ os.umask(0o077)
+ with open(dest, "w", encoding="utf-8") as f:
+ json.dump(s, f, indent=2)
+MCP_LOCALI
+}
+con_plugin=""
+if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && command -v claude >/dev/null && python3 .claude/plugin.py claude "$radice"; then
+ con_plugin=si
+ mcp_locali togli
+else
+ python3 .claude/plugin.py rimuovi "$radice" >/dev/null 2>&1 || true
+fi
+scarica_client opencode-client.js .claude/opencode.js "$(_f "$M_senza_client_plugin" indirizzo "$URL/static/kit/opencode-client.js")"
+if cli_presente opencode || [ -f .opencode/plugins/delminio.js ]; then
+ python3 .claude/plugin.py opencode "$radice" || true
+fi
+ganci_claude_nel_progetto=""
+if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || { [ -z "$con_plugin" ] && command -v claude >/dev/null; }; then
+ ganci_claude_nel_progetto=si
+fi
+
+if [ -z "$con_plugin" ] && command -v claude >/dev/null; then
+ mcp_locali togli
+ mcp_locali da-parte
+ claude mcp remove memoria -s local >/dev/null 2>&1 || true
+ cj="${CLAUDE_CONFIG_DIR:-$HOME}/.claude.json"
+ conf=$(python3 -c 'import json,sys
+url, f, cj, radice = sys.argv[1:5]
+try:
+ fidato = json.load(open(cj, encoding="utf-8")).get("projects", {}).get(radice, {}).get("hasTrustDialogAccepted") is True
+except (OSError, ValueError, AttributeError):
+ fidato = False
+h = "printf %s \"$(cat %s)\"" % (chr(39) + "{\"Authorization\":\"Bearer %s\"}" + chr(39), chr(39) + f + chr(39))
+if not fidato or chr(39) in f or not all(32 <= ord(c) < 127 for c in h):
+ sys.exit(1)
+print(json.dumps({"type": "http", "url": url + "/mcp", "headersHelper": h}))' "$URL" "$file_token" "$cj" "$radice" 2>/dev/null || true)
+ if [ -z "$conf" ] || ! claude mcp add-json -s local memoria "$conf" >/dev/null 2>&1 \
+ || ! python3 -c 'import json,sys
+s = json.load(open(sys.argv[1], encoding="utf-8"))["projects"][sys.argv[2]]["mcpServers"]["memoria"]
+sys.exit(0 if s.get("headersHelper") else 1)' "$cj" "$radice" 2>/dev/null; then
+ claude mcp remove memoria -s local >/dev/null 2>&1 || true
+ claude mcp add -s local -t http memoria "$URL/mcp" -H "Authorization: Bearer $token" >/dev/null \
+ || muori "$M_mcp_fallito"
+ fi
+elif [ -z "$con_plugin" ] && [ -z "$installa" ] && ! cli_presente codex && ! cli_presente qwen; then
+ avvisa "$M_mcp_senza_claude"
+fi
+for parte in lanciatori:lanciatori.sh ganci-git:ganci-git.sh worktree:worktree.sh consumi:consumi.py firme:firme.py; do
+ scarica_client "${parte%%:*}" ".claude/${parte#*:}" "$(_f "$M_senza_client" indirizzo "$URL/static/kit/${parte%%:*}-client")"
+done
+client_scaricato=$(mktemp) || muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"
+curl -fsS -K <(_chiave "$token") "$URL/static/kit/delminio-client" -o "$client_scaricato" \
+ || { rm -f "$client_scaricato"; muori "$(_f "$M_senza_client" indirizzo "$URL/static/kit/delminio-client")"; }
+_firmato "$URL" delminio-client "$client_scaricato" \
+ || { rm -f "$client_scaricato"; muori "$(_f "$M_kit_non_firmato" file delminio-client url "$URL")"; }
+{
+ echo '#!/usr/bin/env bash'
+ echo "# Il client di Delminio per gli hook di Claude Code, scritto da aggancia.sh."
+ echo "# Il token sta fuori dal repo, nel file qui sotto (600). Per cambiarlo, rilancia l'aggancio."
+ printf 'URL=%q\nFILE_TOKEN=%q\nMEMORIA=%q\nCLONE=%q\nKIT=%q\nREMOTO=%q\n' "$URL" "$file_token" "$memoria" "$clone" "$kit" "$remoto_repo"
+ echo 'TOKEN=$(cat "$FILE_TOKEN" 2>/dev/null || true)'
+ printf '%s\n' "$PORTABILI"
+ cat "$client_scaricato"
+} > .claude/delminio.sh.nuovo
+rm -f "$client_scaricato"
+mv -f .claude/delminio.sh.nuovo .claude/delminio.sh
+chmod 700 .claude/delminio.sh
+comando_client=$(python3 -c 'import shlex,sys; print("bash " + shlex.quote(sys.argv[1]))' "$radice/.claude/delminio.sh")
+
+mkdir -p .claude/commands
+if [ -f .claude/commands/risveglio.md ] && grep -q 'delminio.sh' .claude/commands/risveglio.md; then
+ rm -f .claude/commands/risveglio.md
+fi
+if [ -z "$ganci_claude_nel_progetto" ]; then
+ for c in apertura chiusura opening closing start handoff; do
+ f=".claude/commands/$c.md"
+ [ -f "$f" ] || continue
+ if grep -q 'delminio.sh' "$f"; then rm -f "$f"
+ elif [ -n "$con_plugin" ] && { [ "$c" = apertura ] || [ "$c" = chiusura ]; }; then rm -f "$f"; fi
+ done
+ rmdir .claude/commands 2>/dev/null || true
+else
+cat > .claude/commands/apertura.md <<COMANDO
+---
+description: "${M_qwen_comando_apertura//\"/\'}"
+argument-hint: "[cosa vuoi dirgli subito]"
+allowed-tools: Bash(bash:*)
+---
+!\`$comando_client prompt\`
+
+\$ARGUMENTS
+COMANDO
+
+cat > .claude/commands/chiusura.md <<COMANDO
+---
+description: "${M_qwen_comando_chiusura//\"/\'}"
+argument-hint: "[cosa fare prima di chiudere]"
+allowed-tools: Bash(bash:*)
+---
+!\`$comando_client chiusura\`
+
+\$ARGUMENTS
+COMANDO
+for coppia in opening:apertura closing:chiusura start:apertura handoff:chiusura; do
+ f=".claude/commands/${coppia%%:*}.md"
+ [ -f "$f" ] && ! grep -q 'delminio.sh' "$f" && continue
+ cp ".claude/commands/${coppia#*:}.md" "$f"
+done
+fi
+while IFS=$'\t' read -r f cli; do
+ [ -n "$f" ] && avvisa "$(_f "$M_mcp_col_nome_nostro" file "$f" cli "$cli")"
+done < <(python3 - "$radice" "$URL" <<'NOME_NOSTRO' 2>/dev/null || true
+import json, os, re, sys
+radice, url = sys.argv[1:3]
+def suo(s):
+ return isinstance(s, dict) and not str(s.get("url") or s.get("httpUrl") or "").startswith(url) \
+ and "delminio" not in json.dumps([s.get("command"), s.get("args")])
+f = os.path.join(radice, ".qwen", "settings.json")
+try:
+ if suo((json.load(open(f, encoding="utf-8")).get("mcpServers") or {}).get("memoria")):
+ print(f"{f}\tQwen Code")
+except (OSError, ValueError, AttributeError):
+ pass
+for f, sempre in ((os.path.join(radice, ".codex", "config.toml"), True),
+ (os.path.expanduser("~/.codex/config.toml"), False)):
+ try:
+ testo = open(f, encoding="utf-8").read()
+ except OSError:
+ continue
+ if re.search(r"(?m)^\[mcp_servers\.memoria\]", testo) and (sempre or re.search(r"(?m)^\[marketplaces\.delminio\]", testo)):
+ print(f"{f}\tCodex")
+NOME_NOSTRO
+)
+for c in apertura chiusura opening closing start handoff; do
+ f="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/commands/$c.md"
+ if [ -f "$f" ] && ! grep -q 'delminio.sh' "$f"; then
+ avvisa "$(_f "$M_comando_tuo" file "$f" c "$c")"
+ fi
+done
+
+python3 - "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" "$radice" <<'GESTITE' || true
+import glob, json, os, runpy, sys
+config, radice = sys.argv[1], sys.argv[2]
+cartelle = os.environ.get("DELMINIO_GESTITE_DIRS",
+ "/etc/claude-code:/Library/Application Support/ClaudeCode:/mnt/c/Program Files/ClaudeCode").split(":")
+def leggi(f):
+ try:
+ with open(f, encoding="utf-8") as h:
+ return json.load(h)
+ except Exception:
+ return None
+def dice(testo):
+ print("⚠️ " + testo, file=sys.stderr)
+for d in cartelle:
+ for f in [os.path.join(d, "managed-settings.json")] + sorted(glob.glob(os.path.join(d, "managed-settings.d", "*.json"))):
+ s = leggi(f)
+ if not isinstance(s, dict):
+ continue
+ if s.get("disableAllHooks") is True:
+ dice(f"{f} (impostazioni gestite di questa macchina) spegne TUTTI gli hook: gli agenti nascono senza l'apertura di Delminio, senza la posta e senza i controlli. Chiedi a chi amministra la macchina di togliere disableAllHooks, o di mettere gli hook di Delminio fra quelli gestiti.")
+ if s.get("allowManagedHooksOnly") is True:
+ dice(f"{f} lascia partire solo gli hook gestiti (allowManagedHooksOnly): quelli di Delminio no. Chiedi a chi amministra la macchina di aggiungerli fra quelli gestiti.")
+ nomi = lambda lista: [str((x or {}).get("serverName") or (x or {}).get("serverUrl") or "") for x in (lista or []) if isinstance(x, dict)]
+ consentiti = s.get("allowedMcpServers")
+ di_delminio = lambda n: "delminio" in n.lower() or n.lower() == "memoria"
+ if (isinstance(consentiti, list) and not any(di_delminio(n) for n in nomi(consentiti))) \
+ or any(di_delminio(n) for n in nomi(s.get("deniedMcpServers"))):
+ dice(f"{f} non lascia collegare il server MCP «memoria» di Delminio: l'agente non raggiungerà la memoria. Chiedi di aggiungerlo fra i server consentiti.")
+ if s.get("allowManagedPermissionRulesOnly") is True:
+ try:
+ nomi_tool = " e ".join(runpy.run_path(".claude/plugin.py")["TOOLS_CLAUDE"])
+ except Exception:
+ nomi_tool = "mcp__plugin_delminio_memoria__delminio e mcp__plugin_delminio_memoria__delminio_write"
+ dice(f"{f} tiene solo i permessi gestiti: ogni chiamata a Delminio chiederà il permesso. Chiedi di consentire {nomi_tool} fra i permessi gestiti.")
+for f in (os.path.join(config, "settings.json"), os.path.join(radice, ".claude", "settings.json"),
+ os.path.join(radice, ".claude", "settings.local.json")):
+ s = leggi(f)
+ if isinstance(s, dict) and s.get("disableAllHooks") is True:
+ dice(f"{f} ha disableAllHooks: true — è tua e non la tocco, ma con quella gli hook di Delminio non partono.")
+for f in ("/etc/codex/requirements.toml", "/etc/codex/managed_config.toml"):
+ if os.path.isfile(f):
+ dice(f"{f}: ci sono regole gestite di Codex su questa macchina. Delminio non le legge: se Codex non fa partire i ganci o il server MCP di Delminio, guarda lì.")
+GESTITE
+
+python3 - "$comando_client" "$memoria" "$con_plugin" "$ganci_claude_nel_progetto" <<'IMPOSTA' || muori "$(_f "$M_json_non_valido" file .claude/settings.local.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, memoria, con_plugin, nel_progetto = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
+pacchetto = runpy.run_path(".claude/plugin.py")
+p = pathlib.Path(".claude/settings.local.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if nel_progetto:
+ metti_ganci(s, comando, pacchetto["GANCI_CLAUDE"])
+else:
+ togli_ganci(s)
+if memoria:
+ s["autoMemoryDirectory"] = memoria
+allow = s.setdefault("permissions", {}).setdefault("allow", [])
+progetto = pacchetto["TOOLS_CLAUDE_PROGETTO"]
+tools, vecchi = ((progetto, pacchetto["TOOLS_CLAUDE"]) if nel_progetto
+ else (pacchetto["TOOLS_CLAUDE"], progetto))
+vecchi = (*vecchi, *pacchetto["TOOLS_CLAUDE_DI_PRIMA"])
+allow[:] = [a for a in allow if a not in vecchi]
+allow.extend(t for t in tools if t not in allow)
+def scelte(f):
+ try:
+ v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("skillOverrides")
+ except (OSError, ValueError, AttributeError):
+ return {}
+ return v if isinstance(v, dict) else {}
+gia = {**scelte(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json"),
+ **scelte(".claude/settings.json")}
+mie = s.get("skillOverrides") if isinstance(s.get("skillOverrides"), dict) else {}
+import subprocess
+try:
+ comune = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"],
+ capture_output=True, text=True, timeout=10).stdout.strip()
+except (OSError, subprocess.SubprocessError):
+ comune = ""
+segno_f844 = pathlib.Path(comune) / "delminio-skill-f844" if comune else None
+if segno_f844 and not segno_f844.exists():
+ prima = pacchetto.get("SKILL_CLAUDE_F811") or {}
+ mie = {n: (pacchetto["SKILL_CLAUDE"].get(n, v) if prima.get(n) == v else v) for n, v in mie.items()}
+ if mie:
+ s["skillOverrides"] = mie
+else:
+ segno_f844 = None
+nuove = {n: v for n, v in pacchetto["SKILL_CLAUDE"].items() if n not in mie and n not in gia}
+if nuove:
+ s["skillOverrides"] = {**mie, **nuove}
+def regole(f):
+ try:
+ v = json.loads(pathlib.Path(f).read_text(encoding="utf-8")).get("permissions") or {}
+ except (OSError, ValueError, AttributeError):
+ return []
+ return [r for k in ("allow", "ask", "deny") for r in (v.get(k) or []) if isinstance(r, str)] if isinstance(v, dict) else []
+sue = regole(pathlib.Path(__import__("os").environ.get("CLAUDE_CONFIG_DIR") or pathlib.Path.home() / ".claude") / "settings.json") \
+ + regole(".claude/settings.json") \
+ + [r for k in ("allow", "deny") for r in (s.get("permissions", {}).get(k) or []) if isinstance(r, str)]
+ask = s.setdefault("permissions", {}).setdefault("ask", [])
+for tool in pacchetto.get("CHIEDI_CLAUDE") or ():
+ if tool not in ask and not any(r == tool or r.startswith(tool + "(") for r in sue):
+ ask.append(tool)
+if not ask:
+ s["permissions"].pop("ask")
+p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+if segno_f844:
+ try:
+ segno_f844.touch()
+ except OSError:
+ pass
+IMPOSTA
+
+if git ls-files --error-unmatch .codex/hooks.json >/dev/null 2>&1; then
+ avvisa "$M_codex_sotto_git"
+else
+mkdir -p .codex
+python3 - "$comando_client" "${DELMINIO_SENZA_PLUGIN:-}" <<'CODEX' || muori "$(_f "$M_json_non_valido" file .codex/hooks.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, senza_plugin = sys.argv[1], sys.argv[2]
+p = pathlib.Path(".codex/hooks.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if senza_plugin:
+ metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_CODEX"])
+else:
+ togli_ganci(s)
+if s or p.exists():
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+CODEX
+rmdir .codex 2>/dev/null || true # vuota: non era dell'umano, e il plugin non la usa
+fi
+
+qwen_senza_plugin=${DELMINIO_SENZA_PLUGIN:-}
+if [ -z "$qwen_senza_plugin" ] && cli_presente qwen; then
+ for w in "${DELMINIO_BIN:-$HOME/.local/bin}"/*; do
+ [ -f "$w" ] && grep -q '^export DELMINIO_CLI_NOME=qwen' "$w" 2>/dev/null || continue
+ grep -q 'DELMINIO_NASCITA=porta' "$w" && continue
+ if ! ( eval "$(grep -E '^export (QWEN_HOME|PATH|DELMINIO_CLI)=' "$w")"
+ [ -n "${QWEN_HOME:-}" ] && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" \
+ python3 .claude/plugin.py qwen "$QWEN_HOME" >/dev/null 2>&1 ); then
+ avvisa "$(_f "$M_qwen_ripiego" agente "$(basename "$w")")"
+ qwen_senza_plugin=si
+ fi
+ done
+fi
+if git ls-files --error-unmatch .qwen/settings.json >/dev/null 2>&1; then
+ avvisa "$M_qwen_sotto_git"
+else
+mkdir -p .qwen
+python3 - "$comando_client" "$qwen_senza_plugin" <<'QWEN' || muori "$(_f "$M_json_non_valido" file .qwen/settings.json)"
+import json, pathlib, runpy, sys
+exec(__import__("os").environ["DELMINIO_GANCI_PY"])
+comando, senza_plugin = sys.argv[1], sys.argv[2]
+p = pathlib.Path(".qwen/settings.json")
+testo = p.read_text(encoding="utf-8") if p.exists() else ""
+s = json.loads(testo) if testo.strip() else {}
+if senza_plugin:
+ metti_ganci(s, comando, runpy.run_path(".claude/plugin.py")["GANCI_QWEN"], matcher_sempre=True)
+else:
+ togli_ganci(s)
+if s or p.exists():
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+QWEN
+if [ -z "$qwen_senza_plugin" ]; then
+ for parola in apertura chiusura opening closing start handoff; do
+ f=".qwen/commands/$parola.md"
+ [ -f "$f" ] && grep -q 'Delminio' "$f" && rm -f "$f"
+ done
+ rmdir .qwen/commands .qwen 2>/dev/null || true
+else
+mkdir -p .qwen/commands
+for parola in apertura chiusura opening closing start handoff; do
+ f=".qwen/commands/$parola.md"
+ [ -f "$f" ] && ! grep -q 'Delminio' "$f" && continue
+ case $parola in
+ apertura|opening|start) descrizione=$M_qwen_comando_apertura ;;
+ *) descrizione=$M_qwen_comando_chiusura ;;
+ esac
+ printf -- '---\ndescription: "%s"\n---\n%s\n' "${descrizione//\"/\'}" "$parola" > "$f"
+done
+fi
+fi
+
+mkdir -p .claude/rules
+cat > .claude/rules/delminio.md <<REGOLA
+# Questo repo è agganciato a Delminio
+
+Se in questa sessione non ti è arrivato niente da Delminio — né l'apertura (il
+contesto che comincia con «# Delminio —») né l'avviso che Delminio non risponde —,
+la CLI è partita da fuori di questo repo, o prima dell'aggancio, o (Codex) senza
+il comando di Delminio: niente memoria, niente posta, niente consegna verificata, e
+il tool \`delminio\` non c'è. Prima di continuare dillo al tuo umano: chiudere e
+rilanciare l'agente dentro $radice (o una sua sottocartella), col comando che scrive
+\`delminio eseguibili\` — con Codex è l'unico modo, perché è il
+lancio a dargli Delminio.
+REGOLA
+
+scarica_client cantiere .claude/cantiere.py "$(_f "$M_senza_client_cantiere" indirizzo "$URL/static/kit/cantiere-client")"
+ln -sfn cantiere.py .claude/backlog.py
+scarica_client eseguibili .claude/eseguibili.py "$(_f "$M_senza_client_eseguibili" indirizzo "$URL/static/kit/eseguibili-client")"
+bin_delminio="${DELMINIO_BIN:-$HOME/.local/bin}"
+comando_delminio="$bin_delminio/delminio"
+if [ -e "$comando_delminio" ] && ! grep -q '^# delminio-comando$' "$comando_delminio" 2>/dev/null; then
+ avvisa "$(_f "$M_comando_occupato" file "$comando_delminio")"
+else
+ mkdir -p "$bin_delminio"
+ {
+ cat <<'COMANDO'
+#!/usr/bin/env bash
+# delminio-comando
+# Scritto da aggancia.sh: i gesti di Delminio da qualunque cartella di un progetto collegato.
+r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""
+if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
+ c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")
+fi
+if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then
+COMANDO
+ printf ' echo %q >&2\n' "$M_comando_fuori"
+ cat <<'COMANDO'
+ exit 1
+fi
+# Tutto al client, anche il Backlog: i nomi dei comandi in ogni lingua li sa lui (F666).
+exec bash "$r/.claude/delminio.sh" "$@"
+COMANDO
+ } > "$comando_delminio.nuovo" && chmod 755 "$comando_delminio.nuovo" && mv -f "$comando_delminio.nuovo" "$comando_delminio"
+fi
+scarica_client cassaforte .claude/cassaforte.py "$(_f "$M_senza_client_cassaforte" indirizzo "$URL/static/kit/cassaforte-client")"
+rm -f .claude/guardia.py
+
+ganci_globali=""
+if ! git config --local core.hooksPath >/dev/null 2>&1 && git config core.hooksPath >/dev/null 2>&1; then
+ ganci_globali=$(git config core.hooksPath)
+fi
+ganci=$(git config --local core.hooksPath || git rev-parse --git-path hooks)
+mkdir -p "$ganci"
+for g in commit-msg post-commit post-rewrite; do
+ if [ -n "$ganci_globali" ]; then
+ _f "$M_gancio_globale" dir "$ganci_globali" file "$ganci_globali/$g" riga "$comando_client $g \"\$@\""
+ continue
+ fi
+ f="$ganci/$g"
+ if [ -e "$f" ] && ! sed -n 2p "$f" | grep -qE '^# (Delminio|Mneme) \(aggancia\.sh\)'; then
+ grep -q "delminio.sh" "$f" \
+ || { riga_gancio="$comando_client $g \"\$@\""; _f "$M_gancio_tuo" file "$f" riga "$riga_gancio"; }
+ continue
+ fi
+ printf '#!/bin/sh\n# Delminio (aggancia.sh): la chiusura giudicata dal motore. Gli altri commit passano.\nexec %s %s "$@"\n' "$comando_client" "$g" > "$f"
+ chmod +x "$f"
+done
+
+pubblico=$(printf '%s' "$repo" | python3 -c 'import json,sys
+try: d = json.load(sys.stdin)
+except Exception: sys.exit(0)
+d = d.get("repo", d) if isinstance(d, dict) else {}
+print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null || true)
+segno="$(git rev-parse --path-format=absolute --git-common-dir)/delminio-pubblico"
+case "$pubblico" in si) : > "$segno" ;; no) rm -f "$segno" ;; esac
+
+escludi=$(git rev-parse --git-path info/exclude)
+mkdir -p "$(dirname "$escludi")"
+for f in $KIT_FILE .claude/delminio-prima/ .claude/delminio-personali/; do
+ case "$f" in .codex/hooks.json|.qwen/settings.json) git ls-files --error-unmatch "$f" >/dev/null 2>&1 && continue ;; esac
+ grep -qxF "$f" "$escludi" 2>/dev/null || echo "$f" >> "$escludi"
+done
+
+DELMINIO_PROVA=1 bash .claude/delminio.sh apertura < /dev/null > /dev/null \
+ || muori "$M_apertura_muta"
+
+spazio=$(python3 .claude/eseguibili.py spazio --da .claude/delminio.sh 2>/dev/null || printf '%s' "${URL%/}")
+case "$spazio" in
+ *"#"*) nome_spazio="${etichetta:-${spazio##*#}}"; dove=$(_f "$M_nello_spazio" spazio "$nome_spazio") ;;
+ *) dove=""
+ python3 -c 'import json,sys; d=json.loads(sys.stdin.read().strip().rsplit(chr(10),1)[0]); sys.exit(0 if len(d.get("spazi") or []) > 1 else 1)' <<<"$risposta" 2>/dev/null \
+ && dove=$(_f "$M_nello_spazio" spazio principale) ;;
+esac
+nome_repo=$(basename "$radice")
+_f "$M_collegato" repo "$nome_repo" url "$URL" dove "$dove" chi "$chi"
+[ -n "$dove" ] && _f "$M_sempre_nello_spazio" dove "$dove"
+if [ -n "$salvato" ]; then
+ _f "$M_prima_al_sicuro" cartella "$salvato"
+fi
+if ha_terminale && [ -f .claude/plugin.py ] && [ "$(python3 .claude/plugin.py app-codex stato 2>/dev/null)" = manca ]; then
+ risposta_app=""; read -rp "$M_app_codex_domanda" risposta_app </dev/tty || true
+ case "$risposta_app" in
+ s|S|si|sì|y|yes) bash .claude/delminio.sh app-codex || true ;;
+ n|N|no) bash .claude/delminio.sh app-codex no || true ;;
+ esac
+fi
+if [ -n "$installa" ]; then
+ _f "$M_installo_cli" cli "$installa"
+ primo=$(mktemp)
+ bash .claude/delminio.sh eseguibili allinea --vuoi "$installa" --primo "$primo" || true
+ lancia=$(cat "$primo" 2>/dev/null || true); rm -f "$primo"
+ [ -n "$lancia" ] && [ -x "$lancia" ] || muori "$(_f "$M_installa_non_riuscita" cli "$installa")"
+ nome_agente=$(basename "$lancia")
+ apertura=$M_rito_apertura; [ "$installa" = codex ] && apertura=$M_rito_apertura_codex # Codex: senza la barra
+ case ":$PATH:" in *":$(dirname "$lancia"):"*) dopo=$nome_agente ;; *) dopo=$lancia ;; esac
+ _f "$M_parto" nome "$nome_agente" apertura "$apertura" cartella "$radice" dopo "$dopo"
+ case "$installa" in
+ codex) echo "$M_parto_codex" ;;
+ qwen) echo "$M_parto_qwen" ;;
+ esac
+ ha_terminale || exit 0
+ if [ -t 0 ]; then exec "$lancia"; fi
+ exec "$lancia" </dev/tty
+fi
+case ":$PATH:" in *":$bin_delminio:"*) ;; *) _f "$M_path_nuovo" cartella "$bin_delminio" comando "$comando_delminio" ;; esac
+if python3 -c 'import json,os,sys
+try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
+except Exception: r = {}
+u = sys.argv[1].rstrip("/")
+s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
+miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
+sys.exit(0 if not s.get("rifiutato") and any(os.path.isfile(p) for p in miei) else 1)' "$spazio"; then
+ bash .claude/delminio.sh eseguibili allinea || true
+ echo "$M_apri_eseguibile"
+else
+ echo "$M_scrivi_eseguibile"
+fi
+if cli_presente codex; then
+ echo "$M_con_codex"
+fi
+if [ -n "$senza_cli" ]; then
+ echo "$M_senza_cli"
+fi
+if cli_presente qwen; then
+ echo "$M_con_qwen"
+fi
+if [ -f .opencode/plugins/delminio.js ]; then
+ echo "$M_con_opencode"
+fi
+if command -v claude >/dev/null; then
+ echo "$M_solo_claude"
+fi
diff --git a/kit/it/cantiere-client b/kit/it/cantiere-client
new file mode 100644
index 0000000..55b97a9
--- /dev/null
+++ b/kit/it/cantiere-client
@@ -0,0 +1,535 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Il Cantiere da riga di comando — il client del registro che vive in Delminio."""
+from __future__ import annotations
+import json
+import os
+import subprocess
+import sys
+import urllib.error
+import urllib.parse
+import urllib.request
+QUI = os.path.dirname(os.path.abspath(__file__))
+RADICE = os.path.dirname(QUI)
+CMD = 'python3 .claude/' + ('backlog.py' if os.path.basename(sys.argv[0]) == 'backlog.py' else 'cantiere.py')
+FRASI = {
+ "aiuto": " {cmd} le attivit\xe0 aperte, per PRIORIT\xc0\n {cmd} lista [dominio] filtrate su un dominio\n {cmd} concept [dominio] solo i concept: cosa c'\xe8 da DECIDERE\n {cmd} veglie [dominio] i promemoria, quelli da guardare in cima\n {cmd} mie quelle in corso con te adesso\n {cmd} assegnate quelle che l'amministratore ha assegnato al tuo utente\n {cmd} domande quelle che si fanno con il tuo utente, e cosa gli serve dire o fare\n {cmd} mostra <id> la scheda intera\n {cmd} cerca \"<parole>\" le pi\xf9 vicine per senso, chiuse comprese (un numero: quella)\n \u26d4 apri vuole --chiesto \"<le parole dell'amministratore>\", o alla chiusura --a-meta \"<cosa stavate facendo>\"\n {cmd} apri --titolo \"...\" --danno \"...\" --chiusura \"...\" --dominio <d> \\\n [--priorita 1-4] [--owner agente|insieme|capo] [--sonda \"cmd\"] \\\n [--domanda \"cosa serve dal tuo utente\" [--tipo decisione|mani]] \\\n [--ferma \"cosa aspetta\"] [--memoria \"<nome della memoria>\"]\n [--aspetta B<n>] facoltativo: si crea in attesa finch\xe9 B<n> non \xe8 chiusa\n {cmd} apri --concept --titolo \"...\" --danno \"...\" --decide \"che decisione manca\" --dominio <d>\n {cmd} apri --veglia --titolo \"...\" --quando <AAAA-MM-GG> \\\n --verifica \"cosa deve essere vero quel giorno\" --dominio <d> [--sonda \"cmd\"]\n \u26d4 una voce che somiglia a una non chiusa non si crea: tocca quella, o\n --diversa-da \"perch\xe9 \xe8 un'altra cosa\" (le vicine le nomina lui; resta nell'origine)\n {cmd} rinvia <id> <AAAA-MM-GG> [\"perch\xe9\"] guardata, non ancora decidibile\n {cmd} lega <id> [--memoria \"X\"] [--togli \"X\"] le memorie da leggere prima di toccarla\n {cmd} prendi <id> \xb7 molla <id> \xb7 riapri <id>\n {cmd} rispondi <id> \"<le sue parole>\" la risposta del tuo utente alla domanda: l'attivit\xe0\n diventa dell'agente. \u26d4 Le sue parole, dette in chat, mai le tue\n {cmd} chiedi <id> \"perch\xe9\" serve l'approvazione dell'amministratore: si ferma finch\xe9 non decide\n (un membro solo sulle attivit\xe0 che ha aperto lui)\n {cmd} assegna <id> <login> l'amministratore d\xe0 un'attivit\xe0 a una persona (senza login la libera)\n {cmd} tocca <id> \"<nota>\" cosa hai scoperto, senza chiuderla (--sostituisci per riscrivere)\n {cmd} correggi <id> [--titolo ..] [--danno ..] [--chiusura ..] [--priorita 1-4|none] [--sonda \"cmd\"|none]\n [--owner ..] [--domanda \"..\"|none] [--tipo decisione|mani]\n {cmd} chiudi <id> [\"come\"] \xe8 fatta, e come \u2014 un concept: la decisione e il perch\xe9\n {cmd} ferma <id> \"<attesa>\" non \xe8 debito: aspetta qualcosa\n {cmd} aspetta <id> B<n> [B<m>] aspetta altre attivit\xe0: si ferma, e quando si chiude l'ultima\n torna aperta da sola \xb7 --togli B<n> scioglie il legame\n {cmd} sonde gira le sonde e chiude ci\xf2 che \xe8 vero\n\nCon insieme la domanda \xe8 obbligatoria: una decisione a parole, o un intervento (un'azione che fa solo il tuo utente).\nPriorit\xe0: P1 adesso \xb7 P2 prossima \xb7 P3 quando c'\xe8 tempo \xb7 P4 un giorno (--priorita 1-4). La decide l'amministratore.",
+ "non_collegato": "\u274c questo repo non \xe8 collegato a Delminio (.claude/delminio.sh): rilancia il collegamento.",
+ "non_risponde": "\u274c Delminio non risponde ({url}): {errore} \u2014 il Backlog sta l\xec.",
+ "chi_sei": "\u274c non so chi sei: il Backlog firma ogni scrittura con la sessione. Lancialo da una CLI collegata, o CANTIERE_SESSIONE=S<N> {cmd} \u2026",
+ "sonda_dice_si": "\u274c questa sonda non sa dire NO: appena attaccata risponde gi\xe0 \xabl'attivit\xe0 \xe8 chiusa\xbb (exit 0).\nIl confronto va DENTRO di lei: test \"$(<misura>)\" -eq 0 \xb7 <misura> | grep -q '<atteso>'\nCi\xf2 che ha risposto:\n",
+ "argomento_sconosciuto": "\u274c argomento sconosciuto: {argomento}",
+ "vuole_valore": "\u274c {argomento} vuole un valore",
+ "uso_mostra": "uso: {cmd} mostra <id>",
+ "uso_cerca": "uso: {cmd} cerca \"<parole o numero>\"",
+ "chiusa": "\u2705 {sigla} chiusa",
+ "memorie_chiusa": "\U0001f4d6 La spiegano queste memorie: rileggile, ora che \xe8 chiusa \u2014 {memorie}",
+ "uso_aspetta": "uso: {cmd} aspetta <id> B<n> [B<m>] \xb7 --togli B<n>",
+ "uso_rinvia": "uso: {cmd} rinvia <id> <AAAA-MM-GG> [\"perch\xe9\"]",
+ "nessuna_sonda": "Nessuna attivit\xe0 viva ha una sonda.",
+ "chiusa_dalla_sonda": "\u2705 {sigla} chiusa dalla sonda",
+ "sonda_muta": "\u26a0\ufe0f {sigla} \u2014 la sonda non ha potuto rispondere (rc={rc}): {uscita}",
+ "sonda_non_accettata": "\u23f8 {sigla} \u2014 la sonda non gira: nessuno l'ha accettata su questa macchina\n | {sonda}",
+ "sonde_da_accettare": "{n} sonde aspettano che una persona le legga e le accetti, da un terminale: {cmd} sonde accetta",
+ "sonda_accetta_domanda": "\n{sigla} \u2014 questa sonda girer\xe0 su questa macchina, in questo repo:\n {sonda}\nLa accetti? [s/N] ",
+ "sonda_si": "s si s\xec y yes",
+ "sonde_accettate": "\u2705 {nuove} sonde accettate ora \xb7 {tutte} in tutto \xb7 la lista: {file}",
+ "accetta_da_terminale": "\u274c le sonde le accetta una persona, da un terminale vero: lancia tu \xab{cmd} sonde accetta\xbb.",
+ "sonda_scaduta": "il tempo \xe8 finito (300 s)",
+ "comando_sconosciuto": "comando sconosciuto: {comando}\n\n{aiuto}",
+ "uso_rispondi": "uso: {cmd} rispondi <id> \"<le parole del tuo utente>\"",
+ "priorita_numero": "\u274c priorit\xe0: 1-4, non \xab{priorita}\xbb"
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+AIUTO = F('aiuto', cmd=CMD)
+
+class Rifiuto(Exception):
+ pass
+
+def _ambiente() -> tuple[str, str, str]:
+ try:
+ out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines()
+ except (OSError, subprocess.TimeoutExpired):
+ out = []
+ url, file_token, sessione = (out + ['', '', ''])[:3]
+ try:
+ with open(file_token, encoding='utf-8') as f:
+ token = f.read().strip()
+ except OSError:
+ token = ''
+ if not url or not token:
+ raise Rifiuto(F('non_collegato'))
+ return (url.rstrip('/'), token, os.environ.get('CANTIERE_SESSIONE') or sessione)
+URL, TOKEN, SESSIONE = ('', '', '')
+
+def _http(metodo: str, percorso: str, corpo: dict | None=None, *, testo: bool=False, params: dict | None=None):
+ q = dict(params or {})
+ if testo:
+ q['formato'] = 'testo'
+ url = f'{URL}/api/cantiere{percorso}' + (f'?{urllib.parse.urlencode(q)}' if q else '')
+ dati = json.dumps(corpo).encode() if corpo is not None else None
+ req = urllib.request.Request(url, data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ raw = r.read().decode()
+ except urllib.error.HTTPError as e:
+ raw = e.read().decode()
+ if testo and (not raw.lstrip().startswith('{')):
+ raise Rifiuto(raw.strip())
+ try:
+ msg = json.loads(raw).get('error', raw)
+ except ValueError:
+ msg = raw
+ raise Rifiuto(f'❌ {msg}')
+ except (urllib.error.URLError, OSError) as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e))
+ return raw if testo else json.loads(raw)
+
+def _sessione() -> str:
+ if not SESSIONE:
+ raise Rifiuto(F('chi_sei', cmd=CMD))
+ return SESSIONE
+
+def _azione(id_: str, azione: str, corpo: dict) -> str:
+ return _http('POST', f'/{urllib.parse.quote(id_)}/{azione}', {'sessione': _sessione(), **corpo}, testo=True)
+
+def _esegui(cmd: str) -> tuple[int, str]:
+ try:
+ r = subprocess.run(cmd, shell=True, cwd=RADICE, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=300, executable='/bin/bash')
+ except subprocess.TimeoutExpired:
+ return (124, F('sonda_scaduta'))
+ return (r.returncode, r.stdout + r.stderr)
+
+def _file_accettate() -> str:
+
+ def git(*a):
+ return subprocess.run(['git', 'rev-parse', '--path-format=absolute', *a], cwd=RADICE, capture_output=True, text=True).stdout.strip()
+ comune = os.path.join(git('--git-common-dir') or os.path.join(RADICE, '.git'), 'delminio-sonde-accettate')
+ sua = git('--git-path', 'delminio-sonde-accettate')
+ if sua and sua != comune and os.path.isfile(sua):
+ try:
+ righe = set(open(sua, encoding='utf-8').read().split())
+ if os.path.isfile(comune):
+ righe |= set(open(comune, encoding='utf-8').read().split())
+ with open(comune, 'w', encoding='utf-8') as f:
+ f.write(''.join((x + '\n' for x in sorted(righe))))
+ os.remove(sua)
+ except OSError:
+ pass
+ return comune
+
+def _impronta(sonda: str) -> str:
+ import hashlib
+ return hashlib.sha256(sonda.encode()).hexdigest()
+
+def _accettate() -> set[str]:
+ try:
+ with open(_file_accettate(), encoding='utf-8') as f:
+ return set(f.read().split())
+ except OSError:
+ return set()
+
+def _scrivi_accettate(tutte: set[str]) -> None:
+ with open(_file_accettate(), 'w', encoding='utf-8') as f:
+ f.write(''.join((x + '\n' for x in sorted(tutte))))
+
+def sonda_sa_dire_no(cmd: str) -> None:
+ rc, out = _esegui(cmd)
+ if rc == 0:
+ raise Rifiuto(F('sonda_dice_si') + '\n'.join((' | ' + r for r in out.splitlines()[:8])))
+
+def _flag(args: list[str], spec: dict[str, str]) -> dict:
+ out: dict = {}
+ i = 0
+ while i < len(args):
+ a = args[i]
+ if not a.startswith('--') or a[2:] not in spec:
+ raise Rifiuto(F('argomento_sconosciuto', argomento=a))
+ tipo, _, dest = spec[a[2:]].partition(':')
+ dest = dest or a[2:]
+ if tipo == 'bool':
+ out[dest] = True
+ i += 1
+ continue
+ if i + 1 >= len(args):
+ raise Rifiuto(F('vuole_valore', argomento=a))
+ if tipo == 'lista':
+ out.setdefault(dest, []).append(args[i + 1])
+ else:
+ out[dest] = args[i + 1]
+ i += 2
+ return out
+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"
+ },
+ "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"
+ }
+}
+
+def in_italiano(argv: list[str]) -> list[str]:
+ if not argv:
+ return argv
+ verbi, opzioni = (COMANDI.get('backlog') or {}, COMANDI.get('backlog_opzioni') or {})
+ valori = {'--tipo': COMANDI.get('backlog_tipo') or {}, '--owner': COMANDI.get('backlog_owner') or {}}
+ out = [verbi.get(argv[0], argv[0])]
+ for a in argv[1:]:
+ if len(out) > 1 and out[-1] in valori:
+ out.append(valori[out[-1]].get(a, a))
+ elif a.startswith('--') and a[2:] in opzioni:
+ out.append('--' + opzioni[a[2:]])
+ else:
+ out.append(a)
+ return out
+
+def comando(argv: list[str]) -> int:
+ argv = in_italiano(argv)
+ cmd = argv[0] if argv else 'lista'
+ resto = argv[1:]
+ arg = resto[0] if resto else ''
+ if cmd in ('aiuto', '-h', '--help', 'help'):
+ print(AIUTO)
+ return 0
+ if cmd == 'assegnate':
+ print(_http('GET', '', testo=True, params={'vista': 'assegnate', 'a': arg}), end='')
+ return 0
+ if cmd == 'assegna':
+ print(_azione(arg, 'assegna', {'a': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'domande':
+ print(_http('GET', '', testo=True, params={'vista': 'domande'}), end='')
+ return 0
+ if cmd == 'rispondi':
+ if len(resto) < 2:
+ raise Rifiuto(F('uso_rispondi', cmd=CMD))
+ print(_azione(arg, 'rispondi', {'risposta': resto[1]}), end='')
+ return 0
+ if cmd in ('lista', 'concept', 'veglie', 'veglia', 'mie'):
+ vista = 'veglie' if cmd == 'veglia' else cmd
+ print(_http('GET', '', testo=True, params={'vista': vista, 'dominio': arg, 'sessione': SESSIONE}), end='')
+ return 0
+ if cmd in ('mostra', 'scheda', 'vedi'):
+ if not arg:
+ raise Rifiuto(F('uso_mostra', cmd=CMD))
+ print(_http('GET', f'/{urllib.parse.quote(arg)}', testo=True), end='')
+ return 0
+ if cmd in ('cerca', 'trova', 'search'):
+ q = ' '.join(resto).strip()
+ if not q:
+ raise Rifiuto(F('uso_cerca', cmd=CMD))
+ print(_http('GET', '/cerca', testo=True, params={'q': q}), end='')
+ return 0
+ if cmd == 'apri':
+ f = _flag(resto, {'titolo': 'val', 'danno': 'val', 'chiusura': 'val', 'verifica': 'val:chiusura', 'decide': 'val:chiusura', 'veglia': 'bool', 'concept': 'bool', 'quando': 'val', 'dominio': 'val', 'owner': 'val', 'priorita': 'val', 'sonda': 'val', 'memoria': 'lista:memorie', 'ferma': 'val', 'aspetta': 'lista:aspetta', 'chiesto': 'val', 'a-meta': 'val:a_meta', 'diversa-da': 'val:diversa_da', 'domanda': 'val', 'tipo': 'val:domanda_tipo'})
+ f['tipo'] = 'veglia' if f.pop('veglia', False) else 'concept' if f.pop('concept', False) else 'opera'
+ if 'priorita' in f:
+ try:
+ f['priorita'] = int(f['priorita'])
+ except ValueError:
+ raise Rifiuto(F('priorita_numero', priorita=f['priorita'])) from None
+ if f.get('sonda') and f['tipo'] != 'concept':
+ sonda_sa_dire_no(f['sonda'])
+ _scrivi_accettate(_accettate() | {_impronta(f['sonda'])})
+ f['sessione'] = _sessione()
+ print(_http('POST', '/apri', f, testo=True), end='')
+ return 0
+ if cmd == 'correggi':
+ f = _flag(resto[1:], {'titolo': 'val', 'danno': 'val', 'chiusura': 'val', 'decide': 'val:chiusura', 'owner': 'val', 'dominio': 'val', 'priorita': 'val', 'sonda': 'val', 'memoria': 'lista:memorie', 'domanda': 'val', 'tipo': 'val:domanda_tipo'})
+ if f.get('sonda') and f['sonda'] not in ('none', '-'):
+ sonda_sa_dire_no(f['sonda'])
+ _scrivi_accettate(_accettate() | {_impronta(f['sonda'])})
+ print(_azione(arg, 'correggi', f), end='')
+ return 0
+ if cmd == 'lega':
+ print(_azione(arg, 'lega', _flag(resto[1:], {'memoria': 'lista:aggiungi', 'togli': 'lista'})), end='')
+ return 0
+ if cmd in ('prendi', 'molla', 'riapri'):
+ print(_azione(arg, cmd, {}), end='')
+ return 0
+ if cmd == 'chiedi':
+ print(_azione(arg, 'chiedi', {'perche': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'tocca':
+ sost = len(resto) > 1 and resto[1] == '--sostituisci'
+ nota = resto[2] if sost and len(resto) > 2 else resto[1] if len(resto) > 1 else ''
+ print(_azione(arg, 'tocca', {'nota': nota, 'sostituisci': sost}), end='')
+ return 0
+ if cmd == 'chiudi':
+ r = _http('POST', f'/{urllib.parse.quote(arg)}/chiudi', {'sessione': _sessione(), 'come': resto[1] if len(resto) > 1 else ''})
+ print(F('chiusa', sigla=r['chiusa']))
+ for riga in r.get('sblocchi') or []:
+ print(f' {riga}')
+ if r.get('memorie'):
+ print(F('memorie_chiusa', memorie=' · '.join(r['memorie'])))
+ return 0
+ if cmd == 'ferma':
+ print(_azione(arg, 'ferma', {'attesa': resto[1] if len(resto) > 1 else ''}), end='')
+ return 0
+ if cmd == 'aspetta':
+ togli = '--togli' in resto
+ sigle = [x for x in resto[1:] if x != '--togli']
+ if not sigle:
+ raise Rifiuto(F('uso_aspetta', cmd=CMD))
+ print(_azione(arg, 'aspetta', {'togli': sigle} if togli else {'su': sigle}), end='')
+ return 0
+ if cmd == 'rinvia':
+ if len(resto) < 2:
+ raise Rifiuto(F('uso_rinvia', cmd=CMD))
+ print(_azione(arg, 'rinvia', {'quando': resto[1], 'perche': resto[2] if len(resto) > 2 else ''}), end='')
+ return 0
+ if cmd == 'sonde':
+ sonde = _http('GET', '', params={'vista': 'sonde'})['sonde']
+ if not sonde:
+ print(F('nessuna_sonda'))
+ return 0
+ accettate = _accettate()
+ if arg == 'accetta':
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ raise Rifiuto(F('accetta_da_terminale', cmd=CMD))
+ nuove = 0
+ for s in sonde:
+ h = _impronta(s['sonda'])
+ if h in accettate:
+ continue
+ tty.write(F('sonda_accetta_domanda', sigla=s['sigla'], sonda=s['sonda']))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('sonda_si').split():
+ accettate.add(h)
+ nuove += 1
+ _scrivi_accettate(accettate)
+ print(F('sonde_accettate', nuove=nuove, tutte=len(accettate), file=_file_accettate()))
+ return 0
+ da_accettare = 0
+ for s in sonde:
+ if _impronta(s['sonda']) not in accettate:
+ da_accettare += 1
+ print(F('sonda_non_accettata', sigla=s['sigla'], sonda=s['sonda']))
+ continue
+ rc, out = _esegui(s['sonda'])
+ if rc == 0:
+ r = _http('POST', f"/{s['id']}/chiudi", {'sessione': SESSIONE or 'S0', 'da_sonda': True, 'misura': ' '.join(out.split())[:200]})
+ print(F('chiusa_dalla_sonda', sigla=s['sigla']))
+ for riga in r.get('sblocchi') or []:
+ print(f' {riga}')
+ elif rc > 125 or rc == 124:
+ print(F('sonda_muta', sigla=s['sigla'], rc=rc, uscita=out[:80]))
+ if da_accettare:
+ print(F('sonde_da_accettare', n=da_accettare, cmd=CMD))
+ return 0
+ print(F('comando_sconosciuto', comando=cmd, aiuto=AIUTO))
+ return 1
+if __name__ == '__main__':
+ try:
+ URL, TOKEN, SESSIONE = _ambiente()
+ sys.exit(comando(sys.argv[1:]))
+ except Rifiuto as e:
+ print(str(e).rstrip(), file=sys.stderr)
+ sys.exit(1)
diff --git a/kit/it/cassaforte-client b/kit/it/cassaforte-client
new file mode 100644
index 0000000..c3b09f1
--- /dev/null
+++ b/kit/it/cassaforte-client
@@ -0,0 +1,625 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La cassaforte da riga di comando (F747): un segreto arriva solo col sì della persona."""
+from __future__ import annotations
+import base64
+import hashlib
+import hmac
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+QUI = os.path.dirname(os.path.abspath(__file__))
+CMD = 'delminio cassaforte'
+ATTESA_S = int(os.environ.get('DELMINIO_CASSAFORTE_ATTESA', '100'))
+INFO = b'delminio-cassaforte-v1'
+FIRMA = b'delminio-cassaforte-firma-v1:'
+FIRMA_DEPOSITO = 'delminio-cassaforte-deposito-v1:'
+FIRMA_PASSAGGIO = 'delminio-cassaforte-passaggio-v1:'
+NOME_RE = re.compile('^[A-Z][A-Z0-9_]{0,63}$')
+NOMI_VIETATI = frozenset({'PATH', 'HOME', 'SHELL', 'IFS', 'ENV', 'BASH_ENV', 'CDPATH', 'PS4', 'PROMPT_COMMAND', 'SHELLOPTS', 'BASHOPTS', 'GLOBIGNORE', 'NODE_OPTIONS', 'NODE_PATH', 'PERL5OPT', 'PERL5LIB', 'PERLLIB', 'RUBYOPT', 'RUBYLIB', 'JAVA_TOOL_OPTIONS', '_JAVA_OPTIONS', 'GIT_SSH', 'GIT_SSH_COMMAND', 'GIT_EXEC_PATH', 'GIT_ASKPASS', 'SSH_ASKPASS', 'EDITOR', 'VISUAL', 'PAGER', 'BROWSER', 'TMPDIR', 'GIT_PROXY_COMMAND', 'GIT_TEMPLATE_DIR', 'ZDOTDIR', 'GCONV_PATH', 'NODE_EXTRA_CA_CERTS', 'SSL_CERT_FILE', 'SSL_CERT_DIR', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'})
+PREFISSI_VIETATI = ('LD_', 'DYLD_', 'PYTHON', 'BASH_FUNC_', 'GIT_CONFIG', 'LUA_')
+FRASI = {
+ "aiuto": " {cmd} elenco i segreti che si possono chiedere (nomi e note, mai valori; \xaba tempo\xbb = si apre con una sola approvazione)\n {cmd} NOME[,NOME\u2026] \"<perch\xe9>\" -- comando [argomenti\u2026]\n chiede i segreti all'amministratore, col perch\xe9: la richiesta arriva sul suo telefono.\n Concessa, il comando parte coi segreti nelle sue variabili d'ambiente (NOME=valore).\n Se un accesso a tempo aperto li copre tutti, parte subito, senza chiedere.\n Le variabili le legge il comando: per usarle negli argomenti, passa da una shell \u2014\n -- bash -c 'curl -u \"admin:$NOME\" \u2026'\n {cmd} apri NOME[,NOME\u2026]|--larghe \"<perch\xe9>\"\n l'accesso a tempo: una sola approvazione per i segreti segnati \xaba tempo\xbb (--larghe: tutti), per il tempo che dice l'app.\n {cmd} finestre | chiudi gli accessi a tempo aperti da qui \xb7 chiuderli tutti\n {cmd} proponi NOME \"<a cosa serve>\"\n propone un segreto che non c'\xe8 ancora: l'amministratore lo approva mettendoci il valore.\n {cmd} deposita NOME[,NOME\u2026] \"<a cosa serve>\" [--larga] [--dal-file FILE]\n mette un valore nella cassaforte senza mostrarlo: da stdin (un nome) o da un file NOME=valore.\n Diventa un segreto quando l'amministratore lo accetta dall'app.",
+ "non_collegato": "\u274c questo repo non \xe8 collegato a Delminio (.claude/delminio.sh): rilancia il collegamento.",
+ "non_risponde": "\u274c Delminio non risponde ({url}): {errore}",
+ "nessun_segreto": "La cassaforte di questo spazio \xe8 vuota: i segreti li aggiunge l'amministratore dall'app (Cassaforte). Se ne serve uno, proponilo col suo nome.",
+ "nessuna_cassaforte": "In questo spazio la cassaforte non c'\xe8: la crea l'amministratore dall'app (Cassaforte).",
+ "uso_chiedi": "uso: {cmd} NOME[,NOME\u2026] \"<perch\xe9>\" -- comando [argomenti\u2026]",
+ "chiesta": "\U0001f511 Richiesta mandata all'amministratore: {nomi}. Diglielo anche in chat: la concede dall'app, sul telefono.",
+ "aspetto": " Aspetto l'approvazione fino a {secondi} s\u2026",
+ "ancora_niente": "\u23f3 Non ancora concessa. Quando l'amministratore decide, la decisione ti arriva sul canale: rilancia allora lo stesso comando, identico, e riprende questa richiesta.",
+ "negata": "\u270b Negata da {chi}{parole}. Il comando non \xe8 partito.",
+ "scaduta": "\u231b La richiesta \xe8 scaduta senza approvazione: il comando non \xe8 partito. Se serve ancora, rilancialo e la richiesta riparte.",
+ "consegna_rotta": "\u274c Ci\xf2 che \xe8 arrivato non si apre (cifrato alterato, o non era per questa richiesta): il comando non \xe8 partito.",
+ "firma_falsa": "\u274c Ci\xf2 che \xe8 arrivato non porta la firma della cassaforte: non l'ha mandato un dispositivo dell'amministratore. Il comando non \xe8 partito; avvisa l'amministratore.",
+ "firma_cambiata": "\u274c La chiave di firma della cassaforte non \xe8 quella vista la prima volta ({file}): il comando non \xe8 partito. Se l'amministratore ha davvero rifatto la cassaforte, cancella quel file.",
+ "nomi_diversi": "\u274c Sono arrivati nomi diversi da quelli chiesti: il comando non \xe8 partito; avvisa l'amministratore.",
+ "nome_vietato": "\u274c {nome} \xe8 una variabile che cambia cosa esegue un comando: non si chiede alla cassaforte.",
+ "impronta": " Impronta della richiesta: {impronta} \u2014 nell'app l'amministratore vede la stessa.",
+ "concessa": "\u2705 Concessa da {chi}: parte il comando.",
+ "comando_mancante": "\u274c manca il comando dopo \xab--\xbb",
+ "uso_proponi": "uso: {cmd} proponi NOME \"<a cosa serve>\"",
+ "proposta": "\U0001f4dd Proposto {nome}: l'amministratore lo vede nell'app e, se lo approva, ci mette il valore. Diglielo anche in chat.",
+ "segno_larga": " \xb7 a tempo",
+ "finestra_chiesta": "\U0001f511 Accesso a tempo chiesto all'amministratore per {n} segreti ({minuti} minuti dall'approvazione). Diglielo anche in chat: lo approva dall'app, sul telefono.",
+ "finestra_aperta": "\u2705 Accesso a tempo aperto da {chi} fino alle {ora}: {nomi}. I comandi con questi segreti partono senza chiedere.",
+ "finestra_usata": "\U0001f511 Dall'accesso a tempo aperto (fino alle {ora}): parte il comando.",
+ "finestra_finita": "\u231b Un accesso a tempo aperto da qui non c'\xe8 pi\xf9 (chiuso o finito).",
+ "finestre_nessuna": "Nessun accesso a tempo aperto da qui.",
+ "finestra_riga": " fino alle {ora} {nomi}",
+ "finestre_chiuse": "\U0001f512 Accessi a tempo chiusi: {n}.",
+ "nessuna_larga": "Nessun segreto \xe8 segnato \xaba tempo\xbb: li segna l'amministratore dall'app, uno per uno.",
+ "uso_apri": "uso: {cmd} apri NOME[,NOME\u2026]|--larghe \"<perch\xe9>\"",
+ "uso_deposita": "uso: {cmd} deposita NOME[,NOME\u2026] \"<a cosa serve>\" [--larga] [--dal-file FILE] (un nome solo: il valore da stdin)",
+ "deposito_senza_chiave": "La cassaforte non ha ancora la chiave dei depositi: la crea l'app quando l'amministratore la apre dal suo dispositivo. Diglielo, poi rilancia.",
+ "deposito_firma": "\u274c La chiave dei depositi non porta la firma della cassaforte: non ci cifro niente. Avvisa l'amministratore.",
+ "deposito_vuoto": "\u274c {nome}: nessun valore (stdin vuoto, o non c'\xe8 nel file). Non ho depositato niente.",
+ "deposito_stdin": "\u274c Con pi\xf9 nomi il valore non viene da stdin: usa --dal-file FILE.",
+ "depositato": "\U0001f4e5 Depositato {nome}, cifrato per la cassaforte: diventa un segreto quando l'amministratore lo accetta dall'app. Diglielo anche in chat.",
+ "non_concessa": "\u274c I segreti non sono arrivati (negati, scaduti o non ancora concessi): niente da fare.",
+ "chiesta_tua": "\U0001f511 Richiesta mandata al telefono del tuo utente: {nomi}. \xc8 un segreto suo: la concede lui dall'app, sul suo telefono. Diglielo anche in chat.",
+ "finestra_chiesta_tua": "\U0001f511 Accesso a tempo chiesto alla persona con cui lavori, per {n} segreti suoi ({minuti} minuti dall'approvazione): lo approva dall'app, sul telefono. Diglielo anche in chat.",
+ "impronta_tua": " Impronta della richiesta: {impronta} \u2014 nell'app, sul suo telefono, il tuo utente vede la stessa."
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+class Rifiuto(Exception):
+
+ def __init__(self, messaggio: str, stato: int=0):
+ super().__init__(messaggio)
+ self.stato = stato
+_P = 2 ** 255 - 19
+_A24 = 121665
+
+def x25519(k: bytes, u: bytes) -> bytes:
+ kk = bytearray(k)
+ kk[0] &= 248
+ kk[31] &= 127
+ kk[31] |= 64
+ n = int.from_bytes(bytes(kk), 'little')
+ x1 = int.from_bytes(u, 'little') & (1 << 255) - 1
+ x2, z2, x3, z3 = (1, 0, x1, 1)
+ swap = 0
+ for t in reversed(range(255)):
+ kt = n >> t & 1
+ if swap ^ kt:
+ x2, x3, z2, z3 = (x3, x2, z3, z2)
+ swap = kt
+ a, b = ((x2 + z2) % _P, (x2 - z2) % _P)
+ aa, bb = (a * a % _P, b * b % _P)
+ e = (aa - bb) % _P
+ c, d = ((x3 + z3) % _P, (x3 - z3) % _P)
+ da, cb = (d * a % _P, c * b % _P)
+ x3, z3 = ((da + cb) ** 2 % _P, x1 * (da - cb) ** 2 % _P)
+ x2, z2 = (aa * bb % _P, e * (aa + _A24 * e) % _P)
+ if swap:
+ x2, z2 = (x3, z3)
+ return (x2 * pow(z2, _P - 2, _P) % _P).to_bytes(32, 'little')
+_Q = 115792089210356248762697446949407573530086143415290314195533631308867097853951
+_B = 41058363725152142129326129780047268409114441015993725554835256314039467401291
+_N = 115792089210356248762697446949407573529996955224135760342422259061068512044369
+_G = (48439561293906451759052585252797914202762949526041747995844080717082404635286, 36134250956749795798585127919587881956611106672985015071877198253568414405109)
+
+def _somma(p1, p2):
+ if p1 is None:
+ return p2
+ if p2 is None:
+ return p1
+ if p1[0] == p2[0] and (p1[1] + p2[1]) % _Q == 0:
+ return None
+ if p1 == p2:
+ m = 3 * (p1[0] * p1[0] - 1) * pow(2 * p1[1], _Q - 2, _Q) % _Q
+ else:
+ m = (p2[1] - p1[1]) * pow(p2[0] - p1[0], _Q - 2, _Q) % _Q
+ x = (m * m - p1[0] - p2[0]) % _Q
+ return (x, (m * (p1[0] - x) - p1[1]) % _Q)
+
+def _per(k: int, p):
+ r = None
+ while k:
+ if k & 1:
+ r = _somma(r, p)
+ p = _somma(p, p)
+ k >>= 1
+ return r
+
+def verifica_firma(pub: bytes, messaggio: bytes, firma: bytes) -> bool:
+ if len(pub) != 65 or pub[0] != 4 or len(firma) != 64:
+ return False
+ x, y = (int.from_bytes(pub[1:33], 'big'), int.from_bytes(pub[33:], 'big'))
+ if not (x < _Q and y < _Q) or (y * y - x * x * x + 3 * x - _B) % _Q:
+ return False
+ r, s = (int.from_bytes(firma[:32], 'big'), int.from_bytes(firma[32:], 'big'))
+ if not (0 < r < _N and 0 < s < _N):
+ return False
+ z = int.from_bytes(hashlib.sha256(messaggio).digest(), 'big')
+ w = pow(s, _N - 2, _N)
+ punto = _somma(_per(z * w % _N, _G), _per(r * w % _N, (x, y)))
+ return punto is not None and punto[0] % _N == r
+
+def pubblica(privata: bytes) -> bytes:
+ return x25519(privata, 9 .to_bytes(32, 'little'))
+
+def hkdf(chiave: bytes, sale: bytes, info: bytes, lunghezza: int) -> bytes:
+ prk = hmac.new(sale, chiave, hashlib.sha256).digest()
+ out, blocco, i = (b'', b'', 1)
+ while len(out) < lunghezza:
+ blocco = hmac.new(prk, blocco + info + bytes([i]), hashlib.sha256).digest()
+ out += blocco
+ i += 1
+ return out[:lunghezza]
+
+def flusso(chiave: bytes, n: int) -> bytes:
+ out = b''
+ i = 0
+ while len(out) < n:
+ out += hmac.new(chiave, i.to_bytes(8, 'big'), hashlib.sha256).digest()
+ i += 1
+ return out[:n]
+
+def chiavi(condiviso: bytes, pub_client: bytes, eph: bytes, rid: str) -> tuple[bytes, bytes]:
+ k = hkdf(condiviso, pub_client + eph, INFO + b':' + rid.encode(), 64)
+ return (k[:32], k[32:])
+
+def apri(privata: bytes, pub_client: bytes, rid: str, consegna: dict, firma_pub: bytes, nomi: list[str]) -> dict:
+ eph, ct, tag, firma = (_b64d(consegna.get(x, '')) for x in ('eph', 'ct', 'tag', 'firma'))
+ if len(eph) != 32 or len(tag) != 32:
+ raise Rifiuto(F('consegna_rotta'))
+ if not verifica_firma(firma_pub, FIRMA + rid.encode() + pub_client + eph + ct + tag, firma):
+ raise Rifiuto(F('firma_falsa'))
+ condiviso = x25519(privata, eph)
+ if condiviso == bytes(32):
+ raise Rifiuto(F('consegna_rotta'))
+ k_cifra, k_tag = chiavi(condiviso, pub_client, eph, rid)
+ if not hmac.compare_digest(hmac.new(k_tag, eph + ct, hashlib.sha256).digest(), tag):
+ raise Rifiuto(F('consegna_rotta'))
+ chiaro = bytes((a ^ b for a, b in zip(ct, flusso(k_cifra, len(ct)))))
+ try:
+ valori = json.loads(chiaro.decode('utf-8'))
+ except (UnicodeDecodeError, ValueError):
+ raise Rifiuto(F('consegna_rotta')) from None
+ if not isinstance(valori, dict) or not all((isinstance(v, str) for v in valori.values())):
+ raise Rifiuto(F('consegna_rotta'))
+ if set(valori) != set(nomi):
+ raise Rifiuto(F('nomi_diversi'))
+ return valori
+
+def vietato(nome: str) -> bool:
+ return not NOME_RE.match(nome) or nome in NOMI_VIETATI or nome.startswith(PREFISSI_VIETATI)
+
+def _firme() -> tuple[str, dict]:
+ percorso = os.path.join(_sospese(), 'firme.json')
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ return (percorso, json.load(f))
+ except (OSError, ValueError):
+ return (percorso, {})
+
+def _di_chi() -> str:
+ return hashlib.sha256(TOKEN.encode()).hexdigest()[:16]
+
+def _spazio() -> str:
+ try:
+ pezzo = TOKEN.split('.')[1]
+ cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
+ except (IndexError, ValueError, AttributeError):
+ cli = ''
+ return URL if cli in ('', 'unico') else f'{URL}#{cli}'
+
+def _segue_la_catena(da: str, a: str, passaggi) -> bool:
+ passaggi = [x for x in passaggi or [] if isinstance(x, dict)]
+ adesso = da
+ for _ in range(len(passaggi)):
+ p = next((x for x in passaggi if x.get('da') == adesso), None)
+ try:
+ if p is None or not verifica_firma(_b64d(adesso), (FIRMA_PASSAGGIO + str(p.get('a'))).encode(), _b64d(str(p.get('firma') or ''))):
+ return False
+ except (ValueError, TypeError):
+ return False
+ adesso = str(p['a'])
+ if adesso == a:
+ return True
+ return False
+
+def firma_ricordata(pub_b64: str, passaggi=None) -> bytes:
+ percorso, note = _firme()
+ if not pub_b64:
+ raise Rifiuto(F('firma_falsa'))
+ vista = note.get(_spazio())
+ if vista and vista != pub_b64 and (not _segue_la_catena(vista, pub_b64, passaggi)):
+ raise Rifiuto(F('firma_cambiata', file=percorso))
+ return _b64d(pub_b64)
+
+def ricorda_firma(pub_b64: str) -> None:
+ percorso, note = _firme()
+ if note.get(_spazio()) == pub_b64:
+ return
+ note[_spazio()] = pub_b64
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump(note, f)
+
+def impronta_richiesta(pub: bytes) -> str:
+ h = hashlib.sha256(pub).hexdigest()[:8].upper()
+ return h[:4] + '-' + h[4:]
+
+def _b64(b: bytes) -> str:
+ return base64.b64encode(b).decode()
+
+def _b64d(s: str) -> bytes:
+ try:
+ return base64.b64decode(s.replace('-', '+').replace('_', '/') + '=' * (-len(s) % 4))
+ except (ValueError, TypeError):
+ return b''
+
+def _ambiente() -> tuple[str, str, str]:
+ try:
+ out = subprocess.run(['bash', os.path.join(QUI, 'delminio.sh'), 'ambiente'], capture_output=True, text=True, timeout=15).stdout.splitlines()
+ except (OSError, subprocess.TimeoutExpired):
+ out = []
+ url, file_token, sessione = (out + ['', '', ''])[:3]
+ try:
+ with open(file_token, encoding='utf-8') as f:
+ token = f.read().strip()
+ except OSError:
+ token = ''
+ if not url or not token:
+ raise Rifiuto(F('non_collegato'))
+ return (url.rstrip('/'), token, sessione)
+URL, TOKEN, SESSIONE = ('', '', '')
+
+def _http(metodo: str, percorso: str, corpo: dict | None=None) -> dict:
+ dati = json.dumps(corpo).encode() if corpo is not None else None
+ req = urllib.request.Request(f'{URL}/api/cassaforte{percorso}', data=dati, method=metodo, headers={'Authorization': f'Bearer {TOKEN}', 'Content-Type': 'application/json'})
+ try:
+ with urllib.request.urlopen(req, timeout=30) as r:
+ return json.loads(r.read().decode())
+ except urllib.error.HTTPError as e:
+ raw = e.read().decode()
+ try:
+ msg = json.loads(raw).get('error', raw)
+ except ValueError:
+ msg = raw
+ raise Rifiuto(f'❌ {msg}', e.code) from None
+ except (urllib.error.URLError, OSError) as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
+
+def _sospese() -> str:
+ d = os.path.join(os.environ.get('XDG_CACHE_HOME') or os.path.expanduser('~/.cache'), 'delminio-cassaforte')
+ os.makedirs(d, mode=448, exist_ok=True)
+ os.chmod(d, 448)
+ return d
+
+def _impronta(nomi: list[str], perche: str, comando: list[str]) -> str:
+ return hashlib.sha256(json.dumps([URL, nomi, perche, comando]).encode()).hexdigest()[:32]
+
+def _riprendi(chiave: str) -> dict | None:
+ try:
+ with open(os.path.join(_sospese(), chiave), encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return None
+
+def _metti_da_parte(chiave: str, dati: dict) -> None:
+ percorso = os.path.join(_sospese(), chiave)
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump(dati, f)
+
+def _dimentica(chiave: str) -> None:
+ try:
+ os.remove(os.path.join(_sospese(), chiave))
+ except OSError:
+ pass
+
+def _finestre_dir() -> str:
+ run = os.environ.get('XDG_RUNTIME_DIR') or ''
+ d = os.path.join(run, 'delminio-cassaforte') if run and os.path.isdir(run) else os.path.join(_sospese(), 'finestre')
+ os.makedirs(d, mode=448, exist_ok=True)
+ os.chmod(d, 448)
+ return d
+
+def _ora(iso: str) -> str:
+ try:
+ from datetime import datetime
+ return datetime.fromisoformat(iso).astimezone().strftime('%H:%M')
+ except (TypeError, ValueError):
+ return '?'
+
+def _finestre() -> list[dict]:
+ from datetime import datetime, timezone
+ adesso = datetime.now(timezone.utc)
+ vive = []
+ cartella = _finestre_dir()
+ for nome in sorted(os.listdir(cartella)):
+ percorso = os.path.join(cartella, nome)
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ w = json.load(f)
+ finita = datetime.fromisoformat(w['scade']) <= adesso
+ except (OSError, ValueError, KeyError, TypeError):
+ finita = True
+ w = {}
+ if finita:
+ try:
+ os.remove(percorso)
+ except OSError:
+ pass
+ elif w.get('spazio') == _spazio() and w.get('token') == _di_chi():
+ w['_file'] = percorso
+ vive.append(w)
+ return vive
+
+def _togli_finestra(w: dict) -> None:
+ try:
+ os.remove(w['_file'])
+ except (OSError, KeyError):
+ pass
+
+def _dalla_finestra(nomi: list[str], comando: str) -> dict | None:
+ for w in _finestre():
+ if not set(nomi) <= set(w['nomi']):
+ continue
+ try:
+ r = _http('GET', '/richiesta/' + urllib.parse.quote(w['id']) + '?comando=' + urllib.parse.quote(comando[:500]))
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ continue
+ if not r.get('consegna'):
+ _togli_finestra(w)
+ print(F('finestra_finita'), file=sys.stderr)
+ continue
+ firma_pub = r.get('firma_pub') or ''
+ valori = apri(_b64d(w['privata']), _b64d(w['pub']), w['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), w['nomi'])
+ print(F('finestra_usata', ora=_ora(w['scade'])), file=sys.stderr)
+ return {n: valori[n] for n in nomi}
+ return None
+
+def elenco() -> int:
+ d = _http('GET', '/elenco')
+ if not d.get('esiste'):
+ print(F('nessuna_cassaforte'))
+ return 0
+ if not d.get('segreti'):
+ print(F('nessun_segreto'))
+ return 0
+ for s in d['segreti']:
+ print(f" {s['nome']}" + (F('segno_larga') if s.get('larga') else '') + (f" — {s['nota']}" if s.get('nota') else ''))
+ return 0
+
+def proponi(argomenti: list[str]) -> int:
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_proponi', cmd=CMD))
+ nome = argomenti[0].strip()
+ if vietato(nome):
+ raise Rifiuto(F('nome_vietato', nome=nome))
+ _http('POST', '/proponi', {'nome': nome, 'nota': ' '.join(argomenti[1:]), 'sessione': SESSIONE})
+ print(F('proposta', nome=nome))
+ return 0
+
+def _nomi(testo: str) -> list[str]:
+ nomi = list(dict.fromkeys((n for n in testo.replace(' ', ',').split(',') if n)))
+ for n in nomi:
+ if vietato(n):
+ raise Rifiuto(F('nome_vietato', nome=n))
+ return nomi
+
+def _attendi(nomi: list[str], perche: str, comando: list[str], finestra: bool):
+ chiave = _impronta(nomi, perche, (['--finestra'] if finestra else []) + comando)
+ sospesa = _riprendi(chiave)
+ gia = None
+ if sospesa is not None:
+ try:
+ gia = _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ _dimentica(chiave)
+ sospesa = None
+ if sospesa is not None and (not gia.get('consegna')) and (gia.get('stato') in ('scaduta', 'ritirata', 'chiusa')):
+ _dimentica(chiave)
+ sospesa, gia = (None, None)
+ if sospesa is None:
+ privata = os.urandom(32)
+ pub = pubblica(privata)
+ r = _http('POST', '/chiedi', {'nomi': nomi, 'perche': perche, 'comando': shlex.join(comando), 'sessione': SESSIONE, 'pub': _b64(pub), 'finestra': finestra})
+ sospesa = {'id': r['id'], 'privata': _b64(privata), 'pub': _b64(pub), 'tua': r.get('decide') == 'tu'}
+ _metti_da_parte(chiave, sospesa)
+ tua = sospesa['tua']
+ minuti = (r.get('finestra_s') or 0) // 60
+ if finestra:
+ print(F('finestra_chiesta_tua', n=len(nomi), minuti=minuti) if tua else F('finestra_chiesta', n=len(nomi), minuti=minuti), file=sys.stderr)
+ else:
+ print(F('chiesta_tua', nomi=', '.join(nomi)) if tua else F('chiesta', nomi=', '.join(nomi)), file=sys.stderr)
+ imp = impronta_richiesta(_b64d(sospesa['pub']))
+ print(F('impronta_tua', impronta=imp) if sospesa.get('tua') else F('impronta', impronta=imp), file=sys.stderr)
+ print(F('aspetto', secondi=ATTESA_S), file=sys.stderr)
+ fine = time.monotonic() + ATTESA_S
+ while True:
+ r = gia if gia is not None else _http('GET', '/richiesta/' + urllib.parse.quote(sospesa['id']))
+ gia = None
+ stato = r.get('stato')
+ if r.get('consegna'):
+ _dimentica(chiave)
+ firma_pub = r.get('firma_pub') or ''
+ valori = apri(_b64d(sospesa['privata']), _b64d(sospesa['pub']), sospesa['id'], r['consegna'], firma_ricordata(firma_pub, r.get('passaggi')), nomi)
+ ricorda_firma(firma_pub)
+ return (sospesa, r, valori)
+ if stato == 'negata':
+ _dimentica(chiave)
+ parole = r.get('parole') or ''
+ print(F('negata', chi=r.get('deciso_da') or '?', parole=f': «{parole}»' if parole else ''), file=sys.stderr)
+ return 3
+ if stato in ('scaduta', 'ritirata', 'chiusa'):
+ _dimentica(chiave)
+ print(F('scaduta'), file=sys.stderr)
+ return 3
+ if time.monotonic() > fine:
+ print(F('ancora_niente'), file=sys.stderr)
+ return 4
+ time.sleep(2)
+
+def valori(nomi: list[str], perche: str, comando: str) -> dict:
+ global URL, TOKEN, SESSIONE
+ if not URL:
+ URL, TOKEN, SESSIONE = _ambiente()
+ nomi = _nomi(','.join(nomi))
+ dalla = _dalla_finestra(nomi, comando)
+ if dalla is not None:
+ return dalla
+ esito = _attendi(nomi, perche, shlex.split(comando) or [comando], False)
+ if isinstance(esito, int):
+ raise Rifiuto(F('non_concessa'), esito)
+ print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
+ return esito[2]
+
+def chiedi(argomenti: list[str]) -> int:
+ if '--' not in argomenti or argomenti.index('--') < 2:
+ raise Rifiuto(F('uso_chiedi', cmd=CMD))
+ i = argomenti.index('--')
+ nomi = _nomi(argomenti[0])
+ perche = ' '.join(argomenti[1:i])
+ comando = argomenti[i + 1:]
+ if not comando:
+ raise Rifiuto(F('comando_mancante'))
+ dati = _dalla_finestra(nomi, shlex.join(comando))
+ if dati is None:
+ esito = _attendi(nomi, perche, comando, False)
+ if isinstance(esito, int):
+ return esito
+ print(F('concessa', chi=esito[1].get('deciso_da') or '?'), file=sys.stderr)
+ dati = esito[2]
+ sys.stderr.flush()
+ os.execvpe(comando[0], comando, dict(os.environ, **dati))
+
+def apri_finestra(argomenti: list[str]) -> int:
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_apri', cmd=CMD))
+ if argomenti[0] == '--larghe':
+ nomi = [s['nome'] for s in _http('GET', '/elenco').get('segreti', []) if s.get('larga')]
+ if not nomi:
+ raise Rifiuto(F('nessuna_larga'))
+ else:
+ nomi = _nomi(argomenti[0])
+ esito = _attendi(nomi, ' '.join(argomenti[1:]), [], True)
+ if isinstance(esito, int):
+ return esito
+ sospesa, r, _ = esito
+ scade = r.get('scade') or ''
+ percorso = os.path.join(_finestre_dir(), 'finestra-' + hashlib.sha256(_spazio().encode()).hexdigest()[:8] + '-' + re.sub('[^A-Za-z0-9_-]', '', sospesa['id']) + '.json')
+ fd = os.open(percorso, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as f:
+ json.dump({**sospesa, 'nomi': nomi, 'scade': scade, 'spazio': _spazio(), 'token': _di_chi()}, f)
+ print(F('finestra_aperta', chi=r.get('deciso_da') or '?', ora=_ora(scade), nomi=', '.join(nomi)), file=sys.stderr)
+ return 0
+
+def finestre() -> int:
+ vive = _finestre()
+ if not vive:
+ print(F('finestre_nessuna'))
+ for w in vive:
+ print(F('finestra_riga', ora=_ora(w['scade']), nomi=', '.join(w['nomi'])))
+ return 0
+
+def chiudi() -> int:
+ n = 0
+ for w in _finestre():
+ try:
+ _http('POST', '/richiesta/' + urllib.parse.quote(w['id']) + '/chiudi', {})
+ except Rifiuto as e:
+ if e.stato != 404:
+ raise
+ _togli_finestra(w)
+ n += 1
+ print(F('finestre_chiuse', n=n))
+ return 0
+
+def _da_file(percorso: str, nomi: list[str]) -> dict:
+ trovati = {}
+ with open(percorso, encoding='utf-8') as f:
+ for riga in f:
+ riga = riga.strip()
+ k, uguale, v = riga.partition('=')
+ if uguale and k.strip() in nomi:
+ trovati[k.strip()] = v.strip().strip('\'"')
+ return trovati
+
+def cifra_deposito(pub: bytes, nome: str, valore: str) -> dict:
+ privata = os.urandom(32)
+ eph = pubblica(privata)
+ condiviso = x25519(privata, pub)
+ if condiviso == bytes(32):
+ raise Rifiuto(F('deposito_firma'))
+ k = hkdf(condiviso, pub + eph, INFO + b':deposito:' + nome.encode(), 64)
+ dati = valore.encode('utf-8')
+ ct = bytes((a ^ b for a, b in zip(dati, flusso(k[:32], len(dati)))))
+ tag = hmac.new(k[32:], eph + ct, hashlib.sha256).digest()
+ return {'eph': _b64(eph), 'ct': _b64(ct), 'tag': _b64(tag)}
+
+def deposita(argomenti: list[str]) -> int:
+ larga = '--larga' in argomenti
+ argomenti = [a for a in argomenti if a != '--larga']
+ file = None
+ if '--dal-file' in argomenti:
+ i = argomenti.index('--dal-file')
+ if i + 1 >= len(argomenti):
+ raise Rifiuto(F('uso_deposita', cmd=CMD))
+ file = argomenti[i + 1]
+ argomenti = argomenti[:i] + argomenti[i + 2:]
+ if len(argomenti) < 2:
+ raise Rifiuto(F('uso_deposita', cmd=CMD))
+ nomi, nota = (_nomi(argomenti[0]), ' '.join(argomenti[1:]))
+ d = _http('GET', '/elenco')
+ if not d.get('esiste'):
+ raise Rifiuto(F('nessuna_cassaforte'))
+ dep = d.get('deposito') or {}
+ if not dep.get('pub'):
+ raise Rifiuto(F('deposito_senza_chiave'))
+ fp = firma_ricordata(dep.get('firma_pub') or '', dep.get('passaggi'))
+ if not verifica_firma(fp, (FIRMA_DEPOSITO + dep['pub']).encode(), _b64d(dep.get('firma') or '')):
+ raise Rifiuto(F('deposito_firma'))
+ ricorda_firma(dep['firma_pub'])
+ if file:
+ trovati = _da_file(file, nomi)
+ elif len(nomi) == 1:
+ trovati = {nomi[0]: sys.stdin.read().rstrip('\n')}
+ else:
+ raise Rifiuto(F('deposito_stdin'))
+ for n in nomi:
+ if not trovati.get(n):
+ raise Rifiuto(F('deposito_vuoto', nome=n))
+ pub = _b64d(dep['pub'])
+ for n in nomi:
+ _http('POST', '/proponi', {'nome': n, 'nota': nota, 'sessione': SESSIONE, 'larga': larga, 'deposito': cifra_deposito(pub, n, trovati[n]), 'per': dep['pub']})
+ print(F('depositato', nome=n))
+ return 0
+
+def main(argv: list[str]) -> int:
+ global URL, TOKEN, SESSIONE
+ if not argv or argv[0] in ('aiuto', 'help', '-h', '--help'):
+ print(F('aiuto', cmd=CMD))
+ return 0
+ try:
+ URL, TOKEN, SESSIONE = _ambiente()
+ gesti = {'elenco': lambda: elenco(), 'proponi': lambda: proponi(argv[1:]), 'apri': lambda: apri_finestra(argv[1:]), 'finestre': lambda: finestre(), 'chiudi': lambda: chiudi(), 'deposita': lambda: deposita(argv[1:])}
+ if argv[0] in gesti:
+ return gesti[argv[0]]()
+ return chiedi(argv)
+ except Rifiuto as e:
+ print(str(e), file=sys.stderr)
+ return 1
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/it/consumi-client b/kit/it/consumi-client
new file mode 100644
index 0000000..061d4e7
--- /dev/null
+++ b/kit/it/consumi-client
@@ -0,0 +1,477 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""I token di una conversazione, letti dalla CLI e mai il testo (F868)."""
+import glob, json, os, re, sys
+POSTA = re.compile('^ \\S+ → \\S+ \\d\\d:\\d\\d UTC$', re.M)
+stato_f = sys.argv[1]
+try:
+ e = json.load(sys.stdin)
+ p = e.get('transcript_path') or ''
+ dim = os.path.getsize(p)
+except Exception:
+ sys.exit(0)
+try:
+ st = json.load(open(stato_f))
+except Exception:
+ st = {}
+oc = e.get('cli') == 'opencode'
+sid_oc = str(e.get('session_id') or '')
+chiave = p + '#' + sid_oc if oc else p
+if st.get('p') != chiave or (not oc and st.get('off', 0) > dim):
+ st = {'p': chiave, 'off': 0, 'cli': '', 'mod': '', 't': {}, 'id': '', 'u': {}, 'n': 0}
+t = st['t']
+
+def oc_testo(x):
+ if isinstance(x, str):
+ return x
+ if isinstance(x, list):
+ return ''.join((oc_testo(b) for b in x))
+ if isinstance(x, dict):
+ return str(x.get('text') or x.get('output') or '')
+ return ''
+
+def oc_risposta(mid, modello, tok, blocchi, risultati):
+ tok = tok or {}
+ cache = tok.get('cache') or {}
+ u = {'input_tokens': int(tok.get('input') or 0), 'cache_read_input_tokens': int(cache.get('read') or 0), 'cache_creation_input_tokens': int(cache.get('write') or 0), 'output_tokens': int(tok.get('output') or 0) + int(tok.get('reasoning') or 0)}
+ out = [{'type': 'assistant', 'message': {'id': mid, 'model': modello, 'usage': u, 'content': blocchi}}]
+ if risultati:
+ out.append({'type': 'user', 'message': {'content': risultati}})
+ return out
+
+def oc_umano(parti):
+ out = []
+ for x in parti:
+ if x.get('type') != 'text' or not x.get('text'):
+ continue
+ if x.get('synthetic'):
+ out.append({'type': 'attachment', 'attachment': {'type': 'hook_additional_context', 'hookEvent': 'opencode', 'content': x['text']}})
+ else:
+ out.append({'type': 'user', 'message': {'content': [{'type': 'text', 'text': x['text']}]}})
+ return out
+
+def oc_righe(db, sid, dopo):
+ import sqlite3
+ righe, fino = ([], list(dopo or [0, '']))
+ try:
+ c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
+ except sqlite3.Error:
+ return (righe, fino)
+ try:
+ tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
+ dove = 'session_id=? and (time_created>? or (time_created=? and id>?)) order by time_created, id'
+ arg = (sid, fino[0], fino[0], fino[1])
+ if 'session_message' in tabelle:
+ for mid, tc, tipo, d in c.execute('select id, time_created, type, data from session_message where ' + dove, arg).fetchall():
+ m = json.loads(d)
+ if tipo == 'assistant':
+ if not (m.get('time') or {}).get('completed'):
+ break
+ mod = m.get('model') or {}
+ modello = (str(mod.get('providerID') or '') + '/' + str(mod.get('id') or '')).strip('/')
+ blocchi, ris = ([], [])
+ for x in m.get('content') or []:
+ k = x.get('type')
+ if k == 'tool':
+ s = x.get('state') or {}
+ blocchi.append({'type': 'tool_use', 'id': x.get('id'), 'name': x.get('name'), 'input': s.get('input') or {}})
+ if s.get('status') in ('completed', 'error'):
+ ris.append({'type': 'tool_result', 'tool_use_id': x.get('id'), 'content': oc_testo(s.get('content') or s.get('error') or '')})
+ elif k == 'text':
+ blocchi.append({'type': 'text', 'text': x.get('text') or ''})
+ elif k == 'reasoning':
+ blocchi.append({'type': 'thinking', 'thinking': oc_testo(x.get('text') or x.get('content'))})
+ righe += oc_risposta(mid, modello, m.get('tokens'), blocchi, ris)
+ elif tipo == 'user':
+ righe += oc_umano([{'type': 'text', 'text': m.get('text') or ''}])
+ elif (tx := oc_testo(m.get('text') or m.get('content'))):
+ righe += oc_umano([{'type': 'text', 'text': tx, 'synthetic': True}])
+ fino = [tc, mid]
+ except (sqlite3.Error, ValueError):
+ pass
+ finally:
+ c.close()
+ return (righe, fino)
+
+def oc_figlie(db, sid):
+ import sqlite3
+ try:
+ c = sqlite3.connect('file:' + db + '?mode=ro', uri=True, timeout=2)
+ except sqlite3.Error:
+ return []
+ try:
+ tabelle = {r[0] for r in c.execute('select name from sqlite_master where type="table"')}
+ figli = {}
+ for tab in ('session', 'session_v2'):
+ if tab in tabelle:
+ for i, padre in c.execute('select id, parent_id from ' + tab + ' where parent_id is not null'):
+ figli.setdefault(padre, []).append(i)
+ except sqlite3.Error:
+ return []
+ finally:
+ c.close()
+ out, coda = ([], [sid])
+ while coda:
+ for i in figli.get(coda.pop(), []):
+ if i not in out:
+ out.append(i)
+ coda.append(i)
+ return out
+
+def somma(d):
+ for k, v in d.items():
+ t[k] = t.get(k, 0) + int(v or 0)
+import re
+_CAR_PER_TOKEN = 3.2
+_FONTI_MAX = 64
+_COMANDO_DELMINIO = re.compile('(?:^|[\\s;&|(\\"\\x27])delminio\\s+[a-z]|delminio\\.sh\\b')
+
+def _fonti_lungo(x):
+ if isinstance(x, str):
+ return len(x)
+ if isinstance(x, list):
+ return sum((6000 if isinstance(b, dict) and b.get('type') == 'image' else _fonti_lungo(b) for b in x))
+ if isinstance(x, dict) and x.get('type') == 'text':
+ return len(x.get('text') or '')
+ return len(json.dumps(x, ensure_ascii=False))
+
+def _fonti_tool(nome, argomenti):
+ nome = str(nome or '?')
+ if 'delminio' in nome.lower():
+ op = argomenti.get('operation') if isinstance(argomenti, dict) else None
+ return 'delminio:' + str(op or nome.rsplit('__', 1)[-1])[:30]
+ testo = argomenti if isinstance(argomenti, str) else json.dumps(argomenti, ensure_ascii=False)
+ if nome in ('Bash', 'bash', 'exec_command', 'shell', 'exec', 'run_shell_command') or 'shell' in nome.lower():
+ return 'delminio:comando' if _COMANDO_DELMINIO.search(testo or '') else 'comando'
+ if nome.startswith('mcp__'):
+ return 'mcp:' + nome.split('__')[1][:30]
+ return 'tool:' + nome[:30]
+
+def fonti_nuovo():
+ return {'E': {}, 'R': {}, 'G': {}, 'pend': [], 'dopo': [], 'tid': {}, 'prev': 0, 'n': 0, 'ultimo': None}
+
+def _fonti_pezzo(a, fonte, car):
+ if car > 0:
+ a['pend'].append([fonte, int(car)])
+
+def _fonti_risposta(a, ctx, pezzi):
+ E = a['E']
+ if a['n'] == 0:
+ stima = {}
+ for f, c in pezzi:
+ stima[f] = stima.get(f, 0) + c / _CAR_PER_TOKEN
+ tot = sum(stima.values())
+ scala = min(1.0, ctx / tot) if tot else 0
+ for f, v in stima.items():
+ E[f] = E.get(f, 0) + v * scala
+ E['sistema'] = E.get('sistema', 0) + max(0, ctx - tot * scala)
+ elif ctx < a['prev']:
+ scala = ctx / a['prev']
+ for f in E:
+ E[f] *= scala
+ else:
+ delta = ctx - a['prev']
+ car = sum((c for _, c in pezzi))
+ if not car:
+ E['altro'] = E.get('altro', 0) + delta
+ for f, c in pezzi:
+ E[f] = E.get(f, 0) + delta * c / car if car else E.get(f, 0)
+ for f, v in E.items():
+ a['R'][f] = a['R'].get(f, 0) + v
+ motori = sorted({f for f, _ in pezzi if f.split(':')[0] in ('delminio', 'comando', 'tool', 'mcp')})
+ if not motori:
+ motori = ['persona'] if any((f == 'persona' for f, _ in pezzi)) else ['altro']
+ for f in motori:
+ a['G'][f] = a['G'].get(f, 0) + ctx / len(motori)
+ a['prev'] = ctx
+ a['n'] += 1
+
+def fonti_riga(a, d):
+ t = d.get('type')
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if t == 'attachment' and isinstance(d.get('attachment'), dict):
+ at = d['attachment']
+ k = str(at.get('type') or '')
+ if k == 'hook_additional_context':
+ _fonti_pezzo(a, 'gancio:' + str(at.get('hookEvent') or '?')[:30], _fonti_lungo(at.get('content') or ''))
+ elif k not in ('hook_success', 'prompt_snapshot', ''):
+ _fonti_pezzo(a, 'cli:' + k[:40], _fonti_lungo({x: y for x, y in at.items() if x != 'type'}))
+ return
+ if t == 'user' and isinstance(d.get('message'), dict) and (not d.get('isSidechain')):
+ c = d['message'].get('content')
+ if isinstance(c, str):
+ _fonti_pezzo(a, 'cli:meta' if d.get('isMeta') else 'persona', len(c))
+ return
+ for b in c if isinstance(c, list) else []:
+ if not isinstance(b, dict):
+ continue
+ if b.get('type') == 'tool_result':
+ _fonti_pezzo(a, a['tid'].pop(b.get('tool_use_id'), 'tool:?'), _fonti_lungo(b.get('content') or ''))
+ elif b.get('type') == 'text':
+ x = b.get('text') or ''
+ f = 'gancio:posta' if POSTA.search(x) else 'cli:promemoria' if '<system-reminder>' in x or d.get('isMeta') else 'persona'
+ _fonti_pezzo(a, f, len(x))
+ elif b.get('type') == 'image':
+ _fonti_pezzo(a, 'persona', 6000)
+ return
+ if t == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict) and (not d.get('isSidechain')):
+ m = d['message']
+ if m.get('id') != a['ultimo']:
+ u = m['usage']
+ a['ultimo'] = m.get('id')
+ _fonti_risposta(a, int(u.get('input_tokens') or 0) + int(u.get('cache_read_input_tokens') or 0) + int(u.get('cache_creation_input_tokens') or 0), a['pend'])
+ a['pend'] = []
+ for b in m.get('content') or []:
+ if not isinstance(b, dict):
+ continue
+ if b.get('type') == 'tool_use':
+ a['tid'][b.get('id')] = _fonti_tool(b.get('name'), b.get('input') or {})
+ _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(b.get('input') or {}))
+ elif b.get('type') == 'thinking':
+ _fonti_pezzo(a, 'modello:pensiero', len(b.get('thinking') or '') or len(b.get('signature') or '') // 2)
+ elif b.get('type') == 'text':
+ _fonti_pezzo(a, 'modello:testo', len(b.get('text') or ''))
+ return
+ if t == 'assistant' and isinstance(d.get('usageMetadata'), dict):
+ _fonti_risposta(a, int(d['usageMetadata'].get('promptTokenCount') or 0), a['pend'])
+ a['pend'] = []
+ for p in (d.get('message') or {}).get('parts') or []:
+ if not isinstance(p, dict):
+ continue
+ if isinstance(p.get('functionCall'), dict):
+ fc = p['functionCall']
+ a['tid'][fc.get('id') or fc.get('name')] = _fonti_tool(fc.get('name'), fc.get('args') or {})
+ _fonti_pezzo(a, 'modello:chiamate', _fonti_lungo(fc.get('args') or {}))
+ elif p.get('text'):
+ _fonti_pezzo(a, 'modello:pensiero' if p.get('thought') else 'modello:testo', len(p['text']))
+ return
+ if t == 'tool_result':
+ for p in (d.get('message') or {}).get('parts') or []:
+ fr = p.get('functionResponse') if isinstance(p, dict) else None
+ if isinstance(fr, dict):
+ f = a['tid'].pop(fr.get('id'), None) or a['tid'].pop(fr.get('name'), None) or _fonti_tool(fr.get('name'), {})
+ _fonti_pezzo(a, f, _fonti_lungo(fr.get('response') or ''))
+ return
+ if t == 'user' and isinstance(d.get('message'), dict):
+ for p in d['message'].get('parts') or []:
+ if isinstance(p, dict) and p.get('text'):
+ _fonti_pezzo(a, 'cli:avviso' if d.get('subtype') else 'persona', len(p['text']))
+ return
+ if t == 'session_meta':
+ _fonti_pezzo(a, 'sistema', _fonti_lungo(pl.get('base_instructions') or ''))
+ elif t == 'response_item':
+ k = pl.get('type')
+ if k == 'message':
+ car = _fonti_lungo(pl.get('content') or [])
+ if pl.get('role') == 'assistant':
+ a['dopo'].append(['modello:testo', car])
+ else:
+ testo = json.dumps(pl.get('content') or [], ensure_ascii=False)
+ f = 'persona' if pl.get('role') == 'user' and '<environment_context>' not in testo and ('AGENTS.md' not in testo) else 'cli:istruzioni'
+ _fonti_pezzo(a, f, car)
+ elif k == 'reasoning':
+ a['dopo'].append(['modello:pensiero', len(pl.get('encrypted_content') or '') // 3 or _fonti_lungo(pl.get('summary') or [])])
+ elif k in ('function_call', 'custom_tool_call', 'local_shell_call'):
+ arg = pl.get('arguments') or pl.get('input') or pl.get('action') or {}
+ if isinstance(arg, str):
+ try:
+ arg = json.loads(arg)
+ except ValueError:
+ pass
+ a['tid'][pl.get('call_id')] = _fonti_tool(pl.get('name') or 'shell', arg)
+ a['dopo'].append(['modello:chiamate', _fonti_lungo(arg)])
+ elif k in ('function_call_output', 'custom_tool_call_output', 'local_shell_call_output'):
+ _fonti_pezzo(a, a['tid'].pop(pl.get('call_id'), 'tool:?'), _fonti_lungo(pl.get('output') or ''))
+ elif t == 'event_msg' and pl.get('type') == 'token_count':
+ u = (pl.get('info') or {}).get('last_token_usage') or {}
+ tot = ((pl.get('info') or {}).get('total_token_usage') or {}).get('total_tokens')
+ if u and tot != a.get('tot_codex'):
+ a['tot_codex'] = tot
+ _fonti_risposta(a, int(u.get('input_tokens') or 0), a.pop('prima', []) + a['pend'])
+ a['pend'] = []
+ a['prima'], a['dopo'] = (a['dopo'], [])
+
+def fonti_fuori(a):
+ tutte = sorted(set(a['E']) | set(a['R']) | set(a['G']), key=lambda f: -a['R'].get(f, 0))
+ out, resto = ({}, [0, 0, 0])
+ for i, f in enumerate(tutte):
+ v = [round(a['E'].get(f, 0)), round(a['R'].get(f, 0)), round(a['G'].get(f, 0))]
+ if i < _FONTI_MAX - 1:
+ out[f] = v
+ else:
+ resto = [x + y for x, y in zip(resto, v)]
+ if any(resto):
+ out['altro'] = [x + y for x, y in zip(out.get('altro', [0, 0, 0]), resto)]
+ return {'contesto': int(a['prev']), 'fonti': out}
+
+def righe_testo(testo):
+ for riga in testo.splitlines():
+ try:
+ d = json.loads(riga)
+ except ValueError:
+ continue
+ if isinstance(d, dict):
+ yield d
+a = st.get('a') or fonti_nuovo()
+st['a'] = a
+if oc:
+ nuove, st['oc'] = oc_righe(p, sid_oc, st.get('oc'))
+ fine = 0
+else:
+ with open(p, 'rb') as f:
+ f.seek(st['off'])
+ pezzo = f.read()
+ fine = pezzo.rfind(b'\n') + 1
+ nuove = righe_testo(pezzo[:fine].decode('utf-8', 'replace'))
+for d in nuove:
+ fonti_riga(a, d)
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if d.get('type') == 'turn_context' and pl.get('model'):
+ st['cli'], st['mod'] = ('codex', str(pl['model']))
+ elif pl.get('type') == 'token_count':
+ u = (pl.get('info') or {}).get('total_token_usage') or {}
+ if u:
+ st['cli'] = 'codex'
+ letta = int(u.get('cached_input_tokens') or 0)
+ st['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ st['n'] += 1
+ elif d.get('type') == 'assistant' and isinstance(d.get('usageMetadata'), dict):
+ u = d['usageMetadata']
+ st['cli'], st['mod'] = ('qwen', str(d.get('model') or st['mod']))
+ letta = int(u.get('cachedContentTokenCount') or 0)
+ somma({'input': max(0, int(u.get('promptTokenCount') or 0) - letta), 'cache_letta': letta, 'output': int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0)})
+ st['n'] += 1
+ elif d.get('type') == 'assistant' and isinstance((d.get('message') or {}).get('usage'), dict):
+ m = d['message']
+ if m.get('model') and (not str(m['model']).startswith('<')):
+ st['mod'] = str(m['model'])
+ st['cli'] = 'opencode' if oc else 'claude'
+ u = m['usage']
+ nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ if m.get('id') != st['id']:
+ if st['id']:
+ somma(st['u'])
+ st['id'] = m.get('id') or ''
+ st['n'] += 1
+ st['u'] = nuovo
+st['off'] += fine
+for k in list(a['tid'])[:-200]:
+ del a['tid'][k]
+tot = dict(t)
+if st['cli'] in ('claude', 'codex', 'opencode'):
+ for k, v in st['u'].items():
+ tot[k] = (tot.get(k, 0) if st['cli'] != 'codex' else 0) + v
+atteso = sum((tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta')))
+if atteso and abs(sum(a['R'].values()) - atteso) > max(1000, atteso // 100):
+ a = fonti_nuovo()
+ if oc:
+ tutte = oc_righe(p, sid_oc, [0, ''])[0]
+ else:
+ with open(p, 'rb') as f:
+ tutte = righe_testo(f.read(st['off']).decode('utf-8', 'replace'))
+ for d in tutte:
+ fonti_riga(a, d)
+ for k in list(a['tid'])[:-200]:
+ del a['tid'][k]
+ st['a'] = a
+sid = os.path.basename(p).rsplit('.', 1)[0]
+radice = {'claude': os.path.join(os.path.dirname(p), sid, 'subagents'), 'qwen': os.path.join(os.path.dirname(os.path.dirname(p)), 'subagents', sid)}.get(st['cli'])
+ag = st.setdefault('ag', {})
+file_agenti = sorted(glob.glob(os.path.join(radice, '**', 'agent-*.jsonl'), recursive=True)) if radice else []
+if st['cli'] == 'codex':
+ casa = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(p))))
+ padri = st.setdefault('padri', {})
+ nato = st.setdefault('nato', os.path.getmtime(p) - 86400)
+ for f in glob.glob(os.path.join(casa, '*', '*', '*', 'rollout-*.jsonl')):
+ if f in padri or f == p:
+ continue
+ try:
+ if os.path.getmtime(f) < nato:
+ continue
+ with open(f, 'rb') as h:
+ m = json.loads(h.readline() or b'{}').get('payload') or {}
+ except (OSError, ValueError):
+ continue
+ sp = ((m.get('source') or {}).get('subagent') or {}).get('thread_spawn') if isinstance(m.get('source'), dict) else None
+ padri[f] = [str(m.get('id') or ''), str((sp or {}).get('parent_thread_id') or '')]
+ try:
+ with open(p, 'rb') as h:
+ mio = str((json.loads(h.readline() or b'{}').get('payload') or {}).get('id') or '')
+ except (OSError, ValueError):
+ mio = ''
+ famiglia, cresce = ({mio or str(e.get('session_id') or '')}, True)
+ while cresce:
+ cresce = False
+ for i, padre in padri.values():
+ if padre in famiglia and i and (i not in famiglia):
+ famiglia.add(i)
+ cresce = True
+ file_agenti = sorted((f for f, (i, padre) in padri.items() if padre in famiglia))
+if oc:
+ file_agenti = ['oc:' + i for i in oc_figlie(p, sid_oc)]
+for f in file_agenti:
+ if f.startswith('oc:'):
+ s = ag.get(f) or {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
+ ag[f] = s
+ righe_ag, s['oc'] = oc_righe(p, f[3:], s.get('oc'))
+ fn = 0
+ else:
+ try:
+ dimf = os.path.getsize(f)
+ except OSError:
+ continue
+ s = ag.get(f)
+ if not s or s['off'] > dimf:
+ s = ag[f] = {'off': 0, 't': {}, 'id': '', 'u': {}, 'n': 0, 'mod': ''}
+ with open(f, 'rb') as h:
+ h.seek(s['off'])
+ pz = h.read()
+ fn = pz.rfind(b'\n') + 1
+ righe_ag = righe_testo(pz[:fn].decode('utf-8', 'replace'))
+ for d in righe_ag:
+ pl = d.get('payload') if isinstance(d.get('payload'), dict) else {}
+ if d.get('type') == 'turn_context' and pl.get('model'):
+ s['mod'] = str(pl['model'])
+ elif pl.get('type') == 'token_count' and (pl.get('info') or {}).get('total_token_usage'):
+ u = pl['info']['total_token_usage']
+ letta = int(u.get('cached_input_tokens') or 0)
+ s['u'] = {'input': max(0, int(u.get('input_tokens') or 0) - letta), 'cache_letta': letta, 'cache_scritta': int(u.get('cache_write_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ s['n'] += 1
+ if d.get('type') != 'assistant':
+ continue
+ if isinstance(d.get('usageMetadata'), dict):
+ u = d['usageMetadata']
+ letta = int(u.get('cachedContentTokenCount') or 0)
+ for k, v in (('input', max(0, int(u.get('promptTokenCount') or 0) - letta)), ('cache_letta', letta), ('output', int(u.get('candidatesTokenCount') or 0) + int(u.get('thoughtsTokenCount') or 0))):
+ s['t'][k] = s['t'].get(k, 0) + v
+ s['n'] += 1
+ s['mod'] = str(d.get('model') or s['mod'])
+ elif isinstance((d.get('message') or {}).get('usage'), dict):
+ m = d['message']
+ u = m['usage']
+ if m.get('model') and (not str(m['model']).startswith('<')):
+ s['mod'] = str(m['model'])
+ nuovo = {'input': int(u.get('input_tokens') or 0), 'cache_letta': int(u.get('cache_read_input_tokens') or 0), 'cache_scritta': int(u.get('cache_creation_input_tokens') or 0), 'output': int(u.get('output_tokens') or 0)}
+ if m.get('id') != s['id']:
+ if s['id']:
+ for k, v in s['u'].items():
+ s['t'][k] = s['t'].get(k, 0) + v
+ s['id'] = m.get('id') or ''
+ s['n'] += 1
+ s['u'] = nuovo
+ s['off'] += fn
+agenti = {}
+for s in ag.values():
+ for k in ('input', 'cache_letta', 'cache_scritta', 'output'):
+ agenti[k] = agenti.get(k, 0) + s['t'].get(k, 0) + s['u'].get(k, 0)
+ agenti['risposte'] = agenti.get('risposte', 0) + s['n']
+ agenti['modello'] = s['mod'] or agenti.get('modello', '')
+tmp = stato_f + '.nuovo'
+json.dump(st, open(tmp, 'w'))
+os.replace(tmp, stato_f)
+if not st['cli']:
+ sys.exit(0)
+fuori = {'conversazione': str(e.get('session_id') or os.path.basename(p))[:80], 'cli': st['cli'], 'modello': st['mod'][:80], 'risposte': st['n'], **{k: tot.get(k, 0) for k in ('input', 'cache_letta', 'cache_scritta', 'output')}, **fonti_fuori(a)}
+if agenti.get('risposte'):
+ fuori['agenti'] = {**agenti, 'modello': agenti.get('modello', '')[:80]}
+print(json.dumps(fuori))
diff --git a/kit/it/copia-client b/kit/it/copia-client
new file mode 100644
index 0000000..a3f8af9
--- /dev/null
+++ b/kit/it/copia-client
@@ -0,0 +1,286 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La copia di sicurezza di ciò che c'era prima del collegamento (F777)."""
+import hashlib, json, os, re, shutil, sys, time
+exec(__import__('os').environ['DELMINIO_F_PY'])
+modo, radice, memoria, comune, url, gitdir = sys.argv[1:7]
+casa = os.path.expanduser('~')
+config = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.join(casa, '.claude')
+memoria = os.path.realpath(memoria) if memoria else ''
+
+def leggi(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return {}
+scelta, da = ('', '')
+for f, nome in ((os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(config, 'settings.json'), os.path.join(config, 'settings.json'))):
+ v = leggi(f).get('autoMemoryDirectory')
+ v = os.path.realpath(os.path.expanduser(v)) if isinstance(v, str) and v else ''
+ if v and v != memoria:
+ scelta, da = (v, nome)
+ break
+progetto = os.environ.get('CLAUDE_CODE_PROJECT_DIR_NAME') or re.sub('[^A-Za-z0-9]', '-', comune)
+vecchia = scelta or os.path.join(config, 'projects', progetto, 'memory')
+if modo == 'controlla':
+ if scelta and memoria:
+ print(f'{scelta}\t{da}')
+ sys.exit(0)
+segno_backup = os.path.join(gitdir, 'delminio-backup')
+cartella = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.join(casa, '.local', 'share'), 'delminio', 'backup', (re.sub('[^A-Za-z0-9._-]', '-', os.path.basename(comune)) or 'repo') + '-' + hashlib.sha256(comune.encode()).hexdigest()[:12])
+try:
+ cartella = open(segno_backup, encoding='utf-8').read().strip() or cartella
+except OSError:
+ pass
+
+def una_copia_c_e():
+ for c in (cartella, os.path.join(radice, '.claude', 'delminio-prima')):
+ if os.path.isdir(c) and any((os.path.isfile(os.path.join(c, d, 'fatti.json')) for d in os.listdir(c))):
+ return True
+ return False
+if os.environ.get('DELMINIO_PRIMA_VOLTA') != 'si' and una_copia_c_e():
+ sys.exit(0)
+dest = os.path.join(cartella, time.strftime('%Y-%m-%d-%H%M%S'))
+copie = []
+copiati = []
+non_copiati = []
+peso = 0
+SEGRETO = re.compile('(^|/)(auth\\.json|\\.credentials\\.json|oauth_creds\\.json|credentials(\\.json)?|\\.env(\\.[^/]*)?|[^/]*\\.(token|pem|key|p12|pfx)|id_(rsa|ed25519|ecdsa|dsa)[^/]*|\\.netrc|\\.git-credentials)$', re.I)
+TETTO_FILE = 20 * 1024 * 1024
+TETTO = 200 * 1024 * 1024
+
+def mostra(p):
+ p = os.path.abspath(p)
+ if p == radice or p.startswith(radice + os.sep):
+ return os.path.relpath(p, radice)
+ return '~' + p[len(casa):] if p.startswith(casa + os.sep) else p
+
+def impronta(p):
+ h = hashlib.sha256()
+ with open(p, 'rb') as f:
+ for pezzo in iter(lambda: f.read(1 << 20), b''):
+ h.update(pezzo)
+ return h.hexdigest()
+
+def metti(sorgente, rel, gruppo):
+ global peso
+ if not os.path.isfile(sorgente):
+ return False
+ if SEGRETO.search(sorgente):
+ non_copiati.append({'da': mostra(sorgente), 'perche': 'credenziali'})
+ return False
+ n = os.path.getsize(sorgente)
+ if n > TETTO_FILE or peso + n > TETTO:
+ non_copiati.append({'da': mostra(sorgente), 'perche': 'grande', 'byte': n})
+ return False
+ p = os.path.join(dest, rel)
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ shutil.copy2(sorgente, p)
+ prima, dopo = (impronta(sorgente), impronta(p))
+ if prima != dopo:
+ print(F('prima_copia_diversa', file=mostra(sorgente)), file=sys.stderr)
+ sys.exit(1)
+ peso += n
+ copiati.append({'da': mostra(sorgente), 'copia': rel, 'sha256': prima, 'byte': n, 'gruppo': gruppo})
+ return True
+
+def metti_cartella(d, rel, gruppo):
+ if not os.path.isdir(d):
+ return
+ for su, cartelle, files in os.walk(d):
+ cartelle[:] = sorted((c for c in cartelle if c not in ('.git', 'node_modules')))
+ for f in sorted(files):
+ metti(os.path.join(su, f), os.path.join(rel, os.path.relpath(os.path.join(su, f), d)), gruppo)
+
+def nel_progetto(rel, gruppo):
+ p = os.path.join(radice, rel)
+ if os.path.isdir(p):
+ metti_cartella(p, rel, gruppo)
+ else:
+ metti(p, rel, gruppo)
+
+def in_casa(p, gruppo):
+ p = os.path.abspath(p)
+ rel = os.path.join('casa', os.path.relpath(p, casa)) if p.startswith(casa + os.sep) else os.path.join('fuori', p.lstrip(os.sep))
+ if os.path.isdir(p):
+ metti_cartella(p, rel, gruppo)
+ else:
+ metti(p, rel, gruppo)
+codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
+qwen_casa = os.path.join(casa, '.qwen')
+for rel in (os.environ.get('DELMINIO_KIT_FILE') or '').split() + ['.claude/mneme.sh', '.claude/commands/risveglio.md']:
+ nel_progetto(rel, 'collegamento')
+for g in ('commit-msg', 'post-commit', 'post-rewrite'):
+ metti(os.path.join(os.environ.get('DELMINIO_GANCI') or os.path.join(gitdir, 'hooks'), g), os.path.join('git', 'hooks', g), 'collegamento')
+metti(os.path.join(gitdir, 'info', 'exclude'), os.path.join('git', 'info', 'exclude'), 'collegamento')
+in_casa(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'), 'collegamento')
+for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', 'AGENTS.md', 'AGENTS.override.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md', '.github/instructions', '.cursor/rules', '.windsurf/rules', 'memory-bank', '.serena/memories', '.claude/agents', '.claude/skills'):
+ nel_progetto(rel, 'istruzioni')
+for p in (os.path.join(config, 'CLAUDE.md'), os.path.join(codex, 'AGENTS.md'), os.path.join(codex, 'AGENTS.override.md'), os.path.join(casa, '.gemini', 'GEMINI.md'), os.path.join(qwen_casa, 'QWEN.md')):
+ in_casa(p, 'istruzioni')
+for rel in ('.claude/settings.json', '.mcp.json', '.codex/config.toml', '.qwen/commands'):
+ nel_progetto(rel, 'impostazioni')
+for p in (os.path.join(config, 'settings.json'), os.path.join(codex, 'config.toml'), os.path.join(codex, 'hooks.json'), os.path.join(qwen_casa, 'settings.json')):
+ in_casa(p, 'impostazioni')
+chiesti = [r.strip() for r in re.split('[\\n:]', os.environ.get('DELMINIO_COPIA_ANCHE') or '') if r.strip()]
+for r in chiesti:
+ p = os.path.realpath(os.path.join(radice, os.path.expanduser(r)))
+ if not (p.startswith(radice + os.sep) or p.startswith(casa + os.sep)):
+ non_copiati.append({'da': r, 'perche': 'fuori'})
+ elif not os.path.exists(p):
+ non_copiati.append({'da': r, 'perche': 'assente'})
+ elif p.startswith(radice + os.sep):
+ nel_progetto(os.path.relpath(p, radice), 'chiesto')
+ else:
+ in_casa(p, 'chiesto')
+for rel in ('CLAUDE.md', '.claude/CLAUDE.md', 'CLAUDE.local.md', '.claude/settings.local.json', '.codex/hooks.json', '.qwen/settings.json'):
+ if os.path.isfile(os.path.join(radice, rel)):
+ copie.append(rel)
+for rel in ('.claude/commands/apertura.md', '.claude/commands/chiusura.md', '.qwen/commands/apertura.md', '.qwen/commands/chiusura.md'):
+ p = os.path.join(radice, rel)
+ segno = 'Delminio' if rel.startswith('.qwen/') else 'delminio.sh'
+ if os.path.isfile(p) and segno not in open(p, encoding='utf-8', errors='replace').read():
+ copie.append(rel)
+note = sorted((n for n in os.listdir(vecchia) if n.endswith('.md'))) if os.path.isdir(vecchia) and os.path.realpath(vecchia) != memoria else []
+if note:
+ metti_cartella(vecchia, 'memoria', 'note')
+mcp = (leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json')).get('projects', {}).get(radice, {}).get('mcpServers') or {}).get('memoria')
+if mcp and (not str(mcp.get('url', '')).startswith(url)):
+ os.makedirs(dest, exist_ok=True)
+ with open(os.path.join(dest, 'mcp-memoria.json'), 'w', encoding='utf-8') as f:
+ json.dump(mcp, f, indent=2)
+ copie.append('mcp-memoria.json')
+else:
+ mcp = None
+
+def nostro(testo):
+ return 'delminio.sh' in str(testo)
+
+def hook_di(s):
+ out = {}
+ for ev, lista in (s.get('hooks') or {} if isinstance(s.get('hooks'), dict) else {}).items():
+ n = sum((1 for b in lista or [] if isinstance(b, dict) for h in b.get('hooks') or [] if isinstance(h, dict) and (not nostro(h.get('command', '')))))
+ if n:
+ out[ev] = n
+ return out
+
+def file_in(d, est='.md'):
+ if not os.path.isdir(d):
+ return []
+ out = []
+ for n in sorted(os.listdir(d)):
+ p = os.path.join(d, n)
+ if n.endswith(est) and os.path.isfile(p):
+ try:
+ if nostro(open(p, encoding='utf-8', errors='replace').read()):
+ continue
+ except OSError:
+ pass
+ out.append(n[:-len(est)])
+ return out
+
+def cartelle_in(d):
+ return sorted((n for n in os.listdir(d) if os.path.isdir(os.path.join(d, n)))) if os.path.isdir(d) else []
+conf = {}
+
+def segna(dove, cosa, valore):
+ if valore:
+ conf.setdefault(dove, {})[cosa] = valore
+for f, dove in ((os.path.join(config, 'settings.json'), '~/.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.json'), '.claude/settings.json'), (os.path.join(radice, '.claude', 'settings.local.json'), '.claude/settings.local.json')):
+ s = leggi(f)
+ if not isinstance(s, dict):
+ continue
+ segna(dove, 'hook', hook_di(s))
+ segna(dove, 'plugin', sorted((k for k, on in (s.get('enabledPlugins') or {}).items() if on)) if isinstance(s.get('enabledPlugins'), dict) else [])
+ segna(dove, 'stile', s.get('outputStyle') if isinstance(s.get('outputStyle'), str) else '')
+ segna(dove, 'permessi_negati', len((s.get('permissions') or {}).get('deny') or []) if isinstance(s.get('permissions'), dict) else 0)
+ segna(dove, 'hook_spenti', s.get('disableAllHooks') is True)
+for base, dove in ((config, '~/.claude'), (os.path.join(radice, '.claude'), '.claude')):
+ segna(dove + '/commands', 'comandi', file_in(os.path.join(base, 'commands')))
+ segna(dove + '/agents', 'agenti', file_in(os.path.join(base, 'agents')))
+ segna(dove + '/skills', 'skill', cartelle_in(os.path.join(base, 'skills')))
+ segna(dove + '/output-styles', 'stili', file_in(os.path.join(base, 'output-styles')))
+cj = leggi(os.path.join(os.environ.get('CLAUDE_CONFIG_DIR') or casa, '.claude.json'))
+
+def suoi_server(d):
+ return sorted((k for k, s in (d or {}).items() if not (k in ('memoria', 'delminio') and isinstance(s, dict) and str(s.get('url', '')).startswith(url))))
+if isinstance(cj, dict):
+ segna('~/.claude.json', 'mcp', suoi_server(cj.get('mcpServers')))
+ segna('~/.claude.json (' + F('prima_questo_progetto') + ')', 'mcp', suoi_server((cj.get('projects') or {}).get(radice, {}).get('mcpServers')))
+mj = leggi(os.path.join(radice, '.mcp.json'))
+if isinstance(mj, dict):
+ segna('.mcp.json', 'mcp', suoi_server(mj.get('mcpServers')))
+codex = os.environ.get('CODEX_HOME') or os.path.join(casa, '.codex')
+ct = os.path.join(codex, 'config.toml')
+if os.path.isfile(ct):
+ testo = open(ct, encoding='utf-8', errors='replace').read()
+ segna('~/.codex/config.toml', 'mcp', sorted(set((m for m in re.findall('^\\[mcp_servers\\.([A-Za-z0-9_-]+)\\]', testo, re.M) if m != 'delminio'))))
+ segna('~/.codex/config.toml', 'profili', sorted(set(re.findall('^\\[profiles\\.([A-Za-z0-9_-]+)\\]', testo, re.M))))
+segna('~/.codex/hooks.json', 'hook', hook_di(leggi(os.path.join(codex, 'hooks.json')) or {}))
+segna('~/.codex/prompts', 'comandi', file_in(os.path.join(codex, 'prompts')))
+altri = {}
+
+def righe_di(p):
+ try:
+ with open(p, encoding='utf-8', errors='replace') as f:
+ testo = f.read()
+ except OSError:
+ return (None, '')
+ return (None, '') if nostro(testo) else (len(testo.splitlines()), testo)
+
+def voci_qwen(testo):
+ m = re.search('^##\\s*Qwen Added Memories\\s*$(.*?)(?=^##\\s|\\Z)', testo, re.M | re.S)
+ return sum((1 for r in m.group(1).splitlines() if r.lstrip().startswith('- '))) if m else 0
+
+def file_altro(dove, p, cosa):
+ n, testo = righe_di(p)
+ if n:
+ v = {'cosa': cosa, 'righe': n}
+ if os.path.basename(p) == 'QWEN.md' and (q := voci_qwen(testo)):
+ v['memorie'] = q
+ altri[dove] = v
+
+def cartella_altro(dove, d, cosa):
+ if os.path.isdir(d):
+ n = sum((1 for _, _, fs in os.walk(d) for f in fs if f.endswith(('.md', '.mdc', '.txt'))))
+ if n:
+ altri[dove + '/'] = {'cosa': cosa, 'file': n}
+for rel in ('AGENTS.md', 'GEMINI.md', 'QWEN.md', '.cursorrules', '.windsurfrules', '.clinerules', '.github/copilot-instructions.md'):
+ if os.path.isfile(os.path.join(radice, rel)):
+ file_altro(rel, os.path.join(radice, rel), 'istruzioni')
+for rel in ('.cursor/rules', '.windsurf/rules', '.clinerules', '.github/instructions'):
+ cartella_altro(rel, os.path.join(radice, rel), 'istruzioni')
+for rel in ('memory-bank', '.serena/memories'):
+ cartella_altro(rel, os.path.join(radice, rel), 'memoria')
+for p, dove in ((os.path.join(config, 'CLAUDE.md'), '~/.claude/CLAUDE.md'), (os.path.join(codex, 'AGENTS.md'), '~/.codex/AGENTS.md'), (os.path.join(casa, '.gemini', 'GEMINI.md'), '~/.gemini/GEMINI.md'), (os.path.join(casa, '.qwen', 'QWEN.md'), '~/.qwen/QWEN.md')):
+ file_altro(dove, p, 'istruzioni personali')
+for v in altri.values():
+ if v.get('memorie'):
+ v['cosa'] += ' + memoria'
+da_ripassare = bool(copie or note or conf or altri or chiesti)
+os.makedirs(dest, exist_ok=True)
+with open(os.path.join(dest, 'fatti.json'), 'w', encoding='utf-8') as f:
+ json.dump({'radice': radice, 'copie': copie, 'memoria': {'cartella': vecchia, 'scelta_in': da, 'note': note}, 'configurazioni': conf, 'altri_strumenti': altri, 'file': copiati, 'non_copiati': non_copiati, 'chiesti': chiesti, 'aggancio_di_prima': os.path.isfile(os.path.join(radice, '.claude', 'delminio.sh'))}, f, indent=2, ensure_ascii=False)
+if not da_ripassare:
+ with open(os.path.join(dest, 'RIPASSATO'), 'w', encoding='utf-8') as f:
+ f.write(time.strftime('%Y-%m-%d %H:%M') + ' ' + F('prima_niente_da_ripassare') + '\n')
+with open(segno_backup, 'w', encoding='utf-8') as f:
+ f.write(cartella + '\n')
+DETTO = {'CLAUDE.md': F('prima_claude_md'), '.claude/CLAUDE.md': F('prima_claude_md'), 'CLAUDE.local.md': F('prima_claude_local'), '.claude/settings.local.json': F('prima_settings'), '.codex/hooks.json': F('prima_hook_codex'), '.qwen/settings.json': F('prima_qwen'), '.claude/commands/apertura.md': F('prima_apertura'), '.claude/commands/chiusura.md': F('prima_chiusura'), '.qwen/commands/apertura.md': F('prima_apertura'), '.qwen/commands/chiusura.md': F('prima_chiusura'), 'mcp-delminio.json': F('prima_mcp', nome='delminio'), 'mcp-memoria.json': F('prima_mcp', nome='memoria')}
+righe = [f'- `{c}` — {DETTO[c]}' for c in copie]
+if note:
+ righe.append(F('prima_note', n=len(note), cartella=vecchia))
+if conf:
+ righe.append(F('prima_configurazioni'))
+if altri:
+ righe.append(F('prima_altri', elenco=', '.join((f'`{k}`' for k in altri))))
+if chiesti:
+ righe.append(F('prima_chiesti', elenco=', '.join((f'`{k}`' for k in chiesti))))
+righe.append(F('prima_tutti', n=len(copiati)))
+PERCHE = {'credenziali': F('prima_perche_credenziali'), 'grande': F('prima_perche_grande'), 'fuori': F('prima_perche_fuori'), 'assente': F('prima_perche_assente')}
+for v in non_copiati:
+ righe.append(F('prima_non_copiato', file=v['da'], perche=PERCHE[v['perche']]))
+with open(os.path.join(dest, 'LEGGIMI.md'), 'w', encoding='utf-8') as f:
+ f.write('# ' + F('prima_leggimi_titolo') + '\n\n' + F('prima_leggimi_testa') + '\n\n' + '\n'.join(righe) + '\n\n' + F('prima_leggimi_note') + '\n\n' + F('prima_leggimi_tornare') + '\n')
+print(mostra(dest))
diff --git a/kit/it/delminio-client b/kit/it/delminio-client
new file mode 100644
index 0000000..4691323
--- /dev/null
+++ b/kit/it/delminio-client
@@ -0,0 +1,3164 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+_conto_t0=${EPOCHREALTIME:-}
+: '⟦frasi: client⟧'
+M_delminio_risponde_prompt='⚠️ Delminio non risponde a {url}: il prompt d'"'"'apertura non è arrivato.'
+M_sandbox_senza_rete='la sandbox di Codex non lascia uscire in rete i comandi, e da qui Delminio ({url}) non si raggiunge: chiedi all'"'"'utente di approvare questo comando, o quelli che cominciano con «delminio»'
+M_delminio_dato_system='⚠️ Delminio ({url}) non ha dato il system prompt del ruolo «{porta}» (HTTP {codice}).'
+M_agente_parte_meta=' L'"'"'agente non parte a metà. Si può aprire come prima, col prompt di serie: claude, poi /apertura.'
+M_ruolo_sola_sua='⚠️ Un ruolo con la sola sua metà su Codex non c'"'"'è ancora: la memoria del ruolo non ha il suo canale.'
+M_agente_parte_meta_2=' L'"'"'agente non parte a metà.'
+M_opencode_gratuito_scelgo=' Scelgo un modello gratuito di OpenCode che risponde adesso (una volta al giorno, qualche secondo)…'
+M_opencode_gratuito_nessuno='⚠️ Nessun modello gratuito di OpenCode risponde adesso: OpenCode parte col suo modello di serie. Per non dipendere dai gratuiti, nella vista Agenti dai all'"'"'agente {nome} il fornitore di cui hai la chiave.'
+M_delminio_argomenti_codex='⚠️ Delminio: gli argomenti di Codex non si ricompongono (python3?). L'"'"'agente non parte a metà.'
+M_ruolo_sola_sua_2='⚠️ Manca il canale del ruolo su questa macchina: rilancia `delminio eseguibili`, che lo prepara.'
+M_delminio_mcp_qwen='⚠️ Delminio: il MCP per Qwen Code non si compone (python3?). L'"'"'agente non parte a metà.'
+M_ponte_muto='Delminio non risponde in questo momento (si sta riavviando?): riprova fra qualche secondo. Se resta muto, dillo al tuo utente.'
+M_guardia_cartella_gira='⛔ Il controllo non sa in che cartella gira questo comando: {incerto}. Ripetilo con `cd <percorso assoluto> && …` in testa al comando, senza workdir'
+M_piu_agenti_insieme='❌ «Più agenti insieme» è spenta dall'"'"'amministratore in questo progetto: niente worktree della sessione.'
+M_chi_sei_bash='❌ non so chi sei: delminio {gesto} S<N>'
+M_gia_entraci_smontalo='❌ {wt} c'"'"'è già: entraci, o smontalo se è finito.'
+M_principale_aggiorna_remoto='⚠️ il principale non si aggiorna dal remoto: parto da quello che c'"'"'è'
+M_ramo='✅ {wt} sul ramo {ramo}.'
+M_codex_resta_dov=' Codex resta dov'"'"'è: metti `cd {wt} && …` in testa a ogni comando, e percorsi assoluti nelle patch.'
+M_entraci_col_tool=' Entraci col tool EnterWorktree (un cd non basta alla CLI);'
+M_lavoro_tocca_altro=' se il lavoro tocca un altro repo, lì git non passa: ExitWorktree con keep, poi cd assoluto in ogni comando.'
+M_tua_cli_modo=' Se la tua CLI non ha un modo di entrarci, metti `cd {wt} && …` in testa a ogni comando e percorsi assoluti nei file.'
+M_merge_lancia_tuo='❌ il merge si lancia dal tuo worktree ({wt}), non da {dove}'
+M_hai_lavoro_committato='❌ hai lavoro non committato: committa prima.'
+M_altro_merge_corso='❌ un altro merge è in corso da 10 minuti: chiedi sul canale.'
+M_principale_lavoro_staging='❌ nel principale c'"'"'è lavoro IN STAGING di qualcun altro: chiedigli di committare.'
+M_principale_aggiorna_remoto_2='❌ il principale non si aggiorna dal remoto (git pull --ff-only): guardalo prima.'
+M_merge_toccherebbe_file='❌ il merge toccherebbe file che nel principale sono modificati e non committati:'
+M_principale_senza_remoto='✅ {ramo} è nel principale (senza remoto: resta su questa macchina).'
+M_mergiato_locale_push='❌ mergiato in locale ma il push è fallito: guardalo prima di chiudere.'
+M_principale_remoto='✅ {ramo} è nel principale e sul remoto.'
+M_nessun_worktree='nessun worktree {wt}'
+M_file_committati_smonta='❌ {wt} ha file non committati: NON si smonta. Guardali: git -C {wt} status'
+M_principale_prima_merge='❌ {ramo} non è nel principale: prima il merge (delminio merge).'
+M_smontato_tolto='✅ {wt} smontato, {ramo} rimosso.'
+M_nessuna_track_misurata='Nessuna track misurata: .delminio/audit/ è vuota. La metà che si conta la costruisci tu'
+M_revisione_memoria_meta='(«La revisione della memoria» § La metà che si conta) — oggi si legge tutto a mano.'
+M_track_pulite_finding='— {pulite} track pulite, {con} con finding. Il resto della revisione si legge (le track senza script).'
+M_chi_sei_bash_2='❌ non so chi sei: delminio domini "cosa tocchi" S<N>'
+M_chi_sei_sandbox='❌ da dentro la sandbox di Codex non vedo la tua sessione: chiedi all'"'"'utente di approvare questo comando, o quelli che cominciano con «delminio». Non aggiungere un numero di sessione a caso: il comando, fuori dalla sandbox, sa chi sei.'
+M_quali_bash_claude='❌ quali? delminio domini "cosa tocchi"'
+M_lavora_altre_sessioni='✅ {nome} lavora su: {valore} — le altre sessioni lo vedono quando si avviano.'
+M_chi_sei_bash_3='❌ non so chi sei: delminio titolo "come ti chiami" S<N>'
+M_quale_bash_claude='❌ quale? delminio titolo "come ti chiami"'
+M_chiama='✅ {nome} si chiama: {valore}'
+M_prompt_chiusura_arrivato='⚠️ {perche}: il prompt di chiusura non è arrivato. Chiudi lo stesso:'
+M_lavoro_committato_pushato='il lavoro committato e pushato; dove sei, e una domanda sola («hai altro?»); poi un commit'
+M_vuoto_git_commit='vuoto (git commit --allow-empty) «Chiusura S<N> — …» con le sezioni Sintesi e Dove siamo,'
+M_push_commit_passera='e push. Il commit passerà senza giudizio: dimmelo.'
+M_chiusura_stata_consegnata='❌ {perche}: la chiusura non è stata consegnata. Riprova fra poco; se Delminio resta muto, dillo all'"'"'utente.'
+M_ripassato_copia_prima='✅ rivisto ({n}): la copia di sicurezza resta in {cartella}, e «delminio stacca» la sa ancora rimettere.'
+M_stacca_lancia_terminale='❌ «delminio stacca» si lancia da un terminale tuo, non da un agente: apri un terminale fuori dall'"'"'agente, in questa cartella'
+M_stacca_lancia_clone='❌ stacca si lancia dal clone principale, non da un worktree'
+M_rimetto_cio_era=' Rimetto ciò che c'"'"'era prima, da {prima}'
+M_copia_prima_tolgo=' ⚠️ non c'"'"'è una copia di prima: rimuovo solo i pezzi di Delminio.'
+M_niente_fatto='Niente di fatto.'
+M_tue_memorie_personali=' le tue {n} memorie personali sono in {personali}'
+M_tue_memorie_personali_2=' ⚠️ {perche}: le tue memorie personali restano in Delminio finché il tuo account esiste: prendile dall'"'"'interfaccia (dopo lo stacco questo client non c'"'"'è più)'
+M_server_mcp_delminio=' il server MCP «{nome}» di prima è tornato'
+M_server_mcp_prima=' ⚠️ il server MCP di prima non è tornato: la sua definizione è in {prima}/mcp-{nome}.json'
+M_tuo_chiama_delminio=' ⚠️ {f} è tuo e chiama Delminio: rimuovi tu la riga di .claude/delminio.sh'
+M_revocare_questo_token=' ⚠️ non so revocare questo token: fallo dall'"'"'interfaccia di Delminio (Accesso)'
+M_token_resta_valido=' il token resta valido: lo usano altri {altri} progetti collegati su questa macchina'
+M_token_questo_aggancio=' il token di questo collegamento è revocato'
+M_token_revocato_fallo=' ⚠️ il token non si è revocato ({perche}): fallo dall'"'"'interfaccia di Delminio (Accesso)'
+M_tolto_clone_memorie=' rimosso il clone delle memorie di questa macchina (le memorie stanno nel loro repo)'
+M_restano_worktree_sessioni=' ⚠️ restano {wt} worktree delle sessioni (git worktree list): se il lavoro è unito, git worktree remove <cartella>'
+M_staccato_cli_torna='✅ staccato. La CLI torna a leggere le sue note; le memorie del progetto restano nel repo delle memorie.'
+M_tue_personali=' Le tue personali: {personali}'
+M_copia_prima_resta=' La copia di prima resta in {prima}: ricollegare la rifà da zero.'
+M_accetta_lancia_terminale='❌ «delminio accetta» si lancia da un terminale tuo, non da un agente: apri un terminale fuori dall'"'"'agente, in questa cartella'
+M_lock_duri_sono='⚠️ {perche}: le decisioni protette che bloccano non sono state controllate su questo commit.'
+M_chiusura_passa_senza='⚠️ {perche}: la chiusura passa senza giudizio, e Delminio non saprà che hai chiuso.'
+M_delminio_chiusa_chi=' Delminio: {n} chiusa. Chi si avvia dopo leggerà questa consegna.'
+M_opere_avevi_mano=' Le attività che avevi in mano tornano libere: {m}.'
+M_risultera_morta_senza='⚠️ {perche}: {n} risulterà morta senza chiusura.'
+M_lancialo_dentro_repo='❌ lancialo dentro un repo collegato'
+M_spazio_repo_aggiunge='Lo spazio non ha repo: li aggiunge l'"'"'amministratore, dalla voce Git.'
+M_repo_dello_spazio='I repo dello spazio, su questa macchina:'
+M_clonato_qui=' · {nome}: non clonato qui'
+M_gia_collegato=' ✅ {nome}: già collegato ({dove})'
+M_uso_bash_claude='uso: delminio perche <file>:<riga>'
+M_nessun_albero='nessun worktree noto'
+M_albero_sporco='worktree {albero} con {n} file non committati'
+M_albero_pulito='worktree {albero} pulito'
+M_merge_non_pulito='❌ il merge non è pulito: rebasa il tuo ramo sul principale (git rebase {ramo}) e riprova.'
+M_stacco='Stacco {repo} da Delminio ({url}), su questa macchina.'
+M_procedo=' Procedo? [s/N] '
+M_collegato_qui=' ✅ {nome}: collegato ({dove})'
+M_collegamento_fallito=' ❌ {nome}: il collegamento in {dove} non è passato — {errore}'
+M_segno_non_versione='il segno esistente non è una versione, non lo sostituisco'
+M_informativa_non_segnata='Delminio: informativa Codex non segnata come vista ({errore}).'
+M_non_risponde_5s='{script} non ha risposto in 5 secondi'
+M_client_fermo='⚠️ Il client di Delminio di questo progetto è fermo a {kit}, Delminio è a {serve}: il collegamento automatico non è passato ({errore}). Dillo al tuo utente: si rilancia il collegamento dal pannello di Delminio.'
+M_parte_manca='⚠️ Manca {file}, una parte del client di Delminio: il collegamento non è passato intero. Dillo al tuo utente: si rilancia il collegamento dal pannello di Delminio.'
+M_riprova_al_primo=' Si riprova da sé al primo messaggio del tuo utente.'
+M_nasce_al_primo='Delminio: questa chat è partita in sottofondo o da un fork, e prende il suo nome, con la memoria, la posta e le altre sessioni, al primo messaggio del tuo utente.'
+M_nasce_senza_memoria='⚠️ {perche}. Questa sessione si avvia SENZA memoria e senza le altre sessioni: dillo subito al tuo utente, prima di ogni altra cosa.{riprova}'
+M_posta_non_arriva='⚠️ {perche}: i messaggi delle altre sessioni non ti arrivano. Si riprova a ogni messaggio; questo avviso esce una volta sola, dillo al tuo utente.'
+M_invia_uso='uso: delminio invia <file> ["nota"]'
+M_invia_non_trovato='❌ {file} non esiste o non si legge'
+M_invia_senza_sessione='❌ Lancialo da un agente: il file parte dalla sua sessione.'
+M_invia_fallito='❌ Il file non è partito: {perche}'
+M_invia_fatto='✅ Inviato: «{nome}». Il tuo utente lo trova nell'"'"'app di Delminio, alla voce File, e riceve la notifica.'
+M_posta_arrivata='📬 Delminio: è arrivato un messaggio da un'"'"'altra sessione — lo trovi qui sotto.'
+M_chiave_nel_messaggio='⛔ Questo messaggio contiene una chiave d’accesso e non è partito: qui la leggerebbe il modello, e resterebbe nella conversazione salvata.
+ Il comando con la chiave si incolla nel TERMINALE, dentro la cartella del progetto.
+ Se l’hai già mandata altrove, revocala: Delminio → Accesso.
+'
+M_gesto_umano='L’utente ha scritto «{parola}»: è la SUA azione, come /{parola} su Claude.'
+M_lock_del_comando='🔒 {codice} — {cosa} (decisione dell'"'"'amministratore su questo comando)
+ perché: {perche}
+ Se il tuo comando la viola, si chiede a lui prima di lanciarlo.'
+M_guardie_giu='⚠️ Delminio non risponde: i controlli sulle azioni (memorie come file, add -A, backtick, pkill -f) non hanno guardato le tue azioni. Stai attento tu, finché non torna.'
+M_dove_albero_sporco='Worktree: {n} file non committati.'
+M_dove_albero_pulito='Worktree pulito.'
+M_commit_non_pushati='{n} commit non pushati su {ramo}.'
+M_tutto_pushato='Tutto pushato.'
+M_ramo_senza_remoto='Il ramo {ramo} non ha un remoto: non è pushato.'
+M_worktree_in_piu='{n} worktree oltre al principale: {alberi}.'
+M_script_non_risponde='⚠️ {script} non ha risposto: {errore}'
+M_chiusura_rifiutata='❌ Delminio rifiuta questa consegna:'
+M_aggiunge_trailer=' Delminio aggiunge «{trailer}».'
+M_aggiunge_trailer_perche=' Delminio aggiunge «{trailer}»: {perche}.'
+M_chiusa_nel_repo='✅ {nome} chiusa: la consegna è nel repo delle memorie ({hash}). La sessione successiva la leggerà.'
+M_perche_tornata='le sessioni che hai incrociato'
+M_perche_memoria='le memorie, committate da Delminio (se il push non è passato, lo dice qui sotto)'
+M_questo_repo='questo repo'
+M_tocco_ospite='🤝 {repo} è dello spazio «{di}», che lo condivide con questo: ci lavori da ospite. Ciò che impari va nelle memorie di questo spazio; le decisioni protette di «{di}» sui suoi file valgono anche per te, e quelle che toccano il file te le dico qui sotto.'
+M_tocco_altro_spazio_tuo='🧭 {repo} è collegato allo spazio «{suo}», e questa sessione scrive le memorie nello spazio «{mio}»: ciò che impari qui finisce in «{mio}». Se il lavoro è di «{suo}», dillo al tuo utente: si apre l'"'"'agente dentro {repo}.'
+M_tocco_non_condiviso='🧭 {repo} è dello spazio «{di}», e non è condiviso con questo: ciò che impari qui finisce nelle memorie di questo spazio, e le decisioni protette di «{di}» da qui non si vedono. Se il lavoro è di «{di}», dillo al tuo utente.'
+M_tocco_lock='🔒 Stai per toccare {file}: lì si applica una decisione protetta dell'"'"'amministratore. Leggila prima di scrivere — se il tuo cambiamento la viola, si chiede a lui.'
+M_tocco_duro=' (BLOCCANTE: al commit gira il suo controllo, e se fallisce il commit di un membro si ferma)'
+M_tocco_duro_ospite=' (BLOCCANTE nello spazio proprietario: qui il suo controllo non gira, rispettala tu)'
+M_tocco_dello_spazio=' (dello spazio «{spazio}»)'
+M_tocco_voce='
+{codice}{di} — {cosa}{duro}
+ perché: {perche}
+ verificata da: {guardia}'
+M_tocco_nessuno='NESSUNO — se lo rompi, non grida niente'
+M_accetta_domanda='
+{codice} — {cosa}
+ scritto da: {chi}
+ il comando che girerà qui, a ogni commit:
+
+ {comando}
+
+Lo accetti? [s/N] '
+M_accetta_si='s si sì y'
+M_accettate='✅ {nuove} accettate ora · {tutte} in tutto · la lista: {file}'
+M_perche_non_committata='{dove} non è ancora committata: il perché è nel lavoro di adesso.'
+M_perche_commit='{dove} → il commit {commit} del {data}, di {autore}: «{soggetto}»'
+M_perche_senza_sessione=' Nessuna sessione di Delminio su questo commit: è di prima di Delminio, o fatto a mano.
+ Il resto lo dice il commit: git show {commit}'
+M_perche_sessione_muto=' → la sessione {sessione}; Delminio non risponde ({errore}), e il resto lo sa lui.'
+M_perche_sessione=' → la sessione {sessione}{agente}{chi}{nata}'
+M_perche_con=', con {chi}'
+M_perche_nata=', avviata il {data}'
+M_perche_senza_chiusura=' Non ha lasciato una chiusura: il perché sta nei suoi commit (git log --grep '"'"'Delminio-Sessione: {sessione}'"'"').'
+M_perche_chiusa=' → ha chiuso il {data} col commit {commit}{repo}: {comando}'
+M_perche_in_repo=' in {repo}'
+M_perche_memorie=' → le memorie che ha toccato:'
+M_perche_nessuna_memoria=' → nessuna memoria toccata in quella chiusura.'
+M_perche_memorie_nel_commit=' → le memorie toccate stanno nel commit {commit} del repo delle memorie.'
+M_perche_le_memorie=' → le memorie: {memorie}'
+M_fermato_codex='Fermato da Delminio: il perché l'"'"'ha ricevuto l'"'"'agente.'
+M_consegna_di_uso='❌ quale? delminio consegna-di S<N>'
+M_consegna_di_curata='⟳ La consegna di S{numero} è CORRETTA: questa è la versione da leggere, non aprire l'"'"'originale con git.'
+M_consegna_di_vuota='La consegna di S{numero} non ha più il testo nel servizio: chi poteva l'"'"'ha eliminato.'
+M_codex_senza_plugin='Il plugin di Delminio non si è installato nella cartella di Codex: la memoria arriva col lancio, ma gli hook (apertura, messaggi, controlli) no. Ricollega il progetto con DELMINIO_SENZA_PLUGIN=1 per rimetterli nel progetto.'
+M_app_codex_fatto='Fatto: l'"'"'app di Codex ora ha Delminio. In ~/.codex/config.toml ho aggiunto solo il plugin di Delminio e il permesso dei suoi due strumenti. Riapri l'"'"'app, apri un repo collegato e approva gli hook di Delminio in «Review hooks» (o in Settings → Hooks), una volta sola; poi scrivi apertura. Per rimuoverlo: delminio app-codex via'
+M_app_codex_assente='Su questo computer non trovo l'"'"'app di Codex (ChatGPT per Mac o per Linux): non c'"'"'è niente da fare. Per il Mac l'"'"'app esiste solo per Apple Silicon.'
+M_app_codex_non_riuscito='Non sono riuscito a mettere Delminio nell'"'"'app di Codex. Chiudi l'"'"'app e rilancia delminio app-codex; se si ferma ancora, mostra questo messaggio all'"'"'amministratore.'
+M_app_codex_tolto='Rimosso: l'"'"'app di Codex non ha più Delminio, e il resto di ~/.codex/config.toml è com'"'"'era.'
+M_app_codex_no='D'"'"'accordo: su questo computer non lo propongo più. Se cambi idea: delminio app-codex'
+M_app_codex_uso='uso: delminio app-codex [via|no|stato]'
+M_qwen_senza_plugin='L'"'"'estensione di Delminio non si è collegata nella cartella di Qwen Code: la memoria arriva col lancio, ma gli hook (apertura, messaggi, controlli) no. Ricollega il progetto con DELMINIO_SENZA_PLUGIN=1 per rimetterli nel progetto.'
+M_script_da_accettare='⏸ {n} script del progetto in .delminio/ non girano su questo computer finché il tuo utente non li accetta: vengono da commit di {chi}. Digli di lanciare, da un suo terminale: delminio accetta'
+M_accetta_script_elenco='
+Gli script del progetto che girano su questo computer all'"'"'apertura o alla chiusura, arrivati da commit di altri e non ancora accettati:
+'
+M_accetta_script_riga=' {percorso} — {chi}, {quando}, {righe} righe'
+M_accetta_script_domanda='
+Gireranno con i tuoi permessi. Li accetti? [t = tutti · u = uno per uno, leggendoli · N = nessuno] '
+M_accetta_script_uno='
+{percorso} — {chi}, {quando}
+
+{testo}
+
+Lo accetti? [s/N] '
+M_accetta_script_tutti_si='t tutti'
+M_accetta_script_uno_si='u uno'
+M_script_accettati='✅ script: {nuovi} accettati ora · {fermi} restano fermi (se uno cambia, lo richiedo)'
+M_pulito_ultimo=' Era l'"'"'ultimo progetto collegato su questo computer: rimossi anche il plugin, le versioni di Codex e Qwen Code scaricate da Delminio e la sua cache.
+ Restano, perché sono tue: le versioni di Claude Code in ~/.local/share/claude/versions (è la cartella del tuo Claude) e le cartelle degli agenti in ~/.local/share/delminio/codex e /qwen, che tengono le loro conversazioni.'
+M_perche_muto='Delminio non risponde a {url}'
+M_perche_token='Delminio a {url} rifiuta il token di questo collegamento (HTTP {codice})'
+M_perche_rifiuta='Delminio a {url} ha detto no (HTTP {codice}: {errore})'
+M_perche_errore='Delminio a {url} ha risposto con un errore (HTTP {codice}{errore})'
+M_prompt_rifiutato='⚠️ Delminio a {url} non ha dato il prompt d'"'"'apertura (HTTP {codice}{errore}): dillo al tuo utente.'
+M_guardie_errore='⚠️ Delminio ha risposto con un errore (HTTP {codice}): i controlli sulle azioni (memorie come file, add -A, backtick, pkill -f) non hanno guardato questa azione. Stai attento tu, e dillo al tuo utente.'
+M_piu_agenti_non_concessa='❌ «Più agenti insieme» non è nella licenza di questo spazio: niente worktree della sessione.'
+M_guardia_non_accettata='⚠️ il controllo di {codice} è nuovo o cambiato, e su questa macchina nessuno l'"'"'ha ancora accettato — non l'"'"'ho eseguito:
+ {comando}
+ Leggilo e, se ti fidi, da un terminale tuo: delminio accetta
+ Il commit passa, ma su questa macchina la decisione protetta non è applicata finché qualcuno non accetta il controllo.'
+M_lock_grida_muto='⚠️ {codice} ha gridato ma Delminio non risponde: il commit passa, e l'"'"'amministratore non lo saprà.'
+M_lock_grida_errore='⚠️ {codice} ha gridato ma Delminio ha risposto con un errore (HTTP {codice_http}): il commit passa, e l'"'"'amministratore non lo saprà. Dillo al tuo utente.'
+M_guardia_dice=' il controllo dice:'
+M_gesto_controllo_non_accettato='⚠️ {codice} — {cosa}: il suo controllo prima di questo comando è nuovo o cambiato, e su questa macchina nessuno l'"'"'ha ancora accettato — non l'"'"'ho eseguito:
+ {comando}
+ Il comando passa, ma su questa macchina la decisione protetta non è applicata finché il controllo non è accettato. Di'"'"' al tuo utente di leggerlo e, se si fida, di lanciare da un suo terminale: delminio accetta'
+M_accetta_domanda_gesto='
+{codice} — {cosa}
+ scritto da: {chi}
+ il controllo che girerà qui, prima di ogni comando che combacia con {gesti}:
+
+ {comando}
+
+Lo accetti? [s/N] '
+M_sessione_non_viva='❌ {nome} non è una sessione aperta: non ho scritto niente. Il tuo nome lo dice l'"'"'apertura.'
+M_skill_nomi_pulita='✅ le skill della squadra: i percorsi che nominano ci sono tutti nel repo (pezzi guardati: {n})'
+M_skill_nomi_finding='❌ {pezzo} ({file}): «{nome}» non c'"'"'è nel repo'
+M_skill_nomi_voluti=' Una skill che nomina un file che non c'"'"'è più va corretta (vista Skill). Se il nome è voluto — un file che arriverà dopo, o di un altro repo —, scrivilo in .delminio/skill-nomi-voluti.txt, uno per riga.'
+M_skill_nomi_nessuna='— la squadra non ha skill, comandi o agenti da confrontare col repo.'
+M_skill_nomi_cieca='⚠️ le skill della squadra non si sono confrontate col repo: Delminio non risponde ({perche}). Non vuol dire che siano a posto.'
+M_squadra_mcp_da_accettare='⏸ {n} server MCP della squadra non partono su questo computer finché il tuo utente non li accetta: vengono dalla squadra dello spazio e girerebbero coi suoi permessi. Digli di lanciare, da un suo terminale: delminio accetta'
+M_squadra_plugin_da_accettare='⏸ {n} plugin della squadra non si installano su questo computer finché il tuo utente non li accetta: vengono dalla squadra dello spazio e girerebbero coi suoi permessi. Digli di lanciare, da un suo terminale: delminio accetta'
+M_riaggancio_non_firmato='L'"'"'aggiornamento del collegamento da {url} non porta la firma dei rilasci di Delminio: non l'"'"'ho installato, e resta il collegamento di prima. Se hai riportato Delminio a una versione precedente, rilancia il collegamento a mano dal terminale.'
+M_eseguibili_da_accettare='⏸ {n} comandi degli agenti non si aggiornano su questo computer finché il tuo utente non accetta i loro argomenti o le loro variabili d'"'"'ambiente: vengono dal registro dello spazio e girerebbero coi suoi permessi. Digli di lanciare, da un suo terminale: delminio accetta'
+M_aiuto='I comandi di Delminio: si lanciano nella cartella di un progetto collegato.
+
+ delminio eseguibili scrive su questo computer gli agenti dello spazio (vista Agenti)
+ delminio eseguibili stato quali agenti ci sono su questo computer, e a che versione
+ delminio accetta accetta le opzioni degli agenti e i server della squadra
+ delminio agganciali collega in un colpo i progetti dello spazio che sono su questo computer
+ delminio backlog aiuto il Backlog dal terminale: cercare, aprire, chiudere le attività
+ delminio cassaforte elenco i segreti che gli agenti possono chiedere, se la cassaforte è accesa
+ delminio perche <file>:<riga> quale sessione ha scritto quella riga, e la sua consegna
+ delminio consegna-di S<numero> la consegna intera di una sessione
+ delminio errori [giorni] le chiamate di tool fallite su questo computer, in breve
+ delminio revisione i controlli automatici del progetto, quelli della revisione
+ delminio invia <file> ["nota"] manda un file a chi lavora con te: lo trova nella vista File
+ delminio app-codex [via|no] Delminio nell'"'"'app desktop di Codex
+ delminio firme controlla [da..a] le modifiche di un ramo: firmate, da firmare, con le parole cambiate
+ delminio firme descrizione [da..a] il testo di una pull request: le parole della persona e i fatti
+ delminio firme resoconto [da..a] il resoconto commit per commit, per chi controlla
+ delminio stacca stacca questo progetto da Delminio e rimette tutto com'"'"'era
+
+Gli altri comandi li lancia l'"'"'agente da solo. Ognuno è spiegato nella guida, alla pagina «I comandi».'
+M_comando_sconosciuto='comando «{nome}» sconosciuto.'
+M_uso_clona='uso: delminio clona <nome del repo> [--no]'
+M_clona_non_dello_spazio='«{nome}» non è un repo di questo spazio: i repo dello spazio li dice l'"'"'apertura, o la voce Git dell'"'"'app.'
+M_clona_no='D'"'"'accordo: su questo computer non propongo più «{nome}». Se serve, delminio clona {nome}'
+M_clona_occupata='{dove} c'"'"'è già e non è un clone di questo repo: non lo tocco. Dillo al tuo utente, che sceglie dove metterlo.'
+M_clona_in_corso='Clono «{nome}» da {url} in {dove}…'
+M_clona_fallito='❌ «{nome}» non si clona da {url}: {errore}. Se git dice che l'"'"'accesso è negato o il repo non esiste, questa persona non ha il permesso su quel repo: lo dà l'"'"'amministratore, sul server git.'
+M_gesto_controllo_non_parte_fermo='⛔ {codice} — {cosa}: il suo controllo non parte ({comando}), e questa decisione blocca: il comando è fermo. Il controllo va sistemato: verifica che il comando esista e sia eseguibile. Fino ad allora il comando passa solo con un'"'"'eccezione dell'"'"'amministratore.'
+M_guardia_non_parte_fermo='⛔ il controllo di {codice} non parte ({comando}), e questa decisione blocca: il commit è fermo. Il controllo va sistemato: verifica che il comando esista e sia eseguibile. Fino ad allora il commit passa solo con un'"'"'eccezione dell'"'"'amministratore.'
+M_gesto_controllo_lento_fermo='⛔ {codice} — {cosa}: il suo controllo non ha risposto in {secondi} secondi ({comando}), e questa decisione si ferma quando il controllo non risponde: il comando è fermo. Riprova. Se succede ancora, il controllo va reso più veloce, o l'"'"'amministratore può dargli più tempo.'
+M_guardia_lento_fermo='⛔ il controllo di {codice} non ha risposto in {secondi} secondi ({comando}), e questa decisione blocca: il commit è fermo. Riprova. Se succede ancora, il controllo va reso più veloce.'
+M_gesto_controllo_lento_passa='⚠️ il controllo di {codice} non ha risposto in {secondi} secondi ({comando}). Il comando passa senza controllo, come stabilito per questa decisione. Se succede spesso, l'"'"'amministratore può dargli più tempo o scegliere di bloccare.'
+M_gesto_controllo_non_parte_passa='⚠️ il controllo di {codice} non parte ({comando}). Il comando passa: questa decisione avvisa e non blocca. Il controllo va sistemato: verifica che il comando esista e sia eseguibile.'
+M_controllo_non_parte_breve='il controllo non parte ({comando}): verifica che il comando esista e sia eseguibile.'
+M_controllo_lento_breve='il controllo non ha risposto in {secondi} secondi ({comando}).'
+: '⟦fine frasi⟧'
+export ${!M_@}
+IFS= read -r -d '' DELMINIO_FIDATI_PY <<'FIDATI' || true
+import hashlib as _hl, os as _os, subprocess as _sp
+def _git_in(albero, *a):
+ r = _sp.run(["git", "-C", albero, *a], capture_output=True, text=True)
+ return r.returncode, r.stdout.strip()
+def accettati_file(albero):
+ rc, c = _git_in(albero, "rev-parse", "--path-format=absolute", "--git-common-dir")
+ return _os.path.join(c, "delminio-script-accettati") if rc == 0 and c else ""
+def accettati(albero):
+ try:
+ return set(open(accettati_file(albero), encoding="utf-8").read().split())
+ except OSError:
+ return set()
+def impronta_script(albero, f):
+ with open(f, "rb") as h:
+ return _hl.sha256(_os.path.relpath(f, albero).encode() + b"\0" + h.read()).hexdigest()
+def di_chi(albero, f):
+ rel = _os.path.relpath(f, albero)
+ if _git_in(albero, "ls-files", "--error-unmatch", "--", rel)[0] != 0:
+ return None
+ if _git_in(albero, "diff", "--quiet", "HEAD", "--", rel)[0] != 0:
+ return None
+ io = _git_in(albero, "config", "user.email")[1].lower()
+ ae, an, ad = (_git_in(albero, "log", "-1", "--format=%ae%x1f%an%x1f%ad", "--date=short", "--", rel)[1].split("\x1f") + ["", "", ""])[:3]
+ if io and ae.lower() == io:
+ return None
+ return (an or ae or "?", ad)
+def da_fidarsi(albero, f, gia):
+ return di_chi(albero, f) is None or impronta_script(albero, f) in gia
+def lascito_del_progetto(albero):
+ """F903 — .delminio/lascito.sh gira alla morte della CLI: come gli altri script
+ del progetto, solo se è di chi lavora qui o una persona l'ha accettato."""
+ f = _os.path.join(albero, ".delminio", "lascito.sh") if albero else ""
+ return [f] if f and _os.path.isfile(f) and _os.access(f, _os.X_OK) else []
+def script_del_progetto(albero, cartelle):
+ out = []
+ for d in cartelle:
+ c = _os.path.join(albero, ".delminio", d)
+ for s in (sorted(_os.listdir(c)) if albero and _os.path.isdir(c) else []):
+ f = _os.path.join(c, s)
+ if _os.path.isfile(f) and _os.access(f, _os.X_OK):
+ out.append(f)
+ return out
+FIDATI
+export DELMINIO_FIDATI_PY
+: '⟦protocollo⟧'
+P_CLOSE='Chiusura|Handoff|Close Session'
+P_TRAILER_TORNATA=Parallel-session
+P_TRAILER_AUDIT='Audit|Review'
+P_TRAILER_MEMORIA='Memoria|Memory'
+export P_CLOSE P_TRAILER_TORNATA P_TRAILER_AUDIT P_TRAILER_MEMORIA
+: '⟦fine protocollo⟧'
+STATO="${TMPDIR:-/tmp}/delminio-$(id -u)"
+mkdir -p "$STATO" 2>/dev/null; chmod 700 "$STATO" 2>/dev/null
+if [ -L "$STATO" ] || [ ! -O "$STATO" ]; then
+ STATO="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-stato"
+ mkdir -p "$STATO" && chmod 700 "$STATO"
+fi
+spazza_stato() {
+ local f p
+ for f in "$STATO"/{attesa,volo,no,nasci,fork,lock-detti,condiviso,avvisato,visto,sessione,cuore,posta-muta}-*; do
+ [ -e "$f" ] || continue
+ p=${f##*-}
+ case $p in *[!0-9]*|'') continue ;; esac
+ kill -0 "$p" 2>/dev/null || rm -f -- "$f"
+ done
+ find "$STATO" -maxdepth 1 -name 'volo-sid-*' -mmin +60 -delete 2>/dev/null || true
+ find "$STATO" -maxdepth 1 -name 'conto-*' -mmin +1440 -delete 2>/dev/null || true
+ find "$STATO" -maxdepth 1 -name 'skill-*' -mmin +1440 -delete 2>/dev/null || true
+}
+in_sottofondo() {
+ [ "${CLAUDE_CODE_SESSION_KIND:-}" = bg ] && return 0
+ [ -r "/proc/$1/environ" ] && tr '\0' '\n' < "/proc/$1/environ" 2>/dev/null | grep -qx 'CLAUDE_CODE_SESSION_KIND=bg'
+}
+madri_del_fork() {
+ printf '%s' "$1" | python3 -c 'import json, sys
+io = sys.argv[1]
+try:
+ t = json.loads(sys.stdin.read() or "{}").get("transcript_path") or ""
+except (ValueError, AttributeError):
+ t = ""
+viste = []
+try:
+ with open(t, encoding="utf-8", errors="replace") as h:
+ for riga in h:
+ try:
+ d = json.loads(riga)
+ except ValueError:
+ continue
+ for k in ("session_id", "sessionId"):
+ v = d.get(k) if isinstance(d, dict) else None
+ if isinstance(v, str) and v and v != io:
+ if v in viste:
+ viste.remove(v)
+ viste.append(v)
+except OSError:
+ pass
+print(json.dumps(viste[::-1][:5]))' "$2" 2>/dev/null || echo '[]'
+}
+zitta_la_prima() {
+ local prima q conv a
+ prima=$(printf '%s' "$1" | campo processo_di_prima)
+ [ -n "$prima" ] && [ "${prima%:*}" = "$(hostname)" ] || return 0
+ q=${prima##*:}
+ case $q in ''|*[!0-9]*) return 0 ;; esac
+ [ "$q" != "$2" ] || return 0
+ rm -f "$STATO/sessione-$q"
+ a=$(cat "$STATO/attesa-$q" 2>/dev/null || true)
+ [ -n "$a" ] && kill "$a" 2>/dev/null
+ rm -f "$STATO/attesa-$q"
+ conv=$(printf '%s' "$1" | campo conversazione_di_prima)
+ if [ -n "$conv" ] && kill -0 "$q" 2>/dev/null; then printf '%s' "$conv" > "$STATO/nasci-$q"; fi
+ return 0
+}
+cli_pid() {
+ if [ -n "${DELMINIO_CLI_PID:-}" ] && kill -0 "$DELMINIO_CLI_PID" 2>/dev/null; then
+ printf '%s' "$DELMINIO_CLI_PID"; return 0
+ fi
+ local p=$$ q exe stato args
+ for _ in 1 2 3 4 5 6 7 8; do
+ if [ -r "/proc/$p/stat" ]; then
+ read -r stato < "/proc/$p/stat"; stato=${stato##*) }; q=${stato#* }; q=${q%% *}
+ else
+ q=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d ' ')
+ fi
+ { [ -z "$q" ] || [ "$q" -le 1 ]; } 2>/dev/null && return 1
+ exe=$(readlink -f "/proc/$q/exe" 2>/dev/null || true)
+ case "$exe" in */claude|*/claude/*|*/versions/*|*/ccd-cli/*|*/bin/codex|*/bin/opencode) printf '%s' "$q"; return 0 ;; esac
+ case "$exe" in ''|*/node*) e_qwen "$q" && { printf '%s' "$q"; return 0; } ;; esac
+ if [ -r "/proc/$q/cmdline" ]; then
+ args=$(tr '\0' ' ' < "/proc/$q/cmdline")
+ else
+ args=$(ps -o args= -p "$q" 2>/dev/null)
+ fi
+ [[ " $args" =~ (^|/|\ )(claude|codex)(\ |$)|/versions/|/ccd-cli/ ]] && { printf '%s' "$q"; return 0; }
+ p=$q
+ done
+ return 1
+}
+_conto_segna() {
+ local t1=${EPOCHREALTIME:-} a b
+ [ -n "$t1" ] && [ -n "${_conto_t0:-}" ] || return 0
+ a=${_conto_t0/[.,]/}; b=${t1/[.,]/}
+ printf '%s %s\n' "$_conto_gesto" $(( (10#$b - 10#$a) / 1000 )) >> "$STATO/conto-$_conto_sid" 2>/dev/null || true
+}
+_conto_somme() {
+ local f="$STATO/conto-${_conto_sid:-}"
+ [ -n "${_conto_sid:-}" ] && [ -s "$f" ] || return 0
+ mv -f "$f" "$f.invio" 2>/dev/null || return 0
+ awk '$1 ~ /^[a-z]+$/ && $2 ~ /^[0-9]+$/ {v[$1]++; m[$1]+=$2}
+ END {s=""; for (g in v) s=s (s ? "," : "") "\"" g "\":[" v[g] "," m[g] "]"; printf "%s", s}' "$f.invio"
+ rm -f "$f.invio"
+}
+_skill_voci() {
+ local sid=${_skill_sid:-${_conto_sid:-}} s=""
+ local f="$STATO/skill-$sid"
+ [ -n "$sid" ] && [ -s "$f" ] || return 0
+ mv -f "$f" "$f.invio" 2>/dev/null || return 0
+ while read -r tipo nome; do
+ [[ $tipo =~ ^(skill|comando)$ && $nome =~ ^[A-Za-z0-9_.:-]+$ ]] || continue
+ s+="${s:+,}[\"$tipo\",\"$nome\"]"
+ done < "$f.invio"
+ rm -f "$f.invio"
+ printf '%s' "$s"
+}
+_quota() {
+ local LC_ALL=C s=$1 i c o=""
+ for ((i = 0; i < ${#s}; i++)); do
+ c=${s:i:1}
+ case $c in
+ [a-zA-Z0-9._~-]) o+=$c ;;
+ *) if [ "$c" = / ] && [ "${2-/}" = / ]; then o+=/; else printf -v c '%%%02X' "'$c"; o+=$c; fi ;;
+ esac
+ done
+ printf '%s' "$o"
+}
+_guardia_serve() {
+ local e=$1 m=${MEMORIA%/} cwd=""
+ [[ $e == *'`'* || $e == *pkill* || $e == *workdir* || $e == *'\u0060'* ]] && return 0
+ [ -n "$m" ] || return 1
+ [[ $e == *"$(basename "$(dirname "$m")")"* || $e == *"$(basename "$m")/"* ]] && return 0
+ [[ $e =~ \"cwd\":\ ?\"([^\"]*)\" ]] && cwd=${BASH_REMATCH[1]}
+ [ -n "$cwd" ] && [[ $m == "${cwd%/}"/* || $m == "$cwd" ]]
+}
+e_codex() { _args "$1" | head -1 | grep -qE '(^|/)codex$'; }
+e_qwen() {
+ _args "$1" | head -1 | grep -qE '(^|/)node[0-9.]*$' || return 1
+ _args "$1" | sed -n 2,4p | grep -v '^-' | head -1 | grep -qE '(^|/)qwen$|/@qwen-code/qwen-code/'
+}
+e_opencode() {
+ [ "$1" = "${DELMINIO_CLI_PID:-}" ] && [ "${DELMINIO_CLI_NOME:-}" = opencode ] && return 0
+ case "$(readlink -f "/proc/$1/exe" 2>/dev/null || true)" in */bin/opencode) return 0 ;; esac
+ _args "$1" | head -1 | grep -qE '(^|/)opencode$'
+}
+cli_di() {
+ if e_codex "$1" 2>/dev/null; then echo codex; elif e_qwen "$1" 2>/dev/null; then echo qwen
+ elif e_opencode "$1" 2>/dev/null; then echo opencode; else echo claude; fi
+}
+headless() {
+ if e_qwen "$1"; then
+ _args "$1" | python3 -c 'import re, sys
+CON_VALORE = {"-m", "--model", "-s", "--sandbox", "--approval-mode", "--mcp-config", "--input-file",
+ "--system-prompt", "--append-system-prompt", "-o", "--output-format", "--input-format",
+ "--session-id", "--include-directories", "--add-dir", "--allowed-tools", "--exclude-tools",
+ "--core-tools", "-e", "--extensions", "--auth-type", "--openai-api-key", "--openai-base-url",
+ "--openai-logging-dir", "--max-session-turns", "--max-wall-time", "--max-tool-calls",
+ "--max-subagent-depth", "--channel", "--json-fd", "--json-file", "--json-schema", "--proxy",
+ "--fallback-model", "--advisor", "--output-style", "--disabled-slash-commands",
+ "--allowed-mcp-server-names", "--disable-mcp-server", "--sandbox-image"}
+a = sys.stdin.read().split("\n")
+script = next((k for k, x in enumerate(a[1:4], 1)
+ if not x.startswith("-") and re.search(r"(^|/)qwen$|/@qwen-code/qwen-code/", x)), None)
+if script is None: sys.exit(1)
+a = a[script + 1:]; i = 0
+while i < len(a):
+ x = a[i]
+ if x in ("-i", "--prompt-interactive") or x.startswith("--prompt-interactive="): sys.exit(1)
+ if x in ("-p", "--prompt") or x.startswith("--prompt="): sys.exit(0)
+ if x == "--": sys.exit(0 if any(a[i + 1:]) else 1)
+ if x in CON_VALORE: i += 2; continue
+ if x in ("-r", "--resume"):
+ i += 2 if i + 1 < len(a) and a[i + 1] and not a[i + 1].startswith("-") else 1
+ continue
+ if x.startswith("-") or not x: i += 1; continue
+ sys.exit(0)
+sys.exit(1)'
+ elif e_opencode "$1"; then
+ [ "$1" = "${DELMINIO_CLI_PID:-}" ] && return 1
+ local chi=$1 su
+ if _args "$chi" | grep -qx -- --service; then
+ if [ -r "/proc/$chi/stat" ]; then read -r su < "/proc/$chi/stat"; su=${su##*) }; su=${su#* }; su=${su%% *}
+ else su=$(ps -o ppid= -p "$chi" 2>/dev/null | tr -d ' '); fi
+ [ -n "$su" ] && e_opencode "$su" && chi=$su
+ fi
+ _args "$chi" | sed 1d | python3 -c 'import sys
+CON_VALORE = {"-m", "--model", "--agent", "-s", "--session", "--port", "--hostname", "--log-level", "--prompt"}
+a = sys.stdin.read().split("\n"); i = 0
+while i < len(a):
+ x = a[i]
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-") or not x: i += 1; continue
+ sys.exit(0 if x == "run" else 1)
+sys.exit(1)'
+ elif _args "$1" | head -1 | grep -qE '(^|/)codex$'; then
+ _args "$1" | sed 1d | python3 -c 'import sys
+CON_VALORE = {"-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a",
+ "--ask-for-approval", "-C", "--cd", "--add-dir", "-i", "--image", "--enable", "--disable",
+ "--remote", "--remote-auth-token-env", "--local-provider"}
+a = sys.stdin.read().split("\n"); i = 0
+while i < len(a):
+ x = a[i]
+ if x == "--": sys.exit(1)
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-"): i += 1; continue
+ sys.exit(0 if x in ("exec", "e", "review") else 1)
+sys.exit(1)'
+ else
+ _args "$1" | grep -qxE -- '-p|--print'
+ fi
+}
+cartella_backup() { # dove sta la copia di sicurezza di questo clone (F777): la scrive il collegamento in .git
+ cat "$(git rev-parse --git-common-dir 2>/dev/null)/delminio-backup" 2>/dev/null || true
+}
+PY_SKILL_NOMI='
+import json, os, re, subprocess, sys
+radice = sys.argv[1]
+p = json.load(sys.stdin)
+plugin = p.get("plugin") or "squadra"
+pezzi = [x for x in p.get("pezzi") or [] if x.get("tipo") in ("skill", "comando", "agente")]
+if not pezzi:
+ print("NESSUNA"); sys.exit(0)
+fatti = subprocess.run(["git", "-C", radice, "ls-files", "-co", "--exclude-standard"],
+ capture_output=True, text=True).stdout.split("\n")
+fatti = {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
+cartelle = {os.path.dirname(f) for f in fatti}
+while any("/" in c and os.path.dirname(c) not in cartelle for c in cartelle):
+ cartelle |= {os.path.dirname(c) for c in cartelle}
+nomi_base = {os.path.basename(f) for f in fatti}
+try:
+ voluti = {r.strip() for r in open(os.path.join(radice, ".delminio", "skill-nomi-voluti.txt"), encoding="utf-8")
+ if r.strip() and not r.startswith("#")}
+except OSError:
+ voluti = set()
+EST = ("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 "
+ "conf csv xml env lock ps1").split()
+def parole(testo):
+ pezzi = re.findall(r"```[^\n]*\n(.*?)```", testo, re.S)
+ resto = re.sub(r"```.*?```", " ", testo, flags=re.S)
+ pezzi += re.findall(r"`([^`\n]+)`", resto)
+ for x in pezzi:
+ for w in re.split(r"[\s;,]+", x):
+ yield w.strip("\"\x27:.()")
+def percorso(w):
+ if not w or w.startswith(("~", "/", "-", "@", "$")) or "://" in w or re.search(r"[<>{}$*?|()\[\]=]", w):
+ return False
+ w = w[2:] if w.startswith("./") else w
+ return ("/" in w and re.fullmatch(r"[\w.@+-]+(/[\w.@+-]+)*/?", w) is not None) \
+ or (re.fullmatch(r"[\w@+-][\w.@+-]*\.(" + "|".join(EST) + ")", w) is not None)
+def c_e(w):
+ w = (w[2:] if w.startswith("./") else w).rstrip("/")
+ if w in fatti or w in cartelle or os.path.exists(os.path.join(radice, w)):
+ return True
+ if "/" not in w:
+ return w in nomi_base
+ return any(f.endswith("/" + w) for f in fatti) or any(c.endswith("/" + w) for c in cartelle)
+trovati = 0
+for x in pezzi:
+ for rel, testo in sorted((x.get("file") or {}).items()):
+ if not rel.endswith(".md"):
+ continue
+ visti = set()
+ for w in parole(testo):
+ if w in visti or w in voluti or not percorso(w):
+ continue
+ visti.add(w)
+ if not c_e(w):
+ trovati += 1
+ print("\t".join(("F", plugin + ":" + x["nome"], rel, w)))
+if trovati:
+ sys.exit(1)
+print("OK\t" + str(len(pezzi)))
+'
+chiedi() { # chiedi GET|POST <percorso> [json] → corpo; esce 1 se Delminio non risponde 200
+ local r c
+ local h=(-H "Content-Type: application/json")
+ [ -n "${CHIEDI_SESSIONE:-}" ] && h+=(-H "X-Delminio-Sessione: $CHIEDI_SESSIONE")
+ if [ -n "${3:-}" ]; then
+ r=$(printf '%s' "$3" | curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
+ "${h[@]}" --data-binary @- "$URL$2" 2>/dev/null)
+ else
+ r=$(curl -sS -m "${CHIEDI_TEMPO:-8}" -w '\n%{http_code}' -X "$1" -K <(_chiave "$TOKEN") \
+ "${h[@]}" "$URL$2" 2>/dev/null)
+ fi
+ c=${r##*$'\n'}
+ if [ "$c" != 200 ]; then
+ local e; e=$(printf '%s' "${r%$'\n'*}" | campo error); e=${e//[$'\t\n']/ }
+ printf '%s\t%s' "${c:-000}" "$e" > "$STATO/no-$$" 2>/dev/null || true
+ return 1
+ fi
+ printf '%s' "${r%$'\n'*}"
+}
+
+carta_richiesta() { # stdin: l'evento della CLI · $1 la sessione
+ local f; f="$(cd "$(dirname "$0")" && pwd)/firme.py"
+ [ -f "$f" ] || return 0
+ DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_STATO="$STATO" python3 "$f" _richiesta "$1" 2>/dev/null || true
+}
+
+cure() {
+ local r d
+ d=$(git rev-parse --git-common-dir 2>/dev/null) || return 0
+ r=$(chiedi GET /api/cure) || return 0
+ printf '%s' "$r" | python3 -c '
+import json, os, re, subprocess, sys
+r, messe_file = json.load(sys.stdin), sys.argv[1]
+def git(*a, inp=None, vero=False):
+ pre = [] if vero else ["--no-replace-objects"]
+ return subprocess.run(["git", *pre, *a], input=inp, capture_output=True, text=True,
+ encoding="utf-8", errors="surrogateescape").stdout
+def testa_senza_firma(testa):
+ fuori, out = False, []
+ for riga in testa.split("\n"):
+ if riga.startswith(("gpgsig ", "gpgsig-sha256 ")):
+ fuori = True
+ continue
+ if fuori and riga.startswith(" "):
+ continue
+ fuori = False
+ out.append(riga)
+ return "\n".join(out)
+try:
+ messe = set(open(messe_file, encoding="utf-8").read().split())
+except OSError:
+ messe = set()
+vive = set()
+for k in r.get("cure") or []:
+ h, n = str(k.get("hash") or ""), int(k.get("numero") or 0)
+ if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h):
+ continue
+ full = git("rev-parse", "-q", "--verify", h + "^{commit}").strip()
+ if not full:
+ continue # quel close non sta in questo repo
+ testa, _, msg = git("cat-file", "commit", full).partition("\n\n")
+ sogg = msg.split("\n", 1)[0]
+ if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), sogg):
+ continue # non è il close di quel numero: non si tocca
+ vive.add(full) # viva anche se qui sotto qualcosa cade: non esce dal git per un giro
+ trailer = git("interpret-trailers", "--parse", inp=msg).strip()
+ corpo = (sogg + "\n\n" + str(k.get("intestazione") or "").strip() + "\n\n" + str(k.get("testo") or "").strip()
+ + "\n" + ("\n" + trailer + "\n" if trailer else ""))
+ nuovo = git("hash-object", "-t", "commit", "-w", "--stdin", inp=testa_senza_firma(testa) + "\n\n" + corpo).strip()
+ if not nuovo:
+ continue
+ if git("rev-parse", "-q", "--verify", "refs/replace/" + full).strip() != nuovo:
+ git("replace", "-f", full, nuovo, vero=True)
+for orig in messe - vive: # tolta nel motore: esce, ma solo se è nostra
+ git("replace", "-d", orig, vero=True)
+with open(messe_file + ".nuovo", "w", encoding="utf-8") as f:
+ f.write("\n".join(sorted(vive)) + ("\n" if vive else ""))
+os.replace(messe_file + ".nuovo", messe_file)
+' "$(_assoluto "$d")/delminio-cure" 2>/dev/null || true
+}
+
+_remoto() { git ${1:+-C "$1"} remote get-url origin 2>/dev/null | sed -E 's#^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@#\1#'; }
+_urlenc() { python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1], safe=""))' "$1"; }
+REPO_NO="${XDG_CONFIG_HOME:-$HOME/.config}/delminio/repo-no.json"
+repo_no_qui() { # → la lista JSON dei «no» di questo collegamento
+ DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" <<'REPO_NO' 2>/dev/null || printf '[]'
+import json, os, sys
+try:
+ d = json.load(open(sys.argv[1], encoding="utf-8"))
+except (OSError, ValueError):
+ d = {}
+v = d.get(os.environ["DELMINIO_CHI"]) if isinstance(d, dict) else None
+print(json.dumps([str(x) for x in v] if isinstance(v, list) else []))
+REPO_NO
+}
+_collega_clone() { # _collega_clone <nome> <cartella>: il clone si collega allo spazio, col token di qui
+ local log="$STATO/collega-$$.log" errore_log
+ if ( cd "$2" && f=$(mktemp) && curl -fsS "$URL/aggancia.sh?segnaposto=1" -o "$f" \
+ && { _firmato "$URL" aggancia.sh "$f" || { _f "$M_riaggancio_non_firmato" url "$URL" > "$log"; rm -f "$f"; exit 1; }; } \
+ && DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" bash "$f" < /dev/null > "$log" 2>&1; r=$?; rm -f "$f"; exit $r ) \
+ && [ -x "$2/.claude/delminio.sh" ]; then
+ rm -f "$log"; _f "$M_collegato_qui" nome "$1" dove "$2"; return 0
+ fi
+ errore_log=$(grep -v '^[[:space:]]*$' "$log" 2>/dev/null | tail -1 | cut -c1-200)
+ rm -f "$log"; _f "$M_collegamento_fallito" nome "$1" dove "$2" errore "$errore_log"; return 1
+}
+
+_segno_pubblico() { local d; d=$(git rev-parse --git-common-dir 2>/dev/null) || return 1; printf '%s/delminio-pubblico' "$(_assoluto "$d")"; }
+pubblico_segna() { # pubblico_segna <json con «pubblico»>: il file segue il motore
+ local f v
+ f=$(_segno_pubblico) || return 0
+ v=$(printf '%s' "$1" | python3 -c 'import json,sys
+try: d = json.load(sys.stdin)
+except Exception: sys.exit(0)
+d = d.get("repo", d) if isinstance(d, dict) else {}
+print("si" if d.get("pubblico") else "no" if "pubblico" in d else "")' 2>/dev/null)
+ case "$v" in si) : > "$f" ;; no) rm -f "$f" ;; esac
+}
+repo_stato() { # nel cuore: chi cambia l'interruttore lo vede qui entro un giro
+ local remoto r
+ remoto=$(_remoto) || return 0
+ [ -n "$remoto" ] || return 0
+ r=$(chiedi GET "/api/repo/stato?remoto=$(_urlenc "$remoto")") || return 0
+ pubblico_segna "$r"
+}
+
+testi() {
+ local r remoto corpo
+ remoto=$(_remoto) || return 0
+ [ -n "$remoto" ] || return 0
+ r=$(chiedi GET "/api/chiusure/testi?remoto=$(_urlenc "$remoto")") || return 0
+ corpo=$(printf '%s' "$r" | python3 -c '
+import json, os, re, subprocess, sys
+def git(*a):
+ return subprocess.run(["git", "--no-replace-objects", *a], capture_output=True, text=True,
+ encoding="utf-8", errors="replace").stdout
+testi, peso = [], 0
+for c in (json.load(sys.stdin).get("chiusure") or [])[:50]:
+ h, n = str(c.get("hash") or ""), int(c.get("numero") or 0)
+ if not n or not re.fullmatch(r"[0-9a-f]{7,40}", h) or not git("rev-parse", "-q", "--verify", h + "^{commit}").strip():
+ continue # non sta in questo git: lo porterà chi lo ha
+ testo = git("log", "-1", "--format=%B", h)
+ if not re.match(r"^(?:%s) S%d\b" % (os.environ["P_CLOSE"], n), testo):
+ continue
+ voce = {"numero": n, "hash": h, "testo": testo}
+ p = len(json.dumps(voce, ensure_ascii=False).encode())
+ if p > 100_000:
+ continue # da solo non passerebbe mai: resta da leggere nel git
+ if peso + p > 100_000:
+ break
+ testi.append(voce)
+ peso += p
+print(json.dumps({"testi": testi}, ensure_ascii=False) if testi else "")
+' 2>/dev/null) || return 0
+ [ -n "$corpo" ] || return 0
+ chiedi POST /api/chiusure/testi "$corpo" >/dev/null || true
+}
+
+perche_no() { # la frase vera dopo un chiedi fallito
+ local c="" e=""
+ IFS=$'\t' read -r c e < "$STATO/no-$$" 2>/dev/null || true
+ rm -f "$STATO/no-$$"
+ case "$c" in
+ ''|000) if [ "${CODEX_SANDBOX_NETWORK_DISABLED:-}" = 1 ]; then _f "$M_sandbox_senza_rete" url "$URL"
+ else _f "$M_perche_muto" url "$URL"; fi ;;
+ 401) _f "$M_perche_token" url "$URL" codice "$c" ;;
+ 403) if [ -n "$e" ] && [ "$e" != unauthorized ]; then _f "$M_perche_rifiuta" url "$URL" codice "$c" errore "$e"
+ else _f "$M_perche_token" url "$URL" codice "$c"; fi ;;
+ *) _f "$M_perche_errore" url "$URL" codice "$c" errore "${e:+: $e}" ;;
+ esac
+}
+mia_sessione() { cat "$STATO/sessione-$1" 2>/dev/null; }
+chi_sei_no() {
+ if [ "${DELMINIO_CLI_NOME:-}" = codex ] || [ -n "${CODEX_SANDBOX_NETWORK_DISABLED:-}${CODEX_SANDBOX:-}" ]; then
+ echo "$M_chi_sei_sandbox" >&2
+ else
+ echo "$1" >&2
+ fi
+}
+albero_di() {
+ git worktree list --porcelain 2>/dev/null | awk -v n="$1" '
+ /^worktree /{w=substr($0, 10)} /^branch /{b=$2; sub(".*/", "", b); if (b == n) {print w; exit}}' \
+ || true
+}
+avvia_ritiro() { # avvia_ritiro <sessione> <albero>
+ local l="$STATO/ritiro-$1" v
+ v=$(cat "$l" 2>/dev/null || true)
+ [ -n "$v" ] && kill -0 "$v" 2>/dev/null && return 0
+ _staccato bash "$0" ritira-file "$1" "$2" >/dev/null 2>&1 < /dev/null &
+}
+ritira_file() { # ritira_file <sessione> <albero>
+ local nome=$1 albero=$2 r dir ex id nm dest tmp
+ [ -n "$albero" ] && [ -d "$albero" ] || return 1
+ r=$(chiedi GET "/api/file/in-arrivo?sessione=$(_urlenc "$nome")") || return 1
+ dir="$albero/.delminio/file"
+ mkdir -p "$dir" && chmod 700 "$dir" || return 1
+ if ex=$(git -C "$albero" rev-parse --git-path info/exclude 2>/dev/null); then
+ case $ex in /*) ;; *) ex="$albero/$ex" ;; esac
+ grep -qxF '/.delminio/file/' "$ex" 2>/dev/null || { mkdir -p "$(dirname "$ex")" && printf '/.delminio/file/\n' >> "$ex"; }
+ fi
+ find "$dir" -maxdepth 1 -type f -mtime +7 -delete 2>/dev/null || true
+ printf '%s' "$r" | python3 -c 'import json, sys
+for f in json.load(sys.stdin).get("file") or []:
+ print(f["id"] + "\t" + f["nome"].replace("\t", " ").replace("\n", " "))' | while IFS=$'\t' read -r id nm; do
+ dest=$(python3 -c 'import os, re, sys, unicodedata
+d, n = sys.argv[1], re.split(r"[\\/]", sys.argv[2])[-1]
+n = "".join(c for c in n if not unicodedata.category(c).startswith("C")).strip().lstrip(".-").strip() or "file"
+b, e = os.path.splitext(n); k, p = 1, os.path.join(d, n)
+while os.path.lexists(p):
+ k += 1; p = os.path.join(d, f"{b} ({k}){e}")
+print(p)' "$dir" "$nm") || continue
+ tmp="$dir/.in-arrivo-$id"
+ if ! curl -sS -f -m 900 -K <(_chiave "$TOKEN") -o "$tmp" "$URL/api/file/$id?scarica=1" 2>/dev/null; then
+ rm -f "$tmp"; continue
+ fi
+ chmod 600 "$tmp" && mv -f "$tmp" "$dest" || { rm -f "$tmp"; continue; }
+ chiedi POST "/api/file/$id/ritirato" "{\"sessione\":$(json_stringa "$nome"),\"percorso\":$(json_stringa "$dest")}" >/dev/null || true
+ done
+}
+chiave_in_uso() {
+ [ -n "${ANTHROPIC_API_KEY:-}" ] && [ "$(uname -s)" = Linux ] || return 0
+ [ -e "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/.credentials.json" ] && return 0
+ printf '%s' "$ANTHROPIC_API_KEY" | sha256sum | cut -c1-16
+}
+fatti_codex() { # cli, evento, fatti JSON
+ [ "$1" = codex ] || { printf '%s' "$3"; return; }
+ local programma
+ IFS= read -r -d '' programma <<'CODEX_FATTI' || true
+import json, os, sys
+from pathlib import Path
+d = json.load(os.fdopen(3))
+try:
+ evento = json.loads(sys.stdin.read() or '{}')
+except (ValueError, TypeError):
+ evento = {}
+if not isinstance(evento, dict):
+ evento = {}
+modo = evento.get('permission_mode', '')
+d['permission_mode'] = modo if modo in ('default', 'acceptEdits', 'plan', 'dontAsk', 'bypassPermissions') else ''
+scelta = os.environ.get('DELMINIO_PERMESSI', '')
+d['permessi_al_lancio'] = scelta if scelta in ('chiede', 'modifiche', 'classificatore') else ''
+casa = os.environ.get('CODEX_HOME')
+segno = Path(casa) / 'delminio-informativa-permessi' if casa else None
+try:
+ d['informativa_codex_vista'] = 0 if segno is None or segno.is_symlink() else int(segno.read_text().strip())
+except (OSError, ValueError):
+ d['informativa_codex_vista'] = 0
+d['sandbox_linux'] = os.environ.get('DELMINIO_SANDBOX_LINUX', '')
+print(json.dumps(d))
+CODEX_FATTI
+ python3 -c "$programma" 3<<< "$3" <<< "$2"
+}
+evento_dove() {
+ local programma
+ IFS= read -r -d '' programma <<'DOVE' || true
+import json, os, re, sys
+e = json.loads(sys.stdin.read() or "{}")
+t = e.get("tool_input") if isinstance(e.get("tool_input"), dict) else {}
+comando = t.get("command") if isinstance(t.get("command"), str) else ""
+base = e.get("cwd") or os.getcwd()
+
+def stringa(s, i):
+ """Il letterale JS che comincia in s[i] → (valore o None se ha ${…}, fine)."""
+ q, j, out = s[i], i + 1, []
+ while j < len(s) and s[j] != q:
+ if s[j] == "\\" and j + 1 < len(s):
+ c = s[j + 1]
+ if c == "u" and re.match(r"[0-9a-fA-F]{4}", s[j + 2:j + 6]):
+ out.append(chr(int(s[j + 2:j + 6], 16))); j += 6; continue
+ out.append({"n": "\n", "t": "\t", "r": "\r", "0": "\0"}.get(c, c)); j += 2; continue
+ if q == "`" and s.startswith("${", j):
+ return None, s.find(q, j) + 1 or len(s)
+ out.append(s[j]); j += 1
+ return "".join(out), j + 1
+
+def salta(js, i):
+ """Se in js[i] comincia un commento o una stringa, dove finisce; se no None."""
+ if js.startswith("//", i):
+ j = js.find("\n", i); return len(js) if j < 0 else j
+ if js.startswith("/*", i):
+ j = js.find("*/", i + 2); return len(js) if j < 0 else j + 2
+ if js[i] in "\"'`":
+ return stringa(js, i)[1]
+ return None
+
+def in_chiave(js, i):
+ """js[i] sta dove comincia una chiave: dopo «{» o «,»."""
+ j = i - 1
+ while j >= 0 and js[j].isspace():
+ j -= 1
+ return j >= 0 and js[j] in "{,"
+
+def chiamate_js(js):
+ """Le exec_command({…}) del CODICE (non di un commento o di una stringa):
+ (cmd, workdir), dove None = non letterale e "" = workdir assente.
+ ⚠️ Ogni altro modo di arrivarci è una chiamata muta (None, None): l'alias
+ (const f = tools.exec_command, tools["exec_command"]), che altrimenti spariva
+ dietro una chiamata letterale con lo stesso cmd scritta lì per finta."""
+ i = 0
+ while i < len(js):
+ if js[i] in "\"'`":
+ v, fine = stringa(js, i)
+ if v == "exec_command":
+ yield None, None
+ i = fine; continue
+ fine = salta(js, i)
+ if fine is not None:
+ i = fine; continue
+ m = re.match(r"exec_command\s*\(\s*(\{)?", js[i:i + 64])
+ if not m or (i and re.match(r"[\w$]", js[i - 1])):
+ if re.match(r"exec_command\b", js[i:i + 13]) and not (i and re.match(r"[\w$]", js[i - 1])):
+ yield None, None
+ i += 12; continue
+ i += 1; continue
+ if not m.group(1): # exec_command(args): una variabile, non si legge
+ yield None, None
+ i += m.end(); continue
+ i, prof, chiavi = i + m.end(), 1, {}
+ while i < len(js) and prof:
+ k = re.match(r"""(["']?)(cmd|workdir)\1\s*:\s*""", js[i:i + 16]) if prof == 1 else None
+ if k and not re.match(r"[\w$]", js[i - 1]):
+ i += k.end()
+ v = None
+ if i < len(js) and js[i] in "\"'`":
+ v, i = stringa(js, i)
+ if not re.match(r"\s*[,}]", js[i:i + 64]):
+ v = None
+ chiavi[k.group(2)] = v
+ continue
+ a = re.match(r"(cmd|workdir)\s*(?=[,}])", js[i:i + 16]) if prof == 1 and in_chiave(js, i) else None
+ if a:
+ chiavi[a.group(1)] = None
+ i += a.end(); continue
+ if prof == 1 and js[i] == "[" and in_chiave(js, i):
+ chiavi = {"cmd": None, "workdir": None}
+ if prof == 1 and js.startswith("...", i):
+ chiavi = {"cmd": None, "workdir": None}
+ i += 3; continue
+ fine = salta(js, i)
+ if fine is not None:
+ i = fine; continue
+ if js[i] in "{[(":
+ prof += 1
+ elif js[i] in "}])":
+ prof -= 1
+ i += 1
+ yield chiavi.get("cmd"), chiavi.get("workdir", "")
+
+def ultime_chiamate(percorso):
+ """Le chiamate dell'ultima risposta del modello, dalla coda del rollout. None se
+ il rollout non si legge o non mostra ancora la chiamata in corso (l'ultima cosa
+ scritta è un'uscita): mai le chiamate di prima al posto di questa."""
+ try:
+ with open(percorso, "rb") as f:
+ f.seek(max(0, os.path.getsize(percorso) - 524288))
+ righe = f.read().decode("utf-8", "replace").splitlines()
+ except OSError:
+ return None
+ viste, voci = [], 0
+ for r in reversed(righe):
+ try:
+ p = json.loads(r).get("payload") or {}
+ except ValueError:
+ continue
+ if p.get("type") == "custom_tool_call" and p.get("name") == "exec":
+ voci += 1
+ viste += list(chiamate_js(p.get("input") or ""))
+ elif p.get("type") == "function_call":
+ voci += 1
+ try:
+ a = json.loads(p.get("arguments") or "{}")
+ except ValueError:
+ a = None
+ if not isinstance(a, dict):
+ viste.append((None, None)); continue
+ if not ({"cmd", "command", "workdir"} & set(a)):
+ continue
+ c = a.get("cmd", a.get("command"))
+ viste.append((c if isinstance(c, str) else None,
+ a.get("workdir", "") if isinstance(a.get("workdir", ""), str) else None))
+ elif p.get("type") in ("custom_tool_call_output", "function_call_output"):
+ if not voci:
+ return None
+ break
+ elif p.get("type") in ("message", "reasoning") and voci:
+ break
+ return viste if voci else None
+
+def cd_letterale(testo):
+ """Un cd iniziale riuscito solo con &&, senza espansioni indovinate.
+ Restituisce destinazione e resto; la stessa prova assolve il rollout assente.
+ """
+ m = re.match(r"""\s*cd\s+("[^"]+"|'[^']+'|[^\s;&|]+)\s*&&""", testo)
+ if not m:
+ return None, testo
+ token = m.group(1)
+ casa = os.path.expanduser("~")
+ if token.startswith("'"):
+ d = token[1:-1]
+ elif token.startswith('"'):
+ d = re.sub(r"^\$(HOME\b|\{HOME\})", lambda _: casa, token[1:-1])
+ if any(c in d for c in ('$', '`', '\\')):
+ return None, testo
+ else:
+ d = re.sub(r"^(~(?=/|$)|\$HOME\b|\$\{HOME\})", lambda _: casa, token)
+ if re.search(r"[$`\\~*?\[\]{}()<>\"']", d):
+ return None, testo
+ return d, testo[m.end():]
+
+cwd, incerto = base, ""
+rollout = e.get("transcript_path") or ""
+if e.get("tool_name") == "Bash" and comando and os.path.basename(rollout).startswith("rollout-"):
+ viste = ultime_chiamate(rollout)
+ if viste is None:
+ viste, e["dove_non_visto"] = [], 1
+ incerto = "il rollout di Codex non mostra la chiamata di questo comando"
+ mie = {w for c, w in viste if c == comando}
+ possibili = mie | {w for c, w in viste if c is None}
+ if e.get("dove_non_visto"):
+ pass
+ elif not possibili:
+ incerto = "non trovo nel code mode la chiamata che lancia questo comando"
+ elif len(possibili) == 1 and None not in possibili:
+ w = possibili.pop()
+ cwd = os.path.join(base, os.path.expanduser(w)) if w else base
+ elif len(mie) > 1:
+ incerto = "lo stesso comando ha più cartelle in questa chiamata"
+ elif None in mie:
+ incerto = "la sua cartella (workdir) non è scritta per esteso"
+ else:
+ incerto = "nella chiamata ci sono un comando o una cartella non scritti per esteso"
+primo, _ = cd_letterale(comando)
+if primo is not None and os.path.isabs(primo):
+ cwd, incerto = base, ""
+resto = comando
+while not incerto:
+ d, dopo = cd_letterale(resto)
+ if d is None:
+ if re.match(r"\s*cd\b", resto) and os.path.basename(rollout).startswith("rollout-"):
+ incerto = "il cd iniziale non è una destinazione letterale seguita da &&"
+ break
+ cwd, resto = os.path.join(cwd, d), dopo
+e["cwd"] = os.path.normpath(cwd)
+if incerto:
+ e["dove_incerto"] = incerto
+print(json.dumps(e))
+DOVE
+ python3 -c "$programma"
+}
+segna_informativa_codex() { # risposta del motore; solo dopo una consegna riuscita a una CLI vera
+ local programma
+ IFS= read -r -d '' programma <<'CODEX_VISTA' || true
+import json, os, sys, tempfile
+from pathlib import Path
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+v = json.load(sys.stdin).get('informativa_codex')
+if not isinstance(v, int) or isinstance(v, bool) or v < 1:
+ sys.exit(0)
+casa = os.environ.get('CODEX_HOME')
+if not casa:
+ sys.exit(0) # un Codex nudo non autorizza scritture nella casa personale
+casa = Path(casa)
+segno = casa / 'delminio-informativa-permessi'
+try:
+ casa.mkdir(parents=True, exist_ok=True)
+ if segno.exists() and (segno.is_symlink() or not segno.read_text().strip().isdigit()):
+ raise ValueError(F("segno_non_versione"))
+ with tempfile.NamedTemporaryFile(mode='w', dir=casa, prefix='.delminio-permessi-', delete=False) as f:
+ f.write(str(v))
+ nome = f.name
+ os.replace(nome, segno)
+except (OSError, ValueError) as e:
+ print(F("informativa_non_segnata", errore=e), file=sys.stderr)
+CODEX_VISTA
+ python3 -c "$programma" <<< "$1"
+}
+strumenti_vivi() {
+ local f r k
+ read -r k _ <<<"$(printf '%s' "$URL$TOKEN" | cksum)"
+ f="$STATO/strumenti-$k"
+ if [ -n "$(find "$f" -mmin -1 2>/dev/null)" ]; then printf '%s' "$(<"$f")"; return 0; fi
+ if r=$(CHIEDI_TEMPO=3 chiedi GET /api/lock/strumenti); then
+ printf '%s' "$r" | python3 -c 'import json,sys
+print("\n".join(g for g in json.load(sys.stdin).get("strumenti") or [] if isinstance(g, str)))' > "$f.$$" 2>/dev/null \
+ && mv -f "$f.$$" "$f"
+ else
+ touch "$f" 2>/dev/null # un minuto senza richiedere: un motore muto non costa a ogni tool
+ fi
+ [ -f "$f" ] && printf '%s' "$(<"$f")"
+ return 0
+}
+accettate_file() {
+ local c w
+ c="$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null || echo .git)/delminio-guardie-accettate"
+ w=$(git rev-parse --path-format=absolute --git-path delminio-guardie-accettate 2>/dev/null || true)
+ if [ -n "$w" ] && [ "$w" != "$c" ] && [ -s "$w" ]; then
+ sort -u "$w" "$c" 2>/dev/null > "$c.$$" && mv -f "$c.$$" "$c" && rm -f "$w"
+ fi
+ printf '%s' "$c"
+}
+modello_dal_transcript() { # modello_dal_transcript <pid> <sessione> <evento json>
+ [ -z "${DELMINIO_MODELLO:-}" ] || return 0
+ local m
+ m=$(printf '%s' "$3" | _tempo 2 python3 -c '
+import json, os, sys
+try:
+ e = json.load(sys.stdin)
+ if isinstance(e.get("model"), str) and e["model"].strip():
+ print(e["model"].strip()[:80]); sys.exit(0)
+ p = e.get("transcript_path") or ""
+ with open(p, "rb") as f:
+ f.seek(max(0, os.path.getsize(p) - 524288))
+ righe = f.read().decode("utf-8", "replace").splitlines()
+except Exception:
+ sys.exit(0)
+for r in reversed(righe):
+ try:
+ d = json.loads(r)
+ except ValueError:
+ continue
+ if not isinstance(d, dict):
+ continue
+ m = ((d.get("payload") or {}).get("model") if d.get("type") == "turn_context"
+ else ((d.get("message") if isinstance(d.get("message"), dict) else {}).get("model") or d.get("model"))
+ if d.get("type") == "assistant" else None)
+ if isinstance(m, str) and m.strip() and not m.startswith("<"): # «<synthetic>» di Claude non è un modello
+ print(m.strip()[:80])
+ break
+' 2>/dev/null || true)
+ [ -n "$m" ] || return 0
+ [ "$m" = "$(cat "$STATO/modello-$1" 2>/dev/null || true)" ] && return 0
+ CHIEDI_TEMPO=2 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$2"),\"agente\":$(json_stringa "$m")}" >/dev/null 2>&1 \
+ && printf '%s' "$m" > "$STATO/modello-$1"
+ return 0
+}
+consumi_dal_transcript() { # consumi_dal_transcript <file di stato> <evento json>
+ printf '%s' "$2" | _tempo 5 python3 "$(dirname "$0")/consumi.py" "$1" 2>/dev/null || true
+}
+totale_cli_qwen() { # totale_cli_qwen <evento json>
+ [ -n "${QWEN_HOME:-}" ] || return 0
+ printf '%s' "$1" | _tempo 7 python3 -c '
+import json, os, sys, time
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+sid = str(e.get("session_id") or "")
+if e.get("hook_event_name") != "SessionEnd" or not sid:
+ sys.exit(0)
+f = os.path.join(os.environ["QWEN_HOME"], "usage_record.jsonl")
+riga = None
+for _ in range(25): # la CLI lo scrive mentre si spegne
+ try:
+ with open(f, encoding="utf-8") as h:
+ for r in h:
+ if sid in r:
+ d = json.loads(r)
+ if d.get("sessionId") == sid:
+ riga = d
+ except (OSError, ValueError):
+ pass
+ if riga:
+ break
+ time.sleep(0.2)
+if not riga:
+ sys.exit(0)
+t = {"input": 0, "cache_letta": 0, "cache_scritta": 0, "output": 0, "risposte": 0}
+for m in (riga.get("models") or {}).values():
+ letta = int(m.get("cachedTokens") or 0)
+ t["input"] += max(0, int(m.get("inputTokens") or 0) - letta)
+ t["cache_letta"] += letta
+ t["output"] += int(m.get("outputTokens") or 0) + int(m.get("thoughtsTokens") or 0)
+ t["risposte"] += int(m.get("requests") or 0)
+print(json.dumps({"conversazione": sid[:80], "cli": "qwen", "totale_cli": t}))
+' 2>/dev/null || true
+}
+fatti_nascita() { # fatti_nascita <pid> <evento json> [si = al primo messaggio]
+ local cli senza="" base programma; cli=$(cli_di "$1"); [ "$cli" = claude ] || senza=1
+ IFS= read -r -d '' programma <<'FATTI' || true
+import json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+processo, albero, agente, dove, memoria, primo, remoto = sys.argv[1:8]
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+try:
+ conversazione = str(json.loads(sys.stdin.read() or "{}").get("session_id") or "")
+except Exception:
+ conversazione = ""
+commit = subprocess.run(["git", "log", "-200", "--format=%h%x1f%s%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)"],
+ capture_output=True, text=True).stdout.splitlines()
+avvisi = []
+exec(os.environ["DELMINIO_FIDATI_PY"])
+gia, fermi = (accettati(albero) if albero else set()), []
+for f in lascito_del_progetto(albero):
+ if not da_fidarsi(albero, f, gia):
+ fermi.append(di_chi(albero, f)[0])
+for f in script_del_progetto(albero, ("apertura", "opening")):
+ s = os.path.basename(f)
+ if not da_fidarsi(albero, f, gia):
+ fermi.append(di_chi(albero, f)[0])
+ continue
+ try:
+ out = subprocess.run([f], cwd=albero, capture_output=True, text=True, timeout=5).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ out = F("non_risponde_5s", script=s)
+ avvisi += [r.strip() for r in out.splitlines() if r.strip()][:3]
+if fermi:
+ avvisi.insert(0, F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
+import glob
+mcp_fermi = 0
+for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
+ "delminio", "squadre", "*", ".mcp-fermi.json")):
+ try:
+ with open(x, encoding="utf-8") as h:
+ mcp_fermi += len(json.load(h))
+ except (OSError, ValueError, TypeError):
+ pass
+if mcp_fermi:
+ avvisi.insert(0, F("squadra_mcp_da_accettare", n=mcp_fermi))
+plugin_fermi = 0
+for x in glob.glob(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"),
+ "delminio", "squadre", "*", ".plugin-fermi.json")):
+ try:
+ with open(x, encoding="utf-8") as h:
+ plugin_fermi += len(json.load(h))
+ except (OSError, ValueError, TypeError):
+ pass
+if plugin_fermi:
+ avvisi.insert(0, F("squadra_plugin_da_accettare", n=plugin_fermi))
+try:
+ with open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
+ encoding="utf-8") as h:
+ righe_ferme = sum(len(sp.get("fermi") or []) for sp in (json.load(h).get("spazi") or {}).values()
+ if isinstance(sp, dict))
+except (OSError, ValueError, TypeError, AttributeError):
+ righe_ferme = 0
+if righe_ferme:
+ avvisi.insert(0, F("eseguibili_da_accettare", n=righe_ferme))
+propri = 0
+for d in ("apertura", "opening", "dove-siamo", "status"):
+ c = os.path.join(albero, ".delminio", d) if albero else ""
+ propri += sum(1 for s in (os.listdir(c) if c and os.path.isdir(c) else [])
+ if os.path.isfile(os.path.join(c, s)) and os.access(os.path.join(c, s), os.X_OK))
+prima = []
+if albero:
+ cartelle = [os.path.join(albero, ".claude", "delminio-prima")]
+ try:
+ cartelle.append(open(os.path.join(albero, ".git", "delminio-backup"), encoding="utf-8").read().strip())
+ except OSError:
+ pass
+ for c in cartelle:
+ for d in sorted(os.listdir(c) if c and os.path.isdir(c) else []):
+ if os.path.isfile(os.path.join(c, d, "fatti.json")) and not os.path.exists(os.path.join(c, d, "RIPASSATO")):
+ p = os.path.join(c, d)
+ prima.append(os.path.relpath(p, albero) if p.startswith(albero + os.sep) else p)
+print(json.dumps({"processo": processo, "albero": albero, "agente": agente, "dove": dove,
+ "commit": commit, "avvisi": avvisi[:12], "propri": propri, "remoto": remoto,
+ "repo_no": json.loads(os.environ.get("DELMINIO_REPO_NO") or "[]"),
+ "conversazione": conversazione, "prima": prima,
+ "madri": json.loads(os.environ.get("DELMINIO_MADRI") or "[]"),
+ "indice": bool(memoria) and os.path.isfile(os.path.join(memoria, "MEMORY.md"))
+ and not os.environ.get("DELMINIO_SENZA_INDICE"),
+ "al_primo_messaggio": primo == "si",
+ "contesto": int(os.environ.get("DELMINIO_CONTESTO") or 0) if (os.environ.get("DELMINIO_CONTESTO") or "").isdigit() else 0,
+ "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"}))
+FATTI
+ base=$(DELMINIO_CLI_NOME="$cli" DELMINIO_SENZA_INDICE="$senza" DELMINIO_REPO_NO="$(repo_no_qui)" \
+ python3 -c "$programma" "$(hostname):$1" "$(git rev-parse --show-toplevel 2>/dev/null)" \
+ "${DELMINIO_MODELLO:-}" "$(hostname)" "$MEMORIA" "${3:-}" "$(_remoto)" <<< "$2"
+ ) || return
+ fatti_codex "$cli" "$2" "$base"
+}
+eseguibili_indietro() { # eseguibili_indietro <impronta voluta> [giorno] → 0 se va riallineato
+ [ -z "${DELMINIO_PROVA:-}" ] && [ "${DELMINIO_ESEGUIBILE:-}" = si ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 1
+ python3 -c 'import json,os,sys,time
+try: r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json")))
+except Exception: r = {}
+m = (r.get("spazi") or {}).get(sys.argv[2], {} if r.get("spazi") else r)
+vecchio = sys.argv[3] == "giorno" and time.time() - (m.get("quando") or 0) > 86400
+sys.exit(0 if (sys.argv[1] and m.get("registro") != sys.argv[1]) or vecchio else 1)' "$1" "$(spazio_qui)" "${2:-}"
+}
+riaggancio_stato() { printf '%s/riaggancio-%s' "$STATO" "$(printf '%s\n' "$1" | cksum | cut -d' ' -f1)"; }
+riaggancia() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] && [ "$1" != "${KIT:-}" ] && [ -d "$2" ] || return 0
+ ra=$(riaggancio_stato "$2")
+ if [ "${3:-}" = presto ] && [ "$(cat "$ra.verso" 2>/dev/null)" = "$1" ] && [ -e "$ra.log" ] \
+ && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -lt 3600 ]; then
+ return 0
+ fi
+ printf '%s' "$1" > "$ra.verso"
+ export -f _firmato
+ export KIT_FIRMA
+ ( cd "$2" && DELMINIO_TOKEN="$TOKEN" _staccato bash -c \
+ 'f=$(mktemp) && curl -fsS "$0/aggancia.sh?segnaposto=1" -o "$f" || exit 1
+ _firmato "$0" aggancia.sh "$f" || { printf "%s\n" "$1" >&2; rm -f "$f"; exit 1; }
+ DELMINIO_URL="$0" bash "$f"; r=$?; rm -f "$f"; exit $r' \
+ "$URL" "$(_f "$M_riaggancio_non_firmato" url "$URL")" > "$ra.log" 2>&1 < /dev/null & )
+}
+fratelli_indietro() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$1" ] || return 0
+ s="$STATO/fratelli.verso"
+ if [ "$(cat "$s" 2>/dev/null)" = "$1" ] && [ $(( $(date +%s) - $(_mtime "$s") )) -lt 3600 ]; then return 0; fi
+ printf '%s' "$1" > "$s"
+ ( _staccato bash "$0" riaggancia-fratelli "$1" > "$STATO/fratelli.log" 2>&1 < /dev/null & )
+}
+allinea_staccato() {
+ _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit allinea \
+ > "$STATO/eseguibili.log" 2>&1 < /dev/null &
+}
+skill_staccato() {
+ [ -z "${DELMINIO_PROVA:-}" ] && [ -f "$(dirname "$0")/eseguibili.py" ] || return 0
+ _staccato python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" skill \
+ > "$STATO/skill.log" 2>&1 < /dev/null &
+}
+spazio_qui() { python3 "$(dirname "$0")/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" spazio 2>/dev/null || printf '%s' "${URL%/}"; }
+stato_eseguibile() { DELMINIO_SPAZIO="$(spazio_qui)" python3 - <<'STATO_ESEGUIBILE'
+import json, os
+try:
+ r = json.load(open(os.path.expanduser(os.environ.get("DELMINIO_ESEGUIBILI") or "~/.config/delminio/eseguibili.json"),
+ encoding="utf-8"))
+except Exception:
+ r = {}
+u = os.environ["DELMINIO_SPAZIO"].rstrip("/")
+s = (r.get("spazi") or {}).get(u, {} if r.get("spazi") else r)
+miei = [p for p, chi in (r.get("padroni") or {}).items() if u in chi] if r.get("spazi") else (r.get("eseguibili") or {})
+print("rifiutato" if s.get("rifiutato") else "si" if any(os.path.isfile(p) for p in miei) else "no")
+STATO_ESEGUIBILE
+}
+
+
+: '⟦comandi⟧'
+_comando() { # _comando <gruppo> <nome> → il nome canonico
+ case "$1:$2" in
+ client:rivisto) printf '%s\n' ripassato ;;
+ client:revisione) printf '%s\n' audit ;;
+ client:backlog) printf '%s\n' cantiere ;;
+ client:firme) printf '%s\n' carta ;;
+ client:accept) printf '%s\n' accetta ;;
+ client:focus) printf '%s\n' domini ;;
+ client:title) printf '%s\n' titolo ;;
+ client:new) printf '%s\n' nuovo ;;
+ client:teardown) printf '%s\n' smonta ;;
+ client:kit-files) printf '%s\n' file-del-kit ;;
+ client:send) printf '%s\n' invia ;;
+ client:agents) printf '%s\n' eseguibili ;;
+ client:vault) printf '%s\n' cassaforte ;;
+ client:reviewed) printf '%s\n' ripassato ;;
+ client:disconnect) printf '%s\n' stacca ;;
+ client:why) printf '%s\n' perche ;;
+ client:handoff) printf '%s\n' consegna ;;
+ client:handoff-of) printf '%s\n' consegna-di ;;
+ client:errors) printf '%s\n' errori ;;
+ client:connect-all) printf '%s\n' agganciali ;;
+ client:review) printf '%s\n' audit ;;
+ client:help) printf '%s\n' aiuto ;;
+ client:clone) printf '%s\n' clona ;;
+ client:signoffs) printf '%s\n' carta ;;
+ client:domains) printf '%s\n' domini ;;
+ eseguibili:status) printf '%s\n' stato ;;
+ eseguibili:rename) printf '%s\n' rinomina ;;
+ eseguibili:test) printf '%s\n' prova ;;
+ eseguibili:sync) printf '%s\n' allinea ;;
+ cassaforte:list) printf '%s\n' elenco ;;
+ cassaforte:propose) printf '%s\n' proponi ;;
+ cassaforte:open) printf '%s\n' apri ;;
+ cassaforte:access) printf '%s\n' finestre ;;
+ cassaforte:close) printf '%s\n' chiudi ;;
+ cassaforte:deposit) printf '%s\n' deposita ;;
+ cassaforte:windows) printf '%s\n' finestre ;;
+ carta:check) printf '%s\n' controlla ;;
+ carta:description) printf '%s\n' descrizione ;;
+ carta:report) printf '%s\n' resoconto ;;
+ carta:export) printf '%s\n' esporta ;;
+ carta:chain) printf '%s\n' catena ;;
+ carta:review) printf '%s\n' revisione ;;
+ carta:checks) printf '%s\n' prove ;;
+ *) printf '%s\n' "$2" ;;
+ esac
+}
+export 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"}}'
+: '⟦fine comandi⟧'
+if [ $# -gt 0 ]; then set -- "$(_comando client "$1")" "${@:2}"; fi
+case "${1:-}" in eseguibili|cassaforte|carta) [ $# -gt 1 ] && set -- "$1" "$(_comando "$1" "$2")" "${@:3}" ;; esac
+
+case "${1:-}" in guardia|condiviso|gesto|tocco|volo|umano|memorie|segreto|rito|attesa)
+ if [ -n "${EPOCHREALTIME:-}" ] && [ -z "${DELMINIO_NO_CODEX:-}" ] && [ ! -t 0 ]; then
+ _conto_gesto=$1
+ _conto_ev=$(cat); exec 0<<<"$_conto_ev"
+ [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _conto_sid=${BASH_REMATCH[1]}
+ [ -n "${_conto_sid:-}" ] && [ "$1" != attesa ] && trap '_conto_segna' EXIT
+ fi ;;
+esac
+case "${1:-}" in volo|umano)
+ if [ ! -t 0 ] && [ -z "${DELMINIO_NO_CODEX:-}" ]; then
+ [ -n "${_conto_ev+x}" ] || { _conto_ev=$(cat); exec 0<<<"$_conto_ev"; }
+ _skill_voce=""
+ if [ "$1" = volo ] && [[ $_conto_ev =~ \"tool_name\":\ ?\"([A-Za-z_]+)\" ]] \
+ && [[ ${BASH_REMATCH[1]} = [Ss]kill ]] \
+ && [[ $_conto_ev =~ \"skill\":\ ?\"([A-Za-z0-9_.:-]{1,161})\" ]]; then
+ _skill_voce="skill ${BASH_REMATCH[1]}"
+ elif [ "$1" = umano ] && [[ $_conto_ev =~ \"prompt\":\ ?\"/([A-Za-z0-9_.:-]{1,161})([\ \"\\]|$) ]]; then
+ _skill_voce="comando ${BASH_REMATCH[1]}"
+ fi
+ [[ $_conto_ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]] && _skill_sid=${BASH_REMATCH[1]}
+ if [ -n "$_skill_voce" ] && [ -n "${_skill_sid:-}" ]; then
+ printf '%s\n' "$_skill_voce" >> "$STATO/skill-$_skill_sid" 2>/dev/null || true
+ fi
+ fi ;;
+esac
+case "${1:-}" in condiviso|gesto|guardia|tocco)
+ if [ -z "${DELMINIO_NO_CODEX:-}" ] && pid_cli=$(cli_pid) && e_codex "$pid_cli"; then
+ entrata=$(mktemp); uscita=$(mktemp); errori=$(mktemp)
+ cat > "$entrata"
+ DELMINIO_NO_CODEX=1 bash "$0" "$@" < "$entrata" > "$uscita" 2> "$errori"; rc=$?
+ if [ "$rc" = 2 ]; then
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
+ "permissionDecision": "deny", "permissionDecisionReason": sys.argv[1],
+ "additionalContext": open(sys.argv[2], encoding="utf-8", errors="replace").read()}}))' "$M_fermato_codex" "$errori"
+ rc=0
+ else
+ cat "$uscita"; cat "$errori" >&2
+ fi
+ rm -f "$entrata" "$uscita" "$errori"; exit "$rc"
+ fi ;;
+esac
+
+parte() { # parte <file accanto al client>
+ [ -f "$(dirname "$0")/$1" ] && return 0
+ _f "$M_parte_manca" file "$(dirname "$0")/$1" >&2
+ exit 1
+}
+
+case "${1:-}" in
+ cantiere) shift; exec python3 "$(dirname "$0")/cantiere.py" "$@" ;;
+ apertura)
+ pid=$(cli_pid || true)
+ cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
+ if [ -n "$pid" ] && headless "$pid"; then pid=""; fi # un -p non è una sessione
+ [ -n "${DELMINIO_PROVA:-}" ] && pid=""
+ DELMINIO_ESEGUIBILE=$(stato_eseguibile 2>/dev/null || true); export DELMINIO_ESEGUIBILE
+ DELMINIO_APP_CODEX=""
+ if [ -f "$(dirname "$0")/plugin.py" ]; then
+ _tempo 20 python3 "$(dirname "$0")/plugin.py" app-codex allinea >/dev/null 2>&1 || true
+ DELMINIO_APP_CODEX=$(python3 "$(dirname "$0")/plugin.py" app-codex stato 2>/dev/null || true)
+ fi
+ export DELMINIO_APP_CODEX
+ senza=""; [ "$cli" = claude ] || senza=1
+ 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")
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ if [ -n "$pid" ] && [ -z "${DELMINIO_PROVA:-}" ]; then
+ sorgente=$(printf '%s' "$evento" | campo source)
+ sid=$(printf '%s' "$evento" | campo session_id)
+ if [ -n "$sid" ] && { [ "$sorgente" = fork ] || in_sottofondo "$pid"; }; then
+ rm -f "$STATO/sessione-$pid"
+ printf '%s' "$sid" > "$STATO/nasci-$pid"
+ if [ "$sorgente" = fork ]; then madri_del_fork "$evento" "$sid" > "$STATO/fork-$pid"; else rm -f "$STATO/fork-$pid"; fi
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$M_nasce_al_primo"
+ exit 0
+ fi
+ fi
+ if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
+ GIT_TERMINAL_PROMPT=0 _tempo 5 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true
+ fi
+ if [ -n "$pid" ]; then fatti=$(fatti_nascita "$pid" "$evento")
+ else fatti=$(fatti_codex "$cli" "$evento" "$fatti"); fi
+ cure
+ if r=$(chiedi POST /api/apertura "$fatti"); then
+ [ "$cli" != codex ] || [ -z "$pid" ] || [ -n "${DELMINIO_PROVA:-}" ] || segna_informativa_codex "$r"
+ nome=$(printf '%s' "$r" | campo sessione); stato=$(printf '%s' "$r" | campo stato)
+ if [ -n "$pid" ] && [ -n "$nome" ]; then
+ rm -f "$STATO/nasci-$pid"
+ if [ "$stato" = chiusa ]; then
+ rm -f "$STATO/sessione-$pid"
+ [ "$(printf '%s' "$r" | campo al_primo_messaggio)" = True ] && \
+ printf '%s' "$evento" | campo session_id > "$STATO/nasci-$pid"
+ else
+ printf '%s' "$nome" > "$STATO/sessione-$pid"
+ zitta_la_prima "$r" "$pid"
+ _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
+ fi
+ fi
+ serve=$(printf '%s' "$r" | campo versione)
+ ra=$(riaggancio_stato "$(git rev-parse --show-toplevel 2>/dev/null)")
+ indietro=""
+ if [ -z "${DELMINIO_PROVA:-}" ] && [ -n "$serve" ] && [ "$serve" != "${KIT:-}" ] && [ -s "$ra.log" ] \
+ && [ "$(cat "$ra.verso" 2>/dev/null)" = "$serve" ] \
+ && [ $(( $(date +%s) - $(_mtime "$ra.log") )) -gt 120 ]; then # più giovane: è ancora in corsa
+ indietro=$(_f "$M_client_fermo" kit "${KIT:-?}" serve "$serve" errore "$(grep -v '^[[:space:]]*$' "$ra.log" | tail -1 | cut -c1-200)")
+ fi
+ riaggancia "$serve" "$(git rev-parse --show-toplevel 2>/dev/null)"
+ fratelli_indietro "$serve"
+ voluto=$(printf '%s' "$r" | campo eseguibili)
+ eseguibili_indietro "$voluto" giorno && allinea_staccato
+ skill_staccato
+ pubblico_segna "$r"
+ printf '%s' "$r" | DELMINIO_INDIETRO="$indietro" python3 -c 'import json,os,sys
+h = json.load(sys.stdin)["hookSpecificOutput"]
+if os.environ.get("DELMINIO_INDIETRO"):
+ h["additionalContext"] = os.environ["DELMINIO_INDIETRO"] + "\n\n" + h.get("additionalContext", "")
+print(json.dumps({"hookSpecificOutput": h}))'
+ exit 0
+ fi
+ perche=$(perche_no)
+ riprova=""
+ if [ -n "$pid" ]; then
+ sid=$(printf '%s' "$evento" | campo session_id)
+ [ -n "$sid" ] && printf '%s' "$sid" > "$STATO/nasci-$pid" && riprova=$M_riprova_al_primo
+ fi
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": sys.argv[1]}}))' "$(_f "$M_nasce_senza_memoria" perche "$perche" riprova "$riprova")"
+ [ -z "${DELMINIO_PROVA:-}" ] || exit 3
+ ;;
+ cuore)
+ pid="$2"; processo="$3"
+ io="$STATO/cuore-$pid"
+ altro=$(cat "$io" 2>/dev/null || true)
+ [ -n "$altro" ] && [ "$altro" != "$$" ] && kill -0 "$altro" 2>/dev/null && exit 0
+ echo "$$" > "$io"
+ spazza_stato
+ albero=$(git rev-parse --show-toplevel 2>/dev/null || true)
+ P=$(json_stringa "$processo")
+ fresco() { [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ] && \
+ GIT_TERMINAL_PROMPT=0 _tempo 20 git -C "$MEMORIA" pull -q --ff-only >/dev/null 2>&1 || true; }
+ principale=$(dirname "$(_assoluto "$(git rev-parse --git-common-dir 2>/dev/null)")")
+ riservo() {
+ local r b corpo rif nome
+ [ -n "$principale" ] && [ "$principale" != . ] || return 0
+ r=$(chiedi GET /api/riservo) || return 0
+ b="${XDG_DATA_HOME:-$HOME/.local/share}/delminio/$(printf '%s' "$principale" | _sha16)"
+ printf '%s' "$r" | (umask 077; python3 -c '
+import hashlib, json, os, re, shutil, sys
+b = sys.argv[1]
+r = json.load(sys.stdin)
+ist, rad = r.get("istanza") or "", r.get("radice") or ""
+if not rad:
+ sys.exit(0)
+d = os.path.join(b, rad[:16], "riservo")
+def leggi(p):
+ try:
+ return open(p, encoding="utf-8").read().strip()
+ except OSError:
+ return ""
+if not os.path.isdir(d) and ist and leggi(os.path.join(b, "riservo", "istanza")) == ist:
+ os.makedirs(os.path.dirname(d), exist_ok=True)
+ os.rename(os.path.join(b, "riservo"), d)
+def nome_file(n):
+ return (re.sub(r"[^a-z0-9]+", "_", n.lower()).strip("_")[:60] or "memoria") + "-" + hashlib.sha1(n.encode()).hexdigest()[:8] + ".md"
+def nome_md(testo):
+ m = re.search(r"^name:\s*(.+?)\s*$", testo, re.M)
+ v = m.group(1) if m else ""
+ try:
+ return json.loads(v) if v.startswith("\"") else v.strip("\x27")
+ except ValueError:
+ return v
+remoti = {k: {m["name"] for m in r.get(k) or []} for k in ("personali", "riservate")}
+if leggi(os.path.join(d, "radice")) == rad:
+ rif = os.path.join(d, "rifiutate")
+ no = set(leggi(rif).splitlines())
+ manca = []
+ for k in ("personali", "riservate"):
+ cart = os.path.join(d, k)
+ for f in sorted(os.listdir(cart)) if os.path.isdir(cart) else []:
+ testo = open(os.path.join(cart, f), encoding="utf-8").read()
+ n = nome_md(testo)
+ if n and n not in remoti[k] and n not in no:
+ manca.append(rif + "\t" + n + "\t" + json.dumps({"md": testo, "riservata": k == "riservate", "radice": rad}, ensure_ascii=False))
+ if manca:
+ print("\n".join(manca))
+ sys.exit(0)
+nuova = d + ".nuova"
+shutil.rmtree(nuova, ignore_errors=True)
+for k in ("personali", "riservate"):
+ os.makedirs(os.path.join(nuova, k))
+ for m in r.get(k) or []:
+ with open(os.path.join(nuova, k, nome_file(m["name"])), "w", encoding="utf-8") as f:
+ f.write(m["md"])
+for n, v in (("istanza", ist), ("radice", rad)):
+ with open(os.path.join(nuova, n), "w", encoding="utf-8") as f:
+ f.write(v)
+os.makedirs(os.path.dirname(d), exist_ok=True)
+vecchia = d + ".vecchia"
+shutil.rmtree(vecchia, ignore_errors=True)
+if os.path.isdir(d):
+ os.rename(d, vecchia)
+os.rename(nuova, d)
+shutil.rmtree(vecchia, ignore_errors=True)
+' "$b") | { umask 077; while IFS=$'\t' read -r rif nome corpo; do
+ if r=$(chiedi POST /api/riservo/riporta "$corpo"); then
+ printf '%s' "$r" | grep -q '"riportata": *false' && printf '%s\n' "$nome" >> "$rif"
+ else
+ case $(cut -f1 "$STATO/no-$$" 2>/dev/null) in 400|409) printf '%s\n' "$nome" >> "$rif" ;; esac
+ fi
+ done; }
+ }
+ giri=0
+ provata="" # l'impronta che questo cuore ha già provato ad allineare: una volta sola
+ passo=${DELMINIO_CUORE_SECONDI:-20}
+ case $passo in ''|*[!0-9]*|0) passo=20 ;; esac
+ while kill -0 "$pid" 2>/dev/null; do
+ vero=$(albero_di "$(mia_sessione "$pid")"); [ -n "$vero" ] && albero="$vero"
+ A=$(json_stringa "$albero")
+ b=$(chiedi POST /api/canale/battito "{\"processo\":$P,\"cuore\":true,\"albero\":$A}" || true)
+ voluto=$(printf '%s' "$b" | campo eseguibili)
+ if [ -n "$voluto" ] && [ "$voluto" != "$provata" ] && eseguibili_indietro "$voluto"; then
+ provata=$voluto
+ allinea_staccato
+ fi
+ giri=$((giri + 1)); [ $((giri % 15)) -eq 0 ] && fresco
+ { [ "$giri" -eq 1 ] || [ $((giri % 15)) -eq 0 ]; } && { cure; testi; repo_stato; riservo; }
+ sleep "$passo"
+ done
+ fresco
+ lascito=""
+ [ -n "$albero" ] && [ -x "$albero/.delminio/lascito.sh" ] && \
+ python3 -c 'import os,sys
+exec(os.environ["DELMINIO_FIDATI_PY"])
+a, f = sys.argv[1:]
+sys.exit(0 if da_fidarsi(a, f, accettati(a)) else 1)' "$albero" "$albero/.delminio/lascito.sh" 2>/dev/null && \
+ lascito=$(_tempo 30 bash "$albero/.delminio/lascito.sh" "$pid" "$albero" 2>/dev/null | head -c 1500 || true)
+ if [ -z "$lascito" ]; then
+ lascito="$M_nessun_albero"
+ if [ -n "$albero" ]; then
+ n=$(git -C "$albero" status --porcelain 2>/dev/null | grep -c . || true)
+ if [ "${n:-0}" -gt 0 ]; then lascito=$(_f "$M_albero_sporco" albero "$albero" n "$n")
+ else lascito=$(_f "$M_albero_pulito" albero "$albero"); fi
+ fi
+ fi
+ L=$(json_stringa "$lascito")
+ chiedi POST /api/sessioni/muori "{\"processo\":$P,\"lascito\":$L}" >/dev/null || true
+ rm -f -- "$STATO"/*-"$pid"
+ ;;
+ segreto)
+ python3 -c '
+import json, re, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+try:
+ p = json.load(sys.stdin).get("prompt") or ""
+except Exception:
+ sys.exit(0)
+if re.search(r"eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{16,}|DELMINIO_TOKEN=\S", p):
+ sys.stderr.write(F("chiave_nel_messaggio"))
+ sys.exit(2)
+'
+ exit $?
+ ;;
+ umano|volo|attesa)
+ if [ "$1" = volo ]; then
+ ev=$(_tempo 2 cat 2>/dev/null || true)
+ if [[ $ev =~ \"session_id\":\ ?\"([A-Za-z0-9_.-]+)\" ]]; then
+ presto="$STATO/volo-sid-${BASH_REMATCH[1]}"
+ [ -f "$presto" ] && [ $(( $(date +%s) - $(_mtime "$presto") )) -lt 10 ] && exit 0
+ touch "$presto"
+ fi
+ fi
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ headless "$pid" && exit 0
+ if e_qwen "$pid" && [ "$1" = umano ]; then
+ letto=""; [ -t 0 ] || letto=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$(printf '%s' "$letto" | campo prompt)" ] || exit 0
+ fi
+ if e_codex "$pid" || e_qwen "$pid" || e_opencode "$pid"; then
+ if [ "$1" = attesa ]; then
+ sid=$(_tempo 2 cat 2>/dev/null | campo session_id || true)
+ if [ -n "$sid" ]; then
+ _staccato bash "$0" attesa-codex "$pid" "$sid" >/dev/null 2>&1 < /dev/null &
+ fi
+ echo '{}'; exit 0
+ fi
+ [ "$1" = umano ] && { v=$(cat "$STATO/attesa-$pid" 2>/dev/null || true); [ -n "$v" ] && kill "$v" 2>/dev/null; rm -f "$STATO/attesa-$pid"; }
+ fi
+ if [ "$1" = volo ]; then
+ if grep -q '"agent_id"' <<<"$ev" && [ -n "$(printf '%s' "$ev" | campo agent_id)" ]; then exit 0; fi
+ fi
+ if [ "$1" = umano ] && [ -f "$STATO/nasci-$pid" ]; then
+ evento=${letto:-}; [ -n "$evento" ] || [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ if [ "$(printf '%s' "$evento" | campo session_id)" != "$(cat "$STATO/nasci-$pid" 2>/dev/null)" ]; then
+ rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
+ elif madri=$(cat "$STATO/fork-$pid" 2>/dev/null || true) \
+ && { [ ! -f "$STATO/fork-$pid" ] || [ "$madri" != '[]' ] || madri=$(madri_del_fork "$evento" "$(cat "$STATO/nasci-$pid")"); } \
+ && r=$(chiedi POST /api/apertura "$(DELMINIO_MADRI="$madri" fatti_nascita "$pid" "$evento" si)"); then
+ e_codex "$pid" && segna_informativa_codex "$r"
+ rm -f "$STATO/nasci-$pid" "$STATO/fork-$pid"
+ nome=$(printf '%s' "$r" | campo sessione)
+ case "$(printf '%s' "$r" | campo stato)" in nuova|ripresa|adottata)
+ if [ -n "$nome" ]; then
+ printf '%s' "$nome" > "$STATO/sessione-$pid"
+ zitta_la_prima "$r" "$pid"
+ _staccato bash "$0" cuore "$pid" "$(hostname):$pid" >/dev/null 2>&1 < /dev/null &
+ printf '%s' "$r" | python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": json.load(sys.stdin)["hookSpecificOutput"]}))'
+ exit 0
+ fi ;;
+ esac
+ fi
+ fi
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ if [ "$1" = volo ]; then
+ ultima="$STATO/volo-$pid"
+ [ -f "$ultima" ] && [ $(( $(date +%s) - $(_mtime "$ultima") )) -lt 10 ] && exit 0
+ touch "$ultima"
+ fi
+ N=$(json_stringa "$nome")
+ albero=$(albero_di "$nome")
+ A=$(json_stringa "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}")
+ giri=0
+ if [ "$1" = attesa ]; then
+ io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
+ [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
+ echo "$$" > "$io"
+ fi
+ avviso=""
+ while :; do
+ somme=$(_conto_somme)
+ voci=$(_skill_voci)
+ if [ -n "$voci" ]; then
+ cli=claude; e_codex "$pid" && cli=codex; e_qwen "$pid" && cli=qwen; e_opencode "$pid" && cli=opencode
+ voci=",\"cli\":\"$cli\",\"skill\":[$voci]"
+ fi
+ if b=$(chiedi POST /api/canale/battito "{\"sessione\":$N,\"albero\":$A${somme:+,\"ganci\":{$somme\}}$voci}"); then
+ rm -f "$STATO/posta-muta-$pid"
+ case "$b" in *'"carta":true'*) : > "$STATO/carta"; rm -f "$STATO/carta-no" ;;
+ *) rm -f "$STATO/carta"; : > "$STATO/carta-no" ;; esac
+ ultimo=$(printf '%s' "$b" | campo ultimo)
+ [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}"
+ else
+ ultimo=""
+ if [ "$1" = umano ] && [ ! -f "$STATO/posta-muta-$pid" ]; then
+ touch "$STATO/posta-muta-$pid"
+ avviso=$(_f "$M_posta_non_arriva" perche "$(perche_no)")
+ fi
+ fi
+ cursore="$STATO/visto-$pid"; [ "$1" = attesa ] && cursore="$STATO/visto-attesa-$pid"
+ if [ -n "$ultimo" ] && [ "$(cat "$cursore" 2>/dev/null)" != "$ultimo" ] \
+ && t=$(chiedi GET "/api/canale/posta/testo?sessione=$nome&momento=$1"); then
+ printf '%s' "$ultimo" > "$cursore"
+ testo=$(printf '%s' "$t" | campo testo)
+ [ -n "$testo" ] && printf '%s' "$ultimo" > "$STATO/visto-$pid"
+ if [ -n "$testo" ]; then
+ if [ "$1" != attesa ]; then
+ evento=PostToolUse; [ "$1" = umano ] && evento=UserPromptSubmit
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": sys.argv[1], "additionalContext": sys.stdin.read()}}))' "$evento" <<<"$testo"
+ exit 0
+ fi
+ printf '%s\n' "$testo" >&2; exit 2
+ fi
+ fi
+ if [ -n "$avviso" ]; then
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.argv[1]}}))' "$avviso"
+ exit 0
+ fi
+ [ "$1" != attesa ] && exit 0
+ kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ] || exit 0
+ giri=$((giri + 1))
+ sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
+ done
+ ;;
+ consumi|consumi-tool)
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ passo="$STATO/consumi-$pid"
+ if [ "$1" = consumi-tool ] && [ -f "$passo" ] && [ $(( $(date +%s) - $(_mtime "$passo") )) -lt 30 ]; then exit 0; fi
+ touch "$passo"
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$evento" ] || exit 0
+ printf '%s' "$evento" > "$STATO/consumi-evento-$pid"
+ _staccato bash "$0" consumi-manda "$pid" "$nome" >/dev/null 2>&1 < /dev/null &
+ exit 0
+ ;;
+ consumi-manda)
+ exec 9>"$STATO/consumi-lock-$2"
+ command -v flock >/dev/null 2>&1 && { flock -w 10 9 || exit 0; }
+ evento=$(cat "$STATO/consumi-evento-$2" 2>/dev/null)
+ corpo=$(consumi_dal_transcript "$STATO/consumi-stato-$2" "$evento")
+ [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
+ corpo=$(totale_cli_qwen "$evento")
+ [ -z "$corpo" ] || CHIEDI_TEMPO=5 chiedi POST /api/canale/battito "{\"sessione\":$(json_stringa "$3"),\"consumi\":$corpo}" >/dev/null 2>&1 || true
+ ;;
+ memorie)
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ headless "$pid" && exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ modello_dal_transcript "$pid" "$nome" "$evento"
+ if [ -f "$STATO/carta" ] || [ ! -f "$STATO/carta-no" ]; then
+ printf '%s' "$evento" | carta_richiesta "$nome"
+ fi
+ corpo=$(printf '%s' "$evento" | python3 -c '
+import json, os, sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+testo = (e.get("prompt") or "").strip()
+if not testo:
+ sys.exit(0)
+
+def risposta(ev):
+ if not isinstance(ev, dict):
+ return ""
+ if ev.get("type") == "response_item":
+ p = ev.get("payload") or {}
+ if p.get("type") == "message" and p.get("role") == "assistant":
+ return "\n".join(b.get("text", "") for b in p.get("content") or []
+ if isinstance(b, dict) and b.get("type") == "output_text").strip()
+ return ""
+ if ev.get("type") != "assistant" or not isinstance(ev.get("message"), dict):
+ return ""
+ m = ev["message"]
+ if m.get("parts") is not None:
+ return "\n".join(x.get("text", "") for x in m["parts"] if isinstance(x, dict)
+ and isinstance(x.get("text"), str) and not x.get("thought")).strip()
+ return "\n".join(b.get("text", "") for b in m.get("content") or []
+ if isinstance(b, dict) and b.get("type") == "text").strip()
+
+coda = e.get("coda") if isinstance(e.get("coda"), str) else ""
+try:
+ with open("" if coda else (e.get("transcript_path") or ""), "rb") as f:
+ f.seek(0, os.SEEK_END)
+ f.seek(max(0, f.tell() - 2_000_000))
+ for riga in reversed(f.read().decode("utf-8", "replace").splitlines()):
+ try:
+ coda = risposta(json.loads(riga))
+ except ValueError:
+ continue
+ if coda:
+ break
+except OSError:
+ pass
+print(json.dumps({"testo": testo[:1500], "coda": coda[-1200:]}, ensure_ascii=False))
+' 2>/dev/null || true)
+ [ -n "$corpo" ] || exit 0
+ r=$(CHIEDI_TEMPO=2 CHIEDI_SESSIONE="$nome" chiedi POST /api/memorie/messaggio "$corpo") || exit 0
+ testo=$(printf '%s' "$r" | campo testo)
+ [ -n "$testo" ] || exit 0
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext": sys.stdin.read()}}))' <<<"$testo"
+ ;;
+ rito)
+ pid=$(cli_pid || true); [ -n "$pid" ] && { e_codex "$pid" || e_qwen "$pid"; } || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ rito=$(printf '%s' "$evento" | python3 -c 'import json,re,sys
+try:
+ p = (json.load(sys.stdin).get("prompt") or "").strip()
+except Exception:
+ sys.exit(0)
+prima, _, resto = p.partition("\n")
+riti = json.loads(__import__("os").environ.get("DELMINIO_COMANDI") or "{}").get("riti") or {"apertura": "apertura", "chiusura": "chiusura"}
+nomi = "|".join(re.escape(n) for n in sorted(riti, key=len, reverse=True))
+m = (re.fullmatch(r"/(" + nomi + r")(?:\s+(.*))?", prima.strip(), re.I | re.S)
+ or re.fullmatch(r"(" + nomi + r")\s*(?::\s*(.*))?", prima.strip(), re.I | re.S))
+if m and re.match(r"/" + m.group(1) + r"\b", resto.strip(), re.I):
+ resto = resto.strip()[len(m.group(1)) + 1:]
+if m:
+ 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)
+ [ -n "$rito" ] || exit 0
+ parola=${rito%%$'\t'*}; dopo=${rito#*$'\t'}
+ if [ "$parola" = apertura ]; then testo=$(bash "$0" prompt); else testo=$(bash "$0" chiusura "$dopo"); fi
+ python3 -c 'import json,sys
+print(json.dumps({"hookSpecificOutput": {"hookEventName": "UserPromptSubmit", "additionalContext":
+ sys.argv[1] + "\n\n" + sys.stdin.read()}}))' "$(_f "$M_gesto_umano" parola "$parola")" <<<"$testo"
+ ;;
+ ritira-file)
+ echo "$$" > "$STATO/ritiro-$2"
+ ritira_file "$2" "$3"
+ rm -f "$STATO/ritiro-$2"
+ ;;
+ invia)
+ f=${2:-}; nota=${3:-}
+ [ -n "$f" ] || { echo "$M_invia_uso" >&2; exit 1; }
+ [ -f "$f" ] && [ -r "$f" ] || { _f "$M_invia_non_trovato" file "$f" >&2; exit 1; }
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { echo "$M_invia_senza_sessione" >&2; exit 1; }
+ tipo=$(python3 -c 'import mimetypes, sys; print(mimetypes.guess_type(sys.argv[1])[0] or "application/octet-stream")' "$f")
+ q="verso=persona&sessione=$(_urlenc "$nome")&nome=$(_urlenc "$(basename "$f")")¬a=$(_urlenc "$nota")"
+ r=$(curl -sS -m 900 -w '\n%{http_code}' -K <(_chiave "$TOKEN") -H "Content-Type: $tipo" \
+ --data-binary @"$f" "$URL/api/file?$q" 2>/dev/null)
+ c=${r##*$'\n'}; r=${r%$'\n'*}
+ if [ "$c" != 200 ]; then
+ e=$(printf '%s' "$r" | campo error); _f "$M_invia_fallito" perche "${e:-HTTP ${c:-000}}" >&2; exit 1
+ fi
+ _f "$M_invia_fatto" nome "$(printf '%s' "$r" | campo nome)"
+ ;;
+ attesa-codex)
+ pid=$2; sid=$3
+ [ -n "$sid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ io="$STATO/attesa-$pid"; vecchio=$(cat "$io" 2>/dev/null || true)
+ [ -n "$vecchio" ] && [ "$vecchio" != "$$" ] && kill "$vecchio" 2>/dev/null
+ echo "$$" > "$io"
+ N=$(json_stringa "$nome")
+ giri=0
+ albero=$(albero_di "$nome"); albero=${albero:-$(git rev-parse --show-toplevel 2>/dev/null || true)}
+ while kill -0 "$pid" 2>/dev/null && [ "$(cat "$io" 2>/dev/null)" = "$$" ]; do
+ b=$(chiedi POST /api/canale/battito "{\"sessione\":$N}" || true)
+ ultimo=$(printf '%s' "$b" | campo ultimo)
+ [ -n "$(printf '%s' "$b" | campo file)" ] && avvia_ritiro "$nome" "$albero"
+ if [ -n "$ultimo" ] && [ "$ultimo" != "${guardato:-}" ] \
+ && [ "$(cat "$STATO/visto-$pid" 2>/dev/null)" != "$ultimo" ] \
+ && [ "$(cat "$STATO/avvisato-$pid" 2>/dev/null)" != "$ultimo" ]; then
+ guardato=$ultimo
+ per_lei=$(chiedi GET "/api/canale/posta?sessione=$nome&segna=0" | python3 -c 'import json,sys
+try:
+ r = json.load(sys.stdin); print(r["sveglie"] if "sveglie" in r else len(r.get("messaggi") or []))
+except Exception: print(0)')
+ [ "${per_lei:-0}" -gt 0 ] || { giri=$((giri + 1)); sleep 3; continue; }
+ avviso_posta=$M_posta_arrivata
+ if e_opencode "$pid"; then
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ printf '%s\n' "$avviso_posta"
+ elif e_qwen "$pid"; then
+ f="${DELMINIO_QWEN_POSTA:-}"
+ 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
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ fi
+ elif "${DELMINIO_CLI:-codex}" queue --thread "$sid" --message "$avviso_posta" >/dev/null 2>&1; then
+ printf '%s' "$ultimo" > "$STATO/avvisato-$pid"
+ fi
+ rm -f "$io"; exit 0
+ fi
+ giri=$((giri + 1))
+ sleep $(( giri < 40 ? 3 : (giri < 80 ? 15 : 30) ))
+ done
+ ;;
+ prompt)
+ porta="${DELMINIO_PORTA:-${DELMINIO_MODELLO:-}}"
+ r=$(curl -sS -m 15 -G -w '\n%{http_code}' -K <(_chiave "$TOKEN") \
+ --data-urlencode "ordine=$porta" --data-urlencode "sistema=$([ -n "${DELMINIO_SISTEMA:-}" ] && echo 1 || echo 0)" \
+ "$URL/api/porte/prompt" 2>/dev/null)
+ codice=${r##*$'\n'}
+ case "$codice" in
+ ''|000) _f "$M_delminio_risponde_prompt" url "$URL" ;;
+ 200) printf '%s\n' "${r%$'\n'*}" ;;
+ *) e=$(printf '%s' "${r%$'\n'*}" | campo error 2>/dev/null || true)
+ _f "$M_prompt_rifiutato" url "$URL" codice "$codice" errore "${e:+: $e}" ;;
+ esac
+ ;;
+ claude|codex|app-codex|qwen|opencode)
+ parte lanciatori.sh && . "$(dirname "$0")/lanciatori.sh" "$@"
+ ;;
+ cassaforte)
+ shift
+ python3 "$(cd "$(dirname "$0")" && pwd)/cassaforte.py" "$@"
+ ;;
+ eseguibili|eseguibile)
+ shift
+ [ $# -eq 0 ] && set -- allinea
+ python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" --url "$URL" --token-file "$FILE_TOKEN" --modo kit "$@"
+ ;;
+ condiviso)
+ evento=$(cat)
+ if [[ $evento == *'cd '* || $evento == *workdir* || $evento == *exec_command* || $evento == *rollout-* ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ dove=$(printf '%s' "$evento" | campo cwd)
+ radice=$(git -C "${dove:-.}" rev-parse --show-toplevel 2>/dev/null) || radice=""
+ if [ -z "$radice" ] || [ ! -f "$radice/.delminio/condivisi" ]; then
+ radice=$(git rev-parse --show-toplevel 2>/dev/null) || exit 0
+ fi
+ [ -f "$radice/.delminio/condivisi" ] || exit 0
+ corpo=$(printf '%s' "$evento" | python3 -c '
+import json, re, sys
+try:
+ c = (json.load(sys.stdin).get("tool_input") or {}).get("command") or ""
+except Exception:
+ c = ""
+for r in open(sys.argv[1], encoding="utf-8"):
+ r = r.strip()
+ if c and r and not r.startswith("#"):
+ try:
+ if re.search(r, c, re.I):
+ print(json.dumps({"sessione": sys.argv[2], "comando": c}))
+ break
+ except re.error:
+ pass' "$radice/.delminio/condivisi" "")
+ [ -n "$corpo" ] || exit 0
+ pid=$(cli_pid || true); [ -n "$pid" ] || exit 0
+ nome=$(mia_sessione "$pid"); [ -n "$nome" ] || exit 0
+ tregua="$STATO/condiviso-$pid"
+ if [ -f "$tregua" ] && [ $(( $(date +%s) - $(_mtime "$tregua") )) -lt 600 ]; then exit 0; fi
+ corpo=$(printf '%s' "$corpo" | python3 -c 'import json,sys; d = json.load(sys.stdin); d["sessione"] = sys.argv[1]; print(json.dumps(d))' "$nome")
+ [ -n "$corpo" ] || exit 0
+ r=$(chiedi POST /api/condiviso "$corpo") || exit 0
+ if DELMINIO_R="$r" python3 -c 'import json,os,sys
+r = json.loads(os.environ["DELMINIO_R"])
+if r.get("ferma"):
+ print(r.get("testo", ""), file=sys.stderr)
+ sys.exit(2)'; then exit 0; fi
+ touch "$tregua"; exit 2
+ ;;
+ gesto)
+ evento=$(cat)
+ strumento=""; [[ $evento =~ \"tool_name\":\ ?\"([^\"]+)\" ]] && strumento=${BASH_REMATCH[1]}
+ case "$strumento" in Bash|exec_command|run_shell_command|"") di_shell=1 ;; *) di_shell="" ;; esac
+ if [ -z "$di_shell" ]; then
+ globi=$(strumenti_vivi) && [ -n "$globi" ] || exit 0
+ combacia=""; shopt -s nocasematch
+ while IFS= read -r g; do
+ [ -n "$g" ] && [[ $strumento == $g ]] && { combacia=1; break; }
+ done <<<"$globi"
+ shopt -u nocasematch
+ [ -n "$combacia" ] || exit 0
+ fi
+ dove_fatto=""
+ if [ -n "$di_shell" ] && [[ $evento == *'"workdir"'* || $evento =~ \"command\":\ ?\"[[:space:]]*cd[[:space:]] ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
+ fi
+ gira="$PWD"; [[ $evento =~ \"cwd\":\ ?\"([^\"]+)\" ]] && gira=${BASH_REMATCH[1]}
+ repo_gesto=$(_remoto "$gira" || true)
+ corpo=$(printf '%s' "$evento" | python3 -c 'import json,sys
+try:
+ e = json.load(sys.stdin)
+ c = (e.get("tool_input") or {}).get("command") or "" if sys.argv[1] else ""
+except Exception:
+ c = ""
+d = {"comando": c} if c else {}
+if sys.argv[2]:
+ d["strumento"] = sys.argv[2]
+if d and sys.argv[3]:
+ d["repo"] = sys.argv[3]
+print(json.dumps(d) if d else "")' "$di_shell" "$strumento" "$repo_gesto")
+ [ -n "$corpo" ] || exit 0
+ r=$(chiedi POST /api/lock "$corpo") || exit 0
+ [[ $r == *'"lock":[]}' || $r == *'"lock": []}' ]] && exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ detti="${pid:+$STATO/lock-detti-$pid}"
+ if [ -z "$dove_fatto" ] && [[ $r =~ \"comando_gesto\":\ ?\"[^\"] ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ read -r -d '' _gesto_py <<'GESTO' || true
+import hashlib, json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+detti_f = sys.argv[1]
+try:
+ detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
+except OSError:
+ detti = set()
+lock = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
+ATTESA_DI_SERIE = 5 # B938: come lock.ATTESA_DI_SERIE nel motore
+evento = sys.stdin.read()
+try:
+ accettate = set(open(os.environ.get("DELMINIO_ACCETTATE") or "", encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+nuovi_detti = []
+
+
+def una_volta(segno, testo):
+ if segno not in detti and segno not in nuovi_detti:
+ nuovi_detti.append(segno)
+ print("dire", json.dumps(testo))
+
+
+def cieco(l, motivo, secondi):
+ """B938 — il controllo non ha detto niente: si conta sempre. In una decisione che
+ blocca, se non parte (o è lento e la decisione lo vuole) il comando si ferma come per
+ una violazione: decide il motore (l'amministratore passa con un avviso). Se no passa."""
+ cmd = l["comando_gesto"]
+ print("cieco", l["codice"], motivo)
+ if l.get("duro") and (motivo == "non_parte" or l.get("se_lento")):
+ if motivo == "non_parte":
+ fermo = F("gesto_controllo_non_parte_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd)
+ breve = F("controllo_non_parte_breve", comando=cmd)
+ else:
+ fermo = F("gesto_controllo_lento_fermo", codice=l["codice"], cosa=l["cosa"], comando=cmd, secondi=secondi)
+ breve = F("controllo_lento_breve", comando=cmd, secondi=secondi)
+ print("viola_cieco", json.dumps({"codice": l["codice"], "breve": breve, "fermo": fermo}))
+ return
+ if motivo == "non_parte":
+ una_volta("?" + l["codice"], F("gesto_controllo_non_parte_passa", codice=l["codice"], comando=cmd))
+ else:
+ una_volta("?" + l["codice"], F("gesto_controllo_lento_passa", codice=l["codice"], comando=cmd, secondi=secondi))
+
+
+def prova(l):
+ """Il controllo di una decisione prima del comando: (gridato, uscita) o None se
+ non ha potuto dire niente — e allora l'ha già detto, o l'ha passato a ``cieco``."""
+ cmd = l["comando_gesto"]
+ impronta = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + cmd).encode()).hexdigest()
+ if impronta not in accettate:
+ una_volta("?" + l["codice"], F("gesto_controllo_non_accettato", codice=l["codice"], cosa=l["cosa"], comando=cmd))
+ return None
+ try:
+ e = json.loads(evento)
+ except ValueError:
+ e = {}
+ dove = str(e.get("cwd") or "")
+ radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True,
+ cwd=dove if os.path.isdir(dove) else None).stdout.strip() or "."
+ comando = str((e.get("tool_input") or {}).get("command") or "")
+ amb = {**os.environ, "DELMINIO_CWD": str(e.get("cwd") or os.getcwd())}
+ if len(comando) < 100000:
+ amb["DELMINIO_COMANDO"] = comando
+ secondi = int(l.get("attesa") or 0) or ATTESA_DI_SERIE
+ try:
+ p = subprocess.run(cmd, shell=True, cwd=radice, input=evento, capture_output=True, text=True,
+ timeout=secondi, env=amb)
+ except subprocess.TimeoutExpired:
+ cieco(l, "lento", secondi)
+ return None
+ except OSError:
+ p = None
+ if p is None or p.returncode in (126, 127):
+ cieco(l, "non_parte", secondi)
+ return None
+ return p.returncode != 0, (p.stdout + p.stderr).strip()
+
+
+for l in lock:
+ if l.get("comando_gesto"):
+ esito = prova(l)
+ if not esito or not esito[0]:
+ continue
+ uscita = esito[1]
+ if l.get("duro"):
+ print("viola", l["codice"], json.dumps(uscita[-3000:]))
+ else:
+ righe = "".join("\n " + r for r in uscita.splitlines()[-15:])
+ testo = F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"])
+ print("dire", json.dumps(testo + ("\n" + F("guardia_dice") + righe if righe else "")))
+ print("conta", l["codice"])
+ continue
+ if l.get("duro"):
+ print("duro", l["codice"])
+ else:
+ una_volta(l["codice"], F("lock_del_comando", codice=l["codice"], cosa=l["cosa"], perche=l["perche"]))
+if nuovi_detti and detti_f:
+ with open(detti_f, "a", encoding="utf-8") as f:
+ f.write("".join(x + "\n" for x in nuovi_detti))
+GESTO
+ piano=$(printf '%s' "$evento" | DELMINIO_LOCK="$r" DELMINIO_ACCETTATE="$(accettate_file 2>/dev/null)" python3 -c "$_gesto_py" "$detti")
+ [ -n "$piano" ] || exit 0
+ contesto=""; impronta=$(chiave_in_uso)
+ descr=$(printf '%s' "$evento" | python3 -c 'import json,sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ e = {}
+t = e.get("tool_input") or {}
+if sys.argv[1]:
+ print("comando: " + str(t.get("command") or ""), end="")
+else:
+ print("strumento: " + sys.argv[2] + " · " + json.dumps(t, ensure_ascii=False)[:300], end="")' "$di_shell" "$strumento")
+ sullo_strumento=false; [ -z "$di_shell" ] && sullo_strumento=true
+ while read -r tipo resto; do
+ case "$tipo" in
+ dire) contesto="$contesto$(python3 -c 'import json,sys; print(json.loads(sys.argv[1]))' "$resto")"$'\n' ;;
+ duro)
+ 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")
+ v=$(chiedi POST /api/lock/violazione "$corpo") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ if [ "$esito" = ferma ]; then echo "🔒 $msg" >&2; exit 2; fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n' ;;
+ cieco)
+ 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")
+ CHIEDI_TEMPO=2 chiedi POST /api/lock/cieco "$corpo_k" >/dev/null 2>&1 || true ;;
+ viola_cieco)
+ corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
+c = json.loads(sys.argv[1])
+print(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")
+ v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ if [ "$esito" = ferma ]; then
+ printf '%s' "$resto" | campo fermo >&2
+ echo "🔒 $msg" >&2; exit 2
+ fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg"$'\n'"$(printf '%s' "$resto" | campo breve)"$'\n' ;;
+ conta)
+ 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")
+ CHIEDI_TEMPO=2 chiedi POST /api/lock/violazione "$corpo_c" >/dev/null 2>&1 || true ;;
+ viola)
+ corpo_v=$(printf '%s' "$descr" | IMPRONTA="$impronta" python3 -c 'import json,os,sys
+codice, uscita = sys.argv[1].split(" ", 1)
+uscita = json.loads(uscita)
+print(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")
+ v=$(chiedi POST /api/lock/violazione "$corpo_v") || continue
+ esito=$(printf '%s' "$v" | campo esito); msg=$(printf '%s' "$v" | campo messaggio)
+ dice=$(printf '%s' "$resto" | python3 -c 'import json,sys
+_, u = sys.stdin.read().split(" ", 1)
+print("".join("\n " + r for r in json.loads(u).splitlines()[-15:]), end="")')
+ if [ "$esito" = ferma ]; then printf '🔒 %s%s\n' "$msg" "${dice:+$'\n'$M_guardia_dice$dice}" >&2; exit 2; fi
+ [ -n "$msg" ] && contesto="$contesto🔒 $msg${dice:+$'\n'$M_guardia_dice$dice}"$'\n' ;;
+ esac
+ done <<<"$piano"
+ [ -n "$contesto" ] && python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$contesto"
+ exit 0
+ ;;
+ dove)
+ evento=$(cat); printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"
+ ;;
+ guardia)
+ evento=$(cat)
+ dove_fatto=""
+ if [[ $evento == *rollout-* || $evento =~ \"tool_name\":\ ?\"apply_patch\" ]]; then
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento"); dove_fatto=1
+ fi
+ if [ -z "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
+ _guardia_serve "$evento" || exit 0
+ evento=$(printf '%s' "$evento" | evento_dove 2>/dev/null || printf '%s' "$evento")
+ fi
+ if incerto=$(printf '%s' "$evento" | campo dove_incerto) && [ -n "$incerto" ]; then
+ _f "$M_guardia_cartella_gira" incerto "$incerto" >&2
+ exit 2
+ fi
+ if [ -n "$dove_fatto" ] && [[ $evento =~ \"tool_name\":\ ?\"(Bash|exec_command|run_shell_command)\" ]]; then
+ _guardia_serve "$evento" || exit 0
+ fi
+ corpo=$(printf '%s' "$evento" | DELMINIO_MEMORIA="$MEMORIA" IMPRONTA="$(chiave_in_uso)" python3 -c 'import json,os,re,sys
+try:
+ e = json.load(sys.stdin)
+except Exception:
+ sys.exit(0)
+t = e.get("tool_input") or {}
+cwd = os.path.realpath(e.get("cwd") or os.getcwd())
+scritti = [t.get("file_path") or t.get("notebook_path") or ""]
+if e.get("tool_name") == "apply_patch":
+ patch = t.get("command") or t.get("input") or t.get("patch") or ""
+ scritti += [p.strip() for p in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M)]
+veri = {p: os.path.realpath(os.path.join(cwd, os.path.expanduser(p))) for p in scritti if p}
+m = os.environ.get("DELMINIO_MEMORIA") or ""
+print(json.dumps({"memoria": os.path.realpath(m) if m else "", "home": os.path.expanduser("~"),
+ "cwd": cwd, "evento": e, "veri": veri, "chiave": os.environ.get("IMPRONTA", ""),
+ "motivo": os.environ.get("DELMINIO_MOTIVO", "")}))') || exit 0
+ [ -n "$corpo" ] || exit 0
+ r=$(printf '%s' "$corpo" | curl -sS -m 3 -w '\n%{http_code}' -X POST -K <(_chiave "$TOKEN") \
+ -H "Content-Type: application/json" --data-binary @- "$URL/api/guardia" 2>/dev/null)
+ if [ "${r##*$'\n'}" != 200 ]; then
+ giu="$STATO/guardia-giu"
+ if [ ! -f "$giu" ] || [ $(( $(date +%s) - $(_mtime "$giu") )) -ge 600 ]; then
+ touch "$giu"
+ case "${r##*$'\n'}" in ''|000) avviso=$M_guardie_giu ;; *) avviso=$(_f "$M_guardie_errore" codice "${r##*$'\n'}") ;; esac
+ python3 -c 'import json,sys; print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": sys.argv[1]}}))' "$avviso"
+ fi
+ exit 0
+ fi
+ [[ ${r%$'\n'*} == '{"ferma":false}' || ${r%$'\n'*} == '{"ferma": false}' ]] && exit 0
+ DELMINIO_R="${r%$'\n'*}" python3 -c 'import json,os,sys
+try:
+ r = json.loads(os.environ["DELMINIO_R"])
+except Exception:
+ sys.exit(0)
+if r.get("ferma"):
+ print(r.get("testo", ""), file=sys.stderr)
+ sys.exit(2)'
+ ;;
+ nuovo|merge|smonta)
+ parte worktree.sh && . "$(dirname "$0")/worktree.sh" "$@"
+ ;;
+ audit)
+ radice=$(git rev-parse --show-toplevel)
+ cartella="$radice/.delminio/audit"
+ if squadra=$(chiedi GET /api/skill/squadra); then
+ nomi=$(printf '%s' "$squadra" | python3 -c "$PY_SKILL_NOMI" "$radice"); e=$?
+ while IFS=$'\t' read -r k a b c; do
+ [ "$k" = F ] && _f "$M_skill_nomi_finding" pezzo "$a" file "$b" nome "$c"
+ done <<<"$nomi"
+ case "$e:$nomi" in
+ 0:NESSUNA*) echo "$M_skill_nomi_nessuna" ;;
+ 0:OK*) _f "$M_skill_nomi_pulita" n "${nomi#OK$'\t'}" ;;
+ 1:*) echo "$M_skill_nomi_voluti" ;;
+ *) _f "$M_skill_nomi_cieca" perche "python3 $e" ;;
+ esac
+ else
+ _f "$M_skill_nomi_cieca" perche "$(perche_no)"
+ fi
+ if [ ! -d "$cartella" ] || [ -z "$(ls -A "$cartella" 2>/dev/null)" ]; then
+ echo "$M_nessuna_track_misurata"
+ echo "$M_revisione_memoria_meta"
+ exit 0
+ fi
+ pulite=0; con=0
+ for s in "$cartella"/*; do
+ [ -f "$s" ] && [ -x "$s" ] || continue
+ out=$(cd "$(git rev-parse --show-toplevel)" && _tempo 300 "$s" 2>&1); e=$?
+ if [ $e = 0 ]; then pulite=$((pulite + 1)); echo "✅ $(basename "$s")"
+ else con=$((con + 1)); echo "❌ $(basename "$s") (uscita $e)"; printf '%s\n' "$out" | head -20 | sed 's/^/ /'
+ fi
+ done
+ _f "$M_track_pulite_finding" pulite "$pulite" con "$con"
+ ;;
+ domini)
+ pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_2"; exit 1; }
+ [ -n "${2:-}" ] || { echo "$M_quali_bash_claude" >&2; exit 1; }
+ D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "domini": sys.argv[2]}))' "$nome" "$2")
+ r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
+ _f "$M_lavora_altre_sessioni" nome "$nome" valore "$2"
+ ;;
+ titolo)
+ pid=$(cli_pid || true); nome="${3:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { chi_sei_no "$M_chi_sei_bash_3"; exit 1; }
+ [ -n "${2:-}" ] || { echo "$M_quale_bash_claude" >&2; exit 1; }
+ D=$(python3 -c 'import json,sys; print(json.dumps({"sessione": sys.argv[1], "titolo": sys.argv[2]}))' "$nome" "$2")
+ r=$(chiedi POST /api/canale/battito "$D") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | grep -q '"vivo": *false' && { _f "$M_sessione_non_viva" nome "$nome" >&2; exit 1; }
+ _f "$M_chiama" nome "$nome" valore "$2"
+ ;;
+ file-del-kit)
+ printf '%s\n' $KIT_FILE
+ ;;
+ ambiente)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ printf '%s\n%s\n%s\n' "$URL" "$FILE_TOKEN" "$nome"
+ ;;
+ chiusura)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ cli=${DELMINIO_CLI_NOME:-claude}; [ -n "$pid" ] && cli=$(cli_di "$pid")
+ corpo=$(DELMINIO_CLI_NOME="$cli" python3 - "$nome" "${2:-}" "$(_remoto)" <<'CHIUSURA'
+import json, os, subprocess, sys
+def git(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+commit = git("log", "-200", "--format=%h%x1f%s%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)%x1f"
+ "%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly,separator=%x20)").splitlines()
+import re, time
+NOMI_COMUNI = 100
+def nomi_cambiati(sessione):
+ if not sessione:
+ return []
+ hh = []
+ for riga in git("log", "-300", "--no-merges",
+ "--format=%H%x1f%(trailers:key=Delminio-Sessione,valueonly,separator=%x20)").splitlines():
+ h, _, chi = riga.partition("\x1f")
+ if sessione in chi.split():
+ hh.append(h)
+ if not hh:
+ return []
+ try:
+ diff = subprocess.run(["git", "show", "-U0", "--format=", *hh], capture_output=True,
+ text=True, errors="replace", timeout=20).stdout
+ except subprocess.TimeoutExpired:
+ return []
+ saldo = {}
+ for l in diff.splitlines():
+ if not l or l[0] not in "+-" or l.startswith(("+++", "---")):
+ continue
+ segno = 1 if l[0] == "+" else -1
+ for n in re.findall(r"[A-Za-z_][A-Za-z0-9_]{3,}", l[1:]):
+ if "_" in n.strip("_") or re.search(r"[a-z][A-Z]", n) or (n.isupper() and len(n) >= 4):
+ saldo[n] = saldo.get(n, 0) + segno
+ fuori, inizio = [], time.time()
+ for n in sorted((n for n, v in saldo.items() if v), key=lambda n: -abs(saldo[n]))[:150]:
+ if time.time() - inizio > 10:
+ break
+ if len(git("grep", "-lwF", "-e", n, "--", ".").splitlines()) <= NOMI_COMUNI:
+ fuori.append(n)
+ return fuori
+righe = []
+sporchi = [r for r in git("status", "--porcelain").splitlines() if r.strip()]
+righe.append(F("dove_albero_sporco", n=len(sporchi)) if sporchi else F("dove_albero_pulito"))
+if git("rev-parse", "--abbrev-ref", "@{u}"):
+ n = git("rev-list", "--count", "@{u}..HEAD")
+ righe.append(F("commit_non_pushati", n=n, ramo=git("rev-parse", "--abbrev-ref", "@{u}"))
+ if n not in ("", "0") else F("tutto_pushato"))
+else:
+ righe.append(F("ramo_senza_remoto", ramo=git("rev-parse", "--abbrev-ref", "HEAD")))
+alberi = [r for r in git("worktree", "list", "--porcelain").splitlines() if r.startswith("worktree ")]
+if len(alberi) > 1:
+ righe.append(F("worktree_in_piu", n=len(alberi) - 1, alberi=", ".join(a[9:] for a in alberi[1:])))
+exec(os.environ["DELMINIO_FIDATI_PY"])
+radice = git("rev-parse", "--show-toplevel")
+gia, fermi = accettati(radice), []
+for f in script_del_progetto(radice, ("dove-siamo", "status")):
+ s = os.path.basename(f)
+ if not da_fidarsi(radice, f, gia):
+ fermi.append(di_chi(radice, f)[0])
+ continue
+ try:
+ out = subprocess.run([f], capture_output=True, text=True, timeout=30).stdout.strip()
+ except (OSError, subprocess.TimeoutExpired) as e:
+ out = F("script_non_risponde", script=s, errore=e)
+ righe += [r for r in out.splitlines() if r.strip()][:3]
+if fermi:
+ righe.append(F("script_da_accettare", n=len(fermi), chi=", ".join(sorted(set(fermi)))))
+print(json.dumps({"sessione": sys.argv[1], "richieste": sys.argv[2], "commit": commit,
+ "dove_siamo": righe, "remoto": sys.argv[3], "nomi": nomi_cambiati(sys.argv[1]),
+ "cli": os.environ.get("DELMINIO_CLI_NOME") or "claude"}))
+CHIUSURA
+)
+ if r=$(chiedi POST /api/chiusura/prompt "$corpo"); then
+ printf '%s' "$r" | campo testo
+ else
+ echo "Chiudiamo. ${2:-}"
+ echo
+ _f "$M_prompt_chiusura_arrivato" perche "$(perche_no)"
+ echo "$M_lavoro_committato_pushato"
+ echo "$M_vuoto_git_commit"
+ echo "$M_push_commit_passera"
+ fi
+ ;;
+ consegna)
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ corpo=$(python3 -c 'import json,sys; print(json.dumps({"messaggio": sys.stdin.read(), "sessione": sys.argv[1], "remoto": sys.argv[2]}))' \
+ "$nome" "$(_remoto)") || exit 1
+ if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/consegna "$corpo"); then
+ _f "$M_chiusura_stata_consegnata" perche "$(perche_no)" >&2
+ exit 1
+ fi
+ printf '%s' "$r" | python3 -c 'import json,sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+r = json.load(sys.stdin)
+if not r.get("ok"):
+ print(F("chiusura_rifiutata"), file=sys.stderr)
+ for m in r.get("motivi") or []:
+ print(f" • {m}", file=sys.stderr)
+ sys.exit(1)
+for k, v in (r.get("aggiunti") or {}).items():
+ print(F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
+for a in r.get("avvisi") or []:
+ print(f"⚠️ {a}", file=sys.stderr)
+nome, h = r.get("sessione"), r.get("hash")
+print(F("chiusa_nel_repo", nome=nome, hash=h))
+if r.get("mollate"):
+ print(F("opere_avevi_mano", m=", ".join(r["mollate"])))'
+ ;;
+ consegna-di)
+ n=${2:-}; n=${n#[Ss]}
+ [[ "$n" =~ ^[0-9]+$ ]] || { echo "$M_consegna_di_uso" >&2; exit 1; }
+ r=$(chiedi GET "/api/chiusure/$n") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ printf '%s' "$r" | M_CURATA="$(_f "$M_consegna_di_curata" numero "$n")" \
+ M_VUOTA="$(_f "$M_consegna_di_vuota" numero "$n")" python3 -c '
+import json, os, sys
+c = json.load(sys.stdin)
+if c.get("cura"):
+ print(os.environ["M_CURATA"] + "\n\n" + c["cura"]["testo"])
+elif c.get("testo"):
+ print(c["testo"])
+else:
+ print(os.environ["M_VUOTA"])'
+ ;;
+ tocco)
+ percorsi=$(python3 -c 'import json,os,re,sys
+try:
+ e = json.load(sys.stdin); t = e.get("tool_input") or {}
+except Exception:
+ sys.exit(0)
+if e.get("tool_name") == "apply_patch":
+ patch = t.get("command") or t.get("input") or t.get("patch") or ""
+ for f in re.findall(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", patch, re.M):
+ print(os.path.join(e.get("cwd") or os.getcwd(), f.strip()))
+else:
+ print(t.get("file_path") or t.get("notebook_path") or "")')
+ percorso=$(printf '%s\n' "$percorsi" | head -1)
+ [ -n "$percorso" ] || exit 0
+ altro=""
+ cima=$(python3 -c 'import os,sys
+d = os.path.dirname(os.path.abspath(sys.argv[1]))
+while d != os.path.dirname(d) and not os.path.exists(os.path.join(d, ".git")):
+ d = os.path.dirname(d)
+print(d if os.path.exists(os.path.join(d, ".git")) else "")' "$percorso" 2>/dev/null || true)
+ qui=$(cd "$(dirname "$0")/.." && pwd)
+ remoto_cima=$(_remoto "${cima:-$qui}" || true)
+ if [ -n "$cima" ] && [ "$cima" != "$qui" ] && [ -f "$cima/.claude/delminio.sh" ] && [ -f "$cima/.claude/eseguibili.py" ]; then
+ suo=$(python3 "$cima/.claude/eseguibili.py" spazio --da "$cima/.claude/delminio.sh" 2>/dev/null || true)
+ mio=$(spazio_qui)
+ if [ -n "$suo" ] && [ "$suo" != "$mio" ]; then
+ altro=$(python3 -c 'import sys
+n = lambda k: k.rsplit("#", 1)[1] if "#" in k else "principale"
+a, b = n(sys.argv[2]), n(sys.argv[3])
+if a == b: a, b = sys.argv[2], sys.argv[3]
+print(sys.argv[1] + "\t" + a + "\t" + b)' "$cima" "$suo" "$mio")
+ fi
+ fi
+ r='{"lock": []}'; con_lock=""
+ qrepo=""
+ [ -z "$remoto_cima" ] || qrepo="&repo=$(_quota "$remoto_cima" "")"
+ while IFS= read -r x; do
+ [ -n "$x" ] || continue
+ uno=$(chiedi GET "/api/lock?percorso=$(_quota "$x" /)$qrepo") || continue
+ printf '%s' "$uno" | grep -q '"codice"' || continue
+ con_lock="$con_lock$x"$'\n'
+ r=$(python3 -c 'import json,sys
+a, b = json.loads(sys.argv[1]), json.loads(sys.argv[2])
+visti = {(l.get("spazio"), l["codice"]) for l in a.get("lock") or []}
+a["lock"] = (a.get("lock") or []) + [l for l in b.get("lock") or [] if (l.get("spazio"), l["codice"]) not in visti]
+a.update({k: b[k] for k in ("condiviso_da", "altro_spazio") if b.get(k)})
+print(json.dumps(a))' "$r" "$uno" 2>/dev/null || printf '%s' "$r")
+ done <<< "$percorsi"
+ pid=$(cli_pid || true); detti="${pid:+$STATO/lock-detti-$pid}"
+ DELMINIO_LOCK="$r" DELMINIO_ALTRO="$altro" DELMINIO_CIMA="$cima" DELMINIO_PERCORSI="${con_lock:-$percorso}" python3 - "$detti" "$percorso" <<'TOCCO'
+import json, os, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+detti_f, percorso = sys.argv[1], sys.argv[2]
+try:
+ detti = set(open(detti_f, encoding="utf-8").read().split()) if detti_f else set()
+except OSError:
+ detti = set()
+righe, segni = [], []
+risposta = json.loads(os.environ["DELMINIO_LOCK"])
+cima = os.environ.get("DELMINIO_CIMA", "")
+nome_cima = os.path.basename(cima) or F("questo_repo")
+altro = os.environ.get("DELMINIO_ALTRO", "").split("\t")
+if risposta.get("condiviso_da") and ("condiviso:" + cima) not in detti:
+ di = risposta["condiviso_da"]
+ segni.append("condiviso:" + cima)
+ righe.append(F("tocco_ospite", repo=nome_cima, di=di))
+elif len(altro) == 3 and ("spazio:" + altro[0]) not in detti:
+ cima, suo, mio = altro
+ segni.append("spazio:" + cima)
+ righe.append(F("tocco_altro_spazio_tuo", repo=os.path.basename(cima), suo=suo, mio=mio))
+elif risposta.get("altro_spazio") and ("spazio:" + cima) not in detti:
+ di = risposta["altro_spazio"]
+ segni.append("spazio:" + cima)
+ righe.append(F("tocco_non_condiviso", repo=nome_cima, di=di))
+nuovi = [l for l in risposta.get("lock") or []
+ if (l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"]) not in detti]
+segni += [l["codice"] if not l.get("spazio") else l["spazio"] + ":" + l["codice"] for l in nuovi]
+if not righe and not nuovi:
+ sys.exit(0)
+if detti_f:
+ with open(detti_f, "a", encoding="utf-8") as f:
+ f.write("".join(x + "\n" for x in segni))
+if nuovi:
+ tocchi = ", ".join(os.path.basename(x) for x in os.environ.get("DELMINIO_PERCORSI", percorso).split("\n") if x)
+ righe.append(F("tocco_lock", file=tocchi))
+for l in nuovi:
+ duro = F("tocco_duro") if l.get("duro") else ""
+ if l.get("spazio"):
+ duro = F("tocco_duro_ospite") if l.get("duro") else ""
+ di = F("tocco_dello_spazio", spazio=l["spazio"]) if l.get("spazio") else ""
+ guardia = l.get("guardia") or F("tocco_nessuno")
+ righe.append(F("tocco_voce", codice=l["codice"], di=di, cosa=l["cosa"], duro=duro, perche=l["perche"], guardia=guardia))
+print(json.dumps({"hookSpecificOutput": {"hookEventName": "PreToolUse",
+ "additionalContext": "\n".join(righe)}}))
+TOCCO
+ ;;
+ ripassato)
+ radice=$(git rev-parse --show-toplevel) || exit 1
+ n=0; cartella=$(cartella_backup)
+ copie_fatte=("$radice"/.claude/delminio-prima/*/)
+ [ -n "$cartella" ] && copie_fatte+=("$cartella"/*/)
+ for d in "${copie_fatte[@]}"; do
+ [ -f "$d/fatti.json" ] && [ ! -e "$d/RIPASSATO" ] || continue
+ date '+%Y-%m-%d %H:%M' > "$d/RIPASSATO"; n=$((n + 1))
+ done
+ _f "$M_ripassato_copia_prima" n "$n" cartella "${cartella:-.claude/delminio-prima}"
+ ;;
+ stacca)
+ { exec 3</dev/tty; } 2>/dev/null || { echo "$M_stacca_lancia_terminale" >&2; exit 1; }
+ radice=$(git rev-parse --show-toplevel) || exit 1
+ [ "$(_assoluto "$(git rev-parse --git-common-dir)")" = "$(_assoluto "$radice/.git")" ] \
+ || { echo "$M_stacca_lancia_clone" >&2; exit 1; }
+ cd "$radice"
+ cartella=$(cartella_backup)
+ prima=$( { [ -n "$cartella" ] && ls -d "$cartella"/*/fatti.json 2>/dev/null; } | tail -1 || true)
+ prima=${prima%fatti.json}
+ [ -n "$prima" ] || prima=$(ls -d .claude/delminio-prima/*/ 2>/dev/null | tail -1 || true)
+ [ -n "$cartella" ] || cartella=$(python3 -c 'import hashlib, os, re, sys
+c = os.path.realpath(sys.argv[1])
+print(os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.join(os.path.expanduser("~"), ".local", "share"), "delminio", "backup",
+ (re.sub(r"[^A-Za-z0-9._-]", "-", os.path.basename(c)) or "repo") + "-" + hashlib.sha256(c.encode()).hexdigest()[:12]))' "$radice")
+ nome_repo=$(basename "$radice")
+ _f "$M_stacco" repo "$nome_repo" url "$URL"
+ [ -n "$prima" ] && _f "$M_rimetto_cio_era" prima "$prima" \
+ || echo "$M_copia_prima_tolgo"
+ read -rp "$M_procedo" si <&3
+ case "$si" in s|S|si|sì|y|yes) ;; *) echo "$M_niente_fatto"; exit 0 ;; esac
+ personali="$cartella/personali-$(date +%Y-%m-%d-%H%M%S)"
+ if r=$(chiedi GET /api/personali); then
+ n=$(umask 077; printf '%s' "$r" | python3 -c '
+import json, os, re, sys
+dest = sys.argv[1]
+mie = json.load(sys.stdin).get("personali") or []
+for m in mie:
+ os.makedirs(dest, exist_ok=True)
+ nome = re.sub(r"[^a-z0-9]+", "_", m["name"].lower()).strip("_")[:80] or "memoria"
+ i = 1
+ while True:
+ percorso = os.path.join(dest, nome + ("" if i == 1 else "_" + str(i)) + ".md")
+ try:
+ f = open(percorso, "x", encoding="utf-8")
+ except FileExistsError:
+ i += 1
+ continue
+ with f:
+ f.write(m["md"])
+ break
+print(len(mie))' "$personali") || exit 1
+ if [ "${n:-0}" -gt 0 ] 2>/dev/null; then _f "$M_tue_memorie_personali" n "$n" personali "$personali"; else personali=""; fi
+ else
+ personali=""
+ _f "$M_tue_memorie_personali_2" perche "$(perche_no)"
+ fi
+ if [ -f .claude/plugin.py ]; then python3 .claude/plugin.py rimuovi "$radice" || true; fi
+ DELMINIO_PRIMA="$prima" DELMINIO_KIT_FILE="$KIT_FILE $KIT_DI_PRIMA" python3 - <<'STACCA'
+import json, os, pathlib, shutil
+exec(os.environ["DELMINIO_GANCI_PY"])
+prima = os.environ.get("DELMINIO_PRIMA", "").rstrip("/")
+try:
+ fatti = json.load(open(os.path.join(prima, "fatti.json"), encoding="utf-8")) if prima else {}
+except (OSError, ValueError):
+ fatti = {}
+copie = set(fatti.get("copie") or [])
+p = pathlib.Path(".claude/settings.local.json")
+if p.exists():
+ s = json.loads(p.read_text(encoding="utf-8") or "{}")
+ togli_ganci(s)
+ allow = (s.get("permissions") or {}).get("allow")
+ if allow is not None:
+ nostri = ({f"mcp__{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")}
+ | {f"mcp__plugin_delminio_{s}__{t}" for s in ("memoria", "delminio") for t in ("delminio", "delminio_write")})
+ allow[:] = [a for a in allow if a not in nostri]
+ s.pop("autoMemoryDirectory", None)
+ if (fatti.get("memoria") or {}).get("scelta_in") == ".claude/settings.local.json":
+ s["autoMemoryDirectory"] = fatti["memoria"]["cartella"]
+ if s or ".claude/settings.local.json" in copie:
+ p.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ else:
+ p.unlink()
+e = pathlib.Path(".qwen/.env")
+if e.is_file() and e.read_text(encoding="utf-8", errors="replace").strip() == "# delminio":
+ e.unlink()
+ try:
+ e.parent.rmdir()
+ except OSError:
+ pass
+for c in (pathlib.Path(".codex/hooks.json"), pathlib.Path(".qwen/settings.json")):
+ if c.exists():
+ try:
+ s = json.loads(c.read_text(encoding="utf-8") or "{}")
+ except ValueError:
+ s = None
+ if s is not None:
+ togli_ganci(s)
+ if s or str(c) in copie:
+ c.write_text(json.dumps(s, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ else:
+ c.unlink()
+ try:
+ c.parent.rmdir() # solo se vuota: il resto di .codex e di .qwen è dell'umano
+ except OSError:
+ pass
+for rel in (f for f in os.environ["DELMINIO_KIT_FILE"].split() if "/commands/" in f):
+ if rel in copie:
+ os.makedirs(os.path.dirname(rel), exist_ok=True)
+ shutil.copy2(os.path.join(prima, rel), rel)
+ elif os.path.isfile(rel) and ("Delminio" if rel.startswith(".qwen/") else "delminio.sh") in open(rel, encoding="utf-8").read():
+ os.unlink(rel)
+STACCA
+ mcp_claude_nostro() { # mcp_claude_nostro <nome>: il server locale di questo repo è il nostro (punta qui)
+ python3 -c 'import json, os, sys
+f = os.path.join(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~"), ".claude.json")
+try:
+ s = json.load(open(f, encoding="utf-8"))["projects"][sys.argv[1]]["mcpServers"][sys.argv[2]]
+except (OSError, ValueError, KeyError, TypeError):
+ sys.exit(1)
+sys.exit(0 if str(s.get("url", "")).startswith(sys.argv[3]) else 1)' "$radice" "$1" "$URL" 2>/dev/null
+ }
+ for n in memoria delminio; do
+ mcp_claude_nostro "$n" && claude mcp remove "$n" -s local >/dev/null 2>&1
+ if [ -n "$prima" ] && [ -f "$prima/mcp-$n.json" ]; then
+ claude mcp add-json -s local "$n" "$(cat "$prima/mcp-$n.json")" >/dev/null \
+ && _f "$M_server_mcp_delminio" nome "$n" \
+ || _f "$M_server_mcp_prima" prima "$prima" nome "$n"
+ fi
+ done
+ ganci=$(git config core.hooksPath || git rev-parse --git-path hooks)
+ for g in commit-msg post-commit post-rewrite; do
+ f="$ganci/$g"
+ [ -f "$f" ] && grep -q "delminio.sh" "$f" || continue
+ if sed -n 2p "$f" | grep -q '^# Delminio (aggancia.sh)'; then rm -f "$f"
+ else _f "$M_tuo_chiama_delminio" f "$f"; fi
+ done
+ escludi=$(git rev-parse --git-path info/exclude)
+ if [ -f "$escludi" ]; then
+ printf '%s\n' $KIT_FILE $KIT_DI_PRIMA $([ -e .qwen/.env ] || echo .qwen/.env) | grep -vxF -f - "$escludi" > "$escludi.delminio" || true
+ mv -f "$escludi.delminio" "$escludi"
+ fi
+ messe="$(git rev-parse --git-common-dir)/delminio-cure"
+ if [ -f "$messe" ]; then
+ while read -r h; do [ -n "$h" ] && git replace -d "$h" >/dev/null 2>&1 || true; done < "$messe"
+ fi
+ 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
+ rm -f "$(git rev-parse --git-path "$s")" "$(git rev-parse --git-common-dir)/$s" 2>/dev/null || true
+ done
+ jti=$(printf '%s' "$TOKEN" | python3 -c '
+import base64, json, sys
+try:
+ p = sys.stdin.read().split(".")[1]
+ print(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))).get("jti") or "")
+except Exception:
+ print("")')
+ altri=$(grep -lxF -- "$TOKEN" "$(dirname "$FILE_TOKEN")"/*.token 2>/dev/null | grep -vxF "$FILE_TOKEN" | wc -l)
+ if [ -z "$jti" ]; then
+ echo "$M_revocare_questo_token"
+ elif [ "$altri" -gt 0 ]; then
+ _f "$M_token_resta_valido" altri "$altri"
+ elif chiedi DELETE "/api/tokens/$jti" >/dev/null; then
+ echo "$M_token_questo_aggancio"
+ else
+ _f "$M_token_revocato_fallo" perche "$(perche_no)"
+ fi
+ if [ "$altri" -eq 0 ] 2>/dev/null && [ -f .claude/eseguibili.py ]; then
+ python3 .claude/eseguibili.py --url "$URL" --token-file "$FILE_TOKEN" lascia || true
+ fi
+ rm -f "$FILE_TOKEN"
+ if ! ls "$(dirname "$FILE_TOKEN")"/*.token >/dev/null 2>&1; then
+ dati="${XDG_DATA_HOME:-$HOME/.local/share}"; cache="${XDG_CACHE_HOME:-$HOME/.cache}"
+ if [ -f .claude/plugin.py ]; then
+ esito=0; python3 .claude/plugin.py app-codex lascia >/dev/null 2>&1 || esito=$?
+ [ "$esito" -eq 2 ] && echo "$M_app_codex_tolto"
+ fi
+ rm -rf "$dati/delminio/plugin" "$dati/codex/versions" "$dati/qwen-code/versions" "$dati/delminio/opencode" \
+ "$cache"/delminio-stato "$cache"/delminio-eseguibili "$cache"/delminio-cassaforte 2>/dev/null || true
+ comando="${DELMINIO_BIN:-$HOME/.local/bin}/delminio"
+ grep -q '^# delminio-comando$' "$comando" 2>/dev/null && rm -f "$comando"
+ echo "$M_pulito_ultimo"
+ fi
+ for f in $KIT_FILE $KIT_DI_PRIMA; do
+ case "$f" in .claude/*.py|.claude/rules/*) rm -f "$f" ;; esac # il resto l'ha già rimesso il python
+ done
+ rmdir .claude/rules "$(dirname "$FILE_TOKEN")" 2>/dev/null || true
+ if [ -n "${CLONE:-}" ] && [ -d "$MEMORIA/.git" ]; then
+ case "$MEMORIA" in "${XDG_DATA_HOME:-$HOME/.local/share}"/delminio/*/memoria) rm -rf "$(dirname "$MEMORIA")"
+ echo "$M_tolto_clone_memorie" ;; esac
+ fi
+ wt=$(git worktree list --porcelain | grep -c '^branch refs/heads/sessione/' || true)
+ [ "$wt" -gt 0 ] && _f "$M_restano_worktree_sessioni" wt "$wt"
+ echo "$M_staccato_cli_torna"
+ [ -n "$personali" ] && _f "$M_tue_personali" personali "$personali"
+ [ -n "$prima" ] && _f "$M_copia_prima_resta" prima "$prima"
+ rm -f .claude/delminio.sh
+ exit 0
+ ;;
+ accetta)
+ { exec 3</dev/tty; } 2>/dev/null || { echo "$M_accetta_lancia_terminale" >&2; exit 1; }
+ DELMINIO_ALBERO="$(git rev-parse --show-toplevel)" python3 - <<'SCRIPT'
+import os
+exec(os.environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+exec(os.environ["DELMINIO_FIDATI_PY"])
+albero = os.environ["DELMINIO_ALBERO"]
+gia = accettati(albero)
+fermi = [f for f in script_del_progetto(albero, ("apertura", "opening", "dove-siamo", "status")) + lascito_del_progetto(albero)
+ if not da_fidarsi(albero, f, gia)]
+if fermi:
+ tty_in, tty = open("/dev/tty"), open("/dev/tty", "w")
+ tty.write(F("accetta_script_elenco"))
+ for f in fermi:
+ chi, quando = di_chi(albero, f)
+ righe = sum(1 for _ in open(f, encoding="utf-8", errors="replace"))
+ tty.write(F("accetta_script_riga", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, righe=righe) + "\n")
+ tty.write(F("accetta_script_domanda"))
+ tty.flush()
+ r, scelti = tty_in.readline().strip().lower(), []
+ if r in F("accetta_script_tutti_si").split():
+ scelti = fermi
+ elif r in F("accetta_script_uno_si").split():
+ for f in fermi:
+ chi, quando = di_chi(albero, f)
+ testo = open(f, encoding="utf-8", errors="replace").read()
+ tty.write(F("accetta_script_uno", percorso=os.path.relpath(f, albero), chi=chi, quando=quando, testo=testo[:4000]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ scelti.append(f)
+ if scelti:
+ with open(accettati_file(albero), "w", encoding="utf-8") as out:
+ out.write("".join(x + "\n" for x in sorted(gia | {impronta_script(albero, f) for f in scelti})))
+ print(F("script_accettati", nuovi=len(scelti), fermi=len(fermi) - len(scelti)))
+SCRIPT
+ if [ -f "$(dirname "$0")/squadra.py" ]; then python3 "$(dirname "$0")/squadra.py" accetta || true; fi
+ if [ -f "$(dirname "$0")/eseguibili.py" ]; then
+ python3 "$(dirname "$0")/eseguibili.py" accetta && [ -z "${DELMINIO_PROVA:-}" ] && allinea_staccato || true
+ fi
+ tutti=$(chiedi GET /api/lock) || { echo "❌ $(perche_no)" >&2; exit 1; }
+ DELMINIO_LOCK="$tutti" DELMINIO_ACCETTATE="$(accettate_file)" python3 - <<'ACCETTA'
+import hashlib, json, os
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+tutti = json.loads(os.environ["DELMINIO_LOCK"]).get("lock") or []
+lock = [l for l in tutti if (l.get("duro") or l.get("firme")) and l.get("comando")]
+prima = [l for l in tutti if l.get("comando_gesto")] # su comandi e strumenti (F903)
+f = os.environ["DELMINIO_ACCETTATE"]
+try:
+ accettate = set(open(f, encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+tty_in, tty = open("/dev/tty"), open("/dev/tty", "w") # r+ vuole un seek, e un terminale non lo ha
+nuove = 0
+for l in lock:
+ h = hashlib.sha256((l["codice"] + "\0" + l["comando"]).encode()).hexdigest()
+ if h in accettate:
+ continue
+ tty.write(F("accetta_domanda", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", comando=l["comando"]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ accettate.add(h); nuove += 1
+for l in prima:
+ h = hashlib.sha256(("gesto\0" + l["codice"] + "\0" + l["comando_gesto"]).encode()).hexdigest()
+ if h in accettate:
+ continue
+ gesti = ", ".join((l.get("gesti") or []) + (l.get("strumenti") or []))
+ tty.write(F("accetta_domanda_gesto", codice=l["codice"], cosa=l["cosa"], chi=l.get("chi") or "?", gesti=gesti, comando=l["comando_gesto"]))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F("accetta_si").split():
+ accettate.add(h); nuove += 1
+with open(f, "w", encoding="utf-8") as out:
+ out.write("".join(x + "\n" for x in sorted(accettate)))
+print(F("accettate", nuove=nuove, tutte=len(accettate), file=f))
+ACCETTA
+ ;;
+ commit-msg|post-rewrite|post-commit|post-rewrite-dopo|post-commit-dopo)
+ parte ganci-git.sh && . "$(dirname "$0")/ganci-git.sh" "$@"
+ ;;
+ errore)
+ [ -f "$(dirname "$0")/eseguibili.py" ] || exit 0
+ evento=""; [ -t 0 ] || evento=$(_tempo 2 cat 2>/dev/null || true)
+ [ -n "$evento" ] || exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid" 2>/dev/null || true)
+ printf '%s' "$evento" | DELMINIO_SESSIONE_NOME="$nome" _tempo 4 python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori-registra >/dev/null 2>&1 || true
+ exit 0
+ ;;
+ errori)
+ shift; exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" errori "$@"
+ ;;
+ pulizia)
+ [ -n "${DELMINIO_CONVERSAZIONI:-}" ] || exit 0
+ exec python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" pulizia
+ ;;
+ ponte)
+ DELMINIO_T="$TOKEN" exec bash "$0" ponte-mcp "$URL"
+ ;;
+ ponte-mcp)
+ programma=$(cat <<'PONTE'
+import json, os, sys, time, urllib.error, urllib.request
+
+URL = sys.argv[1].rstrip("/") + "/mcp"
+TESTA = {"Authorization": "Bearer " + os.environ.pop("DELMINIO_T", ""),
+ "X-Delminio-Modello": os.environ.get("DELMINIO_MODELLO", ""),
+ "Content-Type": "application/json", "Accept": "application/json, text/event-stream"}
+MUTO = os.environ.get("DELMINIO_PONTE_MUTO", "Delminio non risponde.")
+RIFIUTO = os.environ.get("DELMINIO_PONTE_RIFIUTO", "HTTP {codice}")
+stato = {"sessione": None, "versione": "2025-06-18"}
+
+
+def _sessione():
+ try:
+ with open(os.environ.get("DELMINIO_SESSIONE_FILE") or "/nonesiste", encoding="utf-8") as f:
+ return f.read().strip()[:40]
+ except OSError:
+ return ""
+
+
+def manda(msg, timeout=120):
+ h = dict(TESTA)
+ if s := _sessione():
+ h["X-Delminio-Sessione"] = s
+ if stato["sessione"]:
+ h["Mcp-Session-Id"] = stato["sessione"]
+ h["MCP-Protocol-Version"] = stato["versione"]
+ r = urllib.request.Request(URL, data=json.dumps(msg).encode(), headers=h, method="POST")
+ with urllib.request.urlopen(r, timeout=timeout) as risp:
+ sid, tipo = risp.headers.get("mcp-session-id"), risp.headers.get("content-type", "")
+ corpo = risp.read().decode("utf-8", "replace")
+ if "id" not in msg:
+ return None, sid
+ if tipo.startswith("text/event-stream"):
+ for riga in corpo.splitlines():
+ if riga.startswith("data:"):
+ d = json.loads(riga[5:].strip())
+ if d.get("id") == msg["id"]:
+ return d, sid
+ raise OSError("lo stream non porta la risposta")
+ return json.loads(corpo), sid
+
+
+def apri():
+ stato["sessione"] = None
+ d, sid = manda({"jsonrpc": "2.0", "id": "ponte", "method": "initialize",
+ "params": {"protocolVersion": stato["versione"], "capabilities": {},
+ "clientInfo": {"name": "delminio-ponte", "version": "1"}}}, 15)
+ stato["sessione"], stato["versione"] = sid, d["result"].get("protocolVersion", stato["versione"])
+ manda({"jsonrpc": "2.0", "method": "notifications/initialized"}, 15)
+ return d["result"]
+
+
+def chiedi(metodo, params, tentativi):
+ """La domanda al motore; a un errore riapre la sessione e riprova (il motore
+ riavviato non conosce più la sessione di prima)."""
+ for n in range(tentativi):
+ try:
+ if stato["sessione"] is None:
+ apri()
+ d, _ = manda({"jsonrpc": "2.0", "id": "p", "method": metodo, "params": params})
+ return d # anche un errore JSON-RPC: è del motore, non della sessione
+ except urllib.error.HTTPError as e:
+ if e.code in (401, 403):
+ return {"result": {"content": [{"type": "text", "text": RIFIUTO.replace("{codice}", str(e.code))}],
+ "isError": True}}
+ except Exception: # noqa: BLE001
+ pass
+ stato["sessione"] = None
+ time.sleep(min(2 * (n + 1), 6))
+ return None
+
+
+inizio = tools = None
+for n in range(8):
+ try:
+ inizio = apri()
+ tools = manda({"jsonrpc": "2.0", "id": "t", "method": "tools/list", "params": {}})[0]["result"]["tools"]
+ break
+ except Exception: # noqa: BLE001
+ time.sleep(1)
+inizio = inizio or {"serverInfo": {"name": "Delminio", "version": "?"}}
+VUOTI = {"prompts/list": "prompts", "resources/list": "resources",
+ "resources/templates/list": "resourceTemplates"}
+
+for riga in sys.stdin:
+ try:
+ m = json.loads(riga)
+ except ValueError:
+ continue
+ if "id" not in m:
+ continue # le notifiche di Qwen non servono al motore
+ metodo, rid = m.get("method"), m["id"]
+ if metodo == "initialize":
+ res = {"protocolVersion": m.get("params", {}).get("protocolVersion", stato["versione"]),
+ "capabilities": {"tools": {"listChanged": False}},
+ "serverInfo": inizio.get("serverInfo"), "instructions": inizio.get("instructions", "")}
+ elif metodo == "tools/list":
+ res = {"tools": tools or []}
+ elif metodo == "tools/call":
+ d = chiedi("tools/call", m.get("params", {}), 4)
+ if d is not None and "error" in d:
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": d["error"]}, ensure_ascii=False), flush=True)
+ continue
+ res = (d or {}).get("result") or {"content": [{"type": "text", "text": MUTO}], "isError": True}
+ elif metodo in VUOTI:
+ res = {VUOTI[metodo]: []}
+ elif metodo == "ping":
+ res = {}
+ else:
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": metodo}}), flush=True)
+ continue
+ print(json.dumps({"jsonrpc": "2.0", "id": rid, "result": res}, ensure_ascii=False), flush=True)
+PONTE
+)
+ p_cli=$(cli_pid || true)
+ DELMINIO_SESSIONE_FILE="${p_cli:+$STATO/sessione-$p_cli}" \
+ DELMINIO_PONTE_MUTO="$M_ponte_muto" DELMINIO_PONTE_RIFIUTO="$(_f "$M_perche_token" url "${2:-$URL}" codice "{codice}")" \
+ exec python3 -c "$programma" "${2:-$URL}"
+ ;;
+ riaggancia-fratelli)
+ serve=${2:-}; [ -n "$serve" ] || exit 0
+ qui=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd -P)
+ python3 - "$qui" "$URL" "$serve" "${DELMINIO_CERCA_IN:-}" <<'FRATELLI' | while IFS=$'\t' read -r dove tf suo; do
+import os, shlex, sys
+qui, url, serve = sys.argv[1:4]
+radici = [os.path.dirname(qui), os.path.expanduser("~")] + [x for x in sys.argv[4].split(":") if x]
+visti = {os.path.realpath(qui)}
+for radice in radici:
+ for d, sotto, _ in os.walk(radice):
+ livello = d[len(radice):].count(os.sep)
+ c = os.path.join(d, ".claude", "delminio.sh")
+ if os.path.isdir(os.path.join(d, ".git")) and os.path.isfile(c) and os.path.realpath(d) not in visti:
+ visti.add(os.path.realpath(d))
+ testa = {}
+ try:
+ for i, riga in zip(range(30), open(c, encoding="utf-8", errors="replace")):
+ k, _, v = riga.strip().partition("=")
+ if k in ("URL", "FILE_TOKEN", "KIT") and v and k not in testa:
+ testa[k] = (shlex.split(v) or [""])[0]
+ except (OSError, ValueError):
+ continue
+ if testa.get("URL", "").rstrip("/") == url.rstrip("/") and testa.get("KIT") != serve and testa.get("FILE_TOKEN"):
+ print(os.path.realpath(d) + "\t" + testa["FILE_TOKEN"] + "\t" + testa.get("KIT", ""))
+ sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
+FRATELLI
+ [ -r "$tf" ] || continue
+ TOKEN=$(cat "$tf") KIT="${suo:-?}" riaggancia "$serve" "$dove" presto
+ echo "$dove"
+ done
+ ;;
+ clona)
+ nome="${2:-}"; [ -n "$nome" ] && [ "$nome" != --no ] || { echo "$M_uso_clona" >&2; exit 2; }
+ qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
+ r=$(chiedi GET /api/repo/spazio) || { echo "❌ $(perche_no)" >&2; exit 1; }
+ riga=$(printf '%s' "$r" | python3 -c 'import json,re,sys
+n = sys.argv[1]
+ok = lambda c: bool(re.fullmatch(r"[\w.-]+", c)) and c not in (".", "..") and not c.startswith("-")
+for x in json.load(sys.stdin).get("repo") or []:
+ if n in (x.get("nome"), x.get("chiave")):
+ k = str(x.get("chiave") or "")
+ c = str(x.get("nome") or "")
+ if not ok(c):
+ c = re.split(r"[/:]", k.rstrip("/"))[-1].removesuffix(".git")
+ print(k); print(c if ok(c) else ""); break' "$nome")
+ { read -r chiave; read -r cartella; } <<<"$riga"
+ [ -n "$chiave" ] && [ -n "$cartella" ] || { _f "$M_clona_non_dello_spazio" nome "$nome" >&2; exit 1; }
+ if [ "${3:-}" = --no ]; then
+ DELMINIO_CHI="${FILE_TOKEN##*/}" python3 - "$REPO_NO" "$chiave" <<'REPO_NO_SCRIVI' || exit 1
+import json, os, sys
+f, chiave = sys.argv[1], sys.argv[2]
+try:
+ d = json.load(open(f, encoding="utf-8"))
+except (OSError, ValueError):
+ d = {}
+d = d if isinstance(d, dict) else {}
+v = [x for x in d.get(os.environ["DELMINIO_CHI"]) or [] if x != chiave] + [chiave]
+d[os.environ["DELMINIO_CHI"]] = v
+os.makedirs(os.path.dirname(f), exist_ok=True)
+nuovo = f + ".nuovo"
+with open(nuovo, "w", encoding="utf-8") as h:
+ json.dump(d, h, ensure_ascii=False, indent=1)
+os.replace(nuovo, f)
+REPO_NO_SCRIVI
+ _f "$M_clona_no" nome "$nome"; exit 0
+ fi
+ url=$(python3 - "$(git -C "$qui" remote get-url origin 2>/dev/null)" "$chiave" <<'CLONA_URL'
+import sys
+PUBBLICI = {"github.com", "gitlab.com", "codeberg.org", "bitbucket.org", "gitea.com", "git.sr.ht"}
+def parti(u):
+ """(host, percorso, come si rifà l'indirizzo con un altro percorso)"""
+ if "://" in u:
+ schema, resto = u.split("://", 1)
+ autorita, _, percorso = resto.partition("/")
+ return autorita.rsplit("@", 1)[-1].split(":", 1)[0].lower(), percorso, lambda q: f"{schema}://{autorita}/{q}"
+ if ":" in u and not u.startswith("/"):
+ testa, _, percorso = u.partition(":")
+ return testa.split("@", 1)[-1].lower(), percorso, lambda q: f"{testa}:{q}"
+ return "", u, None
+origine, chiave = sys.argv[1], sys.argv[2]
+ho, po, rifai = parti(origine)
+ht, pt, _ = parti(chiave)
+pt = pt.strip("/")
+if rifai and ht and pt and (ht == ho or (ht not in PUBBLICI and ho not in PUBBLICI)):
+ print(rifai(pt.removesuffix(".git") + (".git" if po.rstrip("/").endswith(".git") else "")))
+else:
+ print(chiave)
+CLONA_URL
+)
+ dove="$(dirname "$qui")/$cartella"
+ if [ -e "$dove" ]; then
+ if [ -d "$dove/.git" ] && corpo=$(python3 -c 'import json,sys; print(json.dumps({"remoti": [sys.argv[1]]}))' "$(_remoto "$dove")") \
+ && r2=$(chiedi POST /api/repo/riconosci "$corpo") \
+ && printf '%s' "$r2" | python3 -c 'import json,sys
+sys.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
+ _collega_clone "$nome" "$dove"; exit $?
+ fi
+ _f "$M_clona_occupata" dove "$dove" >&2; exit 1
+ fi
+ _f "$M_clona_in_corso" nome "$nome" url "$url" dove "$dove"
+ log="$STATO/clona-$$.log"
+ if ! GIT_TERMINAL_PROMPT=0 _tempo 600 git clone -q -- "$url" "$dove" > "$log" 2>&1; then
+ errore_log=$(grep -v '^[[:space:]]*$' "$log" | tail -1 | cut -c1-200); rm -f "$log"
+ _f "$M_clona_fallito" nome "$nome" url "$url" errore "$errore_log" >&2; exit 1
+ fi
+ rm -f "$log"
+ _collega_clone "$nome" "$dove"
+ ;;
+ agganciali)
+ qui=$(git rev-parse --show-toplevel 2>/dev/null) || { echo "$M_lancialo_dentro_repo" >&2; exit 1; }
+ trovati=$(python3 - "$qui" "${DELMINIO_CERCA_IN:-}" <<'CERCA'
+import json, os, subprocess, sys
+qui, altre = sys.argv[1], [x for x in sys.argv[2].split(":") if x]
+radici = [os.path.dirname(qui), os.path.expanduser("~")] + altre
+visti, cloni = set(), []
+for radice in radici:
+ for d, sotto, _ in os.walk(radice):
+ livello = d[len(radice):].count(os.sep)
+ if ".git" in sotto and os.path.isdir(os.path.join(d, ".git")): # un clone, non un worktree
+ p = os.path.realpath(d)
+ if p not in visti:
+ visti.add(p)
+ r = subprocess.run(["git", "-C", d, "remote", "get-url", "origin"], capture_output=True, text=True)
+ if r.returncode == 0 and r.stdout.strip():
+ cloni.append((p, r.stdout.strip()))
+ sotto[:] = [x for x in sotto if not x.startswith(".") and x != "node_modules"] if livello < 2 else []
+print(json.dumps({"cloni": cloni}))
+CERCA
+)
+ corpo=$(printf '%s' "$trovati" | python3 -c 'import json,re,sys
+c = json.load(sys.stdin)["cloni"]
+print(json.dumps({"remoti": [re.sub(r"^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@", r"\1", r) for _, r in c]}))')
+ r=$(chiedi POST /api/repo/riconosci "$corpo") || { echo "❌ $(perche_no)" >&2; exit 1; }
+ elenco=$(DELMINIO_CLONI="$trovati" python3 -c 'import json,os,sys
+cloni = json.loads(os.environ["DELMINIO_CLONI"])["cloni"]
+for x in json.load(sys.stdin)["repo"]:
+ dove = [cloni[i][0] for i in x["trovati"]]
+ print(x["nome"] + "\t" + (dove[0] if dove else ""))' <<< "$r")
+ [ -n "$elenco" ] || { echo "$M_spazio_repo_aggiunge"; exit 0; }
+ echo "$M_repo_dello_spazio"
+ falliti=0
+ while IFS=$'\t' read -r nome dove; do
+ if [ -z "$dove" ]; then _f "$M_clonato_qui" nome "$nome"; continue; fi
+ if [ -x "$dove/.claude/delminio.sh" ]; then _f "$M_gia_collegato" nome "$nome" dove "$dove"; continue; fi
+ _collega_clone "$nome" "$dove" || falliti=$((falliti + 1))
+ done <<< "$elenco"
+ [ "$falliti" -eq 0 ]
+ ;;
+ carta)
+ shift
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" DELMINIO_SESSIONE="$sess" DELMINIO_STATO="$STATO" \
+ python3 "$(cd "$(dirname "$0")" && pwd)/firme.py" "$@"
+ ;;
+ perche)
+ dove="${2:-}"
+ case "$dove" in *:[0-9]*) ;; *) echo "$M_uso_bash_claude" >&2; exit 2 ;; esac
+ DELMINIO_U="$URL" DELMINIO_T="$TOKEN" python3 - "$dove" <<'PERCHE'
+import json, os, shlex, subprocess, sys, urllib.parse, urllib.request
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+f, _, riga = sys.argv[1].rpartition(":")
+q = shlex.quote
+
+def g(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True)
+
+def delminio(q):
+ req = urllib.request.Request(os.environ["DELMINIO_U"] + "/api/perche?" + urllib.parse.urlencode(q),
+ headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"]})
+ return json.loads(urllib.request.urlopen(req, timeout=8).read())
+
+b = g("blame", "-L", f"{riga},{riga}", "--porcelain", "--", f)
+if b.returncode:
+ sys.exit(f"❌ {b.stderr.strip()}")
+h = b.stdout.split()[0]
+if set(h) == {"0"}:
+ sys.exit(print(F("perche_non_committata", dove=f"{f}:{riga}")))
+info = g("log", "-1", "--date=short", "--format=%h%x00%an%x00%ad%x00%s%x00%(trailers:key=Delminio-Sessione,valueonly)", h)
+corto, autore, data, soggetto, sess = (info.stdout.split("\0") + [""] * 5)[:5]
+print(F("perche_commit", dove=f"{f}:{riga}", commit=corto, data=data, autore=autore, soggetto=soggetto))
+sess = (sess.strip().splitlines() or [""])[0].strip()
+if not sess:
+ print(F("perche_senza_sessione", commit=corto))
+ sys.exit(0)
+try:
+ r = delminio({"sessione": sess})
+except Exception as e:
+ sys.exit(print(F("perche_sessione_muto", sessione=sess, errore=e)))
+agente = f" ({r['agente']})" if r.get("agente") else ""
+con = F("perche_con", chi=r["chi"]) if r.get("chi") else ""
+nata = F("perche_nata", data=r["nata"][:10]) if r.get("nata") else ""
+print(F("perche_sessione", sessione=r["sessione"], agente=agente, chi=con, nata=nata))
+c = r.get("chiusura")
+h = (c or {}).get("hash") or ""
+if c and not (7 <= len(h) <= 40 and all(x in "0123456789abcdef" for x in h)):
+ c = None
+if not c:
+ sys.exit(print(F("perche_senza_chiusura", sessione=sess)))
+qui = g("cat-file", "-e", f"{c['hash']}^{{commit}}").returncode == 0
+in_repo = F("perche_in_repo", repo=c["repo"]) if c.get("repo") else ""
+comando = (f"git show {q(c['hash'])}" if qui or not c.get("remoto")
+ else f"git fetch -q {q(c['remoto'])} && git show {q(c['hash'])}")
+print(F("perche_chiusa", data=(c.get("quando") or "?")[:10], commit=c["hash"], repo=in_repo, comando=comando))
+mem = g("log", "-1", "--format=%(trailers:" + ",".join("key=" + k for k in os.environ["P_TRAILER_MEMORIA"].split("|"))
+ + ",valueonly)", c["hash"]).stdout.strip() if qui else ""
+primo = mem.split()[0] if mem else ""
+if primo and all(x in "0123456789abcdef" for x in primo) and len(primo) >= 7:
+ try:
+ nomi = delminio({"sessione": sess, "memoria": primo}).get("memorie")
+ except Exception:
+ nomi = None
+ if nomi:
+ print(F("perche_memorie") + "\n" + "\n".join(f" · {n}" for n in nomi))
+ elif nomi == []:
+ print(F("perche_nessuna_memoria"))
+ else:
+ print(F("perche_memorie_nel_commit", commit=primo))
+elif mem:
+ print(F("perche_le_memorie", memorie=mem))
+PERCHE
+ ;;
+ ""|aiuto|-h|--help) echo "$M_aiuto" ;;
+ *) _f "$M_comando_sconosciuto" nome "$1" >&2; echo "$M_aiuto" >&2; exit 2 ;;
+esac
diff --git a/kit/it/eseguibili-client b/kit/it/eseguibili-client
new file mode 100644
index 0000000..6745ca3
--- /dev/null
+++ b/kit/it/eseguibili-client
@@ -0,0 +1,3884 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Gli eseguibili di Delminio su questa macchina, in pari col registro."""
+import argparse
+import base64
+import collections
+import datetime
+import difflib
+import hashlib
+import io
+import json
+import math
+import os
+import platform
+import re
+import runpy
+import shlex
+import shutil
+import socket
+import subprocess
+import sys
+import tarfile
+import tempfile
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+try:
+ import fcntl
+except ImportError:
+ fcntl = None
+RILASCI = 'https://downloads.claude.ai/claude-code-releases'
+CANALI = {'stabile': 'stable', 'latest': 'latest'}
+CODEX_RILASCI = 'https://releases.openai.com/codex/releases'
+CODEX_TARGET = {'linux-x64': 'x86_64-unknown-linux-musl', 'linux-x64-musl': 'x86_64-unknown-linux-musl', 'linux-arm64': 'aarch64-unknown-linux-musl', 'linux-arm64-musl': 'aarch64-unknown-linux-musl', 'darwin-x64': 'x86_64-apple-darwin', 'darwin-arm64': 'aarch64-apple-darwin'}
+NODE_QWEN = '22.23.4'
+CLI_NOMI = {'claude': 'Claude Code', 'codex': 'Codex', 'qwen': 'Qwen Code', 'opencode': 'OpenCode'}
+SERVER_RUOLO = 'memoria-ruolo'
+NODE_RILASCI = 'https://nodejs.org/dist'
+NODE_TARGET = {'linux-x64': 'linux-x64', 'linux-arm64': 'linux-arm64', 'darwin-x64': 'darwin-x64', 'darwin-arm64': 'darwin-arm64'}
+_VERSIONE = re.compile('^\\d+\\.\\d+\\.\\d+$')
+_NOME_OK = re.compile('[A-Za-z0-9][A-Za-z0-9._-]{0,63}')
+FRASI = {
+ "modello_gratuito_nessuno": "nessuno dei {n} modelli gratuiti di OpenCode risponde adesso: serve la chiave di un fornitore",
+ "modello_gratuito_risposta": "pronto",
+ "modello_gratuito_domanda": "Rispondi solo con la parola: pronto",
+ "modello_gratuito_uso": "uso: modello-gratuito <il binario di opencode>",
+ "installa_agente_uso": "uso: installa-agente claude|codex|qwen|opencode <versione>",
+ "installa_agente_no": "{cli} non si \xe8 installato: {errore}",
+ "skill_riferite": "\U0001f9e9 Le skill di qui dette a Delminio, con i comandi, gli agenti e i server MCP: {n}; le scelte della vista Skill applicate: {scelte}.",
+ "posta_arrivata": "\U0001f4ec Delminio: \xe8 arrivato un messaggio da un'altra sessione \u2014 lo trovi qui sotto.",
+ "riga_senza_numero": "la riga di {cli} non ha ancora un numero di versione: risalvala nella vista Agenti",
+ "non_versione": "\xab{versione}\xbb non \xe8 una versione",
+ "senza_cli_ufficiale": "questa macchina ({sistema}) non ha una CLI ufficiale: Linux o macOS (su Windows, dentro WSL)",
+ "versione_assente": "la versione {versione} non c'\xe8 per {piattaforma}",
+ "scarico_cli": " scarico la CLI {versione} per {piattaforma} ({mb} MB)\u2026",
+ "checksum_cli": "il checksum della CLI {versione} non torna: non la installo",
+ "senza_codex_ufficiale": "questa macchina ({sistema}) non ha un Codex ufficiale: Linux o macOS (su Windows, dentro WSL)",
+ "codex_senza_pacchetto": "la versione {versione} di Codex non ha il pacchetto per {piattaforma}",
+ "scarico_codex": " scarico Codex {versione} per {piattaforma}\u2026",
+ "digest_codex": "il digest di Codex {versione} non torna: non lo installo",
+ "pacchetto_fuori": "il pacchetto di {chi} esce dalla sua cartella: non lo installo",
+ "codex_senza_binario": "nel pacchetto di Codex {versione} non c'\xe8 bin/codex",
+ "senza_node_ufficiale": "questa macchina ({sistema}) non ha un Node ufficiale per Qwen Code: Linux o macOS con glibc (su Windows, dentro WSL)",
+ "node_senza_pacchetto": "il Node {versione} non ha il pacchetto per {piattaforma}",
+ "scarico_node": " scarico Node {versione} per Qwen Code\u2026",
+ "checksum_node": "il checksum di Node {versione} non torna: non lo installo",
+ "installo_qwen": " installo Qwen Code {versione}\u2026",
+ "installo_opencode": " installo OpenCode {versione}\u2026",
+ "opencode_integrita": "OpenCode {versione}: il pacchetto non ha l'integrit\xe0 del registro npm, e non si installa",
+ "opencode_senza_binario": "nel pacchetto di OpenCode {versione} non c'\xe8 bin/opencode",
+ "opencode_solo_v2": "OpenCode {versione} \xe8 della versione 1, che Delminio non supporta pi\xf9: nella vista Agenti scegli una versione 2",
+ "wrapper_opencode_solo_kit": "\u26a0\ufe0f {nome}: un agente OpenCode si lancia da un progetto collegato a Delminio, dove il suo plugin porta memoria, messaggi e i comandi di apertura e chiusura.",
+ "commento_config_opencode": "La configurazione di OpenCode per questo agente: fornitore e modello, niente aggiornamenti da s\xe9. La porta la aggiunge il client al lancio.",
+ "qwen_non_installato": "Qwen Code {versione} non si \xe8 installato: {perche}",
+ "npm_muto": "npm muto",
+ "cosa_posta_ruolo": "i messaggi del ruolo",
+ "settings_file": "\u26a0\ufe0f le --settings di questa riga sono un file: {cosa} non ci entra",
+ "cosa_ricerca_spenta": "la ricerca web spenta",
+ "rito_apertura_descrizione": "Apre la sessione col tuo utente: i passi del tuo ruolo te li porta Delminio",
+ "rito_apertura_corpo": "Apro la sessione.",
+ "rito_chiusura_descrizione": "Chiude la sessione col tuo utente: i passi del tuo ruolo te li porta Delminio",
+ "rito_chiusura_corpo": "Chiudo la sessione.",
+ "rito_plugin": "/apertura e /chiusura per gli agenti con un ruolo di Delminio",
+ "rito_negato": "\u26a0\ufe0f Delminio non ha dato il testo di /{parola}: {perche}. Dillo al tuo utente.",
+ "rito_muto": "\u26a0\ufe0f Delminio non risponde: il testo di /{parola} non \xe8 arrivato. Dillo al tuo utente.",
+ "chiudi_commento": "A fine sessione: ci\xf2 che hai scritto entra nella storia della tua area di lavoro, e va al suo\nrepo se ne ha uno. Lo scrive Delminio a ogni avvio; non prende argomenti. Se l'area di lavoro ha un suo prima-di-chiudere.sh, lo esegue prima.",
+ "chiudi_niente": "niente di nuovo da mettere nella storia",
+ "chiudi_nella_storia": "\u2705 nella storia: {commit}",
+ "chiudi_senza_repo": "la tua area di lavoro non ha un repo dove mandarla: la storia resta qui",
+ "chiudi_mandata": "\u2705 mandata al suo repo",
+ "chiudi_push_fallito": "\u26a0\ufe0f il push non \xe8 passato, dillo al tuo utente: {errore}",
+ "non_si_clona": "non si clona",
+ "pull_fallito": "il pull non \xe8 passato",
+ "altri_file": "- \u2026 e altri {n} file",
+ "repo_ruolo_lontano_nuova": "il repo del ruolo ({repo}) da qui non si raggiunge: la storia resta nell'area di lavoro",
+ "repo_ruolo_cambiato": "il repo del ruolo \xe8 cambiato: ora {repo}",
+ "repo_ruolo_lontano": "il repo del ruolo da qui non si raggiunge: lavori sull'area di lavoro di prima",
+ "casa_ferma": "l'area di lavoro non si aggiorna dal suo repo: lavori su quella di prima",
+ "uso_casa": "uso: casa <delminio.sh del progetto> <ruolo> <agente> [<cartella>]",
+ "casa_nel_progetto": "\u26a0\ufe0f {agente}: l'area di lavoro isolata non pu\xf2 stare nel progetto (n\xe9 contenerlo): l\xec ci sono i suoi file veri. Cambia la cartella dell'agente nella vista Agenti.",
+ "casa_non_detta": "\u26a0\ufe0f {agente}: Delminio non ha detto dov'\xe8 l'area di lavoro ({errore}): lavori su quella di prima.",
+ "casa_senza_repo": "\u26a0\ufe0f {agente}: Delminio non ha detto quali repo vede il ruolo ({errore}): l'area di lavoro non si crea.",
+ "novita_titolo": "Cosa \xe8 cambiato",
+ "novita_uscito": "Il tuo ruolo non lo vede pi\xf9: \xe8 uscito dall'area di lavoro.",
+ "novita_non_si_clona": "\u26a0\ufe0f Da questa macchina non si clona ({repo}): {perche}. Dillo al tuo utente.",
+ "novita_copia_repo": "La copia \xe8 stata creata adesso: \xe8 il repo com'\xe8.",
+ "avviso_non_si_clona": "{repo} non si clona: {perche}",
+ "avviso_non_si_aggiorna": "{repo} non si aggiorna: {perche}",
+ "novita_non_si_aggiorna": "\u26a0\ufe0f Non si aggiorna ({perche}): lavori sulla copia di prima.",
+ "novita_niente": "Niente di nuovo dall'ultima volta.",
+ "novita_uscito_spazio": "(Il repo \xab{repo}\xbb non \xe8 pi\xf9 dello spazio: non si copia.)",
+ "copia_progetto_ferma": "la copia del progetto non si aggiorna: {perche}",
+ "progetto_non_si_copia": "\u26a0\ufe0f {agente}: non riesco a copiare il progetto in {casa}",
+ "novita_copia_progetto": "La copia \xe8 stata creata adesso: \xe8 il progetto com'\xe8, nella cartella progetto/.",
+ "novita_al_tecnico": "Da dire al tuo utente",
+ "commento_al_lancio": "Prima di partire, il registro: se nella vista Agenti \xe8 stata scelta un'altra versione,\nil comando si allinea adesso e riparte riscritto. Se non riesce, parte com'era.",
+ "commento_prompt": "Il system prompt da Delminio, in un file col pid (che exec lascia alla CLI): quelli\ndelle CLI gi\xe0 chiuse li elimina l'avvio dopo. Senza prompt l'agente non si avvia a met\xe0.",
+ "prompt_negato": "\u26a0\ufe0f {nome}: Delminio non ha dato il system prompt del ruolo \xab{porta}\xbb (HTTP {codice}).",
+ "commento_hook_sistema": "Gli hook lo leggono: le regole sono gi\xe0 in cima.",
+ "codex_ruolo_solo": "un ruolo con la sola sua met\xe0 su Codex non c'\xe8 ancora: la memoria del ruolo passa da --mcp-config, che Codex non ha",
+ "wrapper_descrizione_serie": "un eseguibile di Delminio",
+ "wrapper_commento": "Lo scrive il client \xabeseguibili\xbb di Delminio dal suo registro (vista Agenti):\nintatto si riscrive a ogni allineamento; se lo cambi resta tuo, e Delminio non lo tocca pi\xf9.",
+ "commento_login_codex": "Il login \xe8 della persona: quello del suo Codex, con un link (mai una copia).",
+ "wrapper_senza_repo": "\u26a0\ufe0f {nome}: qui non c'\xe8 un repo collegato a Delminio. Entra nel clone del progetto.",
+ "fornitore_ignoto": "il fornitore \xab{fornitore}\xbb di Qwen Code questo Delminio non lo conosce",
+ "wrapper_senza_chiave": "\u26a0\ufe0f {nome}: manca la chiave di {fornitore}. Mettila nel tuo ambiente, come {variabile}=\u2026 (nel profilo della shell), e rilancia.",
+ "commento_settings_qwen": "Le impostazioni di Qwen Code per questo agente: fornitore e modello, e niente che parli ad Alibaba.",
+ "commento_mie_qwen": "Lo strato della persona: ~/.config/delminio/mie-qwen.json e, per questo solo agente, mie.json in questa cartella, uniti sopra le impostazioni qui sopra a ogni avvio. Delminio non li scrive mai; restano sue solo le chiavi in QWEN_DI_DELMINIO, e le sue opzioni cedono alle chiavi che lo strato scrive.",
+ "mie_qwen_illeggibili": "\u26a0\ufe0f {file} non \xe8 un JSON valido, e l'agente parte con le sole impostazioni di Delminio: {errore}",
+ "commento_mie_codex": "Lo strato della persona: ~/.config/delminio/mie-codex.toml, unito a ogni avvio nel config.toml che Delminio prepara per Codex. Delminio non lo scrive mai; restano sue solo le chiavi in CODEX_DI_DELMINIO, e le sue opzioni cedono alle chiavi che lo strato scrive.",
+ "mie_di_delminio": "\u26a0\ufe0f {nome} resta di Delminio: nelle tue impostazioni non vale, e l'agente usa la sua.",
+ "mie_della_riga": "\u26a0\ufe0f {nome} la sceglie l'agente (vista Agenti): nelle tue impostazioni non vale.",
+ "mie_codex_illeggibili": "\u26a0\ufe0f {file} non si legge come TOML, e l'agente parte con le sole impostazioni di Delminio: {errore}",
+ "mie_codex_casa_illeggibile": "\u26a0\ufe0f {file} non si legge a pezzi: le tue impostazioni stavolta non entrano, e il file resta com'\xe8 ({errore})",
+ "mie_codex_scontro": "\u26a0\ufe0f {file} si scontra con la configurazione che Delminio prepara per Codex, e l'agente parte senza le tue impostazioni: {errore}",
+ "mie_toml_chiave": "riga {riga}: qui ci vuole una chiave o un'intestazione",
+ "mie_toml_aperta": "riga {riga}: una stringa su pi\xf9 righe che non si chiude",
+ "explore_descrizione": "Agente veloce in sola lettura per esplorare il codice: trova file per schema (es. \"src/components/**/*.tsx\"), cerca parole nel codice (es. \"gli endpoint delle API\") o risponde a domande sul codice (es. \"come funzionano gli endpoint?\"). Di' quanto a fondo: \"veloce\", \"medio\" o \"a fondo\".",
+ "explore_prompt": "Sei un agente specializzato nella ricerca nei file: esplori il codice a fondo.\n\n\xc8 un lavoro in SOLA LETTURA: hai solo gli strumenti per trovare, cercare e leggere i file. Non provare a creare, modificare, spostare o cancellare niente, e non provare a lanciare comandi.\n\nCome lavori:\n- glob per cercare i file per schema\n- grep_search per cercare nel contenuto dei file con una regex\n- read_file quando sai quale file ti serve\n- adatta la ricerca a quanto a fondo ti \xe8 stato chiesto\n- quando puoi, fai pi\xf9 ricerche e letture in parallelo\n- i percorsi dei file nella risposta finale sono sempre assoluti\n- il resoconto lo scrivi direttamente come messaggio, senza emoji\n\nNella risposta finale dai i percorsi assoluti dei file che contano per il lavoro. Riporta il codice solo quando il testo esatto conta (un difetto trovato, la firma di una funzione che ti hanno chiesto): non riassumere il codice che hai solo letto.",
+ "commento_casa": "L'area di lavoro isolata: i repo che il suo ruolo vede, aggiornati, e `consegne/` dove scrive.",
+ "commento_autoupdater": "la versione la decide il registro, non la CLI",
+ "commento_catalogo_opencode": "l'elenco dei modelli \xe8 quello dentro OpenCode: nessuna richiesta a models.opencode.ai",
+ "commento_token_progetto": "Il token \xe8 del progetto: si passa dal client del repo collegato in cui sei\n(un worktree non ha il client, che sta nel clone principale).",
+ "wrapper_senza_repo_claude": "\u26a0\ufe0f {nome}: qui non c'\xe8 un repo collegato a Delminio. Entra nel clone del progetto, o apri claude.",
+ "wrapper_altro_spazio": "\u26a0\ufe0f {nome}: \xe8 un ruolo dello spazio \xab{spazio}\xbb, e questa cartella \xe8 collegata a un altro spazio. Entra nel clone di un progetto di quello spazio.",
+ "spazio_principale": "principale",
+ "pulizia": " pulizia: rimosse {n} versioni ({tolte}), tenute {tenute}{riparo}",
+ "potate": " versioni che nessuno usa, eliminate: {tolte}",
+ "errori_testa": "Le chiamate di tool fallite su questo computer negli ultimi {giorni} giorni: {n} (il registro: {file})",
+ "errori_nascosti": " {n} non sono errori (un Esc, un comando che dice no per mestiere): li mostra --tutti",
+ "errori_nessuno": " nessuna.",
+ "errori_per_specie": "Per specie:",
+ "errori_per_programma": "Per tool e programma:",
+ "errori_ultime": "Le ultime:",
+ "nessuna": "nessuna",
+ "al_riparo": " (di riserva: {versione})",
+ "installo_chiesta": " l'amministratore chiede {cli} su questa macchina: lo installo",
+ "prova_strumento": "Conta le lettere di una parola.",
+ "prova_chiedi": "Usa lo strumento conta_lettere sulla parola \xabDelminio\xbb. Non rispondere a parole.",
+ "prova_regola": "Regola {i} di questa prova: rispondi in breve, nella lingua di chi scrive, e non inventare ci\xf2 che non sai.",
+ "prova_senza_chiave": "manca la chiave: mettila nell'ambiente come {variabile}=\u2026 e rilancia",
+ "prova_sistema": "Sei un assistente che usa gli strumenti.",
+ "prova_chiave_rifiutata": "il fornitore rifiuta la chiave ({codice}): {testo}",
+ "prova_strumento_errore": "la richiesta con lo strumento risponde {codice}",
+ "prova_ok": "Rispondi solo: ok.",
+ "prova_senza_strumento": "il modello non ha chiamato lo strumento: non pu\xf2 lavorare con Delminio",
+ "prova_contesto_stretto": "contesto di {contesto} token: stretto",
+ "prova_cache_muta": "il fornitore non dice cosa legge dalla cache",
+ "aiuto_descrizione": "Gli eseguibili di Delminio su questa macchina, sincronizzati col registro.",
+ "aiuto_nomi": "per rinomina: il vecchio e il nuovo",
+ "aiuto_da": "per spazio: il client .claude/delminio.sh di un progetto collegato",
+ "aiuto_converti": "con --modo kit, riscrive anche i wrapper scritti con `--modo casa`",
+ "aiuto_vuoi": "la CLI che la persona ha scelto al collegamento: si installa anche se qui non c'\xe8",
+ "aiuto_primo": "un file dove scrivere il comando del primo agente di quella CLI, per lanciarlo",
+ "nessun_agente_di": "In questo spazio non c'\xe8 ancora un agente {cli}: l'amministratore lo accende nella vista Agenti, con \xabAggiungi agente\xbb, poi si rilancia il collegamento.",
+ "aiuto_al_lancio": "allinea: lo chiede il wrapper prima di partire \u2014 esce 0 se il registro \xe8 gi\xe0 quello applicato, 3 se ha allineato e il comando va rilanciato",
+ "servono_url_token": "servono --url e --token-file (o --da)",
+ "rifiutati": "segnato: su questa macchina gli eseguibili di Delminio non si propongono pi\xf9",
+ "lasciati": " gli eseguibili di questo spazio: {n} rimossi da questa macchina",
+ "registro_muto": "\u26a0\ufe0f il registro degli eseguibili non arriva da {url}: {errore}",
+ "nomi_fuori_forma": "\u26a0\ufe0f righe del registro con un nome fuori forma, saltate: {nomi}",
+ "uso_prova": "prova NOME \u2014 il nome di un agente Qwen Code del registro (vista Agenti)",
+ "prova_inizio_locale": "Prova di {nome} ({modello}): tre richieste al server locale\u2026",
+ "prova_inizio_fornitore": "Prova di {nome} ({modello}): tre richieste al fornitore, pochi centesimi\u2026",
+ "prova_non_fatta": "\u26a0\ufe0f la prova non si \xe8 fatta: {errore}",
+ "prova_riga_strumenti": " strumenti: {valore}",
+ "prova_si": "s\xec",
+ "prova_no": "NO",
+ "prova_riga_cache": " cache: {valore}",
+ "prova_cache_non_detta": "il fornitore non lo dice",
+ "prova_cache_letti": "{letti} token letti su {totale}",
+ "prova_riga_contesto": " contesto: {valore}",
+ "prova_non_lo_dice": "non lo dice",
+ "prova_riga_verdetto": " verdetto: {valore}{nota}",
+ "prova_va": "va",
+ "prova_senza_cache": "va, ma senza cache: ogni richiesta si paga piena",
+ "prova_non_va": "non va",
+ "verdetto_perso": "\u26a0\ufe0f il verdetto non \xe8 arrivato a Delminio: {errore}",
+ "uso_rinomina": "rinomina VECCHIO NUOVO",
+ "rinomina_assente": "\u274c nel registro non c'\xe8 \xab{nome}\xbb",
+ "rinomina_rifiutata": "\u274c Delminio non rinomina: {errore}",
+ "rinominato": "\u2705 \xab{vecchio}\xbb ora si chiama \xab{nuovo}\xbb nel registro: \xaballinea\xbb scrive il comando nuovo e rimuove il vecchio su ogni macchina",
+ "stato_assente": "non c'\xe8",
+ "stato_cambiato": "cambiato da chi lo usa: resta suo",
+ "stato_non_suo": "c'\xe8, ma non \xe8 di Delminio",
+ "stato_intatto": "intatto",
+ "stato_altro_spazio": "intatto, ma \xe8 il comando di un altro spazio ({spazi})",
+ "stato_riga": "{nome}: CLI {versione}{da_scaricare} \xb7 {modello} \xb7 porta {porta} \xb7 {stato}",
+ "da_scaricare": " (da scaricare)",
+ "modello_di_serie": "modello di default",
+ "stato_rifiutato": "l'utente ha detto che non li vuole su questa macchina (allinea li scrive lo stesso)",
+ "registro_vuoto": "il registro \xe8 vuoto: nessun eseguibile",
+ "allinea_in_corso": " un altro allineamento \xe8 in corso su questa macchina: lo lascio finire",
+ "al_lancio": "\u23f3 nella vista Agenti \xe8 cambiato qualcosa: allineo i comandi prima di partire\u2026",
+ "al_lancio_attesa": "\u23f3 un allineamento \xe8 gi\xe0 in corso su questa macchina: aspetto che finisca, poi parto sulla versione nuova\u2026",
+ "senza_cli_qui": " {nome}: su questa macchina non c'\xe8 {cli}, non lo scarico",
+ "passo_controllo": "{nome}: controllo {cli} {versione}",
+ "passo_scarico": "{nome}: scarico {cli} {versione}, {mb} MB",
+ "passo_di": " di {mb}",
+ "non_di_delminio": "\u274c {percorso} c'\xe8 gi\xe0 e non \xe8 di Delminio: scegli un altro nome nella vista Agenti.",
+ "toccato_resta": " {percorso}: cambiato da chi lo usa, resta com'\xe8",
+ "smista_testa": "agente di pi\xf9 spazi su questa macchina: lo spazio lo decide la cartella in cui lo lanci",
+ "smista_fuori": "\u26a0\ufe0f {nome} \xe8 un agente di pi\xf9 spazi su questa macchina ({spazi}): lancialo dalla cartella di un progetto collegato, e lo spazio lo decide lei.",
+ "smista_non_qui": "\u26a0\ufe0f {nome} non \xe8 un agente dello spazio di questa cartella: \xe8 di {spazi}. Lancialo dalla cartella di un progetto di uno di quegli spazi.",
+ "smistato": "\U0001f500 {nome}: pi\xf9 spazi di questa macchina lo vogliono, con righe diverse ({spazi}). Il nome resta uno: lo spazio lo decide la cartella in cui lo lanci.",
+ "scritto": "\u2705 {percorso}: scritto (CLI {versione})",
+ "aggiornato": "\u2705 {percorso}: aggiornato, CLI {prima} \u2192 {versione}",
+ "rinfrescato": "\u267b\ufe0f {percorso}: riscritto con la stessa CLI {versione} ({righe} righe cambiate: il perch\xe9 in eseguibili-diario.log, accanto al registro dei comandi)",
+ "passo_scritto": "{nome}: scritto, {cli} {versione}",
+ "lasciato_ad_altri": " {percorso}: questo spazio lo lascia, resta per {spazi}",
+ "tolto": " {percorso}: rimosso, non \xe8 pi\xf9 nel registro",
+ "fuori_dal_path": "\u26a0\ufe0f {cartella} non \xe8 nel PATH: aggiungi export PATH=\"{cartella}:$PATH\" al profilo della shell (~/.bashrc, ~/.zshrc), o lancia gli eseguibili col percorso intero.",
+ "wrapper_chiave_negata": "\u26a0\ufe0f {nome}: Delminio non mi d\xe0 la chiave \xab{scelta}\xbb scelta nella vista Agenti. La risposta:",
+ "commento_chiave_dal_motore": "La chiave del fornitore la sceglie l'amministratore nella vista Agenti: si chiede a Delminio a ogni\nlancio e resta solo nell'ambiente di questo processo \u2014 mai in un file, mai nel profilo della shell.",
+ "commento_chiave_di_qwen": "La chiave data a Qwen Code al suo primo avvio, se nell'ambiente non c'\xe8.",
+ "prova_chiave_negata": "Delminio non d\xe0 la chiave \xab{scelta}\xbb scelta nella vista Agenti: {errore}",
+ "commento_progetto_di_riserva": "Lanciato da fuori da un repo collegato (la sua cartella, una qualunque): il repo di questo\nspazio da cui il client si \xe8 allineato l'ultima volta.",
+ "wrapper_casa_senza_repo": "\u26a0\ufe0f {nome}: non so ancora da quale repo collegato prendere la chiave. Lancialo una volta da dentro un repo collegato a questo spazio: dopo parte da dove vuoi.",
+ "commento_plugin_codex": "Il plugin di Delminio nella cartella di Codex di questo agente: gli hook arrivano da l\xec.",
+ "posta_ruolo_rifiutata": "\u26a0\ufe0f Delminio rifiuta il token di questo ruolo (HTTP {codice}): i messaggi delle altre sessioni non ti arrivano. Si riprova a ogni messaggio; questo avviso esce una volta sola, dillo al tuo utente.",
+ "porto_non_qui": "\U0001f4e6 \xab{cartella}\xbb non si manda alla squadra: non \xe8 una skill, un comando o un agente dentro le cartelle che le CLI leggono.",
+ "porto_troppo": "\U0001f4e6 \xab{cartella}\xbb \xe8 troppo grande per la squadra: al pi\xf9 {file} file e {peso} byte di testo.",
+ "porto_fatto": "\U0001f4e6 \xab{nome}\xbb \xe8 nella squadra: dal prossimo avvio arriva a ogni agente.",
+ "porto_no": "\U0001f4e6 \xab{cartella}\xbb resta fuori dalla squadra: {errore}",
+ "squadra_muta": "\U0001f465 Le skill della squadra non sono arrivate ({errore}): restano quelle di prima, ci si riprova al prossimo avvio.",
+ "squadra_qui": "\U0001f465 La squadra su questo computer, nel plugin \xab{plugin}\xbb: {skill} skill, {comandi} comandi, {agenti} agenti, {mcp} server MCP.",
+ "squadra_plugin_qui": "\U0001f50c I plugin della squadra: {accettati} accettati su questo computer \xb7 {fermi} aspettano l'approvazione del tuo utente (delminio accetta, da un suo terminale).",
+ "riga_da_accettare": "\u23f8 {nome}: il registro gli d\xe0 argomenti o variabili d'ambiente che su questo computer non hai ancora accettato. Resta il comando di prima; da un tuo terminale: delminio accetta",
+ "accetta_senza_terminale": "delminio accetta si lancia da un terminale: un agente non pu\xf2 accettare al posto tuo.",
+ "accetta_riga_domanda": "\nL'agente \xab{nome}\xbb ({cli}) dello spazio {spazio} partirebbe con:\n argomenti: {argomenti}\n ambiente: {ambiente}\n\nGirano su questo computer, coi tuoi permessi, ogni volta che lo lanci. Li accetti? [s/N] ",
+ "accetta_si": "s si s\xec y yes",
+ "accetta_righe_esito": "\u2705 agenti: {nuovi} accettati ora \xb7 {restano} restano fermi (se uno cambia, lo richiedo). I comandi si riscrivono alla prossima apertura."
+}
+
+def F(chiave, **sost):
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+def _esc(t):
+ return re.sub('([\\\\"$`])', '\\\\\\1', t)
+
+def _sh(t, **codice):
+ q = '"' + _esc(t) + '"'
+ for k, v in codice.items():
+ q = q.replace('{' + k + '}', v)
+ return q
+
+def _printf(t, **args):
+ ordine = sorted(((t.index('{' + k + '}'), k) for k in args if '{' + k + '}' in t))
+ fmt = _esc(t.replace('%', '%%'))
+ for k in args:
+ fmt = fmt.replace('{' + k + '}', '%s')
+ return f'printf "{fmt}\\n" ' + ' '.join((args[k] for _, k in ordine))
+
+def _commento(testo):
+ return ['# ' + r for r in testo.split('\n')]
+
+def _v(t):
+ return tuple((int(x) for x in t.split('.')))
+
+def _get(url, token=None, timeout=30, metodo='GET', corpo=None, nome=False):
+ h = {'Authorization': f'Bearer {token}'} if token else {}
+ if nome:
+ h['User-Agent'] = 'delminio-eseguibili'
+ dati = None
+ if corpo is not None:
+ dati, h['Content-Type'] = (json.dumps(corpo).encode(), 'application/json')
+ req = urllib.request.Request(url, data=dati, headers=h, method=metodo)
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return r.read()
+
+def _scarica(url, timeout, su=None, nome=False):
+ h = {'User-Agent': 'delminio-eseguibili'} if nome else {}
+ with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=timeout) as r:
+ totale = int(r.headers.get('Content-Length') or 0)
+ pezzi, fatti, detti = ([], 0, 0)
+ while True:
+ pezzo = r.read(1 << 20)
+ if not pezzo:
+ break
+ pezzi.append(pezzo)
+ fatti += len(pezzo)
+ if su and fatti - detti >= 4 << 20:
+ detti = fatti
+ su(fatti, totale)
+ return b''.join(pezzi)
+
+def piattaforma():
+ s, m = (platform.system().lower(), platform.machine().lower())
+ arch = {'x86_64': 'x64', 'amd64': 'x64', 'aarch64': 'arm64', 'arm64': 'arm64'}.get(m)
+ if s not in ('linux', 'darwin') or not arch:
+ return None
+ p = f'{s}-{arch}'
+ if s == 'linux':
+ try:
+ ldd = subprocess.run(['ldd', '--version'], capture_output=True, text=True).stdout
+ ldd += subprocess.run(['ldd', '--version'], capture_output=True, text=True).stderr
+ except OSError:
+ ldd = ''
+ if 'musl' in ldd.lower() or any((f.startswith('ld-musl-') for f in os.listdir('/lib') if os.path.isdir('/lib'))):
+ p += '-musl'
+ return p
+
+def versione_voluta(riga, canali):
+ v = riga['versione']
+ if v in CANALI and _VERSIONE.match(str(riga.get('versione_oggi') or '')):
+ v = riga['versione_oggi']
+ if v in CANALI and riga.get('cli') != 'claude':
+ chi = CLI_NOMI.get(riga.get('cli'), riga.get('cli'))
+ raise RuntimeError(F('riga_senza_numero', cli=chi))
+ if v in CANALI:
+ if v not in canali:
+ canali[v] = _get(f'{RILASCI}/{CANALI[v]}', timeout=15).decode().strip()
+ v = canali[v]
+ if riga.get('minimo') and _VERSIONE.match(riga['minimo']) and _VERSIONE.match(v) and (_v(v) < _v(riga['minimo'])):
+ v = riga['minimo']
+ if not _VERSIONE.match(v):
+ raise RuntimeError(F('non_versione', versione=v))
+ return v
+
+def assicura_cli(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ if os.path.isfile(dove) and os.access(dove, os.X_OK):
+ return dove
+ p = piattaforma()
+ if not p:
+ raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ manifesto = json.loads(_get(f'{RILASCI}/{versione}/manifest.json', timeout=20))
+ voce = (manifesto.get('platforms') or {}).get(p)
+ if not voce:
+ raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p))
+ print(F('scarico_cli', versione=versione, piattaforma=p, mb=voce.get('size', 0) // 1000000), flush=True)
+ dati = _scarica(f"{RILASCI}/{versione}/{p}/{voce.get('binary', 'claude')}", 600, su=su)
+ if hashlib.sha256(dati).hexdigest() != voce.get('checksum'):
+ raise RuntimeError(F('checksum_cli', versione=versione))
+ os.makedirs(cartella, exist_ok=True)
+ with open(dove + '.nuovo', 'wb') as f:
+ f.write(dati)
+ os.chmod(dove + '.nuovo', 493)
+ os.replace(dove + '.nuovo', dove)
+ return dove
+
+def assicura_codex(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'codex')
+ if os.path.isfile(binario) and os.access(binario, os.X_OK):
+ return binario
+ target = CODEX_TARGET.get(piattaforma() or '')
+ if not target:
+ raise RuntimeError(F('senza_codex_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ rilascio = json.loads(_get(f'{CODEX_RILASCI}/{versione}/release.json', timeout=20, nome=True))
+ nome = f'codex-package-{target}.tar.gz'
+ voce = next((x for x in rilascio.get('assets') or [] if x.get('name') == nome), None)
+ if not voce or not str(voce.get('digest') or '').startswith('sha256:'):
+ raise RuntimeError(F('codex_senza_pacchetto', versione=versione, piattaforma=target))
+ print(F('scarico_codex', versione=versione, piattaforma=target), flush=True)
+ dati = _scarica(f'{CODEX_RILASCI}/{versione}/{nome}', 600, su=su, nome=True)
+ if hashlib.sha256(dati).hexdigest() != voce['digest'].split(':', 1)[1]:
+ raise RuntimeError(F('digest_codex', versione=versione))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
+ for m in t.getmembers():
+ fuori = lambda x: x.startswith('/') or '..' in x.split('/')
+ if fuori(m.name) or m.islnk() or m.isdev() or (m.issym() and fuori(m.linkname)):
+ raise RuntimeError(F('pacchetto_fuori', chi=f'Codex {versione}'))
+ t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
+ if not os.path.isfile(os.path.join(tappa, 'bin', 'codex')):
+ shutil.rmtree(tappa, ignore_errors=True)
+ raise RuntimeError(F('codex_senza_binario', versione=versione))
+ for f in ('bin/codex', 'bin/codex-code-mode-host', 'codex-path/rg', 'codex-resources/bwrap'):
+ if os.path.isfile(os.path.join(tappa, f)):
+ os.chmod(os.path.join(tappa, f), 493)
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+
+def _estrai(dati, tappa, chi):
+ with tarfile.open(fileobj=io.BytesIO(dati), mode='r:gz') as t:
+ for m in t.getmembers():
+ dentro = os.path.normpath(m.name)
+ if m.name.startswith('/') or dentro.startswith('..') or m.islnk() or m.isdev():
+ raise RuntimeError(F('pacchetto_fuori', chi=chi))
+ if m.issym():
+ dove = os.path.normpath(os.path.join(os.path.dirname(dentro), m.linkname))
+ if m.linkname.startswith('/') or dove.startswith('..'):
+ raise RuntimeError(F('pacchetto_fuori', chi=chi))
+ t.extractall(tappa, **{'filter': 'data'} if hasattr(tarfile, 'data_filter') else {})
+
+def node_di(versioni_qwen):
+ return os.path.join(os.path.dirname(os.path.normpath(versioni_qwen)), f'node-{NODE_QWEN}')
+
+def assicura_node(versioni_qwen, su=None):
+ dove = node_di(versioni_qwen)
+ if os.access(os.path.join(dove, 'bin', 'node'), os.X_OK):
+ return dove
+ target = NODE_TARGET.get(piattaforma() or '')
+ if not target:
+ raise RuntimeError(F('senza_node_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ nome = f'node-v{NODE_QWEN}-{target}'
+ somme = _get(f'{NODE_RILASCI}/v{NODE_QWEN}/SHASUMS256.txt', timeout=20).decode()
+ attesa = next((r.split()[0] for r in somme.splitlines() if r.endswith(f' {nome}.tar.gz')), '')
+ if not attesa:
+ raise RuntimeError(F('node_senza_pacchetto', versione=NODE_QWEN, piattaforma=target))
+ print(F('scarico_node', versione=NODE_QWEN), flush=True)
+ dati = _scarica(f'{NODE_RILASCI}/v{NODE_QWEN}/{nome}.tar.gz', 600, su=su)
+ if hashlib.sha256(dati).hexdigest() != attesa:
+ raise RuntimeError(F('checksum_node', versione=NODE_QWEN))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(tappa)
+ _estrai(dati, tappa, f'Node {NODE_QWEN}')
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(os.path.join(tappa, nome), dove)
+ shutil.rmtree(tappa, ignore_errors=True)
+ return dove
+
+def assicura_qwen(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'qwen')
+ if os.path.isfile(binario):
+ return binario
+ node = assicura_node(cartella, su=su)
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ print(F('installo_qwen', versione=versione), flush=True)
+ env = {**os.environ, 'PATH': os.path.join(node, 'bin') + os.pathsep + os.environ.get('PATH', ''), 'npm_config_update_notifier': 'false', 'npm_config_fund': 'false', 'npm_config_audit': 'false'}
+ r = subprocess.run([os.path.join(node, 'bin', 'npm'), 'install', '-g', '--prefix', tappa, '--cache', os.path.join(os.path.dirname(os.path.normpath(cartella)), 'npm-cache'), '--ignore-scripts', '--no-fund', '--no-audit', f'@qwen-code/qwen-code@{versione}'], env=env, capture_output=True, text=True, timeout=900)
+ if r.returncode != 0 or not os.path.isfile(os.path.join(tappa, 'bin', 'qwen')):
+ shutil.rmtree(tappa, ignore_errors=True)
+ coda = (r.stderr or r.stdout or '').strip().splitlines()[-3:]
+ raise RuntimeError(F('qwen_non_installato', versione=versione, perche=' / '.join(coda) or F('npm_muto')))
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+OPENCODE_NPM = 'https://registry.npmjs.org'
+OPENCODE_PACCHETTO = '@opencode/cli-{p}'
+
+def assicura_opencode(versione, cartella, prova, su=None):
+ if prova:
+ return prova
+ if not opencode_v2(versione):
+ raise RuntimeError(F('opencode_solo_v2', versione=versione))
+ dove = os.path.join(cartella, versione)
+ binario = os.path.join(dove, 'bin', 'opencode')
+ if os.path.isfile(binario) and os.access(binario, os.X_OK):
+ return binario
+ p = piattaforma()
+ if not p:
+ raise RuntimeError(F('senza_cli_ufficiale', sistema=f'{platform.system()} {platform.machine()}'))
+ pacchetto = OPENCODE_PACCHETTO.format(p=p)
+ try:
+ meta = json.loads(_get(f"{OPENCODE_NPM}/{pacchetto.replace('/', '%2F')}/{versione}", timeout=20))
+ except Exception:
+ raise RuntimeError(F('versione_assente', versione=versione, piattaforma=p)) from None
+ dist = meta.get('dist') or {}
+ integrity = str(dist.get('integrity') or '')
+ if not integrity.startswith('sha512-') or not dist.get('tarball'):
+ raise RuntimeError(F('opencode_integrita', versione=versione))
+ print(F('installo_opencode', versione=versione), flush=True)
+ dati = _scarica(dist['tarball'], 600, su=su)
+ if 'sha512-' + base64.b64encode(hashlib.sha512(dati).digest()).decode() != integrity:
+ raise RuntimeError(F('opencode_integrita', versione=versione))
+ tappa = dove + '.nuovo'
+ shutil.rmtree(tappa, ignore_errors=True)
+ os.makedirs(cartella, exist_ok=True)
+ _estrai(dati, tappa, f'OpenCode {versione}')
+ dentro = os.path.join(tappa, 'package', 'bin', 'opencode')
+ if not os.path.isfile(dentro):
+ shutil.rmtree(tappa, ignore_errors=True)
+ raise RuntimeError(F('opencode_senza_binario', versione=versione))
+ os.makedirs(os.path.join(tappa, 'bin'), exist_ok=True)
+ os.replace(dentro, os.path.join(tappa, 'bin', 'opencode'))
+ os.chmod(os.path.join(tappa, 'bin', 'opencode'), 493)
+ shutil.rmtree(os.path.join(tappa, 'package'), ignore_errors=True)
+ shutil.rmtree(dove, ignore_errors=True)
+ os.replace(tappa, dove)
+ return binario
+
+def _q(s):
+ return shlex.quote(str(s))
+
+def cli_qui(cli, versioni, versioni_codex, prova, versioni_qwen='', volute=(), versioni_opencode=''):
+ if prova:
+ return True
+ nome = cli if cli in CLI_NOMI else 'claude'
+ if shutil.which(nome) or cli in volute:
+ return True
+ cartella = {'codex': versioni_codex, 'qwen': versioni_qwen, 'opencode': versioni_opencode}.get(cli) or versioni
+ try:
+ return any((_VERSIONE.match(f) for f in os.listdir(cartella)))
+ except OSError:
+ return False
+
+def installa_agente(argv):
+ if len(argv) != 2 or argv[0] not in ('claude', 'codex', 'qwen', 'opencode'):
+ print(F('installa_agente_uso'), file=sys.stderr)
+ return 2
+ cli, versione = argv
+ prova = os.environ.get('DELMINIO_CLI_PROVA', '')
+ registro = os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
+ try:
+ v = versione if cli in ('qwen', 'opencode') else versione_voluta({'versione': versione, 'cli': cli}, {})
+ if not _VERSIONE.match(v):
+ raise RuntimeError(F('non_versione', versione=v))
+ if cli == 'claude':
+ binario = assicura_cli(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions'), prova)
+ elif cli == 'codex':
+ binario = assicura_codex(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions'), prova)
+ elif cli == 'qwen':
+ versioni_qwen = os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
+ binario = assicura_qwen(v, versioni_qwen, prova)
+ if not prova:
+ print('DELMINIO_NODE=' + os.path.join(node_di(versioni_qwen), 'bin'), flush=True)
+ else:
+ binario = assicura_opencode(v, os.path.expanduser(os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions'), prova)
+ except (RuntimeError, OSError, ValueError, urllib.error.URLError) as e:
+ print(F('installa_agente_no', cli=CLI_NOMI[cli], errore=e), file=sys.stderr)
+ return 1
+ mio = _leggi(registro)
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {cli})
+ _scrivi(registro, mio)
+ print(binario)
+ return 0
+
+def modello_gratuito(argv):
+ if len(argv) != 1 or not os.access(argv[0], os.X_OK):
+ print(F('modello_gratuito_uso'), file=sys.stderr)
+ return 2
+ oc = argv[0]
+ try:
+ elenco = subprocess.run([oc, '--standalone', 'models'], capture_output=True, text=True, timeout=60).stdout
+ except (OSError, subprocess.TimeoutExpired):
+ elenco = ''
+ candidati = [r.strip() for r in elenco.splitlines() if r.strip().startswith('opencode/') and r.strip().endswith('-free')]
+ for m in candidati:
+ try:
+ r = subprocess.run([oc, '--standalone', 'run', '-m', m, F('modello_gratuito_domanda')], capture_output=True, text=True, timeout=90, cwd=tempfile.gettempdir())
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+ if r.returncode == 0 and F('modello_gratuito_risposta').lower() in r.stdout.lower():
+ print(m)
+ return 0
+ print(F('modello_gratuito_nessuno', n=len(candidati)), file=sys.stderr)
+ return 1
+
+def personaggio(riga):
+ return bool(riga.get('porta')) and riga.get('nascita') == 'porta'
+
+def spazio_di(url, token):
+ u = url.rstrip('/')
+ try:
+ pezzo = token.split('.')[1]
+ cli = json.loads(base64.urlsafe_b64decode(pezzo + '=' * (-len(pezzo) % 4))).get('cli') or ''
+ except (IndexError, ValueError, AttributeError):
+ cli = ''
+ k = u if cli in ('', 'unico') else f'{u}#{cli}'
+ return _ALIASI.get(k, k)
+_ALIASI = {}
+
+def _alias(mio, chiave, istanza):
+ if not istanza:
+ return chiave
+ for k, sp in list((mio.get('spazi') or {}).items()):
+ if k != chiave and sp.get('istanza') == istanza and (k not in (mio.get('alias') or {})):
+ mio.setdefault('alias', {})[chiave] = k
+ _ALIASI[chiave] = k
+ mio.get('spazi', {}).pop(chiave, None)
+ for chi in (mio.get('padroni') or {}).values():
+ if chiave in chi:
+ chi[:] = list(dict.fromkeys((k if c == chiave else c for c in chi)))
+ return k
+ return chiave
+
+def _istanza_di(url, token):
+ try:
+ return json.loads(_get(url.rstrip('/') + '/api/eseguibili', token, timeout=10)).get('istanza') or ''
+ except (OSError, ValueError, AttributeError, urllib.error.URLError):
+ return ''
+
+def nome_spazio(spazio):
+ return spazio.rsplit('#', 1)[1] if '#' in spazio else F('spazio_principale')
+
+def _token_di(token_file):
+ try:
+ with open(os.path.expanduser(token_file), encoding='utf-8') as f:
+ return f.read().strip()
+ except OSError:
+ return ''
+
+def canale_del_ruolo(spazio, porta):
+ spazio = hashlib.sha256(spazio.encode()).hexdigest()[:12]
+ chiave = re.sub('[^a-z0-9._-]+', '-', porta.lower()).strip('-') or 'ruolo'
+ return os.path.join(os.path.expanduser('~/.config/delminio/ruoli'), spazio, chiave + '.json')
+
+def progetto_dello_spazio(spazio):
+ return os.path.join(os.path.dirname(canale_del_ruolo(spazio, 'x')), 'progetto')
+
+def ricorda_il_progetto(spazio):
+ qui = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ try:
+ c = subprocess.run(['git', '-C', qui, 'rev-parse', '--path-format=absolute', '--git-common-dir'], capture_output=True, text=True, timeout=10)
+ if c.returncode == 0 and c.stdout.strip():
+ qui = os.path.dirname(c.stdout.strip())
+ except (OSError, subprocess.SubprocessError):
+ pass
+ if not os.access(os.path.join(qui, '.claude', 'delminio.sh'), os.X_OK):
+ return
+ f = progetto_dello_spazio(spazio)
+ try:
+ with open(f, encoding='utf-8') as fh:
+ if fh.read().strip() == qui:
+ return
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
+ tmp = f + '.nuovo'
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as fh:
+ fh.write(qui + '\n')
+ os.replace(tmp, f)
+
+def _righe_del_repo(riga, spazio, avviso):
+ righe = ['r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi']
+ if (riga.get('scelte') or {}).get('casa') == 'separata' or riga.get('cartella'):
+ righe += [*_commento(F('commento_progetto_di_riserva')), 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', f' r=$(cat {_q(progetto_dello_spazio(spazio))} 2>/dev/null) || r=""', 'fi']
+ avviso = F('wrapper_casa_senza_repo', nome=riga['nome'])
+ return righe + ['if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' echo ' + _sh(avviso) + ' >&2', ' exit 1', 'fi']
+
+def assicura_canale(base_url, token, porta):
+ f = canale_del_ruolo(spazio_di(base_url, token), porta)
+ precedente, col_nome = ('', False)
+ if os.path.isfile(f):
+ try:
+ with open(f, encoding='utf-8') as h:
+ srv = json.load(h)['mcpServers']
+ col_nome = SERVER_RUOLO in srv
+ precedente = (srv.get(SERVER_RUOLO) or srv['delminio-ruolo'])['headers']['Authorization'].removeprefix('Bearer ')
+ except (ValueError, KeyError, TypeError, FileNotFoundError):
+ pass
+ d = json.loads(_get(base_url.rstrip('/') + '/api/porte/' + urllib.parse.quote(porta) + '/token', token, metodo='POST', corpo={'precedente': precedente}))
+ if precedente and d['token'] == precedente and col_nome:
+ return f
+ os.makedirs(os.path.dirname(f), mode=448, exist_ok=True)
+ conf = {'mcpServers': {SERVER_RUOLO: {'type': 'http', 'url': base_url.rstrip('/') + '/mcp', 'headers': {'Authorization': 'Bearer ' + d['token']}}}}
+ fd = os.open(f + '.nuovo', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384)
+ with os.fdopen(fd, 'w', encoding='utf-8') as h:
+ json.dump(conf, h)
+ os.replace(f + '.nuovo', f)
+ return f
+
+def ganci_della_posta(canale):
+
+ def cmd(momento):
+ return f'python3 "$DELMINIO_POSTA_CLIENT" posta-ruolo {_q(canale)} {momento}'
+ pulizia = {'type': 'command', 'command': 'python3 "$DELMINIO_POSTA_CLIENT" pulizia', 'timeout': 10}
+ return {'UserPromptSubmit': [{'hooks': [{'type': 'command', 'command': cmd('umano'), 'timeout': 30}]}], 'PostToolUse': [{'hooks': [{'type': 'command', 'command': cmd('volo'), 'timeout': 10}]}], 'Stop': [{'hooks': [{'type': 'command', 'command': cmd('attesa'), 'timeout': 43200, 'asyncRewake': True}, dict(pulizia)]}], 'SessionEnd': [{'hooks': [dict(pulizia)]}]}
+
+def con_i_ganci(args, ganci):
+ return con_le_impostazioni(args, {'hooks': ganci}, F('cosa_posta_ruolo'))
+
+def _unisci(s, extra):
+ for k, v in extra.items():
+ if isinstance(v, dict) and isinstance(s.get(k), dict):
+ _unisci(s[k], v)
+ elif isinstance(v, list) and isinstance(s.get(k), list):
+ s[k].extend((x for x in v if x not in s[k]))
+ else:
+ s.setdefault(k, v)
+
+def con_le_impostazioni(args, extra, cosa):
+ args = list(args)
+ for i, a in enumerate(args[:-1]):
+ if a == '--settings' and args[i + 1].lstrip().startswith('{'):
+ try:
+ s = json.loads(args[i + 1])
+ except ValueError:
+ break
+ _unisci(s, json.loads(json.dumps(extra)))
+ args[i + 1] = json.dumps(s, ensure_ascii=False, separators=(',', ':'))
+ return args
+ if '--settings' in args:
+ sys.stderr.write(F('settings_file', cosa=cosa) + '\n')
+ return args
+ return args + ['--settings', json.dumps(extra, ensure_ascii=False, separators=(',', ':'))]
+PERMESSI = {'claude': {'chiede': ['--permission-mode', 'manual'], 'modifiche': ['--permission-mode', 'acceptEdits'], 'classificatore': ['--permission-mode', 'auto']}, 'codex': {'chiede': ['-s', 'read-only', '-a', 'on-request'], 'modifiche': ['-s', 'workspace-write', '-a', 'on-request'], 'classificatore': ['--approve-for-me']}, 'qwen': {'chiede': ['--approval-mode', 'default'], 'modifiche': ['--approval-mode', 'auto-edit'], 'classificatore': ['--approval-mode', 'auto']}}
+
+def ambiente_della_riga(riga):
+ return {k: v for k, v in (riga.get('ambiente') or {}).items() if not str(k).startswith('DELMINIO_')}
+
+def lancio_delle_scelte(riga):
+ sc, cli = (riga.get('scelte') or {}, riga.get('cli') or 'claude')
+ args, env = (list(PERMESSI.get(cli, {}).get(sc.get('permessi'), [])), {})
+ if sc.get('conversazioni') in CONVERSAZIONI:
+ env['DELMINIO_CONVERSAZIONI'] = sc['conversazioni']
+ if cli == 'opencode':
+ return (args, env)
+ if cli == 'qwen':
+ if sc.get('ricerca_web') == 'spenta':
+ args += ['--exclude-tools', 'web_search', '--exclude-tools', 'web_fetch']
+ return (args, env)
+ if cli == 'codex':
+ if sc.get('ricerca_web') == 'spenta':
+ args += ['-c', 'web_search="disabled"']
+ if sc.get('telemetria') == 'spenta':
+ args += ['-c', 'analytics.enabled=false', '-c', 'feedback.enabled=false']
+ if sc.get('velocita') == 'fast':
+ args += ['-c', 'service_tier="fast"', '-c', 'features.fast_mode=true']
+ return (args, env)
+ if sc.get('ricerca_web') == 'spenta':
+ args = con_le_impostazioni(args, {'permissions': {'deny': ['WebSearch', 'WebFetch']}}, F('cosa_ricerca_spenta'))
+ if sc.get('telemetria') == 'spenta':
+ env.update({'DISABLE_TELEMETRY': '1', 'DISABLE_ERROR_REPORTING': '1', 'CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY': '1'})
+ if sc.get('classificatore'):
+ env['CLAUDE_CODE_AUTO_MODE_MODEL'] = sc['classificatore']
+ if sc.get('casa') == 'separata':
+ args += ['--restricted', '--allowedTools=Edit(consegne/**)']
+ return (args, env)
+
+def _pid_della_cli():
+ pid = os.getppid()
+ for _ in range(4):
+ try:
+ exe = os.path.basename(os.readlink(f'/proc/{pid}/exe'))
+ if _VERSIONE.match(exe) or exe == 'claude':
+ return pid
+ with open(f'/proc/{pid}/stat', encoding='utf-8') as f:
+ pid = int(f.read().rsplit(')', 1)[1].split()[1])
+ except (OSError, ValueError, IndexError):
+ break
+ return os.getppid()
+
+def _rito_del_ruolo():
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'rito-del-ruolo')
+_SKILL_DEL_RITO = {'apertura': (F('rito_apertura_descrizione'), F('rito_apertura_corpo')), 'chiusura': (F('rito_chiusura_descrizione'), F('rito_chiusura_corpo'))}
+COMANDI = {
+ "riti": {
+ "apertura": "apertura",
+ "chiusura": "chiusura",
+ "closing": "chiusura",
+ "handoff": "chiusura",
+ "opening": "apertura",
+ "start": "apertura"
+ }
+}
+_SINONIMI_DEL_RITO = dict(COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'})
+_SKILL_DEL_RITO.update({nome: _SKILL_DEL_RITO[nostra] for nome, nostra in _SINONIMI_DEL_RITO.items()})
+
+def assicura_rito():
+ voluti = {os.path.join('.claude-plugin', 'plugin.json'): json.dumps({'name': 'delminio', 'description': F('rito_plugin')}, ensure_ascii=False, indent=2) + '\n'}
+ for nome, (descrizione, corpo) in _SKILL_DEL_RITO.items():
+ voluti[os.path.join('skills', nome, 'SKILL.md')] = f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\ndisable-model-invocation: true\n---\n{corpo} $ARGUMENTS\n'
+ for rel, testo in voluti.items():
+ p = os.path.join(_rito_del_ruolo(), rel)
+ try:
+ with open(p, encoding='utf-8') as f:
+ if f.read() == testo:
+ continue
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.replace(p + '.nuovo', p)
+ return _rito_del_ruolo()
+_NOMI_DEL_RITO = '|'.join((re.escape(n) for n in sorted(_SINONIMI_DEL_RITO, key=len, reverse=True)))
+_GESTO_DEL_RITO = re.compile('(?:/(?:delminio:)?(' + _NOMI_DEL_RITO + ')(?:\\s.*)?|(' + _NOMI_DEL_RITO + ')\\s*(?::.*)?)', re.I | re.S)
+
+def _rito_del_messaggio(base, token, radice, evento):
+ prima = (evento.get('prompt') or '').strip().split('\n', 1)[0].strip()
+ m = _GESTO_DEL_RITO.fullmatch(prima)
+ parola = (m.group(1) or m.group(2)).lower() if m else ''
+ parola = _SINONIMI_DEL_RITO.get(parola, parola)
+ segno = radice + '.aperta'
+ if not parola and os.path.exists(segno):
+ return ''
+ q = urllib.parse.urlencode({'parola': parola or 'apertura', 'da_se': '' if parola else '1'})
+ try:
+ testo = json.loads(_get(f'{base}/api/canale/ruolo/rito?{q}', token, timeout=15)).get('testo') or ''
+ open(segno, 'w').close()
+ return testo
+ except urllib.error.HTTPError as e:
+ if not parola:
+ return ''
+ try:
+ perche = json.loads(e.read()).get('error') or str(e)
+ except ValueError:
+ perche = str(e)
+ return F('rito_negato', parola=parola, perche=perche)
+ except (OSError, ValueError, urllib.error.URLError):
+ return F('rito_muto', parola=parola) if parola else ''
+CHIUDI_SH = '\n'.join(['#!/bin/bash', *_commento(F('chiudi_commento')), 'CASA="$(cd "$(dirname "$0")" && pwd)"\ncd "$CASA" || exit 1\n[ -f "$CASA/prima-di-chiudere.sh" ] && bash "$CASA/prima-di-chiudere.sh"\ngit add -A\nif git diff --cached --quiet; then', ' echo ' + _sh(F('chiudi_niente')), 'else\n file=$(git diff --cached --name-only | head -8 | tr \'\\n\' \' \')\n git commit -q -m "$(git config user.name): $(date \'+%d/%m %H:%M\') — $file" \\', ' && echo ' + _sh(F('chiudi_nella_storia', commit='{commit}'), commit="$(git log -1 --format='%h %s')"), 'fi\nif ! git remote get-url origin >/dev/null 2>&1; then', ' echo ' + _sh(F('chiudi_senza_repo')), 'elif out=$(git push -q origin HEAD 2>&1); then echo ' + _sh(F('chiudi_mandata')), 'else echo ' + _sh(F('chiudi_push_fallito', errore='{errore}'), errore='$out') + '; fi', ''])
+_IGNORATI_DELLA_CASA = ('/repo/', '/progetto/', '/NOVITA.md', '/.visto*')
+
+def _riga_exec(*pezzi):
+ return 'exec ' + ' '.join((p for p in pezzi if p))
+
+def _chiave_repo(remoto):
+ r = (remoto or '').strip()
+ if not r or r.startswith('locale:'):
+ return r
+ if '://' in r:
+ r = r.split('://', 1)[1]
+ autorita, separatore, percorso = r.partition('/')
+ r = autorita.rsplit('@', 1)[-1] + separatore + percorso
+ host, _, percorso = r.partition('/')
+ host = host.split(':', 1)[0]
+ elif ':' in r and (not r.startswith('/')):
+ host, _, percorso = r.partition(':')
+ host = host.split('@', 1)[-1]
+ else:
+ return r.rstrip('/').removesuffix('.git')
+ return f"{host.lower()}/{percorso.strip('/').removesuffix('.git').rstrip('/')}"
+
+def _git(*args, cwd=None):
+ env = {**os.environ, 'GIT_TERMINAL_PROMPT': '0'}
+ return subprocess.run(['git', *args], cwd=cwd, env=env, capture_output=True, text=True)
+
+def _origine(cartella):
+ o = _git('remote', 'get-url', 'origin', cwd=cartella).stdout.strip()
+ if o and os.path.isdir(o):
+ o = _git('remote', 'get-url', 'origin', cwd=o).stdout.strip() or o
+ return o
+
+def _https(remoto):
+ c = _chiave_repo(remoto)
+ return f'https://{c}.git' if '/' in c and '.' in c.split('/', 1)[0] else ''
+
+def _clona(remoto, progetto, dest, cartelle):
+ fonti = []
+ if progetto and _chiave_repo(_origine(progetto)) == _chiave_repo(remoto):
+ fonti.append(progetto)
+ fonti += [remoto] + ([_https(remoto)] if _https(remoto) else [])
+ ultimo = ''
+ for f in fonti:
+ r = _git('clone', '-q', '--no-checkout', f, dest)
+ if r.returncode == 0:
+ if cartelle:
+ _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
+ c = _git('checkout', '-q', cwd=dest)
+ if c.returncode == 0:
+ return ''
+ ultimo = c.stderr.strip()
+ else:
+ ultimo = r.stderr.strip()
+ shutil.rmtree(dest, ignore_errors=True)
+ return ultimo.splitlines()[-1] if ultimo else F('non_si_clona')
+
+def _aggiorna(dest, cartelle):
+ if cartelle:
+ _git('sparse-checkout', 'set', '--no-cone', *cartelle, cwd=dest)
+ elif _git('config', 'core.sparseCheckout', cwd=dest).stdout.strip() == 'true':
+ _git('sparse-checkout', 'disable', cwd=dest)
+ r = _git('pull', '-q', '--ff-only', cwd=dest)
+ return '' if r.returncode == 0 else (r.stderr.strip().splitlines() or [F('pull_fallito')])[-1]
+
+def _testa(cartella):
+ return _git('rev-parse', 'HEAD', cwd=cartella).stdout.strip()
+
+def _uscito(cartella, prima, cartelle=(), quanti=40):
+ spec = [f":(exclude){c[1:].lstrip('/')}" if c.startswith('!') else c.lstrip('/') or '*' for c in cartelle]
+ file = _git('diff', '--name-only', f'{prima}..HEAD', '--', *spec, cwd=cartella).stdout.splitlines()
+ righe = [f'- {f}' for f in file[:quanti]]
+ if len(file) > quanti:
+ righe.append(F('altri_file', n=len(file) - quanti))
+ return righe
+
+def _la_casa_e_un_repo(casa, suo, agente):
+ avvisi = []
+ if not os.path.isdir(os.path.join(casa, '.git')):
+ vuota = not os.path.isdir(casa) or not os.listdir(casa)
+ if suo and vuota and (_git('clone', '-q', suo, casa).returncode == 0):
+ pass
+ else:
+ os.makedirs(casa, exist_ok=True)
+ _git('init', '-q', '-b', 'main', cwd=casa)
+ if suo:
+ _git('remote', 'add', 'origin', suo, cwd=casa)
+ if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
+ avvisi.append(F('repo_ruolo_lontano_nuova', repo=suo))
+ elif _git('rev-parse', '-q', '--verify', 'origin/main', cwd=casa).returncode == 0:
+ _git('checkout', '-q', '-B', 'main', 'origin/main', cwd=casa)
+ else:
+ ora = _git('remote', 'get-url', 'origin', cwd=casa).stdout.strip()
+ if suo and (not ora):
+ _git('remote', 'add', 'origin', suo, cwd=casa)
+ elif suo and _chiave_repo(ora) != _chiave_repo(suo):
+ _git('remote', 'set-url', 'origin', suo, cwd=casa)
+ avvisi.append(F('repo_ruolo_cambiato', repo=suo))
+ if suo or ora:
+ ramo = _git('rev-parse', '--abbrev-ref', 'HEAD', cwd=casa).stdout.strip() or 'main'
+ if _git('fetch', '-q', 'origin', cwd=casa).returncode != 0:
+ avvisi.append(F('repo_ruolo_lontano'))
+ elif _git('rev-parse', '-q', '--verify', f'origin/{ramo}', cwd=casa).returncode == 0 and _git('merge', '-q', '--ff-only', f'origin/{ramo}', cwd=casa).returncode != 0:
+ avvisi.append(F('casa_ferma'))
+ if not _git('config', '--local', 'user.name', cwd=casa).stdout.strip():
+ _git('config', 'user.name', agente, cwd=casa)
+ _git('config', 'user.email', f'{agente}@ruoli.delminio', cwd=casa)
+ return avvisi
+
+def _scrivi_se_cambia(percorso, testo, modo=None):
+ try:
+ with open(percorso, encoding='utf-8') as f:
+ if f.read() == testo:
+ return
+ except OSError:
+ pass
+ with open(percorso + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ if modo:
+ os.chmod(percorso + '.nuovo', modo)
+ os.replace(percorso + '.nuovo', percorso)
+
+def casa(argv):
+ if len(argv) not in (3, 4):
+ sys.stderr.write(F('uso_casa') + '\n')
+ return 2
+ client, ruolo, agente = argv[:3]
+ url = token_file = ''
+ for riga in open(client, encoding='utf-8'):
+ k, _, v = riga.strip().partition('=')
+ if k == 'URL' and v:
+ url = (shlex.split(v) or [''])[0]
+ elif k == 'FILE_TOKEN' and v:
+ token_file = (shlex.split(v) or [''])[0]
+ token = _token_di(token_file)
+ progetto = os.path.dirname(os.path.dirname(os.path.abspath(client)))
+ spazio = spazio_di(url, token)
+ casa = os.path.abspath(os.path.expanduser(argv[3])) if len(argv) == 4 and argv[3] else os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'case', hashlib.sha256(spazio.encode()).hexdigest()[:12], agente)
+ vero = os.path.realpath(progetto)
+ if os.path.realpath(casa) == vero or os.path.realpath(casa).startswith(vero + os.sep) or vero.startswith(os.path.realpath(casa) + os.sep):
+ sys.stderr.write(F('casa_nel_progetto', agente=agente) + '\n')
+ return 1
+ try:
+ conf = json.loads(_get(f"{url.rstrip('/')}/api/porte/{urllib.parse.quote(ruolo)}/casa", token, timeout=15))
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ if os.path.isdir(casa):
+ sys.stderr.write(F('casa_non_detta', agente=agente, errore=e) + '\n')
+ print(casa)
+ return 0
+ sys.stderr.write(F('casa_senza_repo', agente=agente, errore=e) + '\n')
+ return 1
+ avvisi = _la_casa_e_un_repo(casa, conf.get('suo') or '', agente)
+ if len(argv) == 3:
+ os.chmod(casa, 448)
+ os.makedirs(os.path.join(casa, 'consegne'), exist_ok=True)
+ scelti = {r['nome']: r for r in conf.get('repo') or []}
+ novita = ['# ' + F('novita_titolo'), '']
+ if scelti:
+ base = os.path.join(casa, 'repo')
+ os.makedirs(base, exist_ok=True)
+ shutil.rmtree(os.path.join(casa, 'progetto'), ignore_errors=True)
+ for d in sorted(os.listdir(base)):
+ if d not in scelti and os.path.isdir(os.path.join(base, d, '.git')):
+ shutil.rmtree(os.path.join(base, d), ignore_errors=True)
+ novita += [f'## repo/{d}', '', F('novita_uscito'), '']
+ for nome, r in scelti.items():
+ dest, cartelle = (os.path.join(base, nome), r.get('cartelle') or [])
+ if os.path.isdir(os.path.join(dest, '.git')) and _chiave_repo(_origine(dest)) != _chiave_repo(r['chiave']):
+ shutil.rmtree(dest, ignore_errors=True)
+ novita += [f'## repo/{nome}', '']
+ if not os.path.isdir(os.path.join(dest, '.git')):
+ perche = _clona(r['chiave'], progetto, dest, cartelle)
+ novita += [F('novita_non_si_clona', repo=r['chiave'], perche=perche) if perche else F('novita_copia_repo'), '']
+ if perche:
+ avvisi.append(F('avviso_non_si_clona', repo=f'repo/{nome}', perche=perche))
+ continue
+ prima = _testa(dest)
+ perche = _aggiorna(dest, cartelle)
+ if perche:
+ avvisi.append(F('avviso_non_si_aggiorna', repo=f'repo/{nome}', perche=perche))
+ novita.append(F('novita_non_si_aggiorna', perche=perche))
+ righe = _uscito(dest, prima, cartelle) if prima and prima != _testa(dest) else []
+ novita += (righe or ([F('novita_niente')] if not perche else [])) + ['']
+ for nome in conf.get('usciti') or []:
+ novita += [F('novita_uscito_spazio', repo=nome), '']
+ else:
+ base = os.path.join(casa, 'repo')
+ if os.path.isdir(base):
+ shutil.rmtree(base, ignore_errors=True)
+ dest = os.path.join(casa, 'progetto')
+ if os.path.isdir(os.path.join(dest, '.git')):
+ prima = _testa(dest)
+ perche = _aggiorna(dest, [])
+ if perche:
+ avvisi.append(F('copia_progetto_ferma', perche=perche))
+ righe = _uscito(dest, prima, quanti=60) if prima != _testa(dest) else []
+ novita += righe or [F('novita_niente')]
+ else:
+ r = _git('clone', '-q', progetto, dest)
+ if r.returncode != 0:
+ sys.stderr.write(F('progetto_non_si_copia', agente=agente, casa=casa) + '\n')
+ return 1
+ novita.append(F('novita_copia_progetto'))
+ if avvisi:
+ novita += ['', '## ' + F('novita_al_tecnico'), ''] + [f'- {a}' for a in avvisi]
+ _scrivi_se_cambia(os.path.join(casa, 'NOVITA.md'), '\n'.join(novita).rstrip() + '\n')
+ _scrivi_se_cambia(os.path.join(casa, 'chiudi.sh'), CHIUDI_SH, 493)
+ ignorati = os.path.join(casa, '.gitignore')
+ try:
+ ci_sono = open(ignorati, encoding='utf-8').read().splitlines()
+ except OSError:
+ ci_sono = []
+ mancano = [x for x in _IGNORATI_DELLA_CASA if x not in ci_sono]
+ if mancano:
+ _scrivi_se_cambia(ignorati, '\n'.join(ci_sono + mancano).strip() + '\n')
+ for a in avvisi:
+ sys.stderr.write(f'⚠️ {agente}: {a}\n')
+ print(casa)
+ return 0
+
+def posta_ruolo(argv):
+ if len(argv) != 2 or argv[1] not in ('umano', 'volo', 'attesa'):
+ return 0
+ canale, momento = argv
+ try:
+ with open(canale, encoding='utf-8') as f:
+ srv = json.load(f)['mcpServers']
+ srv = srv.get(SERVER_RUOLO) or srv['delminio-ruolo']
+ base = srv['url'].rsplit('/mcp', 1)[0]
+ token = srv['headers']['Authorization'].split(' ', 1)[1]
+ except (OSError, ValueError, KeyError, IndexError):
+ return 0
+ evento = {}
+ if not sys.stdin.isatty():
+ try:
+ evento = json.loads(sys.stdin.read() or '{}')
+ except ValueError:
+ pass
+ if momento == 'volo' and evento.get('agent_id'):
+ return 0
+ cli = _pid_della_cli()
+ sid = re.sub('[^A-Za-z0-9_-]', '', str(evento.get('session_id') or cli))[:64]
+ stato = os.path.join(os.path.dirname(canale), 'posta')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ radice = os.path.join(stato, os.path.splitext(os.path.basename(canale))[0] + '-' + sid)
+ if momento == 'volo':
+ try:
+ if time.time() - os.path.getmtime(radice + '.volo') < 10:
+ return 0
+ except OSError:
+ pass
+ open(radice + '.volo', 'w').close()
+
+ def guarda(segna=True):
+ with open(radice + '.lock', 'w') as lk:
+ if fcntl is not None:
+ fcntl.flock(lk, fcntl.LOCK_EX)
+ try:
+ with open(radice + '.visto', encoding='utf-8') as f:
+ dopo = f.read().strip()
+ except OSError:
+ dopo = ''
+ q = urllib.parse.urlencode({'dopo': dopo, 'momento': momento})
+ try:
+ r = json.loads(_get(f'{base}/api/canale/ruolo?{q}', token, timeout=10))
+ except urllib.error.HTTPError as e:
+ if segna and e.code in (401, 403) and (not os.path.exists(radice + '.rifiutato')):
+ open(radice + '.rifiutato', 'w').close()
+ return F('posta_ruolo_rifiutata', codice=e.code)
+ return ''
+ except (OSError, ValueError, urllib.error.URLError):
+ return ''
+ if os.path.exists(radice + '.rifiutato'):
+ os.remove(radice + '.rifiutato')
+ if segna and r.get('ultimo') and (r['ultimo'] != dopo):
+ with open(radice + '.visto', 'w', encoding='utf-8') as f:
+ f.write(r['ultimo'])
+ if not segna and r.get('testo'):
+ return r.get('ultimo') or ''
+ return r.get('testo') or ''
+ if momento != 'attesa':
+ testo = guarda()
+ if momento == 'umano':
+ testo = '\n\n'.join((t for t in (_rito_del_messaggio(base, token, radice, evento), testo) if t))
+ if testo:
+ nome = 'UserPromptSubmit' if momento == 'umano' else 'PostToolUse'
+ print(json.dumps({'hookSpecificOutput': {'hookEventName': nome, 'additionalContext': testo}}))
+ return 0
+ posta_qwen = os.environ.get('DELMINIO_QWEN_POSTA') or ''
+ if posta_qwen:
+ m = re.search('-(\\d+)\\.jsonl$', posta_qwen)
+ if m:
+ cli = int(m.group(1))
+ if not os.path.isfile(posta_qwen) or os.fork():
+ return 0
+ os.setsid()
+ nulla = os.open(os.devnull, os.O_RDWR)
+ for fd in (0, 1, 2):
+ os.dup2(nulla, fd)
+ with open(radice + '.attesa', 'w', encoding='utf-8') as f:
+ f.write(str(os.getpid()))
+ giri = 0
+ while True:
+ testo = guarda(segna=not posta_qwen)
+ if testo and posta_qwen:
+ with open(radice + '.avviso.lock', 'w') as lk:
+ if fcntl is not None:
+ fcntl.flock(lk, fcntl.LOCK_EX)
+ mia, gia = (False, '')
+ try:
+ with open(radice + '.attesa', encoding='utf-8') as f:
+ mia = f.read().strip() == str(os.getpid())
+ except OSError:
+ pass
+ try:
+ with open(radice + '.avvisato', encoding='utf-8') as f:
+ gia = f.read().strip()
+ except OSError:
+ pass
+ if not mia:
+ return 0
+ if testo != gia:
+ with open(posta_qwen, 'a', encoding='utf-8') as f:
+ f.write(json.dumps({'type': 'submit', 'text': F('posta_arrivata')}, ensure_ascii=False) + '\n')
+ with open(radice + '.avvisato', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ return 0
+ elif testo:
+ sys.stderr.write(testo + '\n')
+ return 2
+ try:
+ os.kill(cli, 0)
+ with open(radice + '.attesa', encoding='utf-8') as f:
+ if f.read().strip() != str(os.getpid()):
+ return 0
+ except (OSError, ValueError):
+ return 0
+ giri += 1
+ time.sleep(3 if giri < 40 else 15 if giri < 80 else 30)
+GIORNI_DOPO_UN_CRASH = 3
+CONVERSAZIONI = ('subito', 'fine_sessione')
+
+def _pid_vivo(pid):
+ try:
+ os.kill(int(pid), 0)
+ return True
+ except ProcessLookupError:
+ return False
+ except (PermissionError, ValueError, TypeError, OverflowError):
+ return True
+
+def _sessioni_vive(registro):
+ vive = set()
+ for f in glob_ordinato(os.path.join(registro, '*.json')):
+ try:
+ with open(f, encoding='utf-8') as h:
+ d = json.load(h)
+ if _pid_vivo(d.get('pid') or os.path.basename(f).split('.')[0]) and d.get('sessionId'):
+ vive.add(str(d['sessionId']))
+ except (OSError, ValueError, AttributeError):
+ continue
+ return vive
+
+def glob_ordinato(schema):
+ import glob
+ return sorted(glob.glob(schema))
+
+def _vecchia(percorsi, giorni):
+ if giorni <= 0:
+ return True
+ soglia = time.time() - giorni * 86400
+ for p in percorsi:
+ try:
+ if os.path.getmtime(p) >= soglia:
+ return False
+ except OSError:
+ continue
+ return True
+
+def _via(p):
+ try:
+ if os.path.isdir(p) and (not os.path.islink(p)):
+ shutil.rmtree(p, ignore_errors=True)
+ elif os.path.lexists(p):
+ os.unlink(p)
+ except OSError:
+ pass
+
+def _ancora_dopo(percorsi, secondi=15):
+ if not percorsi or os.fork():
+ return
+ try:
+ os.setsid()
+ nulla = os.open(os.devnull, os.O_RDWR)
+ for fd in (0, 1, 2):
+ os.dup2(nulla, fd)
+ time.sleep(secondi)
+ for p in percorsi:
+ _via(p)
+ finally:
+ os._exit(0)
+
+def _da_togliere(sessioni, vive, mia, fine, subito, giorni):
+ via = set()
+ for sid, percorsi in sessioni.items():
+ if sid == mia:
+ if fine or subito:
+ via.add(sid)
+ continue
+ if sid in vive:
+ continue
+ if _vecchia(percorsi, giorni):
+ via.add(sid)
+ return via
+
+def _pulisci_claude(evento, mia, fine, subito, giorni):
+ casa = os.path.realpath(os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude'))
+ progetti = os.path.join(casa, 'projects')
+ trascritto = str(evento.get('transcript_path') or '')
+ if trascritto:
+ cartella = os.path.dirname(os.path.realpath(trascritto))
+ else:
+ dove = os.environ.get('CLAUDE_PROJECT_DIR') or str(evento.get('cwd') or '')
+ if not dove:
+ return
+ cartella = os.path.join(progetti, re.sub('[^A-Za-z0-9]', '-', dove))
+ if os.path.dirname(cartella) != progetti or not os.path.isdir(cartella):
+ return
+ sessioni = {}
+ for nome in os.listdir(cartella):
+ sid = nome[:-6] if nome.endswith('.jsonl') else nome
+ if sid == 'memory' or not re.fullmatch('[0-9a-fA-F-]{8,}', sid):
+ continue
+ sessioni.setdefault(sid, []).append(os.path.join(cartella, nome))
+ via = _da_togliere(sessioni, _sessioni_vive(os.path.join(casa, 'sessions')), mia, fine, subito, giorni)
+ for sid in via:
+ for p in sessioni[sid]:
+ _via(p)
+ for p in (os.path.join(casa, 'file-history', sid), os.path.join(casa, 'session-env', sid), os.path.join(casa, 'tasks', sid), *glob_ordinato(os.path.join(casa, 'todos', sid + '*'))):
+ _via(p)
+ if via:
+ _togli_dalla_cronologia(os.path.join(casa, 'history.jsonl'), via)
+ if fine and mia in via:
+ _ancora_dopo([os.path.join(cartella, mia + '.jsonl'), os.path.join(cartella, mia)])
+
+def _togli_dalla_cronologia(f, via):
+ try:
+ with open(f, encoding='utf-8') as h:
+ righe = h.readlines()
+ except OSError:
+ return
+ tenute = []
+ for r in righe:
+ try:
+ if str(json.loads(r).get('sessionId') or '') in via:
+ continue
+ except (ValueError, AttributeError):
+ pass
+ tenute.append(r)
+ if len(tenute) == len(righe):
+ return
+ tmp = f + '.delminio'
+ try:
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 384), 'w', encoding='utf-8') as h:
+ h.writelines(tenute)
+ os.replace(tmp, f)
+ except OSError:
+ _via(tmp)
+
+def _casa_delminio(var, sotto):
+ h = os.environ.get(var)
+ if not h:
+ return None
+ casa = os.path.realpath(h)
+ base = os.path.realpath(os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', sotto))
+ return casa if os.path.dirname(casa) == base and os.path.isdir(casa) else None
+
+def _pulisci_qwen(mia, fine, subito, giorni):
+ casa = _casa_delminio('QWEN_HOME', 'qwen')
+ if not casa:
+ return
+ eta, tutto = ({}, {})
+ for p in glob_ordinato(os.path.join(casa, 'projects', '*', 'chats', '*')):
+ sid = os.path.basename(p).split('.', 1)[0]
+ eta.setdefault(sid, []).append(p)
+ tutto.setdefault(sid, []).append(p)
+ degli_agenti = {}
+ for d in glob_ordinato(os.path.join(casa, 'projects', '*', 'subagents', '*')):
+ sid = os.path.basename(d)
+ tutto.setdefault(sid, []).append(d)
+ degli_agenti.setdefault(sid, []).extend([d, *glob_ordinato(os.path.join(d, '*'))])
+ for sid, percorsi in degli_agenti.items():
+ eta.setdefault(sid, percorsi)
+ for p in [*glob_ordinato(os.path.join(casa, 'file-history', '*')), *glob_ordinato(os.path.join(casa, 'tmp', '*', 'background-shells', '*'))]:
+ tutto.setdefault(os.path.basename(p), []).append(p)
+ for sid, percorsi in tutto.items():
+ eta.setdefault(sid, percorsi)
+ vive = _sessioni_vive(os.path.join(casa, 'sessions'))
+ via = _da_togliere(eta, vive, mia, fine, subito, giorni)
+ for sid in via:
+ for p in tutto[sid]:
+ _via(p)
+ if fine and mia in via:
+ _ancora_dopo(tutto[mia])
+ for f in glob_ordinato(os.path.join(casa, 'sessions', '*.json')):
+ if not _pid_vivo(os.path.basename(f).split('.')[0]):
+ _via(f)
+ if not vive - ({mia} if fine else set()):
+ for d in glob_ordinato(os.path.join(casa, 'tmp', '*')):
+ for x in ('logs.json', 'tool-results', 'checkpoints'):
+ _via(os.path.join(d, x))
+
+def _pulisci_codex(mia, fine, giorni):
+ casa = _casa_delminio('CODEX_HOME', 'codex')
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if not casa or os.path.basename(cli) != 'codex' or (not os.path.isfile(cli)):
+ return
+ stato = os.path.join(casa, 'delminio-pulizia')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ if fine and re.fullmatch('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', mia):
+ open(os.path.join(stato, mia + '.pending'), 'a').close()
+ if not fine and giorni > 0:
+ return
+ env = {k: os.environ[k] for k in ('HOME', 'PATH', 'CODEX_HOME', 'DELMINIO_CLI', 'LANG', 'XDG_DATA_HOME', 'DELMINIO_CONVERSAZIONI') if k in os.environ}
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-codex', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
+
+def _codex_vivi(casa):
+ for p in glob_ordinato('/proc/[0-9]*'):
+ try:
+ if os.path.basename(os.path.realpath(os.path.join(p, 'exe'))) != 'codex':
+ continue
+ with open(os.path.join(p, 'environ'), 'rb') as h:
+ v = h.read().split(b'\x00')
+ c = next((x.split(b'=', 1)[1] for x in v if x.startswith(b'CODEX_HOME=')), None)
+ if c is None or os.path.realpath(os.fsdecode(c)) == casa:
+ return True
+ except FileNotFoundError:
+ continue
+ except OSError:
+ return True
+ return False
+
+def pulizia_codex(argv):
+ import fcntl, sqlite3, uuid
+ from contextlib import closing
+ casa = _casa_delminio('CODEX_HOME', 'codex')
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if not casa or os.path.basename(cli) != 'codex':
+ return 0
+ giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
+ stato = os.path.join(casa, 'delminio-pulizia')
+ os.makedirs(stato, mode=448, exist_ok=True)
+ with open(os.path.join(stato, 'lock'), 'w') as lk:
+ try:
+ fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return 0
+ while _codex_vivi(casa):
+ time.sleep(3)
+ via = {os.path.basename(p)[:-8] for p in glob_ordinato(os.path.join(stato, '*.pending'))}
+ db = os.path.join(casa, 'state_5.sqlite')
+ if os.path.isfile(db) and glob_ordinato(os.path.join(casa, 'state_*.sqlite')) == [db]:
+ soglia = time.time() - giorni * 86400
+ with closing(sqlite3.connect('file:' + db + '?mode=ro', uri=True)) as c:
+ for sid, ultima in c.execute('SELECT id, updated_at FROM threads').fetchall():
+ if isinstance(ultima, (int, float)) and 0 < ultima < soglia:
+ via.add(str(sid))
+ tolte = []
+ for sid in sorted(via):
+ try:
+ sid = str(uuid.UUID(sid))
+ except ValueError:
+ continue
+ if _codex_vivi(casa):
+ return 0
+ r = subprocess.run([cli, 'delete', '--force', sid], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=120)
+ if r.returncode == 0:
+ tolte.append(sid)
+ _via(os.path.join(stato, sid + '.pending'))
+ for s in glob_ordinato(os.path.join(casa, 'shell_snapshots', sid + '.*.sh')):
+ _via(s)
+ if tolte and (not _codex_vivi(casa)):
+ for prefisso in ('state', 'thread_history', 'queue', 'logs', 'goals', 'memories'):
+ for p in glob_ordinato(os.path.join(casa, prefisso + '_*.sqlite')):
+ try:
+ with closing(sqlite3.connect(p, timeout=5)) as c:
+ if c.execute('PRAGMA wal_checkpoint(TRUNCATE)').fetchone()[0]:
+ continue
+ c.execute('VACUUM')
+ c.execute('PRAGMA wal_checkpoint(TRUNCATE)')
+ except sqlite3.Error:
+ continue
+ return 0
+_SESSIONE_OPENCODE = re.compile('ses_[A-Za-z0-9]{8,64}')
+
+def _segni_opencode():
+ d = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'opencode', 'conversazioni')
+ os.makedirs(d, mode=448, exist_ok=True)
+ return d
+
+def _pulisci_opencode(mia, fine, giorni):
+ cli = os.environ.get('DELMINIO_CLI') or ''
+ if os.path.basename(cli) != 'opencode' or not os.path.isfile(cli) or (not _SESSIONE_OPENCODE.fullmatch(mia)):
+ return
+ stato = _segni_opencode()
+ pid = os.environ.get('DELMINIO_CLI_PID') or str(os.getppid())
+ with open(os.path.join(stato, mia + '.json'), 'w', encoding='utf-8') as h:
+ json.dump({'pid': pid, 'cli': cli, 'linea': '2'}, h)
+ if fine:
+ open(os.path.join(stato, mia + '.fine'), 'a').close()
+ env = {k: os.environ[k] for k in ('HOME', 'PATH', 'LANG', 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME') if k in os.environ}
+ subprocess.Popen([sys.executable, os.path.abspath(__file__), 'pulizia-opencode', str(giorni)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True, env=env)
+
+def pulizia_opencode(argv):
+ import fcntl
+ giorni = int(argv[0]) if argv and argv[0].isdigit() else GIORNI_DOPO_UN_CRASH
+ stato = _segni_opencode()
+ with open(os.path.join(stato, 'lock'), 'w') as lk:
+ try:
+ fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return 0
+ while True:
+ segnate, attese = ({}, False)
+ for f in glob_ordinato(os.path.join(stato, 'ses_*.json')):
+ sid = os.path.basename(f)[:-5]
+ try:
+ with open(f, encoding='utf-8') as h:
+ segnate[sid] = (json.load(h), f)
+ except (OSError, ValueError):
+ continue
+ via = []
+ for sid, (d, f) in segnate.items():
+ finita = os.path.exists(os.path.join(stato, sid + '.fine'))
+ if _pid_vivo(d.get('pid')):
+ attese = attese or finita
+ continue
+ if finita or _vecchia([f], giorni):
+ via.append((sid, d))
+ for sid, d in via:
+ cli = d.get('cli') if os.path.isfile(str(d.get('cli') or '')) else ''
+ if d.get('linea') != '2':
+ for x in ('.json', '.fine'):
+ _via(os.path.join(stato, sid + x))
+ continue
+ if not cli:
+ continue
+ cmd = [cli, 'session', 'delete', sid, '--standalone']
+ try:
+ r = subprocess.run(cmd, stdin=subprocess.DEVNULL, capture_output=True, timeout=120)
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+ if r.returncode == 0 or b'Session not found' in r.stdout + r.stderr:
+ for x in ('.json', '.fine'):
+ _via(os.path.join(stato, sid + x))
+ if not attese:
+ return 0
+ time.sleep(3)
+
+def pulizia(argv):
+ modo = os.environ.get('DELMINIO_CONVERSAZIONI') or ''
+ if modo not in CONVERSAZIONI:
+ return 0
+ try:
+ evento = json.loads(sys.stdin.read() or '{}') if not sys.stdin.isatty() else {}
+ if not isinstance(evento, dict):
+ evento = {}
+ except ValueError:
+ evento = {}
+ fine = evento.get('hook_event_name') == 'SessionEnd' or argv[:1] == ['fine']
+ mia = str(evento.get('session_id') or '')
+ subito = modo == 'subito'
+ giorni = 0 if subito else GIORNI_DOPO_UN_CRASH
+ cli = os.environ.get('DELMINIO_CLI_NOME') or 'claude'
+ try:
+ if cli == 'qwen':
+ _pulisci_qwen(mia, fine, subito, giorni)
+ elif cli == 'codex':
+ _pulisci_codex(mia, fine, giorni)
+ elif cli == 'opencode':
+ _pulisci_opencode(mia, fine, giorni)
+ elif cli == 'claude':
+ _pulisci_claude(evento, mia, fine, subito, giorni)
+ except Exception:
+ pass
+ return 0
+ERRORI_TETTO_BYTE = 2000000
+ERRORI_RIGHE = 3
+ERRORI_CARATTERI = 300
+_USCITA = re.compile('^Exit code (\\d+)\\s*')
+_DICE_NO = {'grep', 'egrep', 'fgrep', 'rg', 'diff', 'cmp', 'test', '[', '[['}
+_SEGRETO = re.compile('(?i)\\b(token|password|passwd|secret|segreto|bearer|api[_-]?key|authorization)\\b(\\S*?)([=:]\\s*|\\s+)\\S+')
+_LUNGO = re.compile('[A-Za-z0-9_\\-+=]{24,}')
+_ESADECIMALE = re.compile('[0-9a-fA-F]{32,}')
+ENTROPIA_DI_UNA_CHIAVE = 4.3
+_FERMATO_CLI = re.compile('^blocked|isolated\\sin\\sthe\\sworktree|permission|denied|rejected')
+_TEMPO = re.compile('timed\\sout|timeout')
+
+def _registro_errori():
+ casa = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
+ return os.path.join(casa, 'delminio', 'errori-strumenti.jsonl')
+
+def _entropia(s):
+ return -sum((k / len(s) * math.log2(k / len(s)) for k in collections.Counter(s).values()))
+
+def _maschera(t):
+ t = _SEGRETO.sub(lambda m: m.group(1) + m.group(2) + m.group(3) + '…', t)
+ t = _ESADECIMALE.sub('…', t)
+ return _LUNGO.sub(lambda m: '…' if _entropia(m.group(0)) > ENTROPIA_DI_UNA_CHIAVE else m.group(0), t)
+
+def _programma(comando):
+ pezzi = [p for p in re.split('&&|\\|\\||;|\\||\\n', comando or '') if p.strip()]
+ if not pezzi:
+ return ''
+ for parola in pezzi[-1].split():
+ if re.match('^[A-Za-z_][A-Za-z0-9_]*=', parola) or parola in ('sudo', 'timeout', 'time', '!'):
+ continue
+ if re.fullmatch('\\d+[smh]?', parola):
+ continue
+ return os.path.basename(parola.strip('\'"()'))[:40]
+ return ''
+
+def _specie(evento, programma, errore):
+ if evento.get('is_interrupt'):
+ return ('interrotto', True)
+ m = _USCITA.match(errore)
+ if m:
+ resto = errore[m.end():].strip()
+ if m.group(1) == '1' and (not resto or programma in _DICE_NO):
+ return ('uscita_senza_errore', True)
+ return ('uscita', False)
+ basso = errore.lower()
+ if '<tool_use_error>' in basso or 'inputvalidationerror' in basso:
+ return ('tool', False)
+ if 'delminio' in basso or '🔒' in errore:
+ return ('fermato_da_delminio', False)
+ if _FERMATO_CLI.search(basso):
+ return ('fermato_dalla_cli', False)
+ if _TEMPO.search(basso):
+ return ('tempo', False)
+ return ('altro', False)
+
+def errori_registra(_argv):
+ try:
+ evento = json.loads(sys.stdin.read() or '{}')
+ tool = str(evento.get('tool_name') or '')[:60]
+ entrata = evento.get('tool_input') or {}
+ comando = entrata.get('command') if isinstance(entrata, dict) else ''
+ programma = _programma(comando) if isinstance(comando, str) else ''
+ errore = str(evento.get('error') or '').strip()
+ specie, non_errore = _specie(evento, programma, errore)
+ righe = [r for r in errore.splitlines() if r.strip()][:ERRORI_RIGHE]
+ voce = {'quando': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), 'sessione': os.environ.get('DELMINIO_SESSIONE_NOME') or '', 'cli': 'claude', 'cartella': str(evento.get('cwd') or '')[:200], 'tool': tool, 'programma': programma, 'specie': specie, 'non_errore': non_errore, 'errore': _maschera(' ⏎ '.join(righe))[:ERRORI_CARATTERI], 'ms': evento.get('duration_ms')}
+ dove = _registro_errori()
+ os.makedirs(os.path.dirname(dove), mode=448, exist_ok=True)
+ with open(dove, 'a', encoding='utf-8') as f:
+ f.write(json.dumps(voce, ensure_ascii=False) + '\n')
+ if os.path.getsize(dove) > ERRORI_TETTO_BYTE:
+ with open(dove, encoding='utf-8', errors='replace') as f:
+ tenute = f.readlines()
+ tenute = tenute[len(tenute) // 2:]
+ nuovo = dove + f'.{os.getpid()}.tmp'
+ with open(nuovo, 'w', encoding='utf-8') as f:
+ f.writelines(tenute)
+ os.replace(nuovo, dove)
+ except Exception:
+ pass
+ return 0
+
+def errori(argv):
+ tutti = '--tutti' in argv or '--all' in argv
+ numeri = [a for a in argv if a.isdigit()]
+ giorni = int(numeri[0]) if numeri else 7
+ dal = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(days=giorni)
+ dove = _registro_errori()
+ voci = []
+ try:
+ with open(dove, encoding='utf-8', errors='replace') as f:
+ for r in f:
+ try:
+ v = json.loads(r)
+ if datetime.datetime.fromisoformat(v['quando']) >= dal:
+ voci.append(v)
+ except (ValueError, KeyError, TypeError):
+ continue
+ except FileNotFoundError:
+ pass
+ nascoste = [v for v in voci if v.get('non_errore')]
+ mostrate = voci if tutti else [v for v in voci if not v.get('non_errore')]
+ print(F('errori_testa', giorni=giorni, n=len(mostrate), file=dove))
+ if nascoste and (not tutti):
+ print(F('errori_nascosti', n=len(nascoste)))
+ if not mostrate:
+ print(F('errori_nessuno'))
+ return 0
+ print(F('errori_per_specie'))
+ for specie, n in collections.Counter((v.get('specie', '') for v in mostrate)).most_common():
+ print(f' {n:4} {specie}')
+ print(F('errori_per_programma'))
+ for (tool, prog), n in collections.Counter(((v.get('tool', ''), v.get('programma', '')) for v in mostrate)).most_common(12):
+ print(f" {n:4} {tool}{(' ' + prog if prog else '')}")
+ print(F('errori_ultime'))
+ for v in mostrate[-15:]:
+ print(f" {v.get('quando', '')[:16].replace('T', ' ')} {v.get('sessione') or '—'} {v.get('tool', '')}{(' ' + v['programma'] if v.get('programma') else '')} · {v.get('specie', '')} · {v.get('errore', '')[:110]}")
+ return 0
+
+def _righe_del_prompt(riga, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ rotta = 'nascita' if riga.get('nascita') == 'intera' else 'sistema'
+ return [*_commento(F('commento_prompt')), 'D="${XDG_CACHE_HOME:-$HOME/.cache}/delminio-eseguibili"', 'mkdir -p "$D" && chmod 700 "$D"', f'for f in "$D"/{nome}-*.txt; do', ' [ -e "$f" ] || continue; p=${f##*-}; p=${p%.txt}', ' kill -0 "$p" 2>/dev/null || rm -f "$f"', 'done', f'F="$D/{nome}-$$.txt"', f"""codice=$( (umask 077; printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -G -o "$F" -w "%{{http_code}}" -K - --data-urlencode {_q('ordine=' + porta)} """ + (f"--data-urlencode {_q('modello=' + riga['ordine'])} " if riga.get('ordine') and rotta == 'nascita' else '') + f"{_q(url.rstrip('/') + '/api/porte/' + rotta)}) 2>/dev/null)", 'if [ "$codice" != 200 ] || [ ! -s "$F" ]; then', ' ' + _printf(F('prompt_negato', nome='{nome}', porta='{porta}', codice='{codice}'), nome=_q(nome), porta=_q(porta), codice='"${codice:-000}"') + ' >&2', ' [ -s "$F" ] && head -c 400 "$F" >&2 && echo >&2', ' rm -f "$F"; exit 1', 'fi', *_commento(F('commento_hook_sistema')), 'export DELMINIO_SISTEMA="$F"']
+
+def _righe_al_lancio(modo, url, token_file):
+ if modo == 'kit':
+ chi = [' q=${r:-$(git rev-parse --show-toplevel 2>/dev/null)}', ' if [ -n "$q" ] && [ -f "$q/.claude/eseguibili.py" ]; then', ' python3 "$q/.claude/eseguibili.py" allinea --al-lancio --modo kit --da "$q/.claude/delminio.sh" >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi', ' fi']
+ else:
+ chi = [f' python3 {_q(os.path.abspath(__file__))} allinea --al-lancio --modo casa --url {_q(url)} --token-file {_q(token_file)} >&2', ' if [ $? = 3 ]; then [ -e "$0" ] || exit 1; export DELMINIO_AL_LANCIO=1; exec "$0" "$@"; fi']
+ return [*_commento(F('commento_al_lancio')), 'if [ -z "${DELMINIO_AL_LANCIO:-}" ]; then', *chi, 'fi', 'unset DELMINIO_AL_LANCIO']
+
+def _testa_del_wrapper(riga):
+ chi = ' '.join(str(riga.get('descrizione') or F('wrapper_descrizione_serie')).split())
+ return ['#!/bin/sh', f"# {riga['nome']} — {chi}", *_commento(F('wrapper_commento'))]
+
+def wrapper_codex(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ if personaggio(riga):
+ raise RuntimeError(F('codex_ruolo_solo'))
+ di_serie = [] if modo == 'kit' else ['--no-daemon', '-c', 'check_for_update_on_startup=false']
+ della_riga = []
+ if riga.get('modello'):
+ della_riga += ['-m', riga['modello']]
+ if riga.get('effort'):
+ della_riga += ['-c', f'''model_reasoning_effort="{riga['effort']}"''']
+ contesto = riga.get('_contesto') or {}
+ espliciti = riga.get('argomenti') or []
+ if contesto.get('massimo') and (not any((x.startswith('model_context_window=') for x in espliciti))):
+ di_serie += ['-c', f"model_context_window={int(contesto['massimo'])}"]
+ if contesto.get('compatta') and (not any((x.startswith('model_auto_compact_token_limit=') for x in espliciti))):
+ di_serie += ['-c', f"model_auto_compact_token_limit={int(contesto['compatta'])}"]
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ della_riga += delle_scelte + list(riga.get('argomenti') or [])
+ casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
+ righe = [*_testa_del_wrapper(riga), f'export CODEX_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/codex/{casa}"', 'export DELMINIO_CLI_NOME=codex', f"export DELMINIO_PERMESSI={_q((riga.get('scelte') or {}).get('permessi') or '')}", f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ righe += ['mkdir -p "$CODEX_HOME" && chmod 700 "$CODEX_HOME"', *_commento(F('commento_login_codex')), '[ -e "$CODEX_HOME/auth.json" ] || [ ! -f "$HOME/.codex/auth.json" ] || ln -s "$HOME/.codex/auth.json" "$CODEX_HOME/auth.json"']
+
+ def strato(client):
+ return [*_commento(F('commento_mie_codex')), f'DELMINIO_MIE=$(python3 {client} mie-codex "$CODEX_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := chiavi_della_riga('codex', della_riga)) else '') + ') || DELMINIO_MIE=""', 'export DELMINIO_MIE', *righe_dello_strato('codex', di_serie, della_riga, 'DELMINIO_MIE')]
+ if modo == 'kit' and porta:
+ righe += [*_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ if (tetto := (riga.get('_base') or {}).get('codex.tetto_uscite')):
+ righe.append(f'export DELMINIO_TETTO_USCITE={int(tetto)}')
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe += strato('"$r/.claude/eseguibili.py"')
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" codex', '"$@"'))
+ return '\n'.join(righe) + '\n'
+ if porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe.append(f'export DELMINIO_PORTA={_q(porta)}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ prompt = ' -c "model_instructions_file=\\"$F\\""' if porta else ''
+ righe += _righe_al_lancio(modo, url, token_file)
+ pacchetto = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugin.py')
+ righe += [*_commento(F('commento_plugin_codex')), f'[ -n "${{DELMINIO_SENZA_PLUGIN:-}}" ] || DELMINIO_CODEX={_q(cli)} python3 {_q(pacchetto)} codex "$CODEX_HOME" >/dev/null 2>&1 || true']
+ righe += strato(_q(os.path.abspath(__file__)))
+ righe.append(_riga_exec(_q(cli), prompt.strip(), '"$@"'))
+ return '\n'.join(righe) + '\n'
+MIE_QWEN = 'mie-qwen.json'
+MIE_CODEX = 'mie-codex.toml'
+QWEN_DI_DELMINIO = ('hooks', 'general.enableAutoUpdate', 'mcpServers.delminio', 'mcpServers.memoria')
+CODEX_DI_DELMINIO = (('hooks',), ('mcp_servers', 'delminio'), ('mcp_servers', 'memoria'), ('plugins', 'delminio@delminio'), ('marketplaces', 'delminio'), ('model_instructions_file',), ('check_for_update_on_startup',))
+OPZIONI_CHIAVE = {'codex': {'-m': 'model', '--model': 'model', '-s': 'sandbox_mode', '--sandbox': 'sandbox_mode', '-a': 'approval_policy', '--ask-for-approval': 'approval_policy'}, 'qwen': {'-m': 'model.name', '--model': 'model.name', '--approval-mode': 'tools.approvalMode', '--exclude-tools': 'tools.exclude'}}
+
+def cartella_mie():
+ return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio')
+
+def _percorsi_json(d, dove=()):
+ for k, v in d.items():
+ if isinstance(v, dict):
+ yield from _percorsi_json(v, dove + (k,))
+ else:
+ yield (dove + (k,))
+
+def _stampa_chiavi(percorsi):
+ print('|' + '|'.join(sorted({'.'.join(p) for p in percorsi})) + '|')
+
+def _della_riga(argomenti):
+ if '--della-riga' in argomenti:
+ i = argomenti.index('--della-riga')
+ return (argomenti[:i] + argomenti[i + 2:], [tuple(k.split('.')) for k in argomenti[i + 1].split(',') if k])
+ return (argomenti, [])
+
+def _sotto(percorso, chiavi):
+ return any((percorso[:len(k)] == k for k in chiavi))
+
+def _sopra(percorso, chiavi):
+ return [k for k in chiavi if len(k) > len(percorso) and k[:len(percorso)] == percorso]
+
+def unisci_mie_qwen(argomenti):
+ argomenti, della_riga = _della_riga(argomenti)
+ casa = argomenti[0]
+ base = json.load(open(os.path.join(casa, 'settings.json'), encoding='utf-8'))
+ scritte = []
+ di_delminio = [tuple(x.split('.')) for x in QWEN_DI_DELMINIO]
+
+ def unisci(a, b, dove=''):
+ for k, v in b.items():
+ if dove + k in QWEN_DI_DELMINIO:
+ print(F('mie_di_delminio', nome=dove + k), file=sys.stderr)
+ continue
+ percorso = tuple((dove + k).split('.'))
+ if _sotto(percorso, della_riga):
+ print(F('mie_della_riga', nome=dove + k), file=sys.stderr)
+ continue
+ dentro_d, dentro_r = (_sopra(percorso, di_delminio), _sopra(percorso, della_riga))
+ if isinstance(v, dict) and (isinstance(a.get(k), dict) or dentro_d or dentro_r):
+ if not isinstance(a.get(k), dict):
+ a[k] = {}
+ unisci(a[k], v, dove + k + '.')
+ elif dentro_d or dentro_r:
+ for x in dentro_d:
+ print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
+ for x in dentro_r:
+ print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
+ else:
+ a[k] = v
+ scritte.extend([percorso + p for p in _percorsi_json(v)] if isinstance(v, dict) else [percorso])
+ for file in (os.path.join(cartella_mie(), MIE_QWEN), os.path.join(casa, 'mie.json')):
+ if not os.path.isfile(file):
+ continue
+ try:
+ mie = json.load(open(file, encoding='utf-8'))
+ if not isinstance(mie, dict):
+ raise ValueError(type(mie).__name__)
+ except (OSError, ValueError) as e:
+ print(F('mie_qwen_illeggibili', file=file, errore=e), file=sys.stderr)
+ continue
+ unisci(base, mie)
+ with open(os.path.join(casa, 'settings.json'), 'w', encoding='utf-8') as h:
+ json.dump(base, h, indent=2, ensure_ascii=False)
+ _stampa_chiavi(scritte)
+ return 0
+
+def _toml_chiave(s, i):
+ parti = []
+ while True:
+ while i < len(s) and s[i] in ' \t':
+ i += 1
+ if i < len(s) and s[i] in '"\'':
+ q, j = (s[i], i + 1)
+ while j < len(s) and s[j] != q and (s[j] != '\n'):
+ j += 2 if q == '"' and s[j] == '\\' else 1
+ nome = s[i + 1:j]
+ if q == '"':
+ try:
+ nome = json.loads('"' + nome + '"')
+ except ValueError:
+ pass
+ parti.append(nome)
+ i = j + 1
+ else:
+ j = i
+ while j < len(s) and (s[j].isalnum() or s[j] in '_-'):
+ j += 1
+ if j == i:
+ raise ValueError(F('mie_toml_chiave', riga=s.count('\n', 0, i) + 1))
+ parti.append(s[i:j])
+ i = j
+ while i < len(s) and s[i] in ' \t':
+ i += 1
+ if s[i:i + 1] != '.':
+ return (tuple(parti), i)
+ i += 1
+
+def _toml_fine_valore(s, i):
+ profondo = 0
+ while i < len(s):
+ if s.startswith('"""', i) or s.startswith("'''", i):
+ q, j = (s[i:i + 3], i + 3)
+ while True:
+ k = s.find(q, j)
+ if k < 0:
+ raise ValueError(F('mie_toml_aperta', riga=s.count('\n', 0, i) + 1))
+ barre = len(s[:k]) - len(s[:k].rstrip('\\'))
+ if q == '"""' and barre % 2:
+ j = k + 1
+ continue
+ i = k + 3
+ while s[i:i + 1] == q[0]:
+ i += 1
+ break
+ continue
+ c = s[i]
+ if c in '"\'':
+ j = i + 1
+ while j < len(s) and s[j] != c and (s[j] != '\n'):
+ j += 2 if c == '"' and s[j] == '\\' else 1
+ i = j + 1
+ continue
+ if c == '#':
+ k = s.find('\n', i)
+ i = len(s) if k < 0 else k
+ continue
+ if c in '[{':
+ profondo += 1
+ elif c in ']}':
+ profondo -= 1
+ elif c == '\n' and profondo <= 0:
+ return i + 1
+ i += 1
+ return i
+
+def toml_pezzi(testo):
+ pezzi, i, tabella = ([], 0, ())
+ while i < len(testo):
+ j = i
+ while j < len(testo) and testo[j] in ' \t\r':
+ j += 1
+ if j >= len(testo) or testo[j] in '\n#':
+ k = testo.find('\n', j)
+ fine = len(testo) if k < 0 else k + 1
+ pezzi.append(('altro', None, testo[i:fine]))
+ i = fine
+ continue
+ if testo[j] == '[':
+ lista = testo.startswith('[[', j)
+ percorso, k = _toml_chiave(testo, j + (2 if lista else 1))
+ if not testo.startswith(']]' if lista else ']', k):
+ raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
+ k = testo.find('\n', k)
+ fine = len(testo) if k < 0 else k + 1
+ tabella = percorso
+ pezzi.append(('lista' if lista else 'tabella', percorso, testo[i:fine]))
+ i = fine
+ continue
+ percorso, k = _toml_chiave(testo, j)
+ if testo[k:k + 1] != '=':
+ raise ValueError(F('mie_toml_chiave', riga=testo.count('\n', 0, j) + 1))
+ fine = _toml_fine_valore(testo, k + 1)
+ pezzi.append(('chiave', tabella + percorso, testo[i:fine]))
+ i = fine
+ return pezzi
+
+def _toml_parti(pezzi):
+ cima, sezioni = ([], [])
+ for p in pezzi:
+ if p[0] in ('tabella', 'lista'):
+ sezioni.append([p])
+ elif sezioni:
+ sezioni[-1].append(p)
+ else:
+ cima.append(p)
+ return (cima, sezioni)
+
+def _di_delminio_codex(percorso):
+ return any((percorso[:len(r)] == r for r in CODEX_DI_DELMINIO))
+SEGNO_MIE = '# delminio-strato:' + MIE_CODEX
+SEGNO_DA_PARTE = '# delminio-strato:da-parte'
+SEGNO_FINE = '# delminio-strato:fine'
+_TRATTO = re.compile('(?ms)^(' + re.escape(SEGNO_MIE) + '|' + re.escape(SEGNO_DA_PARTE) + ')[^\\n]*\\n(.*?)^' + re.escape(SEGNO_FINE) + '[^\\n]*\\n?')
+
+def _unito(pezzi):
+ t = ''.join((p[2] for p in pezzi))
+ return t if not t or t.endswith('\n') else t + '\n'
+
+def _tratto(segno, testo, prefisso=''):
+ if not testo.strip():
+ return ''
+ return segno + '\n' + ''.join((prefisso + r for r in testo.splitlines(keepends=True))) + SEGNO_FINE + '\n'
+
+def _casa_codex(testo):
+ da_parte = []
+
+ def via(m):
+ if m.group(1) == SEGNO_DA_PARTE:
+ da_parte.extend((r[3:] if r.startswith('#= ') else r[2:] if r.startswith('#=') else '' for r in m.group(2).splitlines(keepends=True)))
+ return ''
+ cima, sezioni = _toml_parti(toml_pezzi(_TRATTO.sub(via, testo)))
+ try:
+ cima_p, sezioni_p = _toml_parti(toml_pezzi(''.join(da_parte)))
+ except ValueError:
+ cima_p, sezioni_p = ([], [])
+ chiavi = {p[1] for p in cima + [x for s in sezioni for x in s] if p[0] == 'chiave'}
+ cima += [p for p in cima_p if p[0] == 'chiave' and p[1] not in chiavi]
+ for s in sezioni_p:
+ torna = [p for p in s[1:] if p[0] != 'chiave' or p[1] not in chiavi]
+ gemella = next((x for x in sezioni if x[0][0] == 'tabella' and x[0][1] == s[0][1]), None)
+ if gemella is None:
+ sezioni.append([s[0]] + torna)
+ else:
+ gemella.extend((p for p in torna if p[0] == 'chiave'))
+ return (cima, sezioni)
+
+def unisci_mie_codex(argomenti):
+ argomenti, della_riga = _della_riga(argomenti)
+ casa = argomenti[0]
+ conf, file = (os.path.join(casa, 'config.toml'), os.path.join(cartella_mie(), MIE_CODEX))
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except FileNotFoundError:
+ testo = ''
+ try:
+ cima_r, sezioni_r = _casa_codex(testo)
+ except ValueError as e:
+ print(F('mie_codex_casa_illeggibile', file=conf, errore=e), file=sys.stderr)
+ _stampa_chiavi([])
+ return 0
+ senza = _unito(cima_r) + _unito([p for s in sezioni_r for p in s])
+ nuovo, scritte = (senza, [])
+ pezzi = None
+ if os.path.isfile(file):
+ try:
+ with open(file, encoding='utf-8') as h:
+ pezzi = toml_pezzi(h.read())
+ except (OSError, ValueError, UnicodeDecodeError) as e:
+ print(F('mie_codex_illeggibili', file=file, errore=e), file=sys.stderr)
+ if pezzi:
+ cima_m, sezioni_m = _toml_parti(pezzi)
+
+ def fuori(percorso):
+ return _di_delminio_codex(percorso) or _sotto(percorso, della_riga)
+
+ def fuori_c(percorso):
+ return fuori(percorso) or bool(_sopra(percorso, CODEX_DI_DELMINIO) or _sopra(percorso, della_riga))
+
+ def dillo(percorso):
+ if fuori(percorso):
+ print(F('mie_di_delminio' if _di_delminio_codex(percorso) else 'mie_della_riga', nome='.'.join(percorso)), file=sys.stderr)
+ return
+ for x in _sopra(percorso, CODEX_DI_DELMINIO):
+ print(F('mie_di_delminio', nome='.'.join(x)), file=sys.stderr)
+ for x in _sopra(percorso, della_riga):
+ print(F('mie_della_riga', nome='.'.join(x)), file=sys.stderr)
+ for p in [p for p in cima_m if p[0] == 'chiave' and fuori_c(p[1])] + [s[0] for s in sezioni_m if fuori(s[0][1])] + [p for s in sezioni_m if not fuori(s[0][1]) for p in s[1:] if p[0] == 'chiave' and fuori_c(p[1])]:
+ dillo(p[1])
+ cima_m = [p for p in cima_m if not (p[0] == 'chiave' and fuori_c(p[1]))]
+ sezioni_m = [[p for p in s if not (p[0] == 'chiave' and fuori_c(p[1]))] for s in sezioni_m if not fuori(s[0][1])]
+ scritte = [p[1] for p in cima_m + [x for s in sezioni_m for x in s] if p[0] == 'chiave']
+ tabelle_m = {s[0][1] for s in sezioni_m if s[0][0] == 'tabella'}
+ coppie_m = set(scritte) | tabelle_m
+
+ def coperta(p):
+ return p[0] == 'chiave' and (p[1] in coppie_m or any((p[1][:len(t)] == t for t in tabelle_m)))
+ fuori = [p for p in cima_r if coperta(p)]
+ cima_r = [p for p in cima_r if not coperta(p)]
+ dentro, fuori_sezioni = ([], [])
+ for s in sezioni_r:
+ if s[0][0] == 'tabella' and s[0][1] in tabelle_m:
+ fuori_sezioni.append(s)
+ elif s[0][0] == 'lista':
+ dentro.append(s)
+ else:
+ dentro.append([s[0]] + [p for p in s[1:] if not coperta(p)])
+ if any((coperta(p) for p in s[1:])):
+ fuori_sezioni.append([s[0]] + [p for p in s[1:] if coperta(p)])
+ fuori += [p for s in sorted(fuori_sezioni, key=lambda s: s[0][1]) for p in s]
+ nuovo = _tratto(SEGNO_MIE + ':chiavi', _unito(cima_m)) + _unito(cima_r) + _tratto(SEGNO_MIE + ':tabelle', _unito([p for s in sezioni_m for p in s])) + _unito([p for s in dentro for p in s]) + _tratto(SEGNO_DA_PARTE, _unito(fuori), '#= ')
+ try:
+ import tomllib
+ except ImportError:
+ tomllib = None
+ if tomllib:
+ try:
+ tomllib.loads(nuovo)
+ except tomllib.TOMLDecodeError as e:
+ print(F('mie_codex_scontro', file=file, errore=e), file=sys.stderr)
+ nuovo, scritte = (senza, [])
+ if nuovo != testo:
+ os.makedirs(casa, exist_ok=True)
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.chmod(conf + '.nuovo', 384)
+ os.replace(conf + '.nuovo', conf)
+ _stampa_chiavi(scritte)
+ return 0
+
+def opzioni_dello_strato(cli, args):
+ gruppi, i, chiavi = ([], 0, OPZIONI_CHIAVE.get(cli, {}))
+ while i < len(args):
+ a = args[i]
+ nome, _, valore = a.partition('=')
+ if cli == 'codex' and a in ('-c', '--config') and (i + 1 < len(args)):
+ gruppi.append((args[i + 1].split('=', 1)[0].strip(), args[i:i + 2]))
+ i += 2
+ elif nome in chiavi and valore:
+ gruppi.append((chiavi[nome], [a]))
+ i += 1
+ elif a in chiavi and i + 1 < len(args):
+ gruppi.append((chiavi[a], args[i:i + 2]))
+ i += 2
+ else:
+ gruppi.append((None, [a]))
+ i += 1
+ return gruppi
+
+def chiavi_della_riga(cli, della_riga):
+ return ','.join(sorted({k for k, _ in opzioni_dello_strato(cli, della_riga) if k}))
+
+def righe_dello_strato(cli, di_serie, della_riga, variabile):
+ righe = ['set -- ' + ' '.join((_q(a) for a in della_riga)) + ' "$@"'] if della_riga else []
+ for chiave, gruppo in reversed(opzioni_dello_strato(cli, di_serie)):
+ metti = 'set -- ' + ' '.join((_q(a) for a in gruppo)) + ' "$@"'
+ if not chiave:
+ righe.append(metti)
+ continue
+ parti = chiave.split('.')
+ casi = '|'.join(('*"|' + '.'.join(parti[:n]) + '|"*' for n in range(1, len(parti) + 1)))
+ righe.append(f'case "${{{variabile}:-}}" in {casi}) ;; *) {metti} ;; esac')
+ return righe
+
+def chiave_qwen(riga):
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ fisso = ((riga.get('_fornitori') or {}).get(tipo) or {}).get('chiave')
+ return fisso if fisso else re.sub('[^A-Z0-9]+', '_', riga['nome'].upper()).strip('_') + '_API_KEY'
+
+def impostazioni_qwen(riga):
+ f = riga.get('fornitore') or {}
+ info = (riga.get('_fornitori') or {}).get(f.get('tipo')) or {}
+ if not info:
+ raise RuntimeError(F('fornitore_ignoto', fornitore=f.get('tipo') or ''))
+ spente = {} if (riga.get('scelte') or {}).get('telemetria') == 'accesa' else {'privacy': {'usageStatisticsEnabled': False}, 'telemetry': {'enabled': False}}
+ auth, modello = (info['auth'], riga.get('modello') or '')
+ indirizzo = f.get('indirizzo') or info.get('indirizzo') or ''
+ fa = info.get('formato_anthropic') or {}
+ if fa.get('prefisso') and modello.startswith(fa['prefisso']):
+ auth, indirizzo = ('anthropic', fa['indirizzo'])
+ contesto = int(f.get('contesto') or 0)
+ memoria = (riga.get('scelte') or {}).get('memoria') == 'accesa'
+ base = riga.get('_base') or {}
+ attesa = int(base.get('qwen.prima_parola_ms') or QWEN_PRIMA_PAROLA_MS)
+ generazione = {'timeout': attesa, 'streamIdleTimeoutMs': attesa, **({'contextWindowSize': contesto} if contesto else {})}
+ compatta, voluto = ({}, int(f.get('compatta') or 0))
+ finestra = contesto or (1000000 if auth == 'anthropic' and QWEN_CLAUDE_1M.search(modello) else 0)
+ if finestra:
+ soglia = min(1.0, voluto / finestra) if voluto else min(0.85, int(base.get('qwen.compatta') or QWEN_SOGLIA) / finestra)
+ if voluto or soglia < 0.85:
+ generazione['contextWindowSize'] = finestra
+ compatta = {'context': {'autoCompactThreshold': round(soglia, 3)}}
+ if info.get('auth') == 'anthropic':
+ generazione['cacheRetention'] = '1h'
+ fornitori = {auth: [{'id': modello, 'name': modello, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo} if indirizzo else {}), **({'generationConfig': generazione} if generazione else {})}]}
+ veloce, extra = ((riga.get('scelte') or {}).get('classificatore') or '', {})
+ if veloce and veloce != modello:
+ auth_v, indirizzo_v = (info['auth'], f.get('indirizzo') or info.get('indirizzo') or '')
+ if fa.get('prefisso') and veloce.startswith(fa['prefisso']):
+ auth_v, indirizzo_v = ('anthropic', fa['indirizzo'])
+ fornitori.setdefault(auth_v, []).append({'id': veloce, 'name': veloce, 'envKey': chiave_qwen(riga), **({'baseUrl': indirizzo_v} if indirizzo_v else {})})
+ extra = {'fastModel': veloce if auth_v == auth else f'{auth_v}:{veloce}'}
+ return {'modelProviders': fornitori, **extra, 'security': {'auth': {'selectedType': auth}}, 'model': {'name': modello}, **spente, **compatta, 'memory': {'enableManagedAutoMemory': memoria, 'enableManagedAutoDream': memoria, 'enableAutoSkill': False, 'enableTeamMemory': False}, 'general': {'enableAutoUpdate': False}, 'ui': {'enableFollowupSuggestions': False, 'showToolCallDetails': False}, 'tools': {'approvalMode': 'default', 'toolSearch': {'enabled': False}}, 'permissions': {'deny': list(QWEN_TOOL_FUORI + (QWEN_TOOL_LARGHI if 0 < contesto < 65536 else ())), 'ask': list(QWEN_CHIEDI)}, 'review': {**QWEN_REVIEW, **({'effort': base['qwen.review']} if base.get('qwen.review') else {})}, 'skills': skill_qwen(riga.get('_skill'))}
+
+def della_riga_qwen(riga):
+ sc, f = (riga.get('scelte') or {}, riga.get('fornitore') or {})
+ chiavi = ['modelProviders', 'model.name', 'security.auth']
+ if sc.get('classificatore'):
+ chiavi.append('fastModel')
+ if sc.get('telemetria'):
+ chiavi += ['privacy.usageStatisticsEnabled', 'telemetry.enabled']
+ if sc.get('memoria'):
+ chiavi += ['memory.enableManagedAutoMemory', 'memory.enableManagedAutoDream']
+ if f.get('compatta'):
+ chiavi.append('context.autoCompactThreshold')
+ if any(((x or {}).get('cli') == 'qwen' for x in riga.get('_skill') or [])):
+ chiavi.append('skills')
+ return ','.join(chiavi)
+
+def skill_qwen(scelte):
+ spente, a_scelta = (list(QWEN_SKILL_SPENTE), list(QWEN_SKILL_A_SCELTA))
+ for x in scelte or []:
+ nome = (x or {}).get('nome')
+ if (x or {}).get('cli') != 'qwen' or not nome:
+ continue
+ if x.get('stato') == 'accesa':
+ spente = [n for n in spente if n != nome]
+ a_scelta = [n for n in a_scelta if n != nome]
+ elif x.get('stato') == 'spenta' and nome not in spente and (nome not in a_scelta):
+ a_scelta.append(nome)
+ return {'disabled': spente, 'defaultDisabled': a_scelta}
+QWEN_TOOL_FUORI = ('artifact', 'autofix_pr', 'cron_create', 'cron_delete', 'cron_list', 'display_image', 'enter_worktree', 'exit_worktree', 'get_goal', 'list_agents', 'loop_wakeup', 'monitor', 'propose_goal', 'read_mcp_resource', 'record_artifact', 'report_findings', 'send_message', 'update_goal', 'zoom_image')
+QWEN_TOOL_LARGHI = ('agent', 'enter_plan_mode', 'exit_plan_mode')
+QWEN_SKILL_ACCESE = ('agent-delegation', 'batch', 'dataviz', 'extension-creator', 'new-app', 'review', 'simplify', 'stuck', 'zvec-grep-install')
+QWEN_SKILL_A_SCELTA = ()
+QWEN_SKILL_SPENTE = ('auto-memory', 'autofix-pr', 'batch-api', 'coordinate', 'goal-draft', 'loop', 'qc-helper', 'workflow-authoring', 'workflow-creator')
+QWEN_CHIEDI = ('agent', 'workflow')
+QWEN_REVIEW = {'effort': 'low'}
+QWEN_SOGLIA = 300000
+QWEN_PRIMA_PAROLA_MS = 60000
+QWEN_CLAUDE_1M = re.compile('claude-(opus|sonnet|fable)-(5|4-[6-9])')
+
+def explore_qwen():
+ return '\n'.join(['---', 'name: Explore', 'description: ' + json.dumps(F('explore_descrizione'), ensure_ascii=False), 'tools:', ' - read_file', ' - grep_search', ' - glob', '---', '', F('explore_prompt')])
+
+def _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file):
+ out = []
+ if (scelta := (riga.get('fornitore') or {}).get('chiave')):
+ if dal_repo:
+ leggi = 'python3 -c \'import shlex, sys\nfor l in open(sys.argv[1], encoding="utf-8"):\n k, _, x = l.strip().partition("=")\n if k == sys.argv[2] and x:\n print((shlex.split(x) or [""])[0])\n break\' "$r/.claude/delminio.sh"'
+ out += [f'T=$({leggi} FILE_TOKEN 2>/dev/null)', f'U=$({leggi} URL 2>/dev/null)']
+ dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat "$T")" | curl -sS -m 30 -K - "${{U%/}}"/api/eseguibili/{_q(urllib.parse.quote(nome))}/chiave"""
+ else:
+ dal_motore = f"""printf 'header = "Authorization: Bearer %s"\\n' "$(cat {_q(token_file)})" | curl -sS -m 30 -K - {_q(url.rstrip('/') + '/api/eseguibili/' + urllib.parse.quote(nome) + '/chiave')}"""
+ out += [*_commento(F('commento_chiave_dal_motore')), f'''K=$( ({dal_motore.replace('curl -sS', 'curl -sSf', 1)}) 2>/dev/null) || K=""''', 'if [ -z "$K" ]; then', ' echo ' + _sh(F('wrapper_chiave_negata', nome=nome, scelta=scelta)) + ' >&2', f' ({dal_motore}) 2>&1 | head -c 400 >&2; echo >&2', ' exit 1', 'fi', f'export {chiave}="$K"', 'unset K' + (' T U' if dal_repo else '')]
+ elif tipo == 'casa':
+ out.append(f'[ -n "${{{chiave}:-}}" ] || export {chiave}=nessuna')
+ else:
+ leggi = f"""python3 -c 'import json, os, sys\ntry:\n e = json.load(open(os.path.expanduser("~/.qwen/settings.json"), encoding="utf-8")).get("env") or {{}}\n print(e.get(sys.argv[1]) or "")\nexcept (OSError, ValueError, AttributeError):\n pass' {chiave}"""
+ out += [f'if [ -z "${{{chiave}:-}}" ]; then', *_commento(F('commento_chiave_di_qwen')), f' {chiave}=$({leggi} 2>/dev/null) || {chiave}=""', f' [ -n "${chiave}" ] && export {chiave}', 'fi', f'if [ -z "${{{chiave}:-}}" ]; then', ' echo ' + _sh(F('wrapper_senza_chiave', nome=nome, fornitore=riga['_fornitori'][tipo]['nome'], variabile=chiave)) + ' >&2', ' exit 1', 'fi']
+ return out
+
+def wrapper_qwen(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ impostazioni = impostazioni_qwen(riga)
+ canale = canale_del_ruolo(spazio_di(url, _token_di(token_file)), porta) if personaggio(riga) else ''
+ if canale:
+ impostazioni['hooks'] = ganci_della_posta(canale)
+ for g in impostazioni['hooks']['Stop'][0]['hooks']:
+ g.pop('asyncRewake', None)
+ g['timeout'] = 10
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ chiave = chiave_qwen(riga)
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
+ casa = hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]
+ node = os.path.join(node_di(os.path.dirname(os.path.dirname(os.path.dirname(cli)))), 'bin')
+ righe = [*_testa_del_wrapper(riga), f'export QWEN_HOME="${{XDG_DATA_HOME:-$HOME/.local/share}}/delminio/qwen/{casa}-{nome}"', 'export DELMINIO_CLI_NOME=qwen', 'export QWEN_CODE_MODELS_DEV=off', 'export QWEN_CODE_DISABLE_ARTIFACT=1', 'export QWEN_CODE_LEGACY_MCP_BLOCKING=1', *([f"export DELMINIO_CONTESTO={int((riga.get('fornitore') or {}).get('contesto') or 0)}"] if int((riga.get('fornitore') or {}).get('contesto') or 0) > 0 else []), f'export PATH={_q(node)}:"$PATH"', f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ dal_repo = modo == 'kit' and bool(porta)
+ if dal_repo:
+ righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
+ righe += _righe_della_chiave(riga, chiave, tipo, nome, dal_repo, url, token_file)
+ righe += ['mkdir -p "$QWEN_HOME" && chmod 700 "$QWEN_HOME"', *_commento(F('commento_settings_qwen')), 'cat > "$QWEN_HOME/settings.json" <<\'IMPOSTAZIONI\'', json.dumps(impostazioni, indent=2, ensure_ascii=False), 'IMPOSTAZIONI', *_commento(F('commento_mie_qwen')), 'python3 ' + ('"$r/.claude/eseguibili.py"' if dal_repo else _q(os.path.abspath(__file__))) + ' mie-qwen "$QWEN_HOME"' + (f' --della-riga {_q(chiavi)}' if (chiavi := ','.join((x for x in (della_riga_qwen(riga), chiavi_della_riga('qwen', delle_scelte + list(riga.get('argomenti') or []))) if x))) else '') + ' >/dev/null', 'mkdir -p "$QWEN_HOME/agents"', 'cat > "$QWEN_HOME/agents/Explore.md" <<\'EXPLORE\'', explore_qwen(), 'EXPLORE']
+ if canale:
+ righe.append('mkdir -p "$QWEN_HOME/commands"')
+ for gesto, (descrizione, _corpo) in _SKILL_DEL_RITO.items():
+ righe += [f"""cat > "$QWEN_HOME/commands/{gesto}.md" <<'RITO'""", f'---\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\n---\n{gesto}', 'RITO']
+ righe += [f'export DELMINIO_CANALE_RUOLO={_q(canale)}']
+ if dal_repo:
+ righe += [f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}"]
+ if canale:
+ righe += _fuori_dal_suo_spazio(nome, spazio_di(url, _token_di(token_file)))
+ righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" qwen', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+ if porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe += [f'export DELMINIO_PORTA={_q(porta)}', 'export QWEN_SYSTEM_MD="$F"']
+ if canale:
+ righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec(_q(cli), fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+
+def opencode_v2(versione):
+ return str(versione).split('.', 1)[0] == '2'
+OPENCODE_SOGLIA = 300000
+OPENCODE_PRIMA_PAROLA_MS = 60000
+
+def config_opencode(riga, versione):
+ f = riga.get('fornitore') or {}
+ tipo = f.get('tipo')
+ info = (riga.get('_fornitori') or {}).get(tipo) or {}
+ if not info:
+ raise RuntimeError(F('fornitore_ignoto', fornitore=tipo or ''))
+ modello = riga.get('modello') or ''
+ anthropic = info.get('auth') == 'anthropic'
+ contesto = int(f.get('contesto') or 0)
+ finestra = contesto or (1000000 if anthropic and QWEN_CLAUDE_1M.search(modello) else 0)
+ base_spazio = riga.get('_base') or {}
+ voluto = int(f.get('compatta') or 0)
+ if finestra:
+ soglia = min(voluto, finestra) if voluto else min(int(finestra * 0.85), int(base_spazio.get('opencode.compatta') or OPENCODE_SOGLIA))
+ riserva = finestra - soglia
+ else:
+ riserva = '15%'
+ base = {'update': 'disable', 'share': 'disabled', 'compaction': {'background': False, 'buffer': riserva}}
+ if tipo == 'zen':
+ return {**base, 'model': f'opencode/{modello}'} if modello else base
+ chiave = chiave_qwen(riga)
+ indirizzo = '' if anthropic else f.get('indirizzo') or info.get('indirizzo') or ''
+ attesa = int(base_spazio.get('opencode.prima_parola_ms') or OPENCODE_PRIMA_PAROLA_MS)
+ impostazioni = {**({'baseURL': indirizzo} if indirizzo else {}), 'headerTimeout': attesa, 'chunkTimeout': attesa}
+ fornitore = {'name': info.get('nome') or tipo, 'env': [chiave], 'package': '@opencode/ai/providers/' + ('anthropic' if anthropic else 'openai-compatible'), 'settings': impostazioni, 'models': {modello: {'name': modello, **({'limit': {'context': finestra, 'output': min(32000, finestra // 4)}} if finestra else {})}}}
+ return {**base, 'providers': {'delminio': fornitore}, 'model': f'delminio/{modello}'}
+
+def wrapper_opencode(riga, cli, modo, url, token_file):
+ nome, porta = (riga['nome'], riga.get('porta'))
+ if modo != 'kit':
+ return '\n'.join([*_testa_del_wrapper(riga), 'echo ' + _sh(F('wrapper_opencode_solo_kit', nome=nome)) + ' >&2', 'exit 1']) + '\n'
+ versione = os.path.basename(os.path.dirname(os.path.dirname(cli)))
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ fissi = ' '.join((_q(a) for a in delle_scelte + list(riga.get('argomenti') or [])))
+ righe = [*_testa_del_wrapper(riga), 'export DELMINIO_CLI_NOME=opencode', 'export OPENCODE_DISABLE_AUTOUPDATE=1 # ' + F('commento_autoupdater'), *_commento(F('commento_config_opencode')), f'export DELMINIO_OPENCODE_CONFIG={_q(json.dumps(config_opencode(riga, versione), ensure_ascii=False, sort_keys=True))}', *([f'export DELMINIO_OPENCODE_GRATUITO={_q(nome)}'] if tipo == 'zen' and (not riga.get('modello')) else []), f'export DELMINIO_SQUADRA={hashlib.sha256(spazio_di(url, _token_di(token_file)).encode()).hexdigest()[:12]}', f'export DELMINIO_CLI={_q(cli)}']
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ righe += _righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo', nome=nome))
+ if tipo != 'zen':
+ righe.append('export OPENCODE_DISABLE_MODELS_FETCH=1 # ' + F('commento_catalogo_opencode'))
+ righe += _righe_della_chiave(riga, chiave_qwen(riga), tipo, nome, True, url, token_file)
+ if porta:
+ righe.append(f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')}")
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ elif riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" opencode', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+
+def _fuori_dal_suo_spazio(nome, spazio):
+ return ['qui=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null)', f'if [ -n "$qui" ] && [ "$qui" != {_q(spazio)} ]; then', ' echo ' + _sh(F('wrapper_altro_spazio', nome=nome, spazio=nome_spazio(spazio))) + ' >&2', ' exit 1', 'fi']
+
+def righe_della_casa(riga, nome, spazio):
+ if (riga.get('scelte') or {}).get('casa') != 'separata':
+ return [f"cd {_q(riga['cartella'])} || exit 1"] if riga.get('cartella') else []
+ dove = _q(riga['cartella']) if riga.get('cartella') else ''
+ return [*_commento(F('commento_casa')), f"""casa=$(python3 "$r/.claude/eseguibili.py" casa "$r/.claude/delminio.sh" {_q(riga['porta'])} {_q(nome)} {dove}) || exit 1""".rstrip(), 'cd "$casa" || exit 1']
+
+def wrapper(riga, cli, modo, url, token_file):
+ if riga.get('cli') == 'codex':
+ return wrapper_codex(riga, cli, modo, url, token_file)
+ if riga.get('cli') == 'qwen':
+ return wrapper_qwen(riga, cli, modo, url, token_file)
+ if riga.get('cli') == 'opencode':
+ return wrapper_opencode(riga, cli, modo, url, token_file)
+ nome = riga['nome']
+ args = []
+ if riga.get('modello'):
+ args += ['--model', riga['modello']]
+ if riga.get('effort'):
+ args += ['--effort', riga['effort']]
+ delle_scelte, env_scelte = lancio_delle_scelte(riga)
+ env_scelte = {**(riga.get('_promemoria') or {}), **env_scelte}
+ args += delle_scelte + list(riga.get('argomenti') or [])
+ if personaggio(riga):
+ spazio = spazio_di(url, _token_di(token_file))
+ canale = canale_del_ruolo(spazio, riga['porta'])
+ args = con_i_ganci(args, ganci_della_posta(canale))
+ args += ['--mcp-config', canale, '--allowedTools', f'mcp__{SERVER_RUOLO}__delminio,mcp__{SERVER_RUOLO}__delminio_write']
+ args += ['--plugin-dir', _rito_del_ruolo()]
+ fissi = ' '.join((_q(a) for a in args))
+ righe = [*_testa_del_wrapper(riga), 'export DISABLE_AUTOUPDATER=1 # ' + F('commento_autoupdater')]
+ if riga.get('ordine'):
+ righe.append(f"export DELMINIO_MODELLO={_q(riga['ordine'])}")
+ for k, v in sorted({**env_scelte, **ambiente_della_riga(riga)}.items()):
+ if re.fullmatch('[A-Z_][A-Z0-9_]*', k):
+ righe.append(f'export {k}={_q(v)}')
+ porta = riga.get('porta')
+ if modo == 'kit':
+ if porta:
+ righe += [*_commento(F('commento_token_progetto')), *_righe_del_repo(riga, spazio_di(url, _token_di(token_file)), F('wrapper_senza_repo_claude', nome=nome)), f"export DELMINIO_PORTA={_q(porta)} DELMINIO_NASCITA={_q(riga.get('nascita') or 'intera')} DELMINIO_CLI={_q(cli)}"]
+ if personaggio(riga):
+ righe += _fuori_dal_suo_spazio(nome, spazio)
+ righe += righe_della_casa(riga, nome, spazio_di(url, _token_di(token_file)))
+ if personaggio(riga):
+ righe.append('export DELMINIO_POSTA_CLIENT="$r/.claude/eseguibili.py"')
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec('bash "$r/.claude/delminio.sh" claude', fissi, '"$@"'))
+ return '\n'.join(righe) + '\n'
+ elif porta:
+ righe += _righe_del_prompt(riga, url, token_file)
+ righe.append(f'export DELMINIO_PORTA={_q(porta)}')
+ if personaggio(riga):
+ righe.append(f'export DELMINIO_POSTA_CLIENT={_q(os.path.abspath(__file__))}')
+ if riga.get('cartella'):
+ righe.append(f"cd {_q(riga['cartella'])} || exit 1")
+ prompt = ' --system-prompt-file "$F"' if porta and modo != 'kit' else ''
+ righe += _righe_al_lancio(modo, url, token_file)
+ righe.append(_riga_exec(_q(cli), fissi, prompt.strip(), '"$@"'))
+ return '\n'.join(righe) + '\n'
+PROMEMORIA_AMMESSI = frozenset({'CLAUDE_CODE_SILENT_TURN_REMINDER_TEXT', 'CLAUDE_CODE_SILENT_TURN_REMINDER'})
+
+def parte_libera(riga):
+ return {'cli': str(riga.get('cli') or 'claude'), 'argomenti': [str(x) for x in riga.get('argomenti') or []], 'ambiente': {str(k): str(v) for k, v in (riga.get('ambiente') or {}).items()}}
+
+def impronta_libera(riga):
+ return hashlib.sha256(json.dumps([str(riga.get('nome') or ''), parte_libera(riga)], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
+
+def da_accettare(riga, accettati):
+ p = parte_libera(riga)
+ return bool(p['argomenti'] or p['ambiente']) and impronta_libera(riga) not in accettati
+
+def _visibile_riga(v):
+ return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
+
+def accetta(registro):
+ mio = _leggi(registro)
+ fermi = [(url, x) for url, sp in (mio.get('spazi') or {}).items() for x in sp.get('fermi') or [] if isinstance(x, dict)]
+ if not fermi:
+ return 0
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ print(F('accetta_senza_terminale'), file=sys.stderr)
+ return 1
+ accettati, presi, restano = (set(mio.get('accettati') or []), set(), 0)
+ for url, x in fermi:
+ p = parte_libera(x)
+ tty.write(F('accetta_riga_domanda', nome=_visibile_riga(x.get('nome')), cli=_visibile_riga(p['cli']), spazio=_visibile_riga(come_si_chiama(url)), argomenti=_visibile_riga(shlex.join(p['argomenti']) or '—'), ambiente=_visibile_riga(' '.join((f'{k}={shlex.quote(v)}' for k, v in sorted(p['ambiente'].items()))) or '—')))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('accetta_si').split():
+ accettati.add(impronta_libera(x))
+ presi.add(url)
+ else:
+ restano += 1
+ mio = _leggi(registro)
+ mio['accettati'] = sorted(set(mio.get('accettati') or []) | accettati)
+ for url in presi:
+ (mio.get('spazi') or {}).get(url, {})['registro'] = ''
+ _scrivi(registro, mio)
+ print(F('accetta_righe_esito', nuovi=len(fermi) - restano, restano=restano))
+ return 0
+
+def _impronta(testo):
+ return hashlib.sha256(testo.encode('utf-8')).hexdigest()[:16]
+
+def _del_file(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return _impronta(f.read())
+ except (OSError, UnicodeDecodeError):
+ return None
+_DIARIO_MAX = 1000000
+
+def _nel_diario(registro, percorso, prima, dopo, vecchio, nuovo):
+ diario = os.path.join(os.path.dirname(registro) or '.', 'eseguibili-diario.log')
+ righe = [r for r in difflib.unified_diff((vecchio or '').splitlines(), nuovo.splitlines(), lineterm='', n=0) if not r.startswith(('---', '+++'))]
+ testa = f"── {time.strftime('%Y-%m-%d %H:%M:%S')} {percorso} · CLI {prima or '—'} → {dopo}"
+ try:
+ if os.path.exists(diario) and os.path.getsize(diario) > _DIARIO_MAX:
+ with open(diario, encoding='utf-8', errors='replace') as f:
+ resto = f.read()[-_DIARIO_MAX // 2:]
+ with open(diario, 'w', encoding='utf-8') as f:
+ f.write(resto[resto.find('\n── ') + 1:] if '\n── ' in resto else resto)
+ with open(os.open(diario, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384), 'a', encoding='utf-8') as f:
+ f.write('\n'.join([testa, *righe]) + '\n')
+ except OSError:
+ pass
+ return sum((1 for r in righe if r.startswith(('+', '-'))))
+_SEGNO_CASA = 'export DELMINIO_SISTEMA="$F"'
+
+def _di_casa(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return _SEGNO_CASA in f.read()
+ except (OSError, UnicodeDecodeError):
+ return False
+
+def _leggi(path):
+ try:
+ with open(path, encoding='utf-8') as f:
+ return json.load(f)
+ except (OSError, ValueError):
+ return {}
+_CHIAVE_PER_SPAZIO = 1792090627
+
+def _spazio(mio, url):
+ spazi = mio.setdefault('spazi', {})
+ base = url.split('#', 1)[0]
+ if url not in spazi and url != base and (base in spazi) and ((spazi[base].get('quando') or 0) < _CHIAVE_PER_SPAZIO) and (not any((k.startswith(base + '#') for k in spazi))):
+ spazi[url] = spazi.pop(base)
+ for chi in mio.get('padroni', {}).values():
+ chi[:] = [url if u == base else u for u in chi]
+ if url not in spazi:
+ s = spazi[url] = {}
+ if len(spazi) == 1:
+ for k in ('registro', 'quando', 'rifiutato', 'cli'):
+ if k in mio:
+ s[k] = mio.pop(k)
+ for p in mio.get('eseguibili', {}):
+ mio.setdefault('padroni', {}).setdefault(p, [url])
+ return spazi[url]
+
+def _scrivi(path, dati):
+ os.makedirs(os.path.dirname(path), mode=448, exist_ok=True)
+ with open(path + '.nuovo', 'w', encoding='utf-8') as f:
+ json.dump(dati, f, ensure_ascii=False, indent=1)
+ os.replace(path + '.nuovo', path)
+
+def _cli_del_wrapper(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ testo = f.read()
+ except OSError:
+ return ''
+ m = re.search('/versions(?:-pinned)?/(\\d+\\.\\d+\\.\\d+)', testo)
+ return m.group(1) if m else '?'
+
+def sul_disco(versioni):
+ try:
+ return sorted((f for f in os.listdir(versioni) if _VERSIONE.match(f)), key=_v, reverse=True)
+ except OSError:
+ return []
+
+def nudo(bin_dir, versioni):
+ p = os.path.join(bin_dir, 'claude')
+ if not os.path.lexists(p):
+ return ''
+ vero = os.path.realpath(p)
+ if os.path.dirname(vero) == os.path.realpath(versioni) and _VERSIONE.match(os.path.basename(vero)):
+ return os.path.basename(vero)
+ return 'altro'
+
+def pulisci(bin_dir, versioni, scelte=None):
+ usate = set()
+ cartelle = {os.path.realpath(versioni), os.path.abspath(os.path.expanduser(versioni))}
+ voce = re.compile('(?:%s|/versions(?:-pinned)?)/(\\d+\\.\\d+\\.\\d+)' % '|'.join((re.escape(c) for c in cartelle)))
+ try:
+ nomi = [os.path.join(bin_dir, n) for n in os.listdir(bin_dir)]
+ except OSError:
+ nomi = []
+ for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
+ nomi += [os.path.join(radice, n) for n in file]
+ for p in nomi:
+ if os.path.islink(p):
+ vero = os.path.realpath(p)
+ if os.path.dirname(vero) == os.path.realpath(versioni):
+ usate.add(os.path.basename(vero))
+ continue
+ try:
+ if os.path.isfile(p) and os.path.getsize(p) < 200000:
+ with open(p, encoding='utf-8', errors='ignore') as f:
+ usate.update(voce.findall(f.read()))
+ except OSError:
+ pass
+ if (n := nudo(bin_dir, versioni)) and n != 'altro':
+ usate.add(n)
+ libere = [v for v in sul_disco(versioni) if v not in usate]
+ alta = max((v for v in usate if _VERSIONE.match(v)), key=_v, default=None)
+ prima = [v for v in libere if alta and _v(v) < _v(alta)]
+ riparo = (prima or libere)[:1]
+ if scelte is not None:
+ riparo = [v for v in libere if v not in scelte]
+ tolte, errori = ([], [])
+ for v in [x for x in libere if x not in riparo]:
+ try:
+ os.remove(os.path.join(versioni, v))
+ tolte.append(v)
+ except OSError as e:
+ errori.append(f'{v}: {e.strerror}')
+ esito = {'tolte': tolte, 'tenute': sorted(usate | set(riparo), key=_v, reverse=True)}
+ if scelte is not None:
+ riparo = []
+ if errori:
+ esito['errore'] = '; '.join(errori)[:300]
+ print(F('pulizia', n=len(tolte), tolte=', '.join(tolte) or F('nessuna'), tenute=', '.join(esito['tenute']) or F('nessuna'), riparo=F('al_riparo', versione=riparo[0]) if riparo else ''))
+ return esito
+
+def _cosa_lancia(bin_dir):
+ nomi = [os.path.join(bin_dir, n) for n in (os.listdir(bin_dir) if os.path.isdir(bin_dir) else ())]
+ for radice, _, file in os.walk(_DIR_COMANDI[0]) if _DIR_COMANDI[0] else ():
+ nomi += [os.path.join(radice, n) for n in file]
+ testi = []
+ for p in nomi:
+ try:
+ if os.path.islink(p):
+ testi.append(os.path.realpath(p))
+ elif os.path.isfile(p) and os.path.getsize(p) < 200000:
+ with open(p, encoding='utf-8', errors='ignore') as f:
+ testi.append(f.read())
+ except OSError:
+ pass
+ if os.path.isdir('/proc'):
+ for pid in os.listdir('/proc'):
+ if pid.isdigit():
+ try:
+ with open(f'/proc/{pid}/cmdline', 'rb') as f:
+ testi.append(f.read().replace(b'\x00', b' ').decode(errors='ignore'))
+ testi.append(os.readlink(f'/proc/{pid}/exe'))
+ except OSError:
+ pass
+ else:
+ try:
+ testi.append(subprocess.run(['ps', '-axww', '-o', 'comm=', '-o', 'command='], capture_output=True, text=True, errors='ignore', timeout=20, check=True).stdout)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return '\n'.join(testi)
+
+def pota(bin_dir, cartelle, nudo_claude=''):
+ testo, tolte = (_cosa_lancia(bin_dir), [])
+ if testo is None:
+ return tolte
+
+ def via(dove, nome):
+ try:
+ shutil.rmtree(dove) if os.path.isdir(dove) and (not os.path.islink(dove)) else os.remove(dove)
+ tolte.append(nome)
+ except OSError:
+ pass
+ for cartella in [c for c in cartelle if c and os.path.isdir(c)]:
+ radici = '|'.join((re.escape(c) for c in {os.path.realpath(cartella), os.path.abspath(cartella)}))
+ usate = set(re.findall('(?:%s)/(\\d+\\.\\d+\\.\\d+)' % radici, testo)) | {nudo_claude}
+ for v in sul_disco(cartella):
+ if v not in usate:
+ via(os.path.join(cartella, v), v)
+ sopra = os.path.realpath(os.path.dirname(os.path.normpath(cartella)))
+ nodi = set(re.findall('%s/(node-\\d[\\w.]*)' % re.escape(sopra), testo))
+ for n in os.listdir(sopra) if nodi else ():
+ if n.startswith('node-') and n not in nodi and os.path.isdir(os.path.join(sopra, n)):
+ via(os.path.join(sopra, n), n)
+ if tolte:
+ print(F('potate', tolte=', '.join(tolte)), flush=True)
+ return tolte
+
+def riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte=None, esito=None, senza_cli=()):
+ stato = []
+ for r in righe:
+ p = os.path.join(bin_dir, r['nome'])
+ ora = _del_file(p)
+ intatto = ora is not None and impronte.get(p) == ora
+ cli = (scritte or {}).get(p, '') if intatto else _cli_del_wrapper(p) if ora else ''
+ stato.append({'nome': r['nome'], 'cli': cli, 'stato': 'senza_cli' if ora is None and r['nome'] in senza_cli else 'manca' if ora is None else 'intatto' if intatto else 'toccato'})
+ corpo = {'host': socket.gethostname(), 'righe': stato, 'registro': registro, 'disco': sul_disco(versioni), 'nudo': nudo(bin_dir, versioni)}
+ if esito:
+ corpo['esito'] = esito
+ try:
+ return json.loads(_get(f'{base}/macchina', token, metodo='POST', corpo=corpo, timeout=10) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError):
+ return {}
+INSTALLABILI = tuple(CLI_NOMI)
+
+def richiesta(base, token, risposta, righe, impronte, bin_dir, versioni, registro, scritte, mio=None, file_mio=''):
+ r = (risposta or {}).get('richiesta') or {}
+ if r.get('pulizia'):
+ scelte = r.get('versioni')
+ esito = pulisci(bin_dir, versioni, scelte if isinstance(scelte, list) else None)
+ riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito=esito)
+ nuove = {c for c in r.get('installa') or [] if c in INSTALLABILI}
+ if nuove and mio is not None and file_mio:
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | nuove)
+ _scrivi(file_mio, mio)
+ print(F('installo_chiesta', cli=', '.join(sorted(nuove))), flush=True)
+ riferisci(base, token, righe, impronte, bin_dir, versioni, registro, scritte, esito={'installate': sorted(nuove)})
+ return True
+ return False
+SEGNO_SMISTA = '# delminio-più-spazi'
+_DIR_COMANDI = ['']
+
+def cartella_dei_comandi(registro):
+ return os.path.join(os.path.dirname(registro) or '.', 'comandi')
+
+def comando_dello_spazio(spazio, nome):
+ return os.path.join(_DIR_COMANDI[0], cartella_dello_spazio(spazio), nome)
+
+def cartella_dello_spazio(spazio):
+ return re.sub('[^A-Za-z0-9._-]', '_', spazio)
+
+def come_si_chiama(spazio):
+ if '#' in spazio:
+ return spazio.rsplit('#', 1)[1]
+ return urllib.parse.urlsplit(spazio).netloc or spazio
+
+def e_smistatore(p):
+ try:
+ with open(p, encoding='utf-8') as f:
+ return SEGNO_SMISTA in f.read()
+ except (OSError, UnicodeDecodeError):
+ return False
+
+def smistatore(nome, spazi):
+ elenco = ', '.join((come_si_chiama(s) for s in spazi))
+ dove = _q(_DIR_COMANDI[0])
+ return '\n'.join(['#!/bin/sh', f'# {nome} — ' + F('smista_testa'), SEGNO_SMISTA, *_commento(F('wrapper_commento')), 'r=$(git rev-parse --show-toplevel 2>/dev/null) || r=""', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ]; then', ' c=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) && r=$(dirname "$c")', 'fi', 'if [ -z "$r" ] || [ ! -x "$r/.claude/delminio.sh" ] || [ ! -f "$r/.claude/eseguibili.py" ]; then', ' echo ' + _sh(F('smista_fuori', nome=nome, spazi=elenco)) + ' >&2', ' exit 1', 'fi', 's=$(python3 "$r/.claude/eseguibili.py" spazio --da "$r/.claude/delminio.sh" 2>/dev/null) || s=""', 'd=$(printf %s "$s" | tr -c \'A-Za-z0-9._-\' \'_\')', f'f={dove}/"$d"/{_q(nome)}', 'if [ -n "$s" ] && [ -x "$f" ]; then', ' exec "$f" "$@"', 'fi', 'echo ' + _sh(F('smista_non_qui', nome=nome, spazi=elenco)) + ' >&2', 'exit 1']) + '\n'
+
+def _scrivi_eseguibile(p, testo):
+ os.makedirs(os.path.dirname(p), mode=448, exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+
+def dividi(p, url, testo, padroni, impronte):
+ chi = padroni.get(p) or []
+ nuovo = not e_smistatore(p)
+ if nuovo:
+ with open(p, encoding='utf-8') as f:
+ di_prima = f.read()
+ for u in chi:
+ if u != url:
+ q = comando_dello_spazio(u, os.path.basename(p))
+ _scrivi_eseguibile(q, di_prima)
+ impronte[q] = _impronta(di_prima)
+ q = comando_dello_spazio(url, os.path.basename(p))
+ _scrivi_eseguibile(q, testo)
+ impronte[q] = _impronta(testo)
+ if url not in chi:
+ chi.append(url)
+ padroni[p] = chi
+ rifai_smistatore(p, chi, impronte)
+ return nuovo
+
+def rifai_smistatore(p, chi, impronte):
+ t = smistatore(os.path.basename(p), chi)
+ if _del_file(p) != _impronta(t):
+ _scrivi_eseguibile(p, t)
+ impronte[p] = _impronta(t)
+
+def lascia_il_nome(p, url, padroni, impronte):
+ chi = padroni.get(p) or []
+ if url in chi:
+ chi.remove(url)
+ smista = e_smistatore(p) and impronte.get(p) == _del_file(p)
+ if smista:
+ q = comando_dello_spazio(url, os.path.basename(p))
+ if impronte.get(q) and _del_file(q) == impronte[q]:
+ os.remove(q)
+ impronte.pop(q, None)
+ if not chi:
+ tolto = os.path.exists(p) and _del_file(p) == impronte.get(p)
+ if tolto:
+ os.remove(p)
+ impronte.pop(p, None)
+ padroni.pop(p, None)
+ return 'tolto' if tolto else 'resta'
+ if not smista:
+ return 'altri'
+ if len(chi) > 1:
+ rifai_smistatore(p, chi, impronte)
+ return 'altri'
+ q = comando_dello_spazio(chi[0], os.path.basename(p))
+ if impronte.get(q) and _del_file(q) == impronte[q]:
+ with open(q, encoding='utf-8') as f:
+ suo = f.read()
+ _scrivi_eseguibile(p, suo)
+ impronte[p] = _impronta(suo)
+ os.remove(q)
+ impronte.pop(q, None)
+ return 'tornato'
+ rifai_smistatore(p, chi, impronte)
+ return 'altri'
+_SKILL_PROGETTO = (('.claude/skills', ('claude',)), ('.agents/skills', ('codex', 'qwen')), ('.qwen/skills', ('qwen',)))
+_SKILL_TETTO = 300
+
+def _skill_testa(percorso):
+ try:
+ with open(percorso, 'rb') as h:
+ crudo = h.read(200000)
+ except OSError:
+ return None
+ testo = crudo.decode('utf-8', errors='replace')
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(\\n|$)', testo, re.S)
+ testa = m.group(1) if m else ''
+
+ def campo(nome):
+ c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
+ if not c:
+ return ''
+ v = ' '.join(c.group(1).split())
+ if v[:1] in '"\'' and v[-1:] == v[:1]:
+ v = v[1:-1]
+ return '' if v in ('>', '|', '>-', '|-') else v
+ nome = campo('name') or os.path.basename(os.path.dirname(percorso))
+ return {'nome': nome, 'descrizione': campo('description')[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16]}
+
+def _skill_in(cartella):
+ if not os.path.isdir(cartella):
+ return []
+ out = []
+ for n in sorted(os.listdir(cartella)):
+ p = os.path.join(cartella, n, 'SKILL.md')
+ if not n.startswith('.') and os.path.isfile(p):
+ t = _skill_testa(p)
+ if t:
+ out.append((t, p))
+ return out
+
+def _da_leggere(p, radice):
+ casa = os.path.expanduser('~')
+ if radice and p.startswith(radice + os.sep):
+ return os.path.relpath(os.path.dirname(p), radice)
+ if p.startswith(casa + os.sep):
+ return '~/' + os.path.relpath(os.path.dirname(p), casa)
+ return os.path.dirname(p)
+
+def _case_codex():
+ base = os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'codex')
+ return sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else []) if os.path.isfile(os.path.join(base, n, 'config.toml'))))
+
+def _blocchi_codex(testo):
+ out = {}
+ for b in re.split('(?m)^\\[\\[skills\\.config\\]\\]\\s*$', testo)[1:]:
+ corpo = re.split('(?m)^\\[', b, maxsplit=1)[0]
+ p = re.search('(?m)^path\\s*=\\s*"((?:[^"\\\\]|\\\\.)*)"', corpo)
+ e = re.search('(?m)^enabled\\s*=\\s*(true|false)', corpo)
+ if p:
+ out[json.loads('"' + p.group(1) + '"')] = not (e and e.group(1) == 'false')
+ return out
+
+def _claude_scelte(radice):
+ out = {}
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ for f in (os.path.join(cfg, 'settings.json'), os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')):
+ s = _leggi(f)
+ if isinstance(s.get('skillOverrides'), dict):
+ out.update(s['skillOverrides'])
+ return out
+_STATO_CLAUDE = {'on': 'accesa', 'name-only': 'accesa', 'user-invocable-only': 'a_mano', 'off': 'spenta'}
+
+def _qwen_stato(nome, livello, scelte):
+ voluta = scelte.get(('qwen', nome))
+ if voluta:
+ return 'accesa' if voluta == 'accesa' else 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano'
+ if livello != 'di_serie':
+ return 'accesa'
+ return 'spenta' if nome in QWEN_SKILL_SPENTE else 'a_mano' if nome in QWEN_SKILL_A_SCELTA else 'accesa'
+
+def _progetto(radice):
+ remoto = ''
+ if radice:
+ try:
+ remoto = subprocess.run(['git', '-C', radice, 'config', '--get', 'remote.origin.url'], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ remoto = ''
+ return 'progetto:' + (re.sub('//[^/@]*@', '//', remoto) or os.path.basename(radice or ''))
+
+def raccogli_skill(radice, versioni_qwen, scelte=None):
+ scelte = scelte or {}
+ carte = []
+ progetto = _progetto(radice)
+ claude = _claude_scelte(radice) if radice else {}
+ case = _case_codex()
+ codex_blocchi = {}
+ for casa in case:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
+ codex_blocchi.update(_blocchi_codex(h.read()))
+
+ def stato(cli, nome, livello, percorsi):
+ out = {}
+ for c in cli:
+ if c == 'claude':
+ out[c] = _STATO_CLAUDE.get(claude.get(nome, 'on'), 'accesa')
+ elif c == 'codex':
+ out[c] = 'spenta' if any((codex_blocchi.get(p) is False for p in percorsi)) else 'accesa'
+ elif c == 'qwen':
+ out[c] = _qwen_stato(nome, livello, scelte)
+ return out
+
+ def metti(livello, dove, cartella, cli):
+ for t, p in _skill_in(cartella):
+ carte.append({**t, 'livello': livello, 'dove': dove, 'cartella': _da_leggere(p, radice), 'cli': list(cli), 'stato': stato(cli, t['nome'], livello, [p])})
+ if radice:
+ for rel, cli in _SKILL_PROGETTO:
+ metti('progetto', progetto, os.path.join(radice, rel), cli)
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ metti('personale', 'personale', os.path.join(cfg, 'skills'), ('claude',))
+ metti('personale', 'personale', os.path.expanduser('~/.agents/skills'), ('codex', 'qwen'))
+ metti('personale', 'personale', os.path.expanduser('~/.qwen/skills'), ('qwen',))
+ viste = set()
+ for casa in case:
+ for t, p in _skill_in(os.path.join(casa, 'skills', '.system')):
+ if t['nome'] not in viste:
+ viste.add(t['nome'])
+ carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'codex', 'cli': ['codex'], 'stato': stato(('codex',), t['nome'], 'di_serie', [os.path.join(c, 'skills', '.system', t['nome'], 'SKILL.md') for c in case])})
+ metti('personale', 'personale', os.path.join(casa, 'skills'), ('codex',))
+ qv = sorted((v for v in (os.listdir(versioni_qwen) if os.path.isdir(versioni_qwen) else []) if _VERSIONE.match(v)), key=lambda v: tuple((int(x) for x in v.split('.'))))
+ if qv:
+ for t, _p in _skill_in(os.path.join(versioni_qwen, qv[-1], 'lib', 'node_modules', '@qwen-code', 'qwen-code', 'bundled')):
+ carte.append({**t, 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'qwen ' + qv[-1], 'cli': ['qwen'], 'stato': stato(('qwen',), t['nome'], 'di_serie', [])})
+ pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
+ if radice and os.path.isfile(pacchetto) and shutil.which(os.environ.get('DELMINIO_CLI') or 'claude'):
+ try:
+ di_claude = runpy.run_path(pacchetto).get('SKILL_CLAUDE') or {}
+ except Exception:
+ di_claude = {}
+ for nome in sorted(di_claude):
+ carte.append({'nome': nome, 'descrizione': '', 'impronta': '', 'livello': 'di_serie', 'dove': 'di_serie', 'cartella': 'claude', 'cli': ['claude'], 'stato': stato(('claude',), nome, 'di_serie', [])})
+ carte += raccogli_pezzi(radice, progetto)
+ return carte[:_SKILL_TETTO]
+_COMANDI = (('.claude/commands', 'claude'), ('.qwen/commands', 'qwen'))
+_AGENTI = (('.claude/agents', 'claude'), ('.qwen/agents', 'qwen'))
+_PEZZO_PESO = 100000
+_CHIAVE_FLAG = re.compile('^--?(?:[\\w-]*(?:token|key|secret|password|passwd|pass|auth|credential)[\\w-]*)$', re.I)
+_CHIAVE_VALORE = re.compile('(?:^(?:sk-|ghp_|gho_|ghs_|github_pat_|xox[abpr]-|glpat-|AKIA|AIza)\\S+)|(?:^(?=[^/.]*\\d)(?=[^/.]*[A-Za-z])[A-Za-z0-9_+=-]{24,}$)')
+NASCOSTO = '•••'
+
+def _testa_md(testo):
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
+ testa, corpo = (m.group(1), testo[m.end():]) if m else ('', testo)
+
+ def campo(nome):
+ c = re.search('^' + nome + ':[ \\t]*(.*(?:\\n[ \\t]+.*)*)', testa, re.M)
+ if not c:
+ return ''
+ v = ' '.join(c.group(1).split())
+ if v[:1] in '"\'' and v[-1:] == v[:1]:
+ v = v[1:-1]
+ return '' if v in ('>', '|', '>-', '|-') else v
+ return (campo, corpo)
+
+def _prima_riga(corpo):
+ for r in corpo.splitlines():
+ r = r.strip().lstrip('#').strip()
+ if r:
+ return r[:200]
+ return ''
+
+def _toml_stringa(testo, chiave):
+ m = re.search('(?m)^' + re.escape(chiave) + '\\s*=\\s*("""(.*?)"""|\\\'\\\'\\\'(.*?)\\\'\\\'\\\'|"((?:[^"\\\\\\n]|\\\\.)*)"|\\\'([^\\\'\\n]*)\\\')', testo, re.S)
+ if not m:
+ return ''
+ if m.group(4) is not None:
+ try:
+ return json.loads('"' + m.group(4) + '"')
+ except ValueError:
+ return m.group(4)
+ return next((g for g in (m.group(2), m.group(3), m.group(5)) if g is not None))
+
+def _scheda_file(p, rel_nome, cli, tipo):
+ try:
+ with open(p, 'rb') as h:
+ crudo = h.read(_PEZZO_PESO + 1)
+ except OSError:
+ return None
+ testo = crudo.decode('utf-8', errors='replace')
+ if p.endswith('.toml'):
+ descrizione, nome = (_toml_stringa(testo, 'description'), rel_nome)
+ else:
+ campo, corpo = _testa_md(testo)
+ nome = (campo('name') if tipo == 'agente' else '') or rel_nome
+ descrizione = campo('description') or (_prima_riga(corpo) if tipo == 'comando' else '')
+ return {'nome': nome, 'descrizione': descrizione[:600], 'impronta': hashlib.sha256(crudo).hexdigest()[:16], 'tipo': tipo, 'cli': [cli], 'stato': {}}
+
+def _file_in(cartella, estensioni, ricorsivo):
+ if not os.path.isdir(cartella):
+ return []
+ out = []
+ for base, cartelle, nomi in os.walk(cartella):
+ cartelle[:] = sorted((c for c in cartelle if not c.startswith('.'))) if ricorsivo else []
+ for n in sorted(nomi):
+ p = os.path.join(base, n)
+ if n.startswith('.') or not n.endswith(estensioni) or (not os.path.isfile(p)):
+ continue
+ rel = os.path.relpath(p, cartella)
+ out.append((p, os.path.splitext(rel)[0].replace(os.sep, ':')))
+ return out
+
+def _cartella_da_leggere(p, radice):
+ casa = os.path.expanduser('~')
+ if radice and p.startswith(radice + os.sep):
+ return os.path.relpath(p, radice)
+ if p.startswith(casa + os.sep):
+ return '~/' + os.path.relpath(p, casa)
+ return p
+
+def _argomenti_puliti(argomenti):
+ out, dopo_flag = ([], False)
+ for a in argomenti or []:
+ a = str(a)
+ if '=' in a and _CHIAVE_FLAG.match(a.split('=', 1)[0]):
+ out.append(a.split('=', 1)[0] + '=' + NASCOSTO)
+ elif dopo_flag or _CHIAVE_VALORE.search(a) or '${' in a:
+ out.append(NASCOSTO)
+ else:
+ out.append(a[:500])
+ dopo_flag = bool(_CHIAVE_FLAG.match(a)) and '=' not in a
+ return out[:40]
+
+def _url_pulito(url):
+ try:
+ u = urllib.parse.urlsplit(str(url or ''))
+ except ValueError:
+ return ''
+ if u.scheme not in ('http', 'https') or not u.hostname:
+ return ''
+ host = u.netloc.rpartition('@')[2]
+ return urllib.parse.urlunsplit((u.scheme, host, u.path, '', ''))[:500]
+
+def _variabile_del_token(intestazioni):
+ for k, v in (intestazioni or {}).items():
+ m = re.fullmatch('(?:Bearer\\s+)?\\$\\{?([A-Za-z_][A-Za-z0-9_]{0,63})\\}?', str(v or '').strip())
+ if str(k).lower() == 'authorization' and m:
+ return m.group(1)
+ return ''
+
+def _server(nome, d, cli, livello, dove, cartella):
+ if not isinstance(d, dict):
+ return None
+ url = d.get('url') or d.get('httpUrl') or ''
+ intest = {}
+ for k in ('headers', 'http_headers', 'env_http_headers'):
+ if isinstance(d.get(k), dict):
+ intest.update(d[k])
+ if url:
+ token = str(d.get('bearer_token_env_var') or '') or _variabile_del_token(intest)
+ mcp = {'tipo': 'remoto', 'url': _url_pulito(url), 'intestazioni': sorted((str(k) for k in intest))[:20]}
+ if token:
+ mcp['token_variabile'] = token
+ elif d.get('command'):
+ variabili = set(d['env']) if isinstance(d.get('env'), dict) else set()
+ variabili |= {str(v) for v in d.get('env_vars') or [] if isinstance(v, str)}
+ mcp = {'tipo': 'locale', 'comando': str(d['command'])[:300], 'argomenti': _argomenti_puliti(d.get('args') if isinstance(d.get('args'), list) else []), 'variabili': sorted(variabili)[:20]}
+ else:
+ return None
+ return {'nome': str(nome), 'descrizione': str(d.get('description') or '')[:600], 'impronta': '', 'tipo': 'mcp', 'cli': [cli], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': cartella, 'mcp': mcp}
+
+def _toml_tabelle(testo, radice_tabella):
+ try:
+ import tomllib
+ d = tomllib.loads(testo).get(radice_tabella)
+ return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}
+ except ImportError:
+ pass
+ except ValueError:
+ return {}
+ out = {}
+ for m in re.finditer('(?m)^\\[' + re.escape(radice_tabella) + '\\.("[^"\\n]+"|[A-Za-z0-9_-]+)(\\.[A-Za-z_]+)?\\]\\s*$', testo):
+ nome = m.group(1).strip('"')
+ corpo = re.split('(?m)^\\[', testo[m.end():], maxsplit=1)[0]
+ campi = out.setdefault(nome, {})
+ if m.group(2):
+ campi[m.group(2)[1:]] = {k.strip('"'): '' for k in re.findall('(?m)^("[^"\\n]+"|[A-Za-z0-9_-]+)\\s*=', corpo)}
+ continue
+ for chiave, valore in re.findall('(?m)^([A-Za-z_]+)\\s*=\\s*(.+?)\\s*$', corpo):
+ if valore.startswith('{'):
+ campi[chiave] = {k.strip('"'): '' for k in re.findall('("[^"]+"|[A-Za-z0-9_-]+)\\s*=', valore)}
+ else:
+ try:
+ campi[chiave] = json.loads(valore)
+ except ValueError:
+ campi[chiave] = valore.strip("'")
+ return out
+
+def _codex_config(radice):
+ out = []
+ if radice:
+ out.append((os.path.join(radice, '.codex', 'config.toml'), 'progetto'))
+ casa = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
+ out.append((os.path.join(casa, 'config.toml'), 'personale'))
+ out += [(os.path.join(c, 'config.toml'), 'personale') for c in _case_codex()]
+ return [(p, l) for p, l in out if os.path.isfile(p)]
+
+def raccogli_pezzi(radice, progetto):
+ carte = []
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ casa_qwen = os.path.expanduser('~/.qwen')
+
+ def file_di(tipo, coppie_progetto, personali, estensioni, ricorsivo):
+ dove_cli = [(os.path.join(radice, rel), cli, 'progetto', progetto) for rel, cli in coppie_progetto] if radice else []
+ dove_cli += [(c, cli, 'personale', 'personale') for c, cli in personali]
+ for cartella, cli, livello, dove in dove_cli:
+ for p, rel_nome in _file_in(cartella, estensioni(cli), ricorsivo):
+ if (s := _scheda_file(p, rel_nome, cli, tipo)):
+ carte.append({**s, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(p, radice)})
+ file_di('comando', _COMANDI, [(os.path.join(cfg, 'commands'), 'claude'), (os.path.join(casa_qwen, 'commands'), 'qwen')], lambda cli: ('.md', '.toml') if cli == 'qwen' else ('.md',), True)
+ file_di('agente', _AGENTI, [(os.path.join(cfg, 'agents'), 'claude'), (os.path.join(casa_qwen, 'agents'), 'qwen')], lambda cli: ('.md',), False)
+
+ def server_json(percorso, chiavi, cli, livello, dove):
+ d = _leggi(percorso)
+ for k in chiavi:
+ d = d.get(k) if isinstance(d, dict) else None
+ for nome, s in (d or {}).items() if isinstance(d, dict) else []:
+ if (x := _server(nome, s, cli, livello, dove, _cartella_da_leggere(percorso, radice))):
+ carte.append(x)
+ stato_claude = os.path.join(os.environ['CLAUDE_CONFIG_DIR'], '.claude.json') if os.environ.get('CLAUDE_CONFIG_DIR') else os.path.expanduser('~/.claude.json')
+ if radice:
+ server_json(os.path.join(radice, '.mcp.json'), ['mcpServers'], 'claude', 'progetto', progetto)
+ server_json(os.path.join(radice, '.qwen', 'settings.json'), ['mcpServers'], 'qwen', 'progetto', progetto)
+ server_json(stato_claude, ['projects', radice, 'mcpServers'], 'claude', 'personale', 'personale')
+ server_json(stato_claude, ['mcpServers'], 'claude', 'personale', 'personale')
+ server_json(os.path.join(casa_qwen, 'settings.json'), ['mcpServers'], 'qwen', 'personale', 'personale')
+ visti = set()
+ for percorso, livello in _codex_config(radice):
+ try:
+ with open(percorso, encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ except OSError:
+ continue
+ dove = progetto if livello == 'progetto' else 'personale'
+ for nome, s in _toml_tabelle(testo, 'mcp_servers').items():
+ if (livello, 'mcp', nome) not in visti and (x := _server(nome, s, 'codex', livello, dove, _cartella_da_leggere(percorso, radice))):
+ visti.add((livello, 'mcp', nome))
+ carte.append(x)
+ for nome, s in _toml_tabelle(testo, 'agents').items():
+ if (livello, 'agente', nome) not in visti:
+ visti.add((livello, 'agente', nome))
+ carte.append({'nome': nome, 'descrizione': str(s.get('description') or '')[:600], 'impronta': '', 'tipo': 'agente', 'cli': ['codex'], 'stato': {}, 'livello': livello, 'dove': dove, 'cartella': _cartella_da_leggere(percorso, radice)})
+ return carte
+
+def applica_skill(radice, scelte, fatte):
+ ora = {f'{c}:{n}': v for (c, n), v in scelte.items()}
+ via = [k for k in fatte or [] if k not in ora]
+ pacchetto = os.path.join(radice or '', '.claude', 'plugin.py')
+ try:
+ p = runpy.run_path(pacchetto) if os.path.isfile(pacchetto) else {}
+ except Exception:
+ p = {}
+ di_serie_claude, spente_codex = (p.get('SKILL_CLAUDE') or {}, set(p.get('SKILL_CODEX_SPENTE') or ()))
+ locale = os.path.join(radice or '', '.claude', 'settings.local.json')
+ if radice and os.path.isfile(locale):
+ s = _leggi(locale)
+ so = s.get('skillOverrides') if isinstance(s.get('skillOverrides'), dict) else {}
+ prima = dict(so)
+ for k, v in ora.items():
+ c, n = k.split(':', 1)
+ if c == 'claude':
+ so[n] = 'on' if v == 'accesa' else 'user-invocable-only'
+ for k in via:
+ c, n = k.split(':', 1)
+ if c == 'claude':
+ if n in di_serie_claude:
+ so[n] = di_serie_claude[n]
+ else:
+ so.pop(n, None)
+ if so != prima:
+ s['skillOverrides'] = so
+ if not so:
+ s.pop('skillOverrides', None)
+ _scrivi_se_cambia(locale, json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ for casa in _case_codex():
+ conf = os.path.join(casa, 'config.toml')
+ with open(conf, encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ nuovo = testo
+
+ def percorsi(n):
+ out = [os.path.join(casa, 'skills', '.system', n, 'SKILL.md'), os.path.join(casa, 'skills', n, 'SKILL.md'), os.path.expanduser(os.path.join('~/.agents/skills', n, 'SKILL.md'))]
+ if radice:
+ out.append(os.path.join(radice, '.agents', 'skills', n, 'SKILL.md'))
+ return [x for x in out if os.path.isfile(x)]
+
+ def blocco(t, percorso, acceso):
+ chiave = json.dumps(percorso)
+ schema = '(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(chiave) + '\\s*\\nenabled\\s*=\\s*(true|false)\\s*\\n?'
+ riga = f"[[skills.config]]\npath = {chiave}\nenabled = {('true' if acceso else 'false')}\n"
+ if acceso is None:
+ return re.sub(schema, '', t)
+ if re.search(schema, t):
+ return re.sub(schema, riga.replace('\\', '\\\\'), t)
+ return t.rstrip('\n') + '\n\n' + riga
+ for k, v in ora.items():
+ c, n = k.split(':', 1)
+ if c == 'codex':
+ for pp in percorsi(n):
+ nuovo = blocco(nuovo, pp, v == 'accesa')
+ for k in via:
+ c, n = k.split(':', 1)
+ if c == 'codex':
+ for pp in percorsi(n):
+ di_serie = '/skills/.system/' in pp.replace(os.sep, '/')
+ nuovo = blocco(nuovo, pp, False if n in spente_codex and di_serie else None)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.replace(conf + '.nuovo', conf)
+ return sorted(ora)
+_PORTO_FILE, _PORTO_PESO = (30, 512000)
+
+def _cartelle_di_skill(radice):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ out = [os.path.join(cfg, 'skills'), os.path.expanduser('~/.agents/skills'), os.path.expanduser('~/.qwen/skills')]
+ out += [os.path.join(c, 'skills') for c in _case_codex()]
+ if radice:
+ out += [os.path.join(radice, rel) for rel, _cli in _SKILL_PROGETTO]
+ return {os.path.realpath(x) for x in out}
+
+def _file_da_portare(radice, cartella):
+ if cartella.startswith('~/'):
+ d = os.path.expanduser(cartella)
+ elif os.path.isabs(cartella):
+ d = cartella
+ else:
+ d = os.path.join(radice or '', cartella)
+ vero = os.path.realpath(d)
+ if os.path.islink(d) or os.path.dirname(vero) not in _cartelle_di_skill(radice) or (not os.path.isfile(os.path.join(vero, 'SKILL.md'))):
+ return (None, F('porto_non_qui', cartella=cartella))
+ file, peso = ({}, 0)
+ for base, cartelle, nomi in os.walk(vero):
+ cartelle[:] = sorted((c for c in cartelle if not c.startswith('.') and (not os.path.islink(os.path.join(base, c)))))
+ for n in sorted(nomi):
+ p = os.path.join(base, n)
+ if n.startswith('.') or os.path.islink(p):
+ continue
+ try:
+ with open(p, 'rb') as h:
+ crudo = h.read(_PORTO_PESO + 1)
+ testo = crudo.decode('utf-8')
+ except (OSError, UnicodeDecodeError):
+ continue
+ peso += len(crudo)
+ if len(file) >= _PORTO_FILE or peso > _PORTO_PESO:
+ return (None, F('porto_troppo', cartella=cartella, file=_PORTO_FILE, peso=_PORTO_PESO))
+ file[os.path.relpath(p, vero).replace(os.sep, '/')] = testo
+ return (file, '')
+
+def _cartelle_di_pezzi(radice):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ out = [os.path.join(cfg, 'commands'), os.path.join(cfg, 'agents'), os.path.expanduser('~/.qwen/commands'), os.path.expanduser('~/.qwen/agents')]
+ if radice:
+ out += [os.path.join(radice, rel) for rel, _cli in _COMANDI + _AGENTI]
+ return [os.path.realpath(x) for x in out]
+
+def _pezzo_da_portare(radice, cartella):
+ if cartella.startswith('~/'):
+ p = os.path.expanduser(cartella)
+ elif os.path.isabs(cartella):
+ p = cartella
+ else:
+ p = os.path.join(radice or '', cartella)
+ vero = os.path.realpath(p)
+ dentro = any((vero.startswith(c + os.sep) for c in _cartelle_di_pezzi(radice)))
+ if os.path.islink(p) or not dentro or (not os.path.isfile(vero)) or (not vero.endswith(('.md', '.toml'))):
+ return (None, F('porto_non_qui', cartella=cartella))
+ try:
+ with open(vero, 'rb') as h:
+ crudo = h.read(_PEZZO_PESO + 1)
+ testo = crudo.decode('utf-8')
+ except (OSError, UnicodeDecodeError):
+ return (None, F('porto_non_qui', cartella=cartella))
+ if len(crudo) > _PEZZO_PESO:
+ return (None, F('porto_troppo', cartella=cartella, file=1, peso=_PEZZO_PESO))
+ return ({os.path.basename(vero): testo}, '')
+
+def _squadra(a, token, url, radice, impronta):
+ pacchetto = os.path.join(radice or '', '.claude', 'squadra.py')
+ if not radice or not os.path.isfile(pacchetto):
+ return ''
+ try:
+ p = runpy.run_path(pacchetto)
+ except Exception:
+ return ''
+ if 'squadra_scrivi' not in p:
+ return ''
+ chiave = hashlib.sha256(url.encode()).hexdigest()[:12]
+ if impronta != (p['squadra_di'](chiave) or {}).get('impronta', ''):
+ if impronta:
+ try:
+ pacco = json.loads(_get(a.url.rstrip('/') + '/api/skill/squadra', token, timeout=30) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ return F('squadra_muta', errore=e)
+ else:
+ pacco = {}
+ if isinstance(pacco, dict):
+ p['squadra_scrivi'](chiave, pacco)
+ p['squadra_claude'](radice, chiave)
+ if 'squadra_plugin_claude' in p:
+ try:
+ p['squadra_plugin_claude'](radice, chiave)
+ except (OSError, subprocess.SubprocessError):
+ pass
+ sq = p['squadra_di'](chiave)
+ if not sq:
+ return ''
+ c = sq['ruoli'].get('conto') or {}
+ detto = F('squadra_qui', skill=c.get('skill', 0), comandi=c.get('comando', 0), agenti=c.get('agente', 0), mcp=c.get('mcp', 0), plugin=sq['plugin'])
+ try:
+ with open(os.path.join(sq['cartella'], '.plugin.json'), encoding='utf-8') as h:
+ plugin_sq = [x for x in json.load(h) if isinstance(x, dict)]
+ except (OSError, ValueError, TypeError):
+ plugin_sq = []
+ if plugin_sq:
+ fermi = sum((1 for x in plugin_sq if not x.get('accettato')))
+ detto += '\n' + F('squadra_plugin_qui', accettati=len(plugin_sq) - fermi, fermi=fermi)
+ return detto
+
+def gesto_skill(a, url, sp, registro, mio):
+ try:
+ radice = subprocess.run(['git', 'rev-parse', '--show-toplevel'], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ radice = ''
+ try:
+ token = open(os.path.expanduser(a.token_file)).read().strip()
+ except OSError as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ base = a.url.rstrip('/') + '/api/skill/macchina'
+ scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in sp.get('skill_scelte') or [] if isinstance(x, dict)}
+ carte = raccogli_skill(radice, os.path.expanduser(a.versioni_qwen), scelte)
+ try:
+ r = json.loads(_get(base, token, metodo='POST', timeout=20, corpo={'host': socket.gethostname(), 'skill': carte, 'plugin': raccogli_plugin(radice, _progetto(radice)), 'ganci': raccogli_ganci(radice, _progetto(radice))}) or b'{}')
+ except (OSError, ValueError, urllib.error.URLError) as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ nuove = r.get('scelte') if isinstance(r.get('scelte'), list) else []
+ scelte = {(x.get('cli'), x.get('nome')): x.get('stato') for x in nuove if isinstance(x, dict) and x.get('stato') in ('accesa', 'spenta') and _NOME_OK.fullmatch(str(x.get('nome') or ''))}
+ chiave = 'skill_applicate:' + (radice or '')
+ sp[chiave] = applica_skill(radice, scelte, sp.get(chiave) or [])
+ sp['skill_scelte'] = [{'cli': c, 'nome': n, 'stato': v} for (c, n), v in sorted(scelte.items())]
+ _scrivi(registro, mio)
+ print(F('skill_riferite', n=len(carte), scelte=len(scelte)))
+ for x in r.get('porta') if isinstance(r.get('porta'), list) else []:
+ cartella = str((x or {}).get('cartella') or '') if isinstance(x, dict) else ''
+ if not cartella:
+ continue
+ file, errore = _pezzo_da_portare(radice, cartella) if x.get('tipo') in ('comando', 'agente') else _file_da_portare(radice, cartella)
+ try:
+ e = json.loads(_get(a.url.rstrip('/') + '/api/skill/porto', token, metodo='POST', timeout=30, corpo={'cartella': cartella, **({'file': file} if file else {'errore': errore})}) or b'{}')
+ print(F('porto_fatto', nome=e.get('nome') or x.get('nome') or '') if e.get('entrata') else F('porto_no', cartella=cartella, errore=e.get('errore') or errore))
+ except (OSError, ValueError, urllib.error.URLError) as err:
+ print(F('registro_muto', url=a.url, errore=err), file=sys.stderr)
+ detto = _squadra(a, token, url, radice, str(r.get('squadra') or ''))
+ if detto:
+ print(detto)
+ return 0
+_PLUGIN_TETTO = 200
+
+def _origine_plugin(fonte):
+ if not isinstance(fonte, dict):
+ return ''
+ tipo = str(fonte.get('source') or fonte.get('source_type') or fonte.get('type') or '')
+ if tipo == 'github' and re.fullmatch('[\\w.-]+/[\\w.-]+', str(fonte.get('repo') or '')):
+ return 'github:' + str(fonte['repo'])
+ valore = str(fonte.get('url') or fonte.get('path') or fonte.get('source') or '')
+ if re.match('(?i)(https?|ssh|git)://', valore):
+ try:
+ u = urllib.parse.urlsplit(valore)
+ except ValueError:
+ return ''
+ return urllib.parse.urlunsplit((u.scheme, u.netloc.rpartition('@')[2], u.path, '', ''))[:300]
+ if re.fullmatch('[\\w.-]+@[\\w.-]+:[\\w./-]+', valore):
+ return valore.partition('@')[2][:300]
+ if valore.startswith(('/', '~')):
+ return 'cartella:' + _cartella_da_leggere(os.path.expanduser(valore), '')
+ return ''
+
+def _di_delminio(mercato, nome=''):
+ return mercato == 'delminio' or mercato.startswith('delminio-squadra-') or (not mercato and nome == 'delminio')
+
+def _carta_plugin(cli, nome, mercato, *, versione='', acceso=None, livello='personale', dove='personale', origine='', cartella=''):
+ return {'tipo': 'plugin', 'cli': cli, 'nome': nome, 'mercato': mercato, 'versione': str(versione or '')[:40], 'stato': '' if acceso is None else 'acceso' if acceso else 'spento', 'livello': livello, 'dove': dove, 'origine': origine, 'cartella': cartella, 'di_delminio': _di_delminio(mercato, nome)}
+
+def _plugin_claude(radice, progetto, carte):
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ acceso = {}
+ impostazioni = [os.path.join(cfg, 'settings.json')]
+ if radice:
+ impostazioni += [os.path.join(radice, '.claude', 'settings.json'), os.path.join(radice, '.claude', 'settings.local.json')]
+ for p in impostazioni:
+ d = _leggi(p).get('enabledPlugins')
+ for k, v in d.items() if isinstance(d, dict) else []:
+ acceso[k] = v is True
+ installati = _leggi(os.path.join(cfg, 'plugins', 'installed_plugins.json')).get('plugins')
+ for pid, voci in installati.items() if isinstance(installati, dict) else []:
+ nome, _, mercato = str(pid).partition('@')
+ for v in voci if isinstance(voci, list) else []:
+ if not isinstance(v, dict):
+ continue
+ if v.get('scope') == 'user':
+ livello, dove = ('personale', 'personale')
+ elif v.get('scope') in ('project', 'local') and radice and (v.get('projectPath') == radice):
+ livello, dove = ('progetto', progetto)
+ else:
+ continue
+ carte.append(_carta_plugin('claude', nome, mercato, versione=v.get('version'), acceso=acceso.get(pid, False), livello=livello, dove=dove))
+ mercati = _leggi(os.path.join(cfg, 'plugins', 'known_marketplaces.json'))
+ for nome, m in mercati.items() if isinstance(mercati, dict) else []:
+ if isinstance(m, dict):
+ carte.append({'tipo': 'marketplace', 'cli': 'claude', 'nome': nome, 'origine': _origine_plugin(m.get('source')), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
+
+def _plugin_codex(carte):
+ casa_persona = os.environ.get('CODEX_HOME') or os.path.expanduser('~/.codex')
+ for casa in dict.fromkeys([casa_persona] + _case_codex()):
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8', errors='replace') as h:
+ testo = h.read()
+ except OSError:
+ continue
+ cartella = _cartella_da_leggere(casa, '')
+ for pid, campi in _toml_tabelle(testo, 'plugins').items():
+ nome, _, mercato = pid.partition('@')
+ cache = os.path.join(casa, 'plugins', 'cache', mercato, nome)
+ versioni = sorted(os.listdir(cache)) if mercato and os.path.isdir(cache) else []
+ carte.append(_carta_plugin('codex', nome, mercato, versione=versioni[-1] if versioni else '', acceso=campi.get('enabled') is not False, cartella=cartella))
+ for nome, campi in _toml_tabelle(testo, 'marketplaces').items():
+ carte.append({'tipo': 'marketplace', 'cli': 'codex', 'nome': nome, 'cartella': cartella, 'origine': _origine_plugin({'source_type': campi.get('source_type'), 'path': campi.get('source')} if campi.get('source_type') == 'local' else {'url': campi.get('source')}), 'livello': 'personale', 'dove': 'personale', 'di_delminio': _di_delminio(nome)})
+
+def _qwen_acceso(regole, qui):
+ acceso = True
+ for r in regole if isinstance(regole, list) else []:
+ r = str(r)
+ base = r.lstrip('!').rstrip('*').rstrip('/')
+ if not base or qui == base or qui.startswith(base + '/'):
+ acceso = not r.startswith('!')
+ return acceso
+
+def _plugin_qwen(radice, carte):
+ dati = os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share')
+ base = os.path.join(dati, 'delminio', 'qwen')
+ case = [os.path.expanduser('~/.qwen')] + sorted((os.path.join(base, n) for n in (os.listdir(base) if os.path.isdir(base) else [])))
+ qui = radice or os.path.expanduser('~')
+ for casa in case:
+ cartella_ext = os.path.join(casa, 'extensions')
+ if not os.path.isdir(cartella_ext):
+ continue
+ regole = _leggi(os.path.join(cartella_ext, 'extension-enablement.json'))
+ for nome in sorted(os.listdir(cartella_ext)):
+ d = os.path.join(cartella_ext, nome)
+ if not os.path.isdir(d):
+ continue
+ inst = _leggi(os.path.join(d, '.qwen-extension-install.json'))
+ sorgente = str(inst.get('source') or '')
+ manifesto = _leggi(os.path.join(d, 'qwen-extension.json')) or (_leggi(os.path.join(sorgente, 'qwen-extension.json')) if inst.get('type') == 'link' else {})
+ nome_vero = str(manifesto.get('name') or inst.get('pluginName') or nome)
+ origine = _origine_plugin({'path': sorgente} if inst.get('type') in ('link', 'local') else {'url': sorgente})
+ mercato = str((inst.get('marketplaceConfig') or {}).get('name') or '') if inst.get('pluginName') else ''
+ carta = _carta_plugin('qwen', nome_vero, mercato, versione=manifesto.get('version'), origine=origine, acceso=_qwen_acceso((regole.get(nome_vero) or {}).get('overrides'), qui), cartella=_cartella_da_leggere(casa, ''))
+ carta['di_delminio'] = nome_vero == 'delminio' or '/delminio/plugin/' in sorgente or '/delminio/squadre/' in sorgente
+ carte.append(carta)
+
+def _plugin_opencode(radice, progetto, carte):
+ casa = os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'opencode')
+ posti = [(casa, 'personale', 'personale')] + ([(radice, 'progetto', progetto)] if radice else [])
+ for cartella, livello, dove in posti:
+ sotto = os.path.join(cartella, 'plugins' if cartella == casa else os.path.join('.opencode', 'plugins'))
+ for f in sorted(os.listdir(sotto)) if os.path.isdir(sotto) else []:
+ nome, est = os.path.splitext(f)
+ if est in ('.js', '.ts', '.mjs') and os.path.isfile(os.path.join(sotto, f)):
+ carta = _carta_plugin('opencode', nome, '', acceso=True, livello=livello, dove=dove, origine='file', cartella=_cartella_da_leggere(sotto, radice))
+ carta['di_delminio'] = nome == 'delminio'
+ carte.append(carta)
+ for nome_conf in ('opencode.json', 'opencode.jsonc'):
+ conf = _leggi(os.path.join(cartella, nome_conf))
+ for pacchetto in conf.get('plugin') if isinstance(conf.get('plugin'), list) else []:
+ m = re.fullmatch('(@?[\\w.-]+(?:/[\\w.-]+)?)(?:@([\\w.^~<>=-]+))?', str(pacchetto))
+ if m:
+ carte.append(_carta_plugin('opencode', m.group(1), '', versione=m.group(2) or '', acceso=True, livello=livello, dove=dove, origine='npm:' + m.group(1)))
+
+def raccogli_plugin(radice, progetto):
+ carte = []
+ for leggi in (lambda: _plugin_claude(radice, progetto, carte), lambda: _plugin_codex(carte), lambda: _plugin_qwen(radice, carte), lambda: _plugin_opencode(radice, progetto, carte)):
+ try:
+ leggi()
+ except (OSError, ValueError, TypeError, AttributeError):
+ continue
+ return carte[:_PLUGIN_TETTO]
+_GANCI_MOMENTI = (('apertura', 'apertura'), ('opening', 'apertura'), ('dove-siamo', 'dove-siamo'), ('status', 'dove-siamo'))
+
+def _ganci_git(radice, *argomenti):
+ try:
+ return subprocess.run(['git', '-C', radice, *argomenti], capture_output=True, text=True, timeout=5).stdout.strip()
+ except (OSError, subprocess.SubprocessError):
+ return ''
+
+def _ganci_accettate(radice):
+ f = os.path.join(_ganci_git(radice, 'rev-parse', '--path-format=absolute', '--git-common-dir'), 'delminio-guardie-accettate')
+ try:
+ with open(f, encoding='utf-8') as h:
+ return sorted({x for x in h.read().split() if re.fullmatch('[0-9a-f]{64}', x)})[:500]
+ except OSError:
+ return []
+
+def _ganci_script(radice):
+ codice = os.environ.get('DELMINIO_FIDATI_PY') or ''
+ if not codice:
+ return []
+ fidati = {}
+ try:
+ exec(codice, fidati)
+ except Exception:
+ return []
+ gia = fidati['accettati'](radice)
+ voci = [(f, momento) for cartella, momento in _GANCI_MOMENTI for f in fidati['script_del_progetto'](radice, (cartella,))]
+ voci += [(f, 'lascito') for f in fidati['lascito_del_progetto'](radice)]
+ out = []
+ for f, momento in voci[:50]:
+ altro = fidati['di_chi'](radice, f)
+ out.append({'percorso': os.path.relpath(f, radice), 'momento': momento, 'gira': fidati['da_fidarsi'](radice, f, gia), 'di': altro[0] if altro else '', 'quando': altro[1] if altro else ''})
+ return out
+
+def raccogli_ganci(radice, progetto):
+ if not radice:
+ return {}
+ return {'dove': progetto, 'accettate': _ganci_accettate(radice), 'script': _ganci_script(radice)}
+PROVA_CONTESTO_MIN = 32768
+PROVA_CONTESTO_COMODO = 65536
+_PROVA_STRUMENTO = {'nome': 'conta_lettere', 'descrizione': F('prova_strumento'), 'parametri': {'type': 'object', 'properties': {'parola': {'type': 'string'}}, 'required': ['parola']}}
+_PROVA_CHIEDI = F('prova_chiedi')
+_PROVA_PREFISSO = ' '.join((F('prova_regola', i=i) for i in range(330)))
+
+def _prova_post(url, intestazioni, corpo, timeout=90):
+ req = urllib.request.Request(url, data=json.dumps(corpo).encode(), method='POST', headers={'Content-Type': 'application/json', **intestazioni})
+ with urllib.request.urlopen(req, timeout=timeout) as r:
+ return json.loads(r.read())
+
+def _prova_cache_letta(formato, risposta):
+ u = risposta.get('usage') or {}
+ if formato == 'anthropic':
+ letti = u.get('cache_read_input_tokens')
+ totale = (u.get('input_tokens') or 0) + (letti or 0) + (u.get('cache_creation_input_tokens') or 0)
+ return (letti, totale)
+ totale = u.get('prompt_tokens') or 0
+ for chi in ((u.get('prompt_tokens_details') or {}).get('cached_tokens'), u.get('prompt_cache_hit_tokens'), u.get('cached_tokens'), (risposta.get('timings') or {}).get('cache_n')):
+ if isinstance(chi, int):
+ return (chi, totale)
+ return (None, totale)
+
+def _prova_contesto(riga, formato, base, intestazioni, modello):
+ f = riga.get('fornitore') or {}
+ if f.get('contesto'):
+ return int(f['contesto'])
+ elenco = 'https://openrouter.ai/api/v1/models' if f.get('tipo') == 'openrouter' else base.rstrip('/') + '/models' if formato == 'openai' else ''
+ if not elenco:
+ return None
+ h = {} if f.get('tipo') == 'openrouter' else intestazioni
+ try:
+ with urllib.request.urlopen(urllib.request.Request(elenco, headers=h), timeout=30) as r:
+ dati = json.loads(r.read())
+ except (OSError, ValueError):
+ return None
+ for m in dati.get('data') or dati.get('models') or []:
+ if m.get('id') == modello or m.get('name') == modello:
+ for k in ('context_length', 'context_window', 'max_model_len', 'max_context_length'):
+ if isinstance(m.get(k), int):
+ return m[k]
+ meta = m.get('meta') or {}
+ if isinstance(meta.get('n_ctx_train'), int):
+ return meta['n_ctx_train']
+ return None
+
+def prova_qwen(riga, dal_motore=''):
+ imp = impostazioni_qwen(riga)
+ formato = imp['security']['auth']['selectedType']
+ p = imp['modelProviders'][formato][0]
+ modello, base, variabile = (p['id'], p.get('baseUrl') or '', p['envKey'])
+ tipo = (riga.get('fornitore') or {}).get('tipo')
+ chiave = dal_motore or os.environ.get(variabile) or ('nessuna' if tipo == 'casa' else '')
+ if not chiave:
+ raise RuntimeError(F('prova_senza_chiave', variabile=variabile))
+ marca = formato == 'anthropic' or 'dashscope' in base
+ if formato == 'anthropic':
+ url, intest = (base.rstrip('/') + '/v1/messages', {'x-api-key': chiave, 'anthropic-version': '2023-06-01'})
+
+ def corpo(sistema, testo, strumenti=False):
+ s = {'type': 'text', 'text': sistema, **({'cache_control': {'type': 'ephemeral'}} if marca else {})}
+ c = {'model': modello, 'max_tokens': 200, 'system': [s], 'messages': [{'role': 'user', 'content': testo}]}
+ if strumenti:
+ c['tools'] = [{'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'input_schema': _PROVA_STRUMENTO['parametri']}]
+ return c
+
+ def chiamato(r):
+ return any((b.get('type') == 'tool_use' and b.get('name') == _PROVA_STRUMENTO['nome'] and ('delminio' in json.dumps(b.get('input') or {}).lower()) for b in r.get('content') or []))
+ else:
+ url, intest = (base.rstrip('/') + '/chat/completions', {'Authorization': f'Bearer {chiave}'})
+
+ def corpo(sistema, testo, strumenti=False):
+ s = [{'type': 'text', 'text': sistema, 'cache_control': {'type': 'ephemeral'}}] if marca else sistema
+ c = {'model': modello, 'max_tokens': 200, 'messages': [{'role': 'system', 'content': s}, {'role': 'user', 'content': testo}]}
+ if strumenti:
+ c['tools'] = [{'type': 'function', 'function': {'name': _PROVA_STRUMENTO['nome'], 'description': _PROVA_STRUMENTO['descrizione'], 'parameters': _PROVA_STRUMENTO['parametri']}}]
+ return c
+
+ def chiamato(r):
+ for c in ((r.get('choices') or [{}])[0].get('message') or {}).get('tool_calls') or []:
+ fn = c.get('function') or {}
+ if fn.get('name') == _PROVA_STRUMENTO['nome'] and 'delminio' in str(fn.get('arguments') or '').lower():
+ return True
+ return False
+ note = []
+ try:
+ tool = chiamato(_prova_post(url, intest, corpo(F('prova_sistema'), _PROVA_CHIEDI, True)))
+ except urllib.error.HTTPError as e:
+ testo = e.read()[:200].decode(errors='replace')
+ if e.code in (401, 403):
+ raise RuntimeError(F('prova_chiave_rifiutata', codice=e.code, testo=testo)) from None
+ tool = False
+ note.append(F('prova_strumento_errore', codice=e.code))
+ letti = totale = None
+ for attesa in (0, 3, 8):
+ time.sleep(attesa)
+ r = _prova_post(url, intest, corpo(_PROVA_PREFISSO, F('prova_ok')))
+ letti, totale = _prova_cache_letta(formato, r)
+ if attesa and (letti is None or letti > 0):
+ break
+ contesto = _prova_contesto(riga, formato, base, intest, modello)
+ if not tool:
+ note.append(F('prova_senza_strumento'))
+ if contesto is not None and contesto < PROVA_CONTESTO_COMODO:
+ note.append(F('prova_contesto_stretto', contesto=contesto))
+ if letti is None:
+ note.append(F('prova_cache_muta'))
+ esito = 'non_va' if not tool or (contesto is not None and contesto < PROVA_CONTESTO_MIN) else 'va' if letti else 'senza_cache'
+ return {'esito': esito, 'tool': tool, 'cache': {'letti': letti, 'totale': totale}, 'contesto': contesto, 'nota': '; '.join(note)}
+
+def comando_prova(a, righe, dati, base, token):
+ riga = next((r for r in righe if a.nomi and r.get('nome') == a.nomi[0]), None)
+ if riga is None or riga.get('cli') != 'qwen':
+ print(F('uso_prova'), file=sys.stderr)
+ return 2
+ riga = {**riga, '_fornitori': dati.get('fornitori_qwen') or {}}
+ locale = (riga.get('fornitore') or {}).get('tipo') == 'casa'
+ print(F('prova_inizio_locale', nome=riga['nome'], modello=riga.get('modello')) if locale else F('prova_inizio_fornitore', nome=riga['nome'], modello=riga.get('modello')))
+ dal_motore = ''
+ if (scelta := (riga.get('fornitore') or {}).get('chiave')):
+ try:
+ dal_motore = _get(base + '/' + urllib.parse.quote(riga['nome']) + '/chiave', token).decode().strip()
+ except urllib.error.HTTPError as e:
+ print(F('prova_chiave_negata', scelta=scelta, errore=e.read()[:400].decode(errors='replace')), file=sys.stderr)
+ return 1
+ except (OSError, urllib.error.URLError) as e:
+ print(F('prova_chiave_negata', scelta=scelta, errore=e), file=sys.stderr)
+ return 1
+ try:
+ v = prova_qwen(riga, dal_motore)
+ except (RuntimeError, OSError, ValueError) as e:
+ print(F('prova_non_fatta', errore=e), file=sys.stderr)
+ return 1
+ c = v['cache']
+ print(F('prova_riga_strumenti', valore=F('prova_si') if v['tool'] else F('prova_no')))
+ print(F('prova_riga_cache', valore=F('prova_cache_non_detta') if c['letti'] is None else F('prova_cache_letti', letti=c['letti'], totale=c['totale'])))
+ print(F('prova_riga_contesto', valore=v['contesto'] or F('prova_non_lo_dice')))
+ print(F('prova_riga_verdetto', valore={'va': F('prova_va'), 'senza_cache': F('prova_senza_cache'), 'non_va': F('prova_non_va')}[v['esito']], nota=f" ({v['nota']})" if v['nota'] else ''))
+ try:
+ _get(base + '/' + urllib.parse.quote(riga['nome']) + '/prova', token, metodo='POST', corpo=v)
+ except (OSError, urllib.error.URLError) as e:
+ print(F('verdetto_perso', errore=e), file=sys.stderr)
+ return 1
+ return 0 if v['esito'] != 'non_va' else 1
+
+def comando_rinomina(a, righe, base, token):
+ if len(a.nomi) != 2:
+ print(F('uso_rinomina'), file=sys.stderr)
+ return 2
+ vecchio, nuovo = a.nomi
+ riga = next((r for r in righe if r['nome'] == vecchio), None)
+ if riga is None:
+ print(F('rinomina_assente', nome=vecchio), file=sys.stderr)
+ return 1
+ try:
+ _get(f'{base}/{urllib.parse.quote(vecchio)}/rinomina', token, metodo='POST', corpo={'nuovo': nuovo})
+ except urllib.error.HTTPError as e:
+ print(F('rinomina_rifiutata', errore=e.read().decode('utf-8', 'replace')[:300]), file=sys.stderr)
+ return 1
+ print(F('rinominato', vecchio=vecchio, nuovo=nuovo))
+ return 0
+
+def comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro):
+ for r in righe:
+ p = os.path.join(bin_dir, r['nome'])
+ try:
+ voluta = versione_voluta(r, canali)
+ except Exception as e:
+ voluta = f'? ({e})'
+ ora = _del_file(p)
+ stato = F('stato_assente') if ora is None else F('stato_cambiato') if impronte.get(p) not in (None, ora) else F('stato_non_suo') if impronte.get(p) is None else F('stato_intatto') if url in padroni.get(p, [url]) else F('stato_altro_spazio', spazi=', '.join(padroni[p]))
+ cli = os.path.join(os.path.expanduser(a.versioni_codex), voluta, 'bin', 'codex') if r.get('cli') == 'codex' else os.path.join(os.path.expanduser(a.versioni_qwen), voluta, 'bin', 'qwen') if r.get('cli') == 'qwen' else os.path.join(os.path.expanduser(a.versioni_opencode), voluta, 'bin', 'opencode') if r.get('cli') == 'opencode' else os.path.join(versioni, voluta)
+ print(F('stato_riga', nome=r['nome'], versione=voluta, da_scaricare='' if os.path.isfile(cli) or prova else F('da_scaricare'), modello=r.get('modello') or F('modello_di_serie'), porta=r.get('porta') or '—', stato=stato))
+ if sp.get('rifiutato'):
+ print(F('stato_rifiutato'))
+ if not righe:
+ print(F('registro_vuoto'))
+ r = riferisci(base, token, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'))
+ richiesta(base, token, r, righe, impronte, bin_dir, versioni, sp.get('registro', ''), sp.get('cli'), mio=mio, file_mio=registro)
+ return 0
+
+def comando_lascia(a, url, padroni, impronte, mio, registro):
+ tolti = 0
+ for p in [x for x, chi in padroni.items() if url in chi]:
+ if lascia_il_nome(p, url, padroni, impronte) == 'tolto':
+ tolti += 1
+ mio['spazi'].pop(url, None)
+ _scrivi(registro, mio)
+ comando = os.path.join(os.path.expanduser(a.bin), 'delminio')
+ if not mio['spazi'] and os.path.isfile(comando):
+ with open(comando, encoding='utf-8', errors='replace') as h:
+ if '# delminio-comando\n' in h.read():
+ os.remove(comando)
+ print(F('lasciati', n=tolti))
+ return 0
+
+def scrivi_il_primo(a, dati, righe, bin_dir, impronte):
+ cli_voluta = a.vuoi or 'claude'
+ catalogo = (dati.get('modelli') or {}).get(cli_voluta) or []
+ ordine = [m.get('id') for m in catalogo]
+ consigliati = {m.get('id') for m in catalogo if m.get('consigliato')}
+ candidati = sorted((r for r in righe if (r.get('cli') or 'claude') == cli_voluta and (not personaggio(r))), key=lambda r: (r.get('modello') not in consigliati, ordine.index(r.get('modello')) if r.get('modello') in ordine else len(ordine)))
+ primo = next((p for p in (os.path.join(bin_dir, r['nome']) for r in candidati) if impronte.get(p) and _del_file(p) == impronte[p]), '')
+ if not candidati:
+ print(F('nessun_agente_di', cli=CLI_NOMI.get(cli_voluta, cli_voluta)))
+ with open(a.primo, 'w', encoding='utf-8') as f:
+ f.write(primo)
+
+def main():
+ if sys.argv[1:2] == ['posta-ruolo']:
+ return posta_ruolo(sys.argv[2:])
+ if sys.argv[1:2] == ['casa']:
+ return casa(sys.argv[2:])
+ if sys.argv[1:2] == ['mie-qwen']:
+ return unisci_mie_qwen(sys.argv[2:])
+ if sys.argv[1:2] == ['mie-codex']:
+ return unisci_mie_codex(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia']:
+ return pulizia(sys.argv[2:])
+ if sys.argv[1:2] == ['errori-registra']:
+ return errori_registra(sys.argv[2:])
+ if sys.argv[1:2] == ['errori']:
+ return errori(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia-codex']:
+ return pulizia_codex(sys.argv[2:])
+ if sys.argv[1:2] == ['pulizia-opencode']:
+ return pulizia_opencode(sys.argv[2:])
+ if sys.argv[1:2] == ['installa-agente']:
+ return installa_agente(sys.argv[2:])
+ if sys.argv[1:2] == ['modello-gratuito']:
+ return modello_gratuito(sys.argv[2:])
+ if sys.argv[1:2] == ['accetta']:
+ return accetta(os.path.expanduser(os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json'))
+ ap = argparse.ArgumentParser(description=F('aiuto_descrizione'))
+ ap.add_argument('comando', nargs='?', default='allinea', choices=['allinea', 'stato', 'no', 'rinomina', 'lascia', 'spazio', 'prova', 'skill'])
+ ap.add_argument('nomi', nargs='*', help=F('aiuto_nomi'))
+ ap.add_argument('--url')
+ ap.add_argument('--token-file')
+ ap.add_argument('--da', help=F('aiuto_da'))
+ ap.add_argument('--modo', choices=['kit', 'casa'], default='kit')
+ ap.add_argument('--al-lancio', action='store_true', help=F('aiuto_al_lancio'))
+ ap.add_argument('--converti', action='store_true', help=F('aiuto_converti'))
+ ap.add_argument('--vuoi', choices=list(CLI_NOMI), help=F('aiuto_vuoi'))
+ ap.add_argument('--primo', help=F('aiuto_primo'))
+ ap.add_argument('--bin', default=os.environ.get('DELMINIO_BIN') or '~/.local/bin')
+ ap.add_argument('--versioni', default=os.environ.get('DELMINIO_VERSIONI') or '~/.local/share/claude/versions')
+ ap.add_argument('--versioni-codex', default=os.environ.get('DELMINIO_VERSIONI_CODEX') or '~/.local/share/codex/versions')
+ ap.add_argument('--versioni-qwen', default=os.environ.get('DELMINIO_VERSIONI_QWEN') or '~/.local/share/qwen-code/versions')
+ ap.add_argument('--versioni-opencode', default=os.environ.get('DELMINIO_VERSIONI_OPENCODE') or '~/.local/share/delminio/opencode/versions')
+ ap.add_argument('--registro', default=os.environ.get('DELMINIO_ESEGUIBILI') or '~/.config/delminio/eseguibili.json')
+ a = ap.parse_args()
+ if a.da:
+ for riga in open(a.da, encoding='utf-8'):
+ k, _, v = riga.strip().partition('=')
+ if k in ('URL', 'FILE_TOKEN') and v:
+ setattr(a, 'url' if k == 'URL' else 'token_file', (shlex.split(v) or [''])[0])
+ if not a.url or not a.token_file:
+ ap.error(F('servono_url_token'))
+ bin_dir, versioni, registro = (os.path.expanduser(x) for x in (a.bin, a.versioni, a.registro))
+ _DIR_COMANDI[0] = cartella_dei_comandi(registro)
+ prova = os.environ.get('DELMINIO_CLI_PROVA', '')
+ mio = _leggi(registro)
+ if a.vuoi and a.comando == 'allinea':
+ mio['cli_volute'] = sorted(set(mio.get('cli_volute') or []) | {a.vuoi})
+ _scrivi(registro, mio)
+ letto = _del_file(registro)
+ impronte = mio.setdefault('eseguibili', {})
+ _ALIASI.update(mio.get('alias') or {})
+ url = spazio_di(a.url, _token_di(a.token_file))
+ if a.comando == 'spazio':
+ if url not in mio.get('spazi', {}) and mio.get('spazi'):
+ vero = _alias(mio, url, _istanza_di(a.url, _token_di(a.token_file)))
+ if vero != url:
+ _scrivi(registro, mio)
+ url = vero
+ print(url)
+ return 0
+ sp = _spazio(mio, url)
+ if a.comando == 'skill':
+ return gesto_skill(a, url, sp, registro, mio)
+ if a.comando == 'allinea' and a.modo == 'kit':
+ ricorda_il_progetto(url)
+ padroni = mio.setdefault('padroni', {})
+ if a.comando == 'no':
+ sp['rifiutato'] = True
+ _scrivi(registro, mio)
+ print(F('rifiutati'))
+ return 0
+ if a.comando == 'lascia':
+ return comando_lascia(a, url, padroni, impronte, mio, registro)
+ base = a.url.rstrip('/') + '/api/eseguibili'
+ try:
+ token = open(os.path.expanduser(a.token_file)).read().strip()
+ dati = json.loads(_get(base, token))
+ righe = dati['eseguibili']
+ except (OSError, ValueError, KeyError, urllib.error.URLError) as e:
+ print(F('registro_muto', url=a.url, errore=e), file=sys.stderr)
+ return 2
+ fuori = [str(r.get('nome')) for r in righe if not _NOME_OK.fullmatch(str(r.get('nome') or ''))]
+ if fuori:
+ print(F('nomi_fuori_forma', nomi=', '.join(map(repr, fuori))), file=sys.stderr)
+ righe = [r for r in righe if _NOME_OK.fullmatch(str(r.get('nome') or ''))]
+ istanza = dati.get('istanza') or ''
+ if (vero := _alias(mio, url, istanza)) != url:
+ url, sp = (vero, _spazio(mio, vero))
+ if istanza:
+ sp['istanza'] = istanza
+ al_lancio = a.comando == 'allinea' and a.al_lancio
+ if al_lancio and sp.get('registro') == dati.get('impronta'):
+ return 3 if os.environ.get('DELMINIO_AL_LANCIO_ATTESO') else 0
+ if al_lancio and (not os.environ.get('DELMINIO_AL_LANCIO_ATTESO')):
+ print(F('al_lancio'), file=sys.stderr)
+ if a.comando == 'prova':
+ return comando_prova(a, righe, dati, base, token)
+ if a.comando == 'rinomina':
+ return comando_rinomina(a, righe, base, token)
+ canali, esito = ({}, 0)
+ if a.comando == 'stato':
+ return comando_stato(a, righe, canali, base, token, bin_dir, versioni, impronte, padroni, url, sp, prova, mio, registro)
+ if fcntl is not None:
+ try:
+ os.makedirs(os.path.dirname(registro) or '.', exist_ok=True)
+ lucchetto = open(registro + '.lock', 'w')
+ fcntl.flock(lucchetto, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ if not al_lancio or os.environ.get('DELMINIO_AL_LANCIO_ATTESO') or 'lucchetto' not in locals():
+ print(F('allinea_in_corso'))
+ return 0
+ print(F('al_lancio_attesa'), file=sys.stderr)
+ fcntl.flock(lucchetto, fcntl.LOCK_EX)
+ lucchetto.close()
+ os.environ['DELMINIO_AL_LANCIO_ATTESO'] = '1'
+ sys.stderr.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ else:
+ if _del_file(registro) != letto and (not os.environ.get('DELMINIO_RILETTO')):
+ lucchetto.close()
+ os.environ['DELMINIO_RILETTO'] = '1'
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ os.makedirs(bin_dir, exist_ok=True)
+ nomi = set()
+ senza_cli = set()
+ detto = [0.0]
+
+ def avanza(percento, passo, subito=False):
+ if not subito and time.time() - detto[0] < 2:
+ return
+ detto[0] = time.time()
+ try:
+ _get(f'{base}/lavoro', token, metodo='POST', corpo={'host': socket.gethostname(), 'percento': int(percento), 'passo': passo[:120]}, timeout=5)
+ except (OSError, ValueError, urllib.error.URLError):
+ pass
+ nomi_cli = dati.get('cli') or {}
+ quante = max(1, len(righe))
+ prima_volta = 'accettati' not in mio
+ accettati, fermi = (set(mio.get('accettati') or []), [])
+ for i, r in enumerate(righe):
+ p = os.path.join(bin_dir, r['nome'])
+ nomi.add(p)
+ quota, nome_cli = (100.0 * i / quante, nomi_cli.get(r.get('cli') or 'claude', r.get('cli') or 'claude'))
+ if not cli_qui(r.get('cli') or 'claude', versioni, os.path.expanduser(a.versioni_codex), prova, os.path.expanduser(a.versioni_qwen), mio.get('cli_volute') or (), os.path.expanduser(a.versioni_opencode)):
+ senza_cli.add(r['nome'])
+ print(F('senza_cli_qui', nome=r['nome'], cli=r.get('cli') or 'claude'))
+ continue
+ if da_accettare(r, accettati):
+ if prima_volta and any((impronte.get(x) for x in (p, comando_dello_spazio(url, r['nome'])))):
+ accettati.add(impronta_libera(r))
+ else:
+ fermi.append({'nome': r['nome'], **parte_libera(r)})
+ print(F('riga_da_accettare', nome=r['nome']))
+ continue
+ try:
+ voluta = versione_voluta(r, canali)
+ avanza(quota, F('passo_controllo', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
+ su = lambda f, t, q=quota, n=nome_cli, vv=voluta, nn=r['nome']: avanza(q + 90.0 / quante * (f / t if t else 0), F('passo_scarico', nome=nn, cli=n, versione=vv, mb=f // 1000000) + (F('passo_di', mb=t // 1000000) if t else ''))
+ cli = assicura_codex(voluta, os.path.expanduser(a.versioni_codex), prova, su=su) if r.get('cli') == 'codex' else assicura_qwen(voluta, os.path.expanduser(a.versioni_qwen), prova, su=su) if r.get('cli') == 'qwen' else assicura_opencode(voluta, os.path.expanduser(a.versioni_opencode), prova, su=su) if r.get('cli') == 'opencode' else assicura_cli(voluta, versioni, prova, su=su)
+ if personaggio(r) and r.get('cli') in ('claude', 'qwen'):
+ assicura_canale(a.url, token, r['porta'])
+ if r.get('cli') == 'claude':
+ assicura_rito()
+ except Exception as e:
+ print(f"❌ {r['nome']}: {e}")
+ esito = 1
+ continue
+ modello = next((m for m in (dati.get('modelli') or {}).get(r.get('cli') or 'claude', []) if m['id'] == r.get('modello')), {})
+ promemoria = ((dati.get('promemoria') or {}).get('ambiente') or {}).get(r.get('cli') or 'claude') or {}
+ promemoria = {k: v for k, v in promemoria.items() if k in PROMEMORIA_AMMESSI}
+ da_lanciare = {**r, '_contesto': modello.get('contesto') or {}, '_promemoria': promemoria, '_fornitori': (dati.get('fornitori_opencode') if r.get('cli') == 'opencode' else dati.get('fornitori_qwen')) or {}, '_skill': dati.get('skill_scelte') or [], '_base': dati.get('parametri_base') or {}}
+ testo = wrapper(da_lanciare, cli, a.modo, a.url, os.path.expanduser(a.token_file))
+ ora = _del_file(p)
+ if ora is not None and p not in impronte:
+ print(F('non_di_delminio', percorso=p))
+ esito = 1
+ continue
+ if ora is not None and impronte.get(p) != ora:
+ print(F('toccato_resta', percorso=p))
+ continue
+ if a.modo == 'kit' and (not a.converti) and (ora != _impronta(testo)) and _di_casa(p):
+ testo = wrapper(da_lanciare, cli, 'casa', a.url, os.path.expanduser(a.token_file))
+ chi = padroni.get(p) or []
+ altri = [u for u in chi if u != url]
+ if ora is not None and altri and (not e_smistatore(p)) and (ora == _impronta(testo)):
+ if url not in chi:
+ chi.append(url)
+ sp.setdefault('cli', {})[p] = voluta
+ continue
+ if ora is not None and (altri or e_smistatore(p)):
+ q = comando_dello_spazio(url, r['nome'])
+ gia = _del_file(q)
+ if gia is not None and impronte.get(q) not in (None, gia):
+ print(F('toccato_resta', percorso=q))
+ continue
+ vecchio = None
+ if gia is not None:
+ with open(q, encoding='utf-8') as f:
+ vecchio = f.read()
+ prima = (sp.get('cli') or {}).get(p)
+ sp.setdefault('cli', {})[p] = voluta
+ if url in chi and gia == _impronta(testo) and e_smistatore(p):
+ continue
+ if dividi(p, url, testo, padroni, impronte):
+ print(F('smistato', nome=r['nome'], spazi=', '.join((come_si_chiama(u) for u in padroni[p]))))
+ cambiate = _nel_diario(registro, q, prima, voluta, vecchio, testo)
+ if gia is None:
+ print(F('scritto', percorso=q, versione=voluta))
+ elif gia != _impronta(testo):
+ print(F('rinfrescato', percorso=q, versione=voluta, righe=cambiate) if prima == voluta else F('aggiornato', percorso=q, prima=prima or '?', versione=voluta))
+ continue
+ padroni[p] = [url] + altri
+ prima = (sp.get('cli') or {}).get(p)
+ sp.setdefault('cli', {})[p] = voluta
+ if ora == _impronta(testo):
+ continue
+ vecchio = None
+ if ora is not None:
+ try:
+ with open(p, encoding='utf-8') as f:
+ vecchio = f.read()
+ except (OSError, UnicodeDecodeError):
+ pass
+ with open(p + '.nuovo', 'w', encoding='utf-8') as f:
+ f.write(testo)
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+ impronte[p] = _impronta(testo)
+ cambiate = _nel_diario(registro, p, prima, voluta, vecchio, testo)
+ if ora is None:
+ print(F('scritto', percorso=p, versione=voluta))
+ elif prima == voluta:
+ print(F('rinfrescato', percorso=p, versione=voluta, righe=cambiate))
+ else:
+ print(F('aggiornato', percorso=p, prima=prima or '?', versione=voluta))
+ avanza(100.0 * (i + 1) / quante, F('passo_scritto', nome=r['nome'], cli=nome_cli, versione=voluta), subito=True)
+ for p in [x for x in impronte if x not in nomi and os.path.dirname(x) == bin_dir]:
+ chi = padroni.get(p) or []
+ if url not in chi:
+ continue
+ sp.get('cli', {}).pop(p, None)
+ com_e = lascia_il_nome(p, url, padroni, impronte)
+ if com_e == 'tolto':
+ print(F('tolto', percorso=p))
+ elif com_e in ('altri', 'tornato'):
+ print(F('lasciato_ad_altri', percorso=p, spazi=', '.join(padroni.get(p) or [])))
+ if righe:
+ sp['rifiutato'] = False
+ mio['accettati'], sp['fermi'] = (sorted(accettati), fermi)
+ sp['registro'], sp['quando'] = (dati.get('impronta', ''), int(time.time()))
+ sp['skill_scelte'] = dati.get('skill_scelte') or []
+ _scrivi(registro, mio)
+ if esito == 0 and righe and (not prova):
+ pota(bin_dir, [versioni] + [os.path.expanduser(c) for c in (a.versioni_codex, a.versioni_qwen, a.versioni_opencode)], nudo(bin_dir, versioni))
+ r = riferisci(base, token, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), senza_cli=senza_cli)
+ if richiesta(base, token, r, righe, impronte, bin_dir, versioni, dati.get('impronta', ''), sp.get('cli'), mio=mio, file_mio=registro) and (not os.environ.get('DELMINIO_RIALLINEATO')):
+ os.environ['DELMINIO_RIALLINEATO'] = '1'
+ sys.stdout.flush()
+ os.execv(sys.executable, [sys.executable, os.path.abspath(sys.argv[0])] + sys.argv[1:])
+ cartelle = [os.path.realpath(os.path.expanduser(c)) for c in os.environ.get('PATH', '').split(os.pathsep) if c]
+ if righe and os.path.realpath(bin_dir) not in cartelle:
+ print(F('fuori_dal_path', cartella=bin_dir))
+ if a.primo:
+ scrivi_il_primo(a, dati, righe, bin_dir, impronte)
+ return 3 if al_lancio and esito == 0 else esito
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/kit/it/firme-client b/kit/it/firme-client
new file mode 100644
index 0000000..f6f8209
--- /dev/null
+++ b/kit/it/firme-client
@@ -0,0 +1,1357 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Le firme delle modifiche da un terminale, dai ganci git e da una CI (B923)."""
+from __future__ import annotations
+import base64
+import datetime
+import hashlib
+import json
+import os
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import urllib.error
+import urllib.request
+CMD = 'delminio firme'
+URL = os.environ.get('DELMINIO_URL', '').rstrip('/')
+TOKEN = os.environ.get('DELMINIO_TOKEN', '')
+STATO = os.environ.get('DELMINIO_STATO', '')
+MASSIMO = 20000
+COMMIT_MAX = 500
+RAMO_MAX = 200
+APP_ANDROID = ('jG9UXQXhlWwgZvpNwGNDmhcDbR_94LnCQOAcyOOgJqg',)
+PROVE_TEMPO = 900
+COMANDI = {
+ "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"
+ }
+}
+FRASI = {
+ "ci_gitlab_passi": "Poi, una volta: Settings \u2192 CI/CD \u2192 Variables, una variabile DELMINIO_FIRME (masked) con la chiave che l'amministratore crea in Delminio, voce Firme \u2192 La chiave per la CI; e Settings \u2192 Merge requests \u2192 \xabPipelines must succeed\xbb, o il merge resta possibile anche col controllo rosso.",
+ "ci_gitlab": "Con GitLab il file \xe8 uno solo per tutto il repo ({file}), e non lo tocco: aggiungi questo job.",
+ "ci_passi_forgejo": "Su Forgejo (o Gitea), tre passi da fare a mano, una volta:\n 1. Un runner: le Actions girano solo se il servizio ne ha uno (nel repo, Impostazioni \u2192 Actions \u2192 Runner). Il file chiede un runner con l'etichetta docker: se il vostro ne ha un'altra, cambia \xabruns-on\xbb nel file.\n 2. Il segreto: Impostazioni \u2192 Actions \u2192 Segreti, nome DELMINIO_FIRME, valore la chiave che l'amministratore crea in Delminio, voce Firme \u2192 La chiave per la CI.\n 3. Il cancello: Impostazioni \u2192 Rami \u2192 una regola di protezione sul ramo {ramo}, con tre cose: il controllo di stato obbligatorio \xabdelminio-firme / controlla (pull_request)\xbb (su Forgejo il nome porta il file e l'evento: \xabcontrolla\xbb da solo non combacia con niente, e il merge resta fermo anche con le firme); il push diretto spento, cos\xec sul ramo si entra solo da una pull request; la regola anche per gli amministratori. Senza questa regola la CI dice rosso, ma il merge resta possibile.\nNelle pull request da un fork i segreti non ci sono: l\xec il controllo non pu\xf2 girare.",
+ "ci_gh_manca": "La CLI di GitHub (gh) non c'\xe8 su questo computer: il segreto e la regola sul ramo restano da fare a mano.",
+ "ci_gh_non_collegato": "La CLI di GitHub c'\xe8, ma non \xe8 collegata a un account (gh auth login): il segreto e la regola sul ramo restano da fare a mano.",
+ "ci_gh_quale_repo": "La CLI di GitHub non riconosce il repo di questa cartella ({errore}): il segreto e la regola sul ramo restano da fare a mano.",
+ "ci_gh_permessi": "Su {repo} il tuo account GitHub non \xe8 amministratore: il segreto e la regola sul ramo li mette chi lo \xe8, a mano o rilanciando questo comando.",
+ "ci_gh_privato": "\u274c GitHub non applica le regole sui rami ai repo privati di un account gratuito: su {repo} il controllo dir\xe0 rosso, ma il merge rester\xe0 possibile. Serve un piano GitHub che le applichi (Team, o Pro per un account personale), o un servizio git vostro.",
+ "ci_gh_regola_no": "\u274c La regola sul ramo {ramo} non si \xe8 messa ({errore}). A mano: Settings \u2192 Branches \u2192 una regola sul ramo {ramo} con il controllo \xabcontrolla\xbb obbligatorio e \xabDo not allow bypassing the above settings\xbb.",
+ "ci_gh_regole_altre": "Il ramo {ramo} ha gi\xe0 le sue regole: le lascio come sono, e aggiungo solo ci\xf2 che manca.",
+ "ci_gh_regola_ok": "\u2705 Su {repo}, il ramo {ramo} vuole il controllo \xabcontrolla\xbb prima di ogni merge, e la regola vale anche per gli amministratori.",
+ "ci_gh_segreto_c_e": "\u2705 Il segreto DELMINIO_FIRME c'\xe8 gi\xe0 su {repo}. GitHub non mostra il valore a nessuno: se la CI dice che la chiave non vale, rimettilo.",
+ "ci_gh_segreto_tu": "Manca il segreto DELMINIO_FIRME, e lo mette una persona, non un agente: nel suo terminale, in questo repo, scrive {cmd} e incolla la chiave per la CI che l'amministratore crea in Delminio, voce Firme \u2192 La chiave per la CI.",
+ "ci_gh_segreto_incolla": "Ora il segreto DELMINIO_FIRME: incolla la chiave per la CI che l'amministratore crea in Delminio, voce Firme \u2192 La chiave per la CI. Non si vede mentre la incolli, e va solo a GitHub.",
+ "ci_gh_segreto_fatto": "\u2705 Il segreto DELMINIO_FIRME \xe8 su {repo}.",
+ "ci_gh_segreto_no": "\u274c Il segreto non si \xe8 messo ({errore}): nel repo, Settings \u2192 Secrets and variables \u2192 Actions, nome DELMINIO_FIRME.",
+ "ci_passi_github": "Su GitHub, due passi da fare a mano, una volta:\n 1. Il segreto: nel repo, Settings \u2192 Secrets and variables \u2192 Actions \u2192 New repository secret. Nome DELMINIO_FIRME, valore la chiave che l'amministratore crea in Delminio, voce Firme \u2192 La chiave per la CI.\n 2. Il cancello: Settings \u2192 Branches (o Rules) \u2192 una regola sul ramo {ramo} che chiede il controllo \xabcontrolla\xbb prima del merge, anche agli amministratori (\xabDo not allow bypassing the above settings\xbb). Il controllo compare nella lista dopo la prima pull request. Senza questa regola la CI dice rosso, ma il merge resta possibile.\nNelle pull request da un fork GitHub non d\xe0 i segreti: l\xec il controllo non pu\xf2 girare.",
+ "ci_esiste_diverso": "\u26a0\ufe0f {file} c'\xe8 gi\xe0, ed \xe8 diverso da quello che scriverei: non lo tocco. Se l'avete cambiato voi, va bene cos\xec; se no, toglietelo e rilanciate.",
+ "ci_gia_pronto": "\u2705 {file} c'\xe8 gi\xe0, ed \xe8 quello giusto.",
+ "ci_scritto": "\u2705 Scritto {file}: committalo e spingilo come ogni altro file.",
+ "ci_commento": "Le firme delle modifiche di Delminio: ogni pull request controlla le firme del suo ramo, ogni push sul ramo principale che non sia entrato niente senza firme. Scritto da \xabdelminio firme ci\xbb; la chiave sta nei segreti del servizio, col nome DELMINIO_FIRME.",
+ "ci_dentro_casa": "\u26a0\ufe0f Questo Delminio sta a {url}, un indirizzo della vostra rete: i computer di una CI in internet (GitHub, GitLab.com) non lo raggiungono. Il controllo funziona solo con una CI che gira dentro la vostra rete (un runner vostro), o con un Delminio raggiungibile da fuori.",
+ "ci_quale": "Non riconosco il servizio git di questo repo. Dimmi quale: delminio firme ci github, forgejo (anche Gitea) o gitlab.",
+ "dell_autore": "dell'autore: non conta",
+ "chi_non_detto": "un'altra sessione",
+ "revisione_dell_autore": "La revisione di {commit} \xe8 registrata, ma sei l'autore: conta quella di chi rivede, col suo agente.",
+ "uso": "uso: {cmd} controlla [<intervallo>] \xb7 {cmd} descrizione [<intervallo>] \xb7 {cmd} resoconto [<intervallo>] [<file>] \xb7 {cmd} esporta [<file>] \xb7 {cmd} catena <file> [<copia di prima>] \xb7 {cmd} revisione <commit|intervallo> pulita|rilievi [N] \xb7 {cmd} prove \xb7 {cmd} ci [github|forgejo|gitlab]",
+ "senza_motore": "\u274c Mancano l'indirizzo di Delminio o la chiave: in una CI servono DELMINIO_URL e DELMINIO_TOKEN (la chiave di lettura che l'amministratore crea in Firme).",
+ "non_risponde": "\u274c Delminio non risponde ({url}): {errore}",
+ "assenti": "Le firme delle modifiche non ci sono in questo spazio: la licenza non le porta.",
+ "intestazione": "Le parole della persona all'agente, registrate da Delminio (le firme delle modifiche):",
+ "non_registrata": "non registrata in Delminio",
+ "controlli": "I controlli prima del commit:",
+ "zona": "\u26a0\ufe0f Questa modifica tocca una zona a firma ({zone}): va firmata nell'app di Delminio, in Firme, prima di andare avanti.",
+ "nascosto": "[nascosto]",
+ "troncata": "[\u2026 altri {n} caratteri non copiati qui]",
+ "nessun_commit": "Nessun commit in {intervallo}.",
+ "intervallo_illeggibile": "\u274c Non leggo i commit di {intervallo}: git non lo trova ({errore}). Senza commit da controllare non si dice verde: nella CI serve tutta la storia (fetch-depth: 0), e dopo un push forzato il commit di prima non c'\xe8 pi\xf9.",
+ "firmata": " \u2705 {commit} firmata \u2014 {soggetto}",
+ "da_firmare": " \u274c {commit} da firmare ({zone}): mancano {manca} \u2014 {soggetto}",
+ "respinta": " \u274c {commit} respinta \u2014 {soggetto}",
+ "libera": " \xb7 {commit} fuori dalle zone a firma \u2014 {soggetto}",
+ "senza": " \u274c {commit} senza firme registrate: in Delminio nessuno ne risponde. \xc8 stato fatto da un computer non collegato, saltando i controlli, con le firme spente, o la rete \xe8 caduta al commit: rifallo da un computer collegato (git commit --amend --no-edit) \u2014 {soggetto}",
+ "senza_in_zona": " \u274c {commit} tocca una zona a firma ({zone}) senza firme registrate: \xe8 stato fatto da un computer non collegato, saltando i controlli, con le firme spente, o la rete \xe8 caduta al commit. Rifallo da un computer collegato (git commit --amend --no-edit) \u2014 {soggetto}",
+ "merge_pulito": " \xb7 {commit} merge senza modifiche sue \u2014 {soggetto}",
+ "unita": " \u2705 {commit} viene dal ramo {ramo}: le sue {n} modifiche hanno le firme \u2014 {soggetto}",
+ "unita_da_firmare": " \u274c {commit} viene dal ramo {ramo}: {n} sue modifiche sono ancora da firmare \u2014 {soggetto}",
+ "unita_mancano": " \u274c {commit} viene dal ramo {ramo}, ma {n} suoi commit non hanno firme registrate \u2014 {soggetto}",
+ "unita_scoperta": " \u274c {commit} viene dal ramo {ramo} e tocca una zona a firma ({zone}) che le sue modifiche registrate non portano: i file registrati non sono quelli del commit. Rifai i commit da un computer collegato \u2014 {soggetto}",
+ "parole_non_tornano": " \u274c {commit}: le parole della richiesta {id} non tornano con la sua impronta \u2014 il messaggio \xe8 stato cambiato",
+ "parole_ignote": " \u274c {commit}: la richiesta {id} non \xe8 quella che Delminio ha registrato",
+ "esito": "{firmate} firmate \xb7 {da_firmare} da firmare \xb7 {libere} fuori dalle zone \xb7 {senza} senza firme registrate \xb7 {rotte} con le parole cambiate \xb7 {urgenti} entrate d'urgenza.",
+ "urgente": " \u26a1 {commit} entrata d'urgenza \u2014 {soggetto} (lasciata passare da {da} il {quando}: \xab{perche}\xbb; le firme si danno dopo)",
+ "gov_urgenza": "{quando} \u2014 {chi} lascia entrare d'urgenza il commit {commit} in {repo}: \xab{perche}\xbb",
+ "esportata": "La catena \xe8 in {file}: {anelli} anelli, {esito}.",
+ "catena_rotta": "rotta all'anello {anello}",
+ "revisione_registrata": "La tua revisione di {commit} \xe8 registrata: ora la puoi firmare dall'app, nella voce Firme.",
+ "revisione_senza_sessione": "La revisione la registra il tuo agente, dalla sua sessione: chiedigli di rivedere il commit e di lanciare lui \xab{cmd} revisione <commit> pulita\xbb (o \xabrilievi N\xbb). Da un terminale fuori da una sessione non si registra, perch\xe9 la revisione \xe8 tua e del modello che hai scelto.",
+ "descr_parole": "### Cosa ha chiesto la persona",
+ "descr_nessuna_parola": "_Nessuna richiesta registrata: modifiche fatte a mano._",
+ "descr_fatti": "### I fatti",
+ "descr_commit": "{n} commit, {file} file",
+ "descr_assistito": "Con l'agente: {con}",
+ "descr_zona": "Zona a firma {codice} \xab{cosa}\xbb: {servono} firme, rivede {chi}",
+ "descr_chiunque": "chiunque nello spazio",
+ "descr_controllo": "Controllo {codice} `{comando}` \u2192 uscita {uscita}",
+ "descr_revisione": "Revisione di {chi}, con {revisore}: {esito}, {rilievi} rilievi ({indipendente})",
+ "indipendente": "indipendente",
+ "stessa_sessione": "dalla sessione che l'ha scritto: non conta",
+ "indipendente_stesso_modello": "indipendente, stesso modello dell'autore",
+ "descr_stati": "Le firme: {stati}",
+ "stato_firmata": "firmate",
+ "stato_unita": "firmate nel ramo",
+ "stato_libera": "fuori dalle zone",
+ "stato_pulito": "merge",
+ "stato_senza": "senza firme registrate",
+ "stato_da_firmare": "da firmare",
+ "stato_respinta": "respinte",
+ "stato_zona": "in una zona senza firme registrate",
+ "res_titolo": "# Le firme delle modifiche \u2014 {remoto} \u2014 {intervallo}",
+ "res_generato": "Scritto il {quando} da Delminio. La catena delle firme: {anelli} anelli, {esito}.",
+ "res_stato": "Stato: {riga}",
+ "res_unita": "Unita nel ramo principale dal ramo {ramo}: le firme stanno sui suoi {n} commit.",
+ "res_autore": "Ne risponde {autore} \xb7 con {con} \xb7 {quando}",
+ "res_a_mano": "nessun agente (a mano)",
+ "res_zona": "Zona a firma {codice} \xab{cosa}\xbb: {servono} firme",
+ "res_firma": "Firma di {persona}, {significato}, {quando}{parole}",
+ "significato_autore": "come autore",
+ "significato_revisione": "come revisione",
+ "significato_respinta": "respinta",
+ "res_nessuna_firma": "Nessuna firma ancora.",
+ "res_richiesta": "Richiesta {id} (impronta {impronta}\u2026): {torna}",
+ "res_torna": "le parole tornano con l'impronta registrata",
+ "res_non_torna": "le parole NON tornano con l'impronta: il messaggio \xe8 stato cambiato",
+ "res_file": "{n} file: {elenco}",
+ "res_come_verificare": "La catena si rif\xe0 senza Delminio: \xabdelminio firme esporta\xbb e poi, dentro il repo, \xabdelminio firme catena <file> [<copia di prima>]\xbb, che controlla anche le ancore scritte nei commit e che la copia di prima sia ancora il suo inizio. Le parole di ogni richiesta stanno nel messaggio del commit, e la loro impronta (sha256) \xe8 quella che Delminio ha registrato quando la persona le ha scritte.",
+ "res_scritto": "Il resoconto \xe8 in {file}: {commit} commit.",
+ "ripresa": " \u2705 {commit} \xe8 una modifica del ramo {ramo} rifatta (rebase o cherry-pick), con le sue firme \u2014 {soggetto}",
+ "ripresa_da_firmare": " \u274c {commit} \xe8 una modifica del ramo {ramo} rifatta (rebase o cherry-pick), ancora da firmare \u2014 {soggetto}",
+ "repo_senza_firme": "Questo repo non ha le firme delle modifiche: niente da controllare. L'amministratore le accende per repo, dalla voce Firme.",
+ "repo_sconosciuto": "\u274c Delminio non conosce questo repo ({remoto}): il controllo non sa cosa guardare, e non dice verde. In una CI la variabile DELMINIO_FIRME_REPO dice il repo com'\xe8 collegato a Delminio: \xabdelminio firme ci\xbb la scrive nel file. Rilancialo da un computer collegato (se il file c'\xe8 gi\xe0, eliminalo prima) e committa quello nuovo.",
+ "scartata": " \u274c {commit} scartata: non si firma pi\xf9 \u2014 {soggetto}",
+ "manca_prove": "le prove della zona su questo commit",
+ "manca_autore": "la firma dell'autore",
+ "manca_persone": "la revisione di chi rivede, col suo agente, e la sua firma",
+ "parole_tolte": " \u274c {commit}: la richiesta {id}, che Delminio ha legato a questo commit, non \xe8 nel messaggio \u2014 le parole sono state rimosse",
+ "ancora_rotta": "\u274c RISCRITTA: l'anello {anello} non \xe8 pi\xf9 quello che il commit {commit} ha ancorato (ancore che non tornano: {n}). Chi tiene il database di Delminio ha cambiato la catena dopo quel commit",
+ "catena_ancorata": "integra, e ancorata in {n} commit di questo repo",
+ "catena_non_ancorata": "integra, ma nessun commit di questa copia del repo la ancora: fino al primo, chi tiene il database potrebbe riscriverla senza che si veda",
+ "gov_accese": "{quando} \u2014 {chi} accende le firme nello spazio",
+ "gov_spente": "{quando} \u2014 {chi} spegne le firme nello spazio: finch\xe9 non si riaccendono non si registra niente",
+ "gov_repo_si": "{quando} \u2014 {chi} accende le firme nel repo {repo}",
+ "gov_repo_no": "{quando} \u2014 {chi} spegne le firme nel repo {repo}: finch\xe9 non si riaccendono l\xec non si registra niente",
+ "gov_chiave_si": "{quando} \u2014 {chi} crea la chiave di lettura \xab{etichetta}\xbb",
+ "gov_chiave_no": "{quando} \u2014 {chi} revoca la chiave di lettura \xab{etichetta}\xbb",
+ "gov_zona_nata": "{quando} \u2014 {chi} crea la zona {codice}: {zona}",
+ "gov_zona_ritirata": "{quando} \u2014 {chi} ritira la zona {codice}",
+ "gov_zona_cambiata": "{quando} \u2014 {chi} cambia la zona {codice}: da {prima} a {dopo}",
+ "gov_zona_detta": "{dove}, {servono} firme, rivede {chi}, prove `{comando}`",
+ "res_governo": "## Chi ha governato le firme",
+ "res_unito_da": "Nel ramo principale da {chi}, il {quando} (lo dice git: chi unisce non passa da Delminio)",
+ "res_git_dice": "Git dice autore {autore}: non verificato, Delminio non ha visto fare questo commit",
+ "res_non_in_catena": "\u274c questa modifica non \xe8 nella catena: il database di Delminio dice cose che la catena non dice",
+ "res_zona_dopo": "{quando}: la zona {zone} \xe8 stata creata dopo il commit, e vale anche per lui",
+ "res_prova_mancante": "Prova {codice} `{comando}` \u2192 non girata su questo commit",
+ "res_firme_diverse": "\u274c il database di Delminio dice altre firme ({motore}): vale la catena, e il database \xe8 stato cambiato",
+ "res_scartata": "Scartata il {quando}: {perche}",
+ "res_parole_altrove": "Le parole stanno nel commit {commit} del ramo {ramo}, che questa copia del repo non ha: git fetch origin {ramo} (su GitHub restano anche in refs/pull/*/head)",
+ "copia_diversa": "\u274c {file} non \xe8 l'inizio di questa catena: l'anello {anello} \xe8 diverso. La catena \xe8 stata riscritta dopo quella copia",
+ "copia_uguale": "{file}: i suoi {anelli} anelli sono l'inizio di questa catena, uguali",
+ "prova_non_accettata": "\u26a0\ufe0f la prova della zona a firma {codice} \xe8 nuova o cambiata, e su questa macchina nessuno l'ha ancora accettata \u2014 non l'ho eseguita:\n {comando}\n Leggila e, se ti fidi, da un terminale tuo: delminio accetta. Poi: delminio firme prove\n Senza la prova girata questo commit non si firma.",
+ "prova_fallita": "\u274c la prova della zona a firma {codice} non \xe8 passata su questo commit (uscita {uscita}): non si firma finch\xe9 non passa su un commit rifatto.\n {comando}",
+ "prova_passata": "\u2705 la prova della zona a firma {codice} \xe8 passata su questo commit.",
+ "prove_albero_diverso": "\u26a0\ufe0f le prove della zona a firma ({zone}) non sono girate: i file qui non sono uguali al commit {commit}, e proverebbero un'altra cosa. Quando lo sono: delminio firme prove",
+ "prove_solo_testa": "Le prove girano sul commit che \xe8 qui adesso (HEAD), con i file uguali al commit. Per un commit pi\xf9 indietro: git rebase --exec \"delminio firme prove\" <base>",
+ "prove_registrate": "Le prove di {commit} sono registrate: {esito}.",
+ "prove_nessuna": "Nessuna zona a firma chiede prove su {commit}.",
+ "res_passkey": "con la passkey \xab{nome}\xbb di {persona}, aggiunta il {quando} (confermata con {come}): la firma del dispositivo torna",
+ "res_passkey_non_torna": "\u274c la firma del dispositivo NON torna ({perche}): questa firma non l'ha data la passkey di {persona}",
+ "res_passkey_cieca": "\u26a0\ufe0f la firma del dispositivo non si pu\xf2 verificare qui: servono il modulo cryptography di Python o il comando openssl",
+ "res_senza_passkey_prima": "firmata nell'app prima che la firma volesse la passkey",
+ "res_senza_passkey_dopo": "\u274c firmata senza passkey dopo che la firma la vuole: questa firma non l'ha data nessun dispositivo",
+ "res_persona": "{persona} \xe8 nello spazio dal {quando}, {da}",
+ "res_persona_invitata": "invitata da {chi}",
+ "res_persona_da_sempre": "da prima che si registrasse chi invita",
+ "res_passkey_mail": "l'email",
+ "res_passkey_password": "la password",
+ "gov_passkey": "{quando} \u2014 da qui ogni firma vuole la passkey del dispositivo di chi firma",
+ "gov_persona_entrata": "{quando} \u2014 {persona} entra nello spazio come {ruolo}, invitata da {chi}",
+ "gov_persona_spenta": "{quando} \u2014 {persona} esce dallo spazio (account spento)",
+ "gov_persona_riaccesa": "{quando} \u2014 {persona} torna nello spazio (account riacceso)",
+ "gov_passkey_nuova": "{quando} \u2014 {persona} aggiunge la passkey \xab{nome}\xbb per {rp}, confermata con {come}",
+ "gov_passkey_revocata": "{quando} \u2014 {chi} revoca la passkey \xab{nome}\xbb di {persona}",
+ "perche_chiave": "la passkey non \xe8 nella catena, o non \xe8 di chi firma",
+ "perche_revocata": "la passkey era revocata",
+ "perche_commit": "il dispositivo ha firmato altri commit",
+ "perche_sfida": "il dispositivo ha firmato altre parole, un altro significato o un'altra persona",
+ "perche_origine": "firmata da un altro indirizzo",
+ "perche_persona": "senza l'impronta o il PIN della persona",
+ "perche_firma": "la firma crittografica non torna con la chiave pubblica"
+}
+
+def F(chiave: str, **sost) -> str:
+ t = FRASI.get(chiave, chiave)
+ for k, v in sost.items():
+ t = t.replace('{' + k + '}', str(v))
+ return t
+
+class Rifiuto(Exception):
+
+ def __init__(self, messaggio: str, codice: int=0):
+ super().__init__(messaggio)
+ self.codice = codice
+
+def forma(testo: str) -> str:
+ return '\n'.join((r.rstrip() for r in (testo or '').strip().splitlines())).strip()
+
+def impronta(testo: str) -> str:
+ return hashlib.sha256(forma(testo).encode('utf-8')).hexdigest()
+
+def verifica_catena(anelli: list) -> object:
+ prima = ''
+ for i, a in enumerate(anelli):
+ atteso = hashlib.sha256((prima + '\n' + a.get('tipo', '') + '\n' + a.get('contenuto', '')).encode('utf-8')).hexdigest()
+ if a.get('prima', '') != prima or a.get('impronta') != atteso:
+ return a.get('seq', i + 1)
+ prima = atteso
+ return None
+
+def git(*a: str) -> str:
+ r = subprocess.run(['git', *a], capture_output=True, text=True, encoding='utf-8', errors='replace')
+ return r.stdout.strip() if r.returncode == 0 else ''
+
+def chiedi(metodo: str, percorso: str, corpo=None, attesa: int=30) -> dict:
+ if not URL or not TOKEN:
+ raise Rifiuto(F('senza_motore'))
+ req = urllib.request.Request(URL + percorso, method=metodo, data=json.dumps(corpo).encode() if corpo is not None else None, headers={'Authorization': 'Bearer ' + TOKEN, 'Content-Type': 'application/json'})
+ try:
+ return json.loads(urllib.request.urlopen(req, timeout=attesa).read())
+ except urllib.error.HTTPError as e:
+ try:
+ perche = json.loads(e.read()).get('error') or str(e)
+ except Exception:
+ perche = str(e)
+ raise Rifiuto(F('assenti') if e.code == 404 and perche == 'Not Found' else '❌ ' + perche, e.code) from None
+ except Exception as e:
+ raise Rifiuto(F('non_risponde', url=URL, errore=e)) from None
+_VUOTO = []
+
+def _albero_vuoto() -> str:
+ if not _VUOTO:
+ r = subprocess.run(['git', 'hash-object', '-t', 'tree', '--stdin'], input=b'', capture_output=True)
+ _VUOTO.append(r.stdout.decode().strip())
+ return _VUOTO[0]
+
+def _patch(da: str, a: str) -> str:
+ d = subprocess.run(['git', '-c', 'diff.noprefix=false', '-c', 'diff.mnemonicPrefix=false', 'diff', '--no-color', '--no-ext-diff', '--binary', da, a], capture_output=True)
+ if d.returncode or not d.stdout.strip():
+ return ''
+ p = subprocess.run(['git', 'patch-id', '--stable'], input=d.stdout, capture_output=True)
+ return (p.stdout.split() or [b''])[0].decode()
+
+def _genitori(h: str) -> list:
+ return git('rev-list', '--parents', '-n', '1', h).split()[1:]
+
+def _principale() -> str:
+ r = git('symbolic-ref', '-q', 'refs/remotes/origin/HEAD')
+ if r:
+ return r
+ for n in ('refs/remotes/origin/main', 'refs/remotes/origin/master'):
+ if git('rev-parse', '-q', '--verify', n):
+ return n
+ return ''
+
+def _ramo(h: str, nome: str='') -> dict | None:
+ principale = _principale()
+ base = git('merge-base', principale, h) if principale else ''
+ if not base:
+ return None
+ commit = git('rev-list', '--no-merges', '--reverse', f'{base}..{h}').split()[-RAMO_MAX:]
+ return {'nome': nome, 'patch': _patch(base, h) if commit else '', 'commit': commit}
+
+def _file(h: str) -> list:
+ file = git('diff-tree', '--no-commit-id', '--name-only', '-r', '-z', '--root', h).split('\x00')
+ return [f for f in file if f.strip()][:400]
+
+def segni(h: str) -> dict:
+ gen = _genitori(h)
+ return {'albero': git('rev-parse', h + '^{tree}'), 'patch': _patch(gen[0] if gen else _albero_vuoto(), h), 'file': _file(h)}
+
+def _parole_nel_messaggio(msg: str) -> tuple[dict, dict]:
+ dette = dict(re.findall('^Delminio-(?:Request|Richiesta): (\\d+) ([0-9a-f]{64})\\s*$', msg, re.M))
+ testi, corrente = ({}, None)
+ for r in msg.splitlines():
+ m = re.match('^\\[(\\d+)\\] ', r)
+ if m:
+ corrente = m.group(1)
+ testi[corrente] = []
+ elif corrente and (r == '>' or r.startswith('> ')):
+ testi[corrente].append(r[2:] if r.startswith('> ') else '')
+ else:
+ corrente = None
+ return (dette, {k: '\n'.join(v) for k, v in testi.items()})
+
+def _parole_rotte(h: str, msg: str, carta: dict | None) -> list:
+ dette, testi = _parole_nel_messaggio(msg)
+ registrate = {x['impronta']: x for x in (carta or {}).get('richieste') or []}
+ rotte = []
+ for rid, imp in dette.items():
+ if impronta(testi.get(rid) or '') != imp:
+ rotte.append((rid, 'non_tornano'))
+ elif carta is not None and imp not in registrate:
+ rotte.append((rid, 'ignote'))
+ scritte = set(dette.values())
+ for imp, x in registrate.items():
+ if imp not in scritte:
+ rotte.append((str(x.get('id') or '?'), 'tolte'))
+ return rotte
+
+def intervallo_di(a: list) -> str:
+ if a:
+ return a[0]
+ if git('rev-parse', '-q', '--verify', '@{upstream}'):
+ return '@{upstream}..HEAD'
+ p = _principale()
+ return f'{p}..HEAD' if p else 'HEAD~1..HEAD'
+
+def _merge_pulito(h: str) -> bool:
+ return len(_genitori(h)) > 1 and (not git('diff-tree', '--cc', '--no-commit-id', '--name-only', '-r', h))
+
+class SenzaFirme(Exception):
+
+ def __init__(self, sconosciuto: bool=False):
+ super().__init__()
+ self.sconosciuto = sconosciuto
+
+def leggi(intervallo: str, promuovi: bool=False) -> list:
+ r = subprocess.run(['git', 'rev-list', '--reverse', intervallo], capture_output=True, text=True, encoding='utf-8', errors='replace')
+ if r.returncode != 0:
+ raise Rifiuto(F('intervallo_illeggibile', intervallo=intervallo, errore=(r.stderr.strip().splitlines() or ['?'])[0][:200]))
+ voluti = r.stdout.split()[-COMMIT_MAX:]
+ if not voluti:
+ return []
+ remoto = _remoto()
+ puliti = {h for h in voluti if _merge_pulito(h)}
+ da_chiedere = [h for h in voluti if h not in puliti]
+ d = chiedi('POST', '/api/carta/commit', {'hash': da_chiedere or voluti[:1], 'remoto': remoto, 'promuovi': promuovi, 'segni': {h: {'file': _file(h)} for h in da_chiedere} if promuovi else {}})
+ if d.get('repo_senza_firme'):
+ raise SenzaFirme(bool(d.get('repo_sconosciuto')))
+ carte = d.get('carte') or {} if da_chiedere else {}
+ urgenze = dict(d.get('urgenze') or {}) if da_chiedere else {}
+ senza = [h for h in da_chiedere if carte.get(h) is None]
+ fuori = {}
+ if senza:
+ d2 = chiedi('POST', '/api/carta/commit', {'hash': senza, 'segni': {h: segni(h) for h in senza}, 'remoto': remoto, 'promuovi': promuovi})
+ fuori = d2.get('fuori') or {}
+ urgenze.update(d2.get('urgenze') or {})
+ out = []
+ for h in voluti:
+ msg = git('log', '-1', '--format=%B', h)
+ out.append({'hash': h, 'msg': msg, 'soggetto': (msg.strip().splitlines() or [''])[0][:70], 'pulito': h in puliti, 'carta': carte.get(h), 'fuori': fuori.get(h) or {}, 'urgenza': urgenze.get(h)})
+ return out
+PASSANO = ('firmata', 'libera', 'unita', 'pulito', 'urgente')
+
+def _mancano(k: dict) -> str:
+ nomi = {'prove': F('manca_prove'), 'autore': F('manca_autore'), 'persone': F('manca_persone')}
+ return ', '.join((nomi.get(m, m) for m in k.get('mancano') or []))
+
+def esito(c: dict) -> tuple[str, str]:
+ st, riga = _esito(c)
+ u = c.get('urgenza')
+ if u and st in ('da_firmare', 'zona', 'senza'):
+ return ('urgente', F('urgente', commit=c['hash'][:10], soggetto=c['soggetto'], da=u.get('da') or '?', quando=_quando(u.get('quando') or ''), perche=u.get('perche') or ''))
+ return (st, riga)
+
+def _esito(c: dict) -> tuple[str, str]:
+ corto, sogg = (c['hash'][:10], c['soggetto'])
+ if c['pulito']:
+ return ('pulito', F('merge_pulito', commit=corto, soggetto=sogg))
+ k = c['carta']
+ if k is not None:
+ st = k['stato']
+ if st == 'firmata':
+ return (st, F('firmata', commit=corto, soggetto=sogg))
+ if st == 'libera':
+ return (st, F('libera', commit=corto, soggetto=sogg))
+ if st == 'respinta':
+ return (st, F('respinta', commit=corto, soggetto=sogg))
+ if st == 'scartata':
+ return (st, F('scartata', commit=corto, soggetto=sogg))
+ return ('da_firmare', F('da_firmare', commit=corto, soggetto=sogg, manca=_mancano(k), zone=', '.join((z['codice'] for z in k.get('zone') or []))))
+ fu = c['fuori']
+ lg = fu.get('legame')
+ zone = ', '.join((z['codice'] for z in fu.get('zone') or []))
+ if lg:
+ ramo = lg.get('ramo') or '?'
+ if lg.get('mancano'):
+ return ('zona', F('unita_mancano', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg['mancano'])))
+ if lg.get('scoperte'):
+ return ('zona', F('unita_scoperta', commit=corto, soggetto=sogg, ramo=ramo, zone=', '.join((z['codice'] for z in lg['scoperte']))))
+ aperte = [x for x in lg.get('carte') or [] if x['stato'] not in ('firmata', 'libera')]
+ if lg.get('via') == 'ripreso':
+ return ('da_firmare', F('ripresa_da_firmare', commit=corto, soggetto=sogg, ramo=ramo)) if aperte else ('unita', F('ripresa', commit=corto, soggetto=sogg, ramo=ramo))
+ if aperte:
+ return ('da_firmare', F('unita_da_firmare', commit=corto, soggetto=sogg, ramo=ramo, n=len(aperte)))
+ return ('unita', F('unita', commit=corto, soggetto=sogg, ramo=ramo, n=len(lg.get('carte') or [])))
+ if zone:
+ return ('zona', F('senza_in_zona', commit=corto, soggetto=sogg, zone=zone))
+ return ('senza', F('senza', commit=corto, soggetto=sogg))
+
+def _dice_rotta(h: str, rid: str, perche: str) -> str:
+ return {'non_tornano': F('parole_non_tornano', commit=h[:10], id=rid), 'tolte': F('parole_tolte', commit=h[:10], id=rid)}.get(perche) or F('parole_ignote', commit=h[:10], id=rid)
+
+def controlla(a: list) -> int:
+ intervallo = intervallo_di(a)
+ commit = leggi(intervallo, promuovi=True)
+ if not commit:
+ print(F('nessun_commit', intervallo=intervallo))
+ return 0
+ conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
+ for c in commit:
+ for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
+ print(_dice_rotta(c['hash'], rid, perche))
+ conti['rotte'] += 1
+ st, riga = esito(c)
+ print(riga)
+ if st in ('firmata', 'unita'):
+ conti['firmate'] += 1
+ elif st in ('libera', 'pulito'):
+ conti['libere'] += 1
+ elif st == 'urgente':
+ conti['urgenti'] += 1
+ elif st in ('senza', 'zona'):
+ conti['senza'] += 1
+ else:
+ conti['da_firmare'] += 1
+ print(F('esito', **conti))
+ return 1 if conti['da_firmare'] or conti['rotte'] or conti['senza'] else 0
+
+def _remoto() -> str:
+ remoto = os.environ.get('DELMINIO_FIRME_REPO', '').strip() or git('remote', 'get-url', 'origin')
+ return re.sub('^([A-Za-z][A-Za-z0-9+.-]*://)[^/]*@', '\\1', remoto)
+
+def _quando(iso: str) -> str:
+ return (iso or '')[:16].replace('T', ' ') + ' UTC' if iso else ''
+
+def _richieste(c: dict) -> list:
+ dette, testi = _parole_nel_messaggio(c['msg'])
+ return [(rid, testi.get(rid) or '', imp, impronta(testi.get(rid) or '') == imp) for rid, imp in dette.items()]
+
+def _nome_stato(st: str) -> str:
+ return {'firmata': F('stato_firmata'), 'unita': F('stato_unita'), 'libera': F('stato_libera'), 'pulito': F('stato_pulito'), 'senza': F('stato_senza'), 'da_firmare': F('stato_da_firmare'), 'respinta': F('stato_respinta'), 'zona': F('stato_zona')}.get(st, st)
+
+def _nome_firma(significato: str) -> str:
+ return {'autore': F('significato_autore'), 'revisione': F('significato_revisione'), 'respinta': F('significato_respinta')}.get(significato, significato)
+
+def descrizione(a: list) -> int:
+ intervallo = intervallo_di(a)
+ commit = [c for c in leggi(intervallo) if not c['pulito']]
+ if not commit:
+ print(F('nessun_commit', intervallo=intervallo))
+ return 0
+ out, viste = ([F('descr_parole'), ''], set())
+ for c in commit:
+ for rid, testo, imp, _torna in _richieste(c):
+ if imp in viste:
+ continue
+ viste.add(imp)
+ out += ['> ' + r if r else '>' for r in testo.split('\n')] + ['']
+ if not viste:
+ out += [F('descr_nessuna_parola'), '']
+ file, assistiti, zone, controlli, revisioni = (set(), set(), {}, {}, [])
+ for c in commit:
+ k = c['carta'] or {}
+ file |= set(k.get('file') or _file(c['hash']))
+ if k.get('assistito'):
+ assistiti.add(k['assistito'])
+ for z in k.get('zone') or c['fuori'].get('zone') or []:
+ zone[z['codice']] = z
+ for x in k.get('controlli') or []:
+ controlli[x['codice'], x['comando']] = x['uscita']
+ revisioni += k.get('revisioni') or []
+ stati = {}
+ for c in commit:
+ st, _ = esito(c)
+ stati[st] = stati.get(st, 0) + 1
+ out += [F('descr_fatti'), '', '- ' + F('descr_commit', n=len(commit), file=len(file))]
+ if assistiti:
+ out.append('- ' + F('descr_assistito', con=', '.join(sorted(assistiti))))
+ for z in zone.values():
+ chi = ', '.join(z['firme'].get('persone') or []) or F('descr_chiunque')
+ out.append('- ' + F('descr_zona', codice=z['codice'], cosa=z['cosa'], servono=z['firme']['servono'], chi=chi))
+ for (codice, comando), uscita in controlli.items():
+ out.append('- ' + F('descr_controllo', codice=codice, comando=comando, uscita=uscita))
+ for r in revisioni:
+ out.append('- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r)))
+ out.append('- ' + F('descr_stati', stati=', '.join((f'{_nome_stato(k)} {v}' for k, v in sorted(stati.items())))))
+ print('\n'.join(out))
+ return 0
+
+def _ancore() -> list:
+ out = []
+ for riga in git('log', '--all', '-n', '20000', '--format=%H%x09%(trailers:key=Delminio-Chain,valueonly,separator=%x2C)%x2C%(trailers:key=Delminio-Catena,valueonly,separator=%x2C)').splitlines():
+ h, _, valori = riga.partition('\t')
+ for v in valori.split(','):
+ m = re.fullmatch('\\s*(\\d+) ([0-9a-f]{64})\\s*', v)
+ if m:
+ out.append((h, int(m.group(1)), m.group(2)))
+ return out
+
+def _ancore_rotte(anelli: list) -> tuple:
+ per_seq = {a.get('seq'): a.get('impronta') for a in anelli}
+ ancore = _ancore()
+ return (len(ancore), [(h, seq) for h, seq, imp in ancore if per_seq.get(seq) != imp])
+
+def _dalla_catena(anelli: list) -> dict:
+ d = {'carte': {}, 'firme': {}, 'revisioni': {}, 'zone_dopo': {}, 'scartate': {}, 'prove': {}, 'governo': [], 'chiavi': {}, 'revocate': {}, 'persone': {}, 'regola': None}
+ for a in anelli:
+ try:
+ x = json.loads(a.get('contenuto') or '{}')
+ except ValueError:
+ continue
+ tipo = a.get('tipo')
+ if tipo == 'carta':
+ d['carte'][x.get('id')] = x
+ elif tipo == 'firma':
+ d['firme'].setdefault(x.get('carta'), []).append({**x, '_seq': a.get('seq')})
+ elif tipo == 'revisione':
+ d['revisioni'].setdefault(x.get('carta'), []).append(x)
+ elif tipo == 'zona_dopo':
+ d['zone_dopo'].setdefault(x.get('carta'), []).append(x)
+ elif tipo == 'scartata':
+ d['scartate'][x.get('carta')] = x
+ elif tipo == 'prove':
+ fatte = d['prove'].setdefault(x.get('carta'), {})
+ for p in x.get('controlli') or []:
+ fatte[p.get('codice')] = p
+ elif tipo in ('funzione', 'repo', 'zona', 'lettore', 'urgenza'):
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'chiave':
+ if x.get('creata'):
+ d['chiavi'][x.get('id')] = {**x, '_seq': a.get('seq')}
+ else:
+ d['revocate'].setdefault(x.get('id'), a.get('seq'))
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'persona':
+ if x.get('gesto') == 'entrata':
+ d['persone'].setdefault(x.get('persona'), x)
+ d['governo'].append({'tipo': tipo, **x})
+ elif tipo == 'regola' and x.get('passkey') and (d['regola'] is None):
+ d['regola'] = a.get('seq')
+ d['governo'].append({'tipo': tipo, **x})
+ return d
+
+def _canonico(d: dict) -> str:
+ return json.dumps(d, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
+
+def _da_b64u(s: str) -> bytes:
+ s = str(s or '')
+ return base64.urlsafe_b64decode(s + '=' * (-len(s) % 4))
+
+def _sfida(cosa: dict, nonce: str) -> str:
+ h = hashlib.sha256((_canonico(cosa) + '\n' + nonce).encode('utf-8')).digest()
+ return base64.urlsafe_b64encode(h).rstrip(b'=').decode()
+
+def _firma_valida(alg: int, pem: str, firma: bytes, dati: bytes):
+ try:
+ from cryptography.exceptions import InvalidSignature
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec, ed25519, padding, rsa
+ k = serialization.load_pem_public_key(pem.encode())
+ try:
+ if isinstance(k, ec.EllipticCurvePublicKey):
+ k.verify(firma, dati, ec.ECDSA(hashes.SHA256()))
+ elif isinstance(k, rsa.RSAPublicKey):
+ k.verify(firma, dati, padding.PKCS1v15(), hashes.SHA256())
+ elif isinstance(k, ed25519.Ed25519PublicKey):
+ k.verify(firma, dati)
+ else:
+ return False
+ return True
+ except (InvalidSignature, ValueError):
+ return False
+ except ImportError:
+ pass
+ if not shutil.which('openssl'):
+ return None
+ with tempfile.TemporaryDirectory() as cartella:
+ percorsi = {}
+ for nome, contenuto in (('chiave.pem', pem.encode()), ('firma', firma), ('dati', dati)):
+ percorsi[nome] = os.path.join(cartella, nome)
+ with open(percorsi[nome], 'wb') as h:
+ h.write(contenuto)
+ if alg == -8:
+ cmd = ['openssl', 'pkeyutl', '-verify', '-pubin', '-inkey', percorsi['chiave.pem'], '-rawin', '-in', percorsi['dati'], '-sigfile', percorsi['firma']]
+ else:
+ cmd = ['openssl', 'dgst', '-sha256', '-verify', percorsi['chiave.pem'], '-signature', percorsi['firma'], percorsi['dati']]
+ return subprocess.run(cmd, capture_output=True).returncode == 0
+
+def _origine_sua(origine: str, rp: str) -> bool:
+ from urllib.parse import urlparse
+ if origine.startswith('android:apk-key-hash:'):
+ return origine[len('android:apk-key-hash:'):] in APP_ANDROID
+ return urlparse(origine).hostname == rp
+
+def _dispositivo(f: dict, k: dict, fatti: dict) -> tuple:
+ d = f.get('dispositivo')
+ if not d:
+ if fatti['regola'] is not None and (f.get('_seq') or 0) > fatti['regola']:
+ return (F('res_senza_passkey_dopo'), False)
+ return (F('res_senza_passkey_prima'), True)
+ persona = f.get('persona') or '?'
+ chiave = fatti['chiavi'].get(d.get('chiave'))
+ perche = ''
+ if chiave is None or chiave.get('persona') != persona or (chiave.get('_seq') or 0) > (f.get('_seq') or 0):
+ perche = F('perche_chiave')
+ elif (rev := fatti['revocate'].get(d.get('chiave'))) is not None and rev < (f.get('_seq') or 0):
+ perche = F('perche_revocata')
+ elif {'id': k.get('id'), 'hash': k.get('hash')} not in (d.get('carte') or []):
+ perche = F('perche_commit')
+ if not perche:
+ cosa = {'persona': persona, 'significato': f.get('significato'), 'parole': f.get('parole') or '', 'carte': d.get('carte') or []}
+ try:
+ cdj = _da_b64u(d.get('client'))
+ cd, ad = (json.loads(cdj), _da_b64u(d.get('autenticatore')))
+ except ValueError:
+ cd, ad, cdj = ({}, b'', b'')
+ rp = chiave.get('rp') or ''
+ if cd.get('type') != 'webauthn.get' or cd.get('challenge') != _sfida(cosa, d.get('nonce') or ''):
+ perche = F('perche_sfida')
+ elif not _origine_sua(cd.get('origin') or '', rp) or ad[:32] != hashlib.sha256(rp.encode()).digest():
+ perche = F('perche_origine')
+ elif len(ad) < 37 or ad[32] & 5 != 5:
+ perche = F('perche_persona')
+ else:
+ esito = _firma_valida(int(chiave.get('alg') or 0), chiave.get('pem') or '', _da_b64u(d.get('firma')), ad + hashlib.sha256(cdj).digest())
+ if esito is None:
+ return (F('res_passkey_cieca'), False)
+ if not esito:
+ perche = F('perche_firma')
+ if perche:
+ return (F('res_passkey_non_torna', perche=perche, persona=persona), False)
+ come = F('res_passkey_mail') if chiave.get('provata') == 'mail' else F('res_passkey_password')
+ return (F('res_passkey', nome=chiave.get('nome') or '—', persona=persona, quando=_quando(chiave.get('quando')), come=come), True)
+
+def _chi_e_entrato(persona: str, fatti: dict) -> str:
+ e = fatti['persone'].get(persona) or {}
+ k = next((x for x in fatti['chiavi'].values() if x.get('persona') == persona), {})
+ quando = e.get('quando') or k.get('entrata') or ''
+ da = e.get('invitata_da') or k.get('invitata_da') or ''
+ if not quando:
+ return ''
+ return F('res_persona', persona=persona, quando=_quando(quando), da=F('res_persona_invitata', chi=da) if da else F('res_persona_da_sempre'))
+
+def _verifica(anelli: list) -> tuple:
+ rotto = verifica_catena(anelli)
+ if rotto is not None:
+ return (F('catena_rotta', anello=rotto), False)
+ n, rotte = _ancore_rotte(anelli)
+ if rotte:
+ h, seq = rotte[0]
+ return (F('ancora_rotta', commit=h[:10], anello=seq, n=len(rotte)), False)
+ return (F('catena_ancorata', n=n) if n else F('catena_non_ancorata'), True)
+
+def _governo(g: dict) -> str:
+ quando, chi = (_quando(g.get('quando')), g.get('chi') or '?')
+ if g['tipo'] == 'funzione':
+ if g.get('accesa'):
+ return F('gov_accese', quando=quando, chi=chi)
+ return F('gov_spente', quando=quando, chi=chi)
+ if g['tipo'] == 'repo':
+ if g.get('firme'):
+ return F('gov_repo_si', quando=quando, chi=chi, repo=g.get('repo') or '?')
+ return F('gov_repo_no', quando=quando, chi=chi, repo=g.get('repo') or '?')
+ if g['tipo'] == 'regola':
+ return F('gov_passkey', quando=quando)
+ if g['tipo'] == 'persona':
+ if g.get('gesto') == 'entrata':
+ return F('gov_persona_entrata', quando=quando, persona=g.get('persona') or '?', ruolo=g.get('ruolo') or '?', chi=g.get('invitata_da') or '?')
+ if g.get('gesto') == 'spenta':
+ return F('gov_persona_spenta', quando=quando, persona=g.get('persona') or '?')
+ return F('gov_persona_riaccesa', quando=quando, persona=g.get('persona') or '?')
+ if g['tipo'] == 'chiave':
+ if g.get('creata'):
+ come = F('res_passkey_mail') if g.get('provata') == 'mail' else F('res_passkey_password')
+ return F('gov_passkey_nuova', quando=quando, persona=g.get('persona') or '?', nome=g.get('nome') or '—', rp=g.get('rp') or '?', come=come)
+ return F('gov_passkey_revocata', quando=quando, chi=chi, persona=g.get('persona') or '?', nome=g.get('nome') or '—')
+ if g['tipo'] == 'urgenza':
+ return F('gov_urgenza', quando=quando, chi=chi, commit=(g.get('hash') or '?')[:10], repo=g.get('remoto') or '?', perche=g.get('perche') or '')
+ if g['tipo'] == 'lettore':
+ if g.get('creata'):
+ return F('gov_chiave_si', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
+ return F('gov_chiave_no', quando=quando, chi=chi, etichetta=g.get('etichetta') or '?')
+ prima, dopo = (g.get('prima'), g.get('dopo'))
+
+ def detta(z):
+ f = z['firme']
+ return F('gov_zona_detta', dove=', '.join(z.get('dove') or []), servono=f.get('servono'), chi=', '.join(f.get('persone') or []) or F('descr_chiunque'), comando=z.get('comando') or '-')
+ if not prima:
+ return F('gov_zona_nata', quando=quando, chi=chi, codice=g.get('codice') or '?', zona=detta(dopo))
+ if not dopo:
+ return F('gov_zona_ritirata', quando=quando, chi=chi, codice=g.get('codice') or '?')
+ return F('gov_zona_cambiata', quando=quando, chi=chi, codice=g.get('codice') or '?', prima=detta(prima), dopo=detta(dopo))
+
+def _parole_dal_git(k: dict) -> list:
+ if subprocess.run(['git', 'cat-file', '-e', k['hash'] + '^{commit}'], capture_output=True).returncode:
+ return None
+ registrate = {x['impronta'] for x in k.get('richieste') or []}
+ return [(rid, testo, imp, torna, imp in registrate) for rid, testo, imp, torna in _richieste({'msg': git('log', '-1', '--format=%B', k['hash'])})]
+
+def _scrivi_parole(out: list, righe, rientro: str) -> None:
+ for rid, testo, imp, torna, *registrata in righe:
+ ok = torna and (not registrata or registrata[0])
+ out.append(rientro + '- ' + F('res_richiesta', id=rid, impronta=imp[:16], torna=F('res_torna') if ok else F('res_non_torna')))
+ out += [rientro + ' > ' + r if r else rientro + ' >' for r in testo.split('\n')]
+
+def resoconto(a: list) -> int:
+ intervallo = intervallo_di(a[:1])
+ dove = a[1] if len(a) > 1 else ''
+ commit = leggi(intervallo)
+ anelli = chiedi('GET', '/api/carta/catena').get('anelli') or []
+ verdetto, ok = _verifica(anelli)
+ fatti = _dalla_catena(anelli)
+ out = [F('res_titolo', remoto=_remoto() or '?', intervallo=intervallo), '', F('res_generato', quando=datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC'), anelli=len(anelli), esito=verdetto), '']
+ for c in commit:
+ st, riga = esito(c)
+ out += [f"## {c['hash'][:10]} — {c['soggetto']}", '', '- ' + F('res_stato', riga=riga.strip())]
+ if c['pulito']:
+ out.append('')
+ continue
+ carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
+ if not c['carta'] and carte:
+ out.append('- ' + F('res_unita', n=len(carte), ramo=c['fuori']['legame'].get('ramo') or '?'))
+ ct = git('log', '-1', '--format=%ct', c['hash'])
+ quando = datetime.datetime.fromtimestamp(int(ct), datetime.timezone.utc).strftime('%Y-%m-%d %H:%M UTC') if ct.isdigit() else ''
+ out.append('- ' + F('res_unito_da', chi=git('log', '-1', '--format=%cn', c['hash']), quando=quando))
+ if not carte:
+ out.append('- ' + F('res_git_dice', autore=git('log', '-1', '--format=%an <%ae>', c['hash'])))
+ for k in carte:
+ dentro = ' ' if not c['carta'] else ''
+ if not c['carta']:
+ out.append(f"- `{k['hash'][:10]}` {k.get('soggetto') or ''}")
+ dalla = fatti['carte'].get(k['id'])
+ if dalla is None:
+ out.append(dentro + '- ' + F('res_non_in_catena'))
+ ok = False
+ out.append(dentro + '- ' + F('res_autore', autore=(dalla or k)['autore'], con=(dalla or k).get('assistito') or F('res_a_mano'), quando=_quando((dalla or k).get('quando'))))
+ for z in (dalla or k).get('zone') or []:
+ out.append(dentro + '- ' + F('res_zona', codice=z['codice'], cosa=z['cosa'], servono=max(int(z['firme'].get('servono') or 0), 2)))
+ for zd in fatti['zone_dopo'].get(k['id']) or []:
+ out.append(dentro + '- ' + F('res_zona_dopo', quando=_quando(zd.get('quando')), zone=', '.join((z['codice'] for z in zd.get('zone') or []))))
+ dopo = fatti['prove'].get(k['id']) or {}
+ for p in (dalla or k).get('prove') or []:
+ fatta = next((x for x in [dopo.get(p['codice'])] + list((dalla or k).get('controlli') or []) if x and x['codice'] == p['codice'] and (x['comando'] == p['comando'])), None)
+ out.append(dentro + '- ' + (F('descr_controllo', codice=p['codice'], comando=p['comando'], uscita=fatta['uscita']) if fatta else F('res_prova_mancante', codice=p['codice'], comando=p['comando'])))
+ for r in fatti['revisioni'].get(k['id']) or []:
+ out.append(dentro + '- ' + F('descr_revisione', chi=r.get('persona') or F('chi_non_detto'), revisore=r['revisore'], esito=r['esito'], rilievi=r['rilievi'], indipendente=_indipendente(r, k.get('autore', ''))))
+ firme_catena = fatti['firme'].get(k['id']) or []
+ for f in firme_catena:
+ out.append(dentro + '- ' + F('res_firma', persona=f['persona'], significato=_nome_firma(f['significato']), quando=_quando(f['quando']), parole=' — «' + f['parole'] + '»' if f.get('parole') else ''))
+ riga, buona = _dispositivo(f, k, fatti)
+ out.append(dentro + ' - ' + riga)
+ if (chi_e := _chi_e_entrato(f['persona'], fatti)):
+ out.append(dentro + ' - ' + chi_e)
+ ok = ok and buona
+ if {(f['persona'], f['significato']) for f in firme_catena} != {(f['persona'], f['significato']) for f in k.get('firme') or []}:
+ out.append(dentro + '- ' + F('res_firme_diverse', motore=', '.join((f"{f['persona']} ({_nome_firma(f['significato'])})" for f in k.get('firme') or [])) or '-'))
+ ok = False
+ if not firme_catena and (k.get('zone') or []):
+ out.append(dentro + '- ' + F('res_nessuna_firma'))
+ if (sc := fatti['scartate'].get(k['id'])):
+ out.append(dentro + '- ' + F('res_scartata', quando=_quando(sc.get('quando')), perche=sc.get('perche') or ''))
+ if not c['carta']:
+ parole = _parole_dal_git(k)
+ if parole is None:
+ out.append(dentro + '- ' + F('res_parole_altrove', commit=k['hash'][:10], ramo=k.get('ramo') or '?'))
+ else:
+ _scrivi_parole(out, parole, dentro)
+ if c['carta'] or not carte:
+ _scrivi_parole(out, _richieste(c), '')
+ for rid, perche in _parole_rotte(c['hash'], c['msg'], c['carta']):
+ if perche == 'tolte':
+ out.append('- ' + _dice_rotta(c['hash'], rid, perche).strip())
+ file = (c['carta'] or {}).get('file') or _file(c['hash'])
+ out.append('- ' + F('res_file', n=len(file), elenco=', '.join((f'`{x}`' for x in file[:30])) + (f' (+{len(file) - 30})' if len(file) > 30 else '')))
+ out.append('')
+ if fatti['governo']:
+ out += [F('res_governo'), ''] + ['- ' + _governo(g) for g in fatti['governo']] + ['']
+ out += [F('res_come_verificare'), '']
+ testo = '\n'.join(out) + '\n'
+ if dove.lower().endswith(('.html', '.htm')):
+ conti = {'firmate': 0, 'da_firmare': 0, 'libere': 0, 'senza': 0, 'rotte': 0, 'urgenti': 0}
+ for c in commit:
+ st = esito(c)[0]
+ chiave = {'firmata': 'firmate', 'unita': 'firmate', 'libera': 'libere', 'pulito': 'libere', 'urgente': 'urgenti', 'senza': 'senza', 'zona': 'senza'}.get(st, 'da_firmare')
+ conti[chiave] += 1
+ testo = _html(testo, F('esito', **conti), ok)
+ elif dove.lower().endswith('.csv'):
+ testo = _csv(commit, fatti, ok)
+ if dove:
+ with open(dove, 'w', encoding='utf-8') as h:
+ h.write(testo)
+ print(F('res_scritto', file=dove, commit=len(commit)))
+ else:
+ sys.stdout.write(testo)
+ return 0 if ok else 1
+_STILE = '\n:root{--fondo:#f6f4ef;--carta:#fff;--testo:#1d1b18;--piano:#6b665c;--oro:#a77d1c;--verde:#2f7d4f;--rosso:#b3362c;--ambra:#b7791f}\n*{box-sizing:border-box}body{margin:0;background:var(--fondo);color:var(--testo);font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif}\nmain{max-width:980px;margin:0 auto;padding:32px 20px 60px}h1{font:600 26px/1.25 Georgia,serif;margin:0 0 6px}\n.sotto{color:var(--piano);margin:0 0 18px}.conto{background:var(--carta);border-radius:10px;padding:14px 18px;margin:0 0 22px;\nborder-left:5px solid var(--oro);font-weight:600}.catena-ok{border-left-color:var(--verde)}.catena-no{border-left-color:var(--rosso)}\nsection{background:var(--carta);border-radius:10px;padding:16px 20px;margin:0 0 14px;border-left:5px solid #ccc;box-shadow:0 1px 2px #0001}\nsection.ok{border-left-color:var(--verde)}section.no{border-left-color:var(--rosso)}section.urgente{border-left-color:var(--ambra)}\nh2{font:600 17px/1.3 Georgia,serif;margin:0 0 8px}ul{margin:4px 0;padding-left:20px}li{margin:2px 0}\ncode{font:13px ui-monospace,Menlo,Consolas,monospace;background:#efece4;padding:1px 5px;border-radius:4px}\nli.parole{list-style:none}blockquote{margin:2px 0 8px 0;padding:4px 12px;border-left:3px solid var(--oro);background:#faf7ef;font-style:italic}\n@media print{body{background:#fff}section,.conto{box-shadow:none;break-inside:avoid}main{padding:0}}\n'
+
+def _inline_html(t: str) -> str:
+ import html
+ pezzi = re.split('(`[^`]+`)', t)
+ out = []
+ for p in pezzi:
+ if len(p) > 1 and p.startswith('`') and p.endswith('`'):
+ out.append('<code>' + html.escape(p[1:-1]) + '</code>')
+ else:
+ out.append(re.sub('\\*\\*(.+?)\\*\\*', '<b>\\1</b>', html.escape(p)))
+ return ''.join(out)
+
+def _html(testo: str, conto: str, catena_ok: bool) -> str:
+ import html
+ righe, corpo, livello, sezione = (testo.splitlines(), [], 0, False)
+ titolo = next((r[2:] for r in righe if r.startswith('# ')), '')
+
+ def chiudi_liste(fino: int=0) -> None:
+ nonlocal livello
+ while livello > fino:
+ corpo.append('</ul>')
+ livello -= 1
+ for i, r in enumerate(righe):
+ if r.startswith('# '):
+ continue
+ if r.startswith('## '):
+ chiudi_liste()
+ if sezione:
+ corpo.append('</section>')
+ stato = next((x for x in righe[i + 1:i + 4] if x.startswith('- ')), '')
+ classe = 'ok' if '✅' in stato else 'urgente' if '⚡' in stato else 'no' if '❌' in stato else ''
+ corpo.append(f'<section class="{classe}"><h2>{_inline_html(r[3:])}</h2>')
+ sezione = True
+ continue
+ m = re.match('^( *)- (.*)$', r)
+ if m:
+ voluto = len(m.group(1)) // 2 + 1
+ if voluto > livello:
+ while livello < voluto:
+ corpo.append('<ul>')
+ livello += 1
+ else:
+ chiudi_liste(voluto)
+ corpo.append(f'<li>{_inline_html(m.group(2))}</li>')
+ continue
+ q = r.lstrip()
+ if q == '>' or q.startswith('> '):
+ corpo.append(f'<li class="parole"><blockquote>{_inline_html(q[2:])}</blockquote></li>' if livello else f'<blockquote>{_inline_html(q[2:])}</blockquote>')
+ continue
+ chiudi_liste()
+ if r.strip():
+ if sezione:
+ corpo.append('</section>')
+ sezione = False
+ corpo.append(f'<p class="sotto">{_inline_html(r)}</p>')
+ chiudi_liste()
+ if sezione:
+ corpo.append('</section>')
+ return f"""<!doctype html>\n<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>{html.escape(titolo)}</title><style>{_STILE}</style></head><body><main><h1>{_inline_html(titolo)}</h1><div class="conto {('catena-ok' if catena_ok else 'catena-no')}">{_inline_html(conto)}</div>""" + '\n'.join(corpo) + '</main></body></html>\n'
+COLONNE_CSV = ('commit', 'committed_at', 'subject', 'status', 'author', 'agent', 'zones', 'checks', 'reviews', 'signoffs', 'signoff_devices_verified', 'urgent_by', 'urgent_at', 'urgent_reason', 'chain_verified')
+
+def _cella(x) -> str:
+ x = '' if x is None else str(x)
+ return "'" + x if x[:1] in ('=', '+', '-', '@', '\t', '\r') else x
+
+def _csv(commit: list, fatti: dict, catena_ok: bool) -> str:
+ import csv
+ import io
+ buf = io.StringIO()
+ w = csv.writer(buf, lineterminator='\n')
+ w.writerow(COLONNE_CSV)
+ for c in commit:
+ st, _riga = esito(c)
+ carte = [c['carta']] if c['carta'] else (c['fuori'].get('legame') or {}).get('carte') or []
+ autori, agenti, zone, prove, rev, firme, buone = ([], [], [], [], [], [], [])
+ for k in carte:
+ dalla = fatti['carte'].get(k['id']) or k
+ autori.append(dalla['autore'])
+ agenti.append(dalla.get('assistito') or '')
+ zone += [z['codice'] for z in dalla.get('zone') or []]
+ fatte = {**{x['codice']: x for x in dalla.get('controlli') or []}, **(fatti['prove'].get(k['id']) or {})}
+ prove += [f"{p['codice']}:{(fatte[p['codice']]['uscita'] if p['codice'] in fatte else '?')}" for p in dalla.get('prove') or []]
+ rev += [f"{r.get('persona') or '?'}:{r['esito']}" for r in fatti['revisioni'].get(k['id']) or []]
+ for f in fatti['firme'].get(k['id']) or []:
+ firme.append(f"{f['persona']}:{f['significato']}@{(f.get('quando') or '')[:19]}")
+ buone.append(_dispositivo(f, k, fatti)[1])
+ ct = git('log', '-1', '--format=%cI', c['hash'])
+ u = c.get('urgenza') or {}
+ w.writerow([_cella(x) for x in (c['hash'], ct, c['soggetto'], st, ' '.join(dict.fromkeys(autori)) or git('log', '-1', '--format=%ae', c['hash']), ' '.join(dict.fromkeys((a for a in agenti if a))), ' '.join(dict.fromkeys(zone)), ' '.join(dict.fromkeys(prove)), ' '.join(dict.fromkeys(rev)), ' '.join(firme), ('yes' if all(buone) else 'no') if buone else '', u.get('da') or '', (u.get('quando') or '')[:19], u.get('perche') or '', 'yes' if catena_ok else 'no')])
+ return buf.getvalue()
+
+def esporta(a: list) -> int:
+ d = chiedi('GET', '/api/carta/catena')
+ dove = a[0] if a else 'delminio-signoff-' + datetime.date.today().isoformat() + '.json'
+ with open(dove, 'w', encoding='utf-8') as h:
+ json.dump({'anelli': d.get('anelli') or []}, h, ensure_ascii=False, indent=1)
+ verdetto, ok = _verifica(d.get('anelli') or [])
+ print(F('esportata', file=dove, anelli=len(d.get('anelli') or []), esito=verdetto))
+ return 0 if ok else 1
+
+def catena(a: list) -> int:
+ if not a:
+ raise Rifiuto(F('uso', cmd=CMD))
+ anelli = json.load(open(a[0], encoding='utf-8')).get('anelli') or []
+ verdetto, ok = _verifica(anelli)
+ print(F('esportata', file=a[0], anelli=len(anelli), esito=verdetto))
+ if len(a) > 1:
+ vecchi = json.load(open(a[1], encoding='utf-8')).get('anelli') or []
+ per_seq = {x.get('seq'): x.get('impronta') for x in anelli}
+ diverso = next((x.get('seq') for x in vecchi if per_seq.get(x.get('seq')) != x.get('impronta')), None)
+ if verifica_catena(vecchi) is not None or diverso is not None:
+ print(F('copia_diversa', file=a[1], anello=diverso if diverso is not None else verifica_catena(vecchi)))
+ ok = False
+ else:
+ print(F('copia_uguale', file=a[1], anelli=len(vecchi)))
+ return 0 if ok else 1
+
+def _indipendente(r: dict, autore: str='') -> str:
+ if not r.get('indipendente'):
+ return F('stessa_sessione')
+ if autore and r.get('persona') == autore:
+ return F('dell_autore')
+ return F('indipendente_stesso_modello') if r.get('stesso_modello') else F('indipendente')
+
+def revisione(a: list) -> int:
+ if len(a) > 1:
+ a[1] = {'clean': 'pulita', 'findings': 'rilievi'}.get(a[1], a[1])
+ sess = os.environ.get('DELMINIO_SESSIONE', '')
+ if len(a) < 2 or a[1] not in ('pulita', 'rilievi'):
+ raise Rifiuto(F('uso', cmd=CMD))
+ if not sess:
+ raise Rifiuto(F('revisione_senza_sessione', cmd=CMD))
+ rilievi = int(a[2]) if len(a) > 2 and a[2].isdigit() else 0
+ voluti = git('rev-list', '--no-merges', '--reverse', a[0]).split() if '..' in a[0] else [git('rev-parse', a[0]) or a[0]]
+ for h in voluti[-COMMIT_MAX:]:
+ try:
+ r = chiedi('POST', '/api/carta/revisione', {'hash': h, 'esito': a[1], 'rilievi': rilievi, 'sessione': sess})
+ except Rifiuto as e:
+ print(f' {h[:10]} {e}', file=sys.stderr)
+ continue
+ ultima = (r.get('revisioni') or [{}])[-1]
+ print(F('revisione_dell_autore', commit=h[:10]) if ultima.get('persona') == r.get('autore') else F('revisione_registrata', commit=h[:10]))
+ return 0
+
+def _stato(nome: str) -> str:
+ return os.path.join(STATO, nome)
+
+def _richiesta(a: list) -> int:
+ sess = a[0] if a else ''
+ try:
+ testo = json.load(sys.stdin).get('prompt') or ''
+ except Exception:
+ return 0
+ if not sess or not isinstance(testo, str) or (not testo.strip()):
+ return 0
+ nascosto = F('nascosto')
+ for r in ('-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]+?-----END [A-Z ]*PRIVATE KEY-----', 'eyJ[A-Za-z0-9_-]{8,}\\.eyJ[A-Za-z0-9_-]{8,}\\.[A-Za-z0-9_-]{16,}', '\\bsk-[A-Za-z0-9_-]{20,}', '\\b(?:ghp|gho|ghu|ghs|github_pat)_[A-Za-z0-9_]{20,}', '\\bAKIA[0-9A-Z]{16}\\b', '\\bxox[abprs]-[A-Za-z0-9-]{10,}', '\\bAIza[0-9A-Za-z_-]{35}\\b', '\\bglpat-[A-Za-z0-9_-]{20,}'):
+ testo = re.sub(r, nascosto, testo)
+ testo = re.sub('(?i)\\b(password|passwd|pwd|secret|token|api[_-]?key)(\\s*[:=]\\s*)\\S+', '\\1\\2' + nascosto, testo)
+ testo = forma(testo)
+ if len(testo) > MASSIMO:
+ testo = forma(testo[:MASSIMO] + '\n' + F('troncata', n=len(testo) - MASSIMO))
+ voce = {'impronta': impronta(testo), 'testo': testo}
+ try:
+ r = chiedi('POST', '/api/carta/richiesta', {'sessione': sess, 'impronta': voce['impronta'], 'remoto': _remoto()}, attesa=3)
+ voce.update(id=r['id'], quando=r['quando'])
+ _segno(True)
+ except Rifiuto as e:
+ if e.codice == 409:
+ return 0
+ if e.codice in (403, 404):
+ _segno(False)
+ return 0
+ voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
+ except Exception:
+ voce['quando'] = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds')
+ fd = os.open(_stato(f'carta-{sess}.jsonl'), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 384)
+ with os.fdopen(fd, 'a', encoding='utf-8') as h:
+ h.write(json.dumps(voce, ensure_ascii=False) + '\n')
+ return 0
+
+def _segno(accese: bool) -> None:
+ si, no = (_stato('carta'), _stato('carta-no'))
+ try:
+ open(si if accese else no, 'a').close()
+ os.remove(no if accese else si)
+ except OSError:
+ pass
+
+def _voci(sess: str) -> list:
+ voci = []
+ if not sess:
+ return voci
+ try:
+ for riga in open(_stato(f'carta-{sess}.jsonl'), encoding='utf-8'):
+ try:
+ voci.append(json.loads(riga))
+ except ValueError:
+ pass
+ except OSError:
+ pass
+ return voci
+
+def _messaggio(a: list) -> int:
+ file, sess, controlli_f = (a + ['', '', ''])[:3]
+ carta = json.loads(os.environ.get('DELMINIO_DURI') or '{}').get('carta') or {}
+ try:
+ controlli = json.load(open(controlli_f, encoding='utf-8'))
+ except (OSError, ValueError):
+ controlli = []
+ voci = _voci(sess)
+ blocco = []
+ if voci:
+ blocco.append(F('intestazione'))
+ for v in voci:
+ blocco.append(f"[{v.get('id') or '-'}] {_quando(v.get('quando'))}" + ('' if v.get('id') else ' · ' + F('non_registrata')))
+ blocco += ['> ' + r if r else '>' for r in v['testo'].split('\n')]
+ blocco.append('')
+ if controlli:
+ blocco.append(F('controlli'))
+ blocco += [f" {c['codice']} `{c['comando']}` → {c['uscita']}" for c in controlli]
+ blocco.append('')
+ testo = open(file, encoding='utf-8').read()
+ if blocco:
+ righe = testo.rstrip('\n').split('\n')
+ fine = len(righe)
+ while fine > 0 and righe[fine - 1].startswith('#'):
+ fine -= 1
+ inizio = fine
+ while inizio > 0 and righe[inizio - 1].strip():
+ inizio -= 1
+ trailer = inizio > 0 and all((re.match('^[A-Za-z0-9-]+: ', r) for r in righe[inizio:fine]))
+ punto = inizio if trailer else fine
+ nuove = righe[:punto] + ([''] if punto and righe[punto - 1].strip() else []) + blocco + righe[punto:]
+ with open(file, 'w', encoding='utf-8') as h:
+ h.write('\n'.join(nuove).rstrip('\n') + '\n')
+ aggiunti = ['Assisted-by: ' + carta['assistito']] if carta.get('assistito') else []
+ aggiunti += [f"Delminio-Request: {v['id']} {v['impronta']}" for v in voci if v.get('id')]
+ testa = carta.get('catena') or {}
+ if isinstance(testa.get('seq'), int) and re.fullmatch('[0-9a-f]{64}', str(testa.get('impronta') or '')):
+ aggiunti.append(f"Delminio-Chain: {testa['seq']} {testa['impronta']}")
+ gia = open(file, encoding='utf-8').read()
+ for t in aggiunti:
+ if t.replace('Delminio-Request:', 'Delminio-Richiesta:').replace('Delminio-Chain:', 'Delminio-Catena:') in gia.splitlines():
+ continue
+ subprocess.run(['git', 'interpret-trailers', '--in-place', '--if-exists', 'addIfDifferent', '--trailer', t, file], check=False)
+ with open(_stato(f"carta-incluse-{sess or 'mano'}.json"), 'w', encoding='utf-8') as h:
+ json.dump({'impronte': [v['impronta'] for v in voci], 'richieste': [v['id'] for v in voci if v.get('id')], 'controlli': controlli}, h)
+ zone = carta.get('zone') or []
+ if zone:
+ print(F('zona', zone=', '.join((f"{z['codice']} «{z['cosa']}»" for z in zone))), file=sys.stderr)
+ return 0
+
+def _commit(a: list) -> int:
+ sess = a[0] if a else ''
+ incl = _stato(f"carta-incluse-{sess or 'mano'}.json")
+ try:
+ d = json.load(open(incl, encoding='utf-8'))
+ except (OSError, ValueError):
+ return 0
+ try:
+ os.remove(incl)
+ except OSError:
+ pass
+ file = [f for f in git('show', '--name-only', '--format=', '-z', 'HEAD').split('\x00') if f.strip()]
+ controlli = list(d.get('controlli') or [])
+ fatte = _gira_prove(git('rev-parse', 'HEAD'), file)
+ if fatte:
+ gia = {x['codice'] for x in fatte}
+ controlli = [x for x in controlli if x.get('codice') not in gia] + fatte
+ dette = list(_parole_nel_messaggio(git('log', '-1', '--format=%B', 'HEAD'))[0])
+ richieste = list(dict.fromkeys([str(x) for x in d.get('richieste') or []] + dette))
+ print(json.dumps({'file': file[:400], 'richieste': [int(x) for x in richieste if x.isdigit()], 'controlli': controlli}))
+ scritte = set(d.get('impronte') or [])
+ if scritte and sess:
+ p = _stato(f'carta-{sess}.jsonl')
+ try:
+ resta = [r for r in open(p, encoding='utf-8') if json.loads(r).get('impronta') not in scritte]
+ with open(p, 'w', encoding='utf-8') as h:
+ h.writelines(resta)
+ except (OSError, ValueError):
+ pass
+ return 0
+
+def _segni(a: list) -> int:
+ h = git('rev-parse', a[0] if a else 'HEAD')
+ if not h:
+ return 0
+ sg = segni(h)
+ nome = git('rev-parse', '--abbrev-ref', 'HEAD')
+ print(json.dumps({'albero': sg['albero'], 'patch': sg['patch'], 'ramo': _ramo(h, '' if nome == 'HEAD' else nome)}))
+ return 0
+
+def _prove_chieste(h: str, file: list) -> list:
+ if not file or not URL or (not TOKEN):
+ return []
+ try:
+ r = chiedi('POST', '/api/lock/commit', {'staged': file, 'sessione': '', 'remoto': os.environ.get('DELMINIO_REMOTO') or _remoto()}, attesa=8)
+ except Rifiuto:
+ return []
+ return (r.get('carta') or {}).get('prove') or []
+
+def _gira_prove(h: str, file: list) -> list | None:
+ prove = _prove_chieste(h, file)
+ if not prove:
+ return []
+ uguale = git('rev-parse', 'HEAD') == h and subprocess.run(['git', 'diff', '--quiet', 'HEAD'], capture_output=True).returncode == 0 and (subprocess.run(['git', 'diff', '--cached', '--quiet', 'HEAD'], capture_output=True).returncode == 0)
+ if not uguale:
+ print(F('prove_albero_diverso', zone=', '.join((p['codice'] for p in prove)), commit=h[:10]), file=sys.stderr)
+ return None
+ try:
+ accettate = set(open(os.environ.get('DELMINIO_ACCETTATE') or git('rev-parse', '--git-path', 'delminio-guardie-accettate'), encoding='utf-8').read().split())
+ except OSError:
+ accettate = set()
+ radice = git('rev-parse', '--show-toplevel') or '.'
+ fatte = []
+ for p in prove:
+ if hashlib.sha256((p['codice'] + '\x00' + p['comando']).encode()).hexdigest() not in accettate:
+ print(F('prova_non_accettata', codice=p['codice'], comando=p['comando']), file=sys.stderr)
+ continue
+ try:
+ e = subprocess.run(p['comando'], shell=True, cwd=radice, capture_output=True, text=True, timeout=PROVE_TEMPO)
+ rc, uscita = (e.returncode, (e.stdout or '') + (e.stderr or ''))
+ except subprocess.TimeoutExpired:
+ rc, uscita = (124, '')
+ fatte.append({'codice': p['codice'], 'comando': p['comando'], 'uscita': rc})
+ if rc == 0:
+ print(F('prova_passata', codice=p['codice']), file=sys.stderr)
+ else:
+ print(F('prova_fallita', codice=p['codice'], comando=p['comando'], uscita=rc), file=sys.stderr)
+ for riga in uscita.strip().splitlines()[-15:]:
+ print(' ' + riga, file=sys.stderr)
+ return fatte
+
+def prove(a: list) -> int:
+ h = git('rev-parse', 'HEAD')
+ if a and git('rev-parse', a[0]) != h:
+ print(F('prove_solo_testa'))
+ return 2
+ fatte = _gira_prove(h, _file(h))
+ if fatte is None:
+ return 1
+ if not fatte:
+ print(F('prove_nessuna', commit=h[:10]))
+ return 0
+ chiedi('POST', '/api/carta/prove', {'hash': h, 'controlli': fatte})
+ esito = ', '.join((f"{x['codice']} → {x['uscita']}" for x in fatte))
+ print(F('prove_registrate', commit=h[:10], esito=esito))
+ return 0 if all((x['uscita'] == 0 for x in fatte)) else 1
+
+def _riscritti(a: list) -> int:
+ coppie = [r.split()[:2] for r in sys.stdin.read().splitlines() if len(r.split()) >= 2 and r.split()[0] != r.split()[1]]
+ sg = {}
+ if a and a[0] == 'segni':
+ for _vecchio, nuovo in coppie:
+ s = segni(nuovo)
+ sg[nuovo] = {'albero': s['albero'], 'patch': s['patch'], 'ramo': _ramo(nuovo)}
+ print(json.dumps({'vecchi': [v for v, _ in coppie], 'coppie': coppie, 'segni': sg}))
+ return 0
+_CI_GITHUB = '# {commento}\nname: delminio-firme\non:\n pull_request:\n push:\n branches: [{ramo}]\njobs:\n controlla:\n runs-on: {macchina}\n steps:\n - uses: actions/checkout@v7\n with:\n fetch-depth: 0\n - name: delminio-firme\n env:\n DELMINIO_URL: {url}\n DELMINIO_FIRME_REPO: {repo}\n DELMINIO_TOKEN: ${{{{ secrets.DELMINIO_FIRME }}}}\n BASE: ${{{{ github.base_ref }}}}\n PRIMA: ${{{{ github.event.before }}}}\n run: |\n curl -fsS -H "Authorization: Bearer $DELMINIO_TOKEN" "$DELMINIO_URL/static/kit/signoff-client" -o "$RUNNER_TEMP/signoff.py"\n if [ -n "$BASE" ]; then\n python3 "$RUNNER_TEMP/signoff.py" controlla "origin/$BASE..HEAD"\n else\n case "$PRIMA" in ""|0000000000000000000000000000000000000000) PRIMA=HEAD~1 ;; esac\n python3 "$RUNNER_TEMP/signoff.py" controlla "$PRIMA..HEAD"\n fi\n'
+_CI_GITLAB = 'delminio-firme:\n image: python:3\n variables:\n GIT_DEPTH: "0"\n DELMINIO_URL: {url}\n DELMINIO_FIRME_REPO: {repo}\n rules:\n - if: $CI_PIPELINE_SOURCE == "merge_request_event"\n script:\n - git fetch -q origin "$CI_MERGE_REQUEST_TARGET_BRANCH_NAME"\n - curl -fsS -H "Authorization: Bearer $DELMINIO_FIRME" "$DELMINIO_URL/static/kit/signoff-client" -o signoff.py\n - DELMINIO_TOKEN="$DELMINIO_FIRME" python3 signoff.py controlla "origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME..HEAD"\n'
+
+def _servizio(a: list) -> str:
+ if a and a[0] in ('github', 'forgejo', 'gitea', 'gitlab'):
+ return 'forgejo' if a[0] == 'gitea' else a[0]
+ host = re.sub('^[a-z][a-z0-9+.-]*://', '', _remoto().lower()).split('@')[-1].split('/')[0].split(':')[0]
+ if host == 'github.com' or host.endswith('.github.com'):
+ return 'github'
+ if 'gitlab' in host:
+ return 'gitlab'
+ if os.path.isdir('.forgejo') or os.path.isdir('.gitea'):
+ return 'forgejo'
+ return ''
+
+def _da_fuori(url: str) -> bool:
+ import ipaddress
+ import urllib.parse
+ host = (urllib.parse.urlparse(url).hostname or '').lower()
+ if not host or host == 'localhost' or '.' not in host or host.endswith(('.local', '.lan', '.home.arpa', '.internal')):
+ return False
+ try:
+ ip = ipaddress.ip_address(host)
+ return not (ip.is_private or ip.is_loopback or ip.is_link_local)
+ except ValueError:
+ return True
+
+def ci(a: list) -> int:
+ servizio = _servizio(a)
+ if not servizio:
+ print(F('ci_quale'))
+ return 2
+ url = os.environ.get('DELMINIO_URL', '').rstrip('/')
+ radice = git('rev-parse', '--show-toplevel') or '.'
+ repo = json.dumps(_remoto())
+ ramo = (git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD') or 'origin/main').split('/', 1)[-1]
+ if not _da_fuori(url):
+ print(F('ci_dentro_casa', url=url))
+ if servizio == 'gitlab':
+ print(F('ci_gitlab', file='.gitlab-ci.yml'))
+ print(_CI_GITLAB.format(url=url, repo=repo))
+ print(F('ci_gitlab_passi'))
+ return 0
+ cartella = '.github' if servizio == 'github' else '.forgejo'
+ file = os.path.join(cartella, 'workflows', 'delminio-firme.yml')
+ testo = _CI_GITHUB.format(commento=F('ci_commento'), ramo=ramo, url=url, repo=repo, macchina='ubuntu-latest' if servizio == 'github' else 'docker')
+ dove = os.path.join(radice, file)
+ if os.path.exists(dove):
+ if open(dove, encoding='utf-8').read() == testo:
+ print(F('ci_gia_pronto', file=file))
+ else:
+ print(F('ci_esiste_diverso', file=file))
+ else:
+ os.makedirs(os.path.dirname(dove), exist_ok=True)
+ with open(dove, 'w', encoding='utf-8') as f:
+ f.write(testo)
+ print(F('ci_scritto', file=file))
+ if servizio == 'github':
+ return _github(ramo)
+ print(F('ci_passi_forgejo', ramo=ramo))
+ return 0
+_CONTROLLO = 'controlla'
+
+def _gh(*a: str, entrata: str | None=None) -> tuple[int, str]:
+ try:
+ r = subprocess.run(['gh', *a], capture_output=True, text=True, input=entrata, timeout=60)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return (1, str(e))
+ return (r.returncode, (r.stdout if r.returncode == 0 else r.stderr or r.stdout).strip())
+
+def _gh_errore(out: str) -> str:
+ righe = [r for r in out.splitlines() if r.strip()]
+ return righe[-1][:300] if righe else '?'
+
+def _github(ramo: str) -> int:
+ if not shutil.which('gh'):
+ print(F('ci_gh_manca'))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ if _gh('auth', 'status')[0] != 0:
+ print(F('ci_gh_non_collegato'))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ rc, out = _gh('repo', 'view', '--json', 'nameWithOwner,viewerPermission')
+ try:
+ r = json.loads(out) if rc == 0 else {}
+ except ValueError:
+ r = {}
+ nwo = r.get('nameWithOwner') or ''
+ if not nwo:
+ print(F('ci_gh_quale_repo', errore=_gh_errore(out)))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ if r.get('viewerPermission') != 'ADMIN':
+ print(F('ci_gh_permessi', repo=nwo))
+ print(F('ci_passi_github', ramo=ramo))
+ return 0
+ regola = _gh_regola(nwo, ramo)
+ segreto = _gh_segreto(nwo)
+ return 0 if regola and segreto else 1
+
+def _gh_regola(nwo: str, ramo: str) -> bool:
+ base = f'repos/{nwo}/branches/{ramo}/protection'
+ rc, out = _gh('api', base)
+ if rc != 0 and 'HTTP 404' not in out:
+ print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ if rc != 0:
+ corpo = {'required_status_checks': {'strict': False, 'contexts': [_CONTROLLO]}, 'enforce_admins': True, 'required_pull_request_reviews': None, 'restrictions': None}
+ rc, out = _gh('api', '-X', 'PUT', base, '--input', '-', entrata=json.dumps(corpo))
+ if rc != 0:
+ print(F('ci_gh_privato', repo=nwo) if 'Upgrade to GitHub Pro' in out else F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ else:
+ d = json.loads(out)
+ rsc = d.get('required_status_checks') or {}
+ if _CONTROLLO not in _gh_controlli(rsc):
+ print(F('ci_gh_regole_altre', ramo=ramo))
+ rc, out = _gh('api', '-X', 'POST', base + '/required_status_checks/contexts', '--input', '-', entrata=json.dumps([_CONTROLLO])) if rsc else _gh('api', '-X', 'PATCH', base + '/required_status_checks', '--input', '-', entrata=json.dumps({'strict': False, 'contexts': [_CONTROLLO]}))
+ if rc != 0:
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ if not (d.get('enforce_admins') or {}).get('enabled'):
+ rc, out = _gh('api', '-X', 'POST', base + '/enforce_admins')
+ if rc != 0:
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out)))
+ return False
+ rc, out = _gh('api', base)
+ d = json.loads(out) if rc == 0 else {}
+ if _CONTROLLO in _gh_controlli(d.get('required_status_checks') or {}) and (d.get('enforce_admins') or {}).get('enabled'):
+ print(F('ci_gh_regola_ok', ramo=ramo, repo=nwo))
+ return True
+ print(F('ci_gh_regola_no', ramo=ramo, errore=_gh_errore(out) if rc else '?'))
+ return False
+
+def _gh_controlli(rsc: dict) -> set:
+ return set(rsc.get('contexts') or []) | {c.get('context') for c in rsc.get('checks') or [] if isinstance(c, dict)}
+
+def _gh_segreto(nwo: str) -> bool:
+ rc, out = _gh('secret', 'list', '--repo', nwo, '--json', 'name')
+ try:
+ nomi = {x.get('name') for x in json.loads(out)} if rc == 0 else set()
+ except ValueError:
+ nomi = set()
+ if rc != 0:
+ print(F('ci_gh_segreto_no', errore=_gh_errore(out)))
+ return False
+ if 'DELMINIO_FIRME' in nomi:
+ print(F('ci_gh_segreto_c_e', repo=nwo))
+ return True
+ imposta = ['gh', 'secret', 'set', 'DELMINIO_FIRME', '--repo', nwo]
+ cmd = ' '.join(imposta)
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
+ print(F('ci_gh_segreto_tu', cmd=cmd))
+ return False
+ print(F('ci_gh_segreto_incolla'))
+ esito = subprocess.run(imposta).returncode
+ if esito != 0:
+ print(F('ci_gh_segreto_no', errore=esito))
+ return False
+ print(F('ci_gh_segreto_fatto', repo=nwo))
+ return True
+VERBI = {'controlla': controlla, 'descrizione': descrizione, 'resoconto': resoconto, 'esporta': esporta, 'catena': catena, 'revisione': revisione, 'prove': prove, 'ci': ci, '_richiesta': _richiesta, '_messaggio': _messaggio, '_commit': _commit, '_segni': _segni, '_riscritti': _riscritti}
+
+def main(argv: list) -> int:
+ verbo = argv[0] if argv else 'controlla'
+ verbo = COMANDI['carta'].get(verbo, verbo)
+ fai = VERBI.get(verbo)
+ if fai is None:
+ print(F('uso', cmd=CMD), file=sys.stderr if verbo not in ('-h', '--help') else sys.stdout)
+ return 0 if verbo in ('-h', '--help') else 2
+ try:
+ return fai(argv[1:])
+ except SenzaFirme as e:
+ if e.sconosciuto:
+ print(F('repo_sconosciuto', remoto=_remoto()), file=sys.stderr)
+ return 2
+ print(F('repo_senza_firme'))
+ return 0
+ except Rifiuto as e:
+ if verbo.startswith('_'):
+ return 0
+ print(str(e), file=sys.stderr)
+ return 2
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/it/ganci-git-client b/kit/it/ganci-git-client
new file mode 100644
index 0000000..2daf4af
--- /dev/null
+++ b/kit/it/ganci-git-client
@@ -0,0 +1,224 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+e_un_close() { grep -qE "^($P_CLOSE) S[0-9]+" <<<"$1"; }
+case "${1:-}" in
+ commit-msg)
+ file="${2:-}"; [ -f "$file" ] || exit 0
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ if [ -n "$sess" ] && ! { f=$(_segno_pubblico) && [ -e "$f" ]; }; then
+ git interpret-trailers --in-place --if-exists doNothing --trailer "Delminio-Sessione: $sess" "$file" 2>/dev/null || true
+ fi
+ staged=$(git diff --cached --name-only -z | python3 -c 'import json,sys; print(json.dumps({"staged": [x for x in sys.stdin.read().split("\0") if x], "sessione": sys.argv[1], "remoto": sys.argv[2]}))' "$sess" "$(_remoto)")
+ controlli_f="$STATO/carta-controlli-$$"; rm -f "$controlli_f"
+ if duri=$(chiedi POST /api/lock/commit "$staged"); then
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ DELMINIO_DURI="$duri" DELMINIO_U="$URL" DELMINIO_T="$TOKEN" DELMINIO_ACCETTATE="$(accettate_file)" \
+ DELMINIO_CONTROLLI_F="$controlli_f" python3 - "$nome" <<'DURI' || exit 1
+import hashlib, json, os, subprocess, sys, urllib.error, urllib.request
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+duri = json.loads(os.environ["DELMINIO_DURI"]).get("duri") or []
+radice = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip() or "."
+try:
+ accettate = set(open(os.environ["DELMINIO_ACCETTATE"], encoding="utf-8").read().split())
+except OSError:
+ accettate = set()
+fermo = False
+fatti = [] # B923: il comando e la sua uscita, le prove nella carta del commit
+GUARDIA_SECONDI = 120 # il controllo del commit ha il suo tempo: ci girano anche i test
+
+
+def manda(percorso, dati):
+ req = urllib.request.Request(os.environ["DELMINIO_U"] + percorso, data=json.dumps(dati).encode(), method="POST",
+ headers={"Authorization": "Bearer " + os.environ["DELMINIO_T"],
+ "Content-Type": "application/json"})
+ return json.loads(urllib.request.urlopen(req, timeout=8).read())
+
+
+def cieco(lk, motivo):
+ """B938 — il controllo non ha detto niente: si conta, e il commit si ferma come per una
+ violazione (le guardie del commit sono tutte di decisioni che bloccano)."""
+ try:
+ manda("/api/lock/cieco", {"codice": lk["codice"], "motivo": motivo, "sessione": sys.argv[1],
+ "comando": lk["comando"]})
+ except Exception:
+ pass # un conto non ferma un commit
+for lk in duri:
+ impronta = hashlib.sha256((lk["codice"] + "\0" + lk["comando"]).encode()).hexdigest()
+ if impronta not in accettate:
+ print(F("guardia_non_accettata", codice=lk["codice"], comando=lk["comando"]), file=sys.stderr)
+ continue
+ fermo_cieco = ""
+ try:
+ p = subprocess.run(lk["comando"], shell=True, cwd=radice, capture_output=True, text=True,
+ timeout=GUARDIA_SECONDI)
+ rc, uscita = p.returncode, p.stdout + p.stderr
+ except subprocess.TimeoutExpired:
+ rc, uscita = 124, F("controllo_lento_breve", comando=lk["comando"], secondi=GUARDIA_SECONDI)
+ fermo_cieco = F("guardia_lento_fermo", codice=lk["codice"], comando=lk["comando"], secondi=GUARDIA_SECONDI)
+ cieco(lk, "lento")
+ except OSError:
+ rc, uscita = 127, ""
+ fatti.append({"codice": lk["codice"], "comando": lk["comando"], "uscita": rc})
+ if rc == 0:
+ continue
+ if rc in (126, 127) and not fermo_cieco:
+ uscita = F("controllo_non_parte_breve", comando=lk["comando"])
+ fermo_cieco = F("guardia_non_parte_fermo", codice=lk["codice"], comando=lk["comando"])
+ cieco(lk, "non_parte")
+ try:
+ r = manda("/api/lock/violazione", {"codice": lk["codice"], "uscita": uscita[-4000:], "sessione": sys.argv[1]})
+ except urllib.error.HTTPError as e:
+ print(F("lock_grida_errore", codice=lk["codice"], codice_http=e.code), file=sys.stderr)
+ r = {"esito": "avviso"}
+ except Exception:
+ print(F("lock_grida_muto", codice=lk["codice"]), file=sys.stderr)
+ r = {"esito": "avviso"}
+ if fermo_cieco and r.get("esito") == "ferma":
+ print(fermo_cieco, file=sys.stderr)
+ print(("❌ " if r.get("esito") == "ferma" else "⚠️ ") + (r.get("messaggio") or lk["cosa"]), file=sys.stderr)
+ if fermo_cieco and r.get("esito") != "ferma":
+ print(" " + uscita.strip(), file=sys.stderr)
+ elif not fermo_cieco:
+ print(F("guardia_dice"), file=sys.stderr)
+ for riga in uscita.strip().splitlines()[-15:]:
+ print(" " + riga, file=sys.stderr)
+ fermo = fermo or r.get("esito") == "ferma"
+with open(os.environ["DELMINIO_CONTROLLI_F"], "w", encoding="utf-8") as h:
+ json.dump(fatti, h)
+sys.exit(1 if fermo else 0)
+DURI
+ case "$duri" in
+ *'"carta":{'*)
+ : > "$STATO/carta"; rm -f "$STATO/carta-no"
+ [ -f "$(dirname "$0")/firme.py" ] && DELMINIO_DURI="$duri" DELMINIO_STATO="$STATO" \
+ python3 "$(dirname "$0")/firme.py" _messaggio "$file" "$sess" "$controlli_f" || true ;;
+ esac
+ rm -f "$controlli_f"
+ else
+ _f "$M_lock_duri_sono" perche "$(perche_no)" >&2
+ fi
+ soggetto=$(grep -v '^#' "$file" | sed -n '/[^[:space:]]/{p;q;}')
+ e_un_close "$soggetto" || exit 0
+ pid=$(cli_pid || true); nome=""; [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ corpo=$(python3 - "$file" "$nome" <<'GIUDIZIO'
+import json, subprocess, sys
+messaggio = open(sys.argv[1], encoding="utf-8").read()
+staged = subprocess.run(["git", "diff", "--cached", "--name-only"],
+ capture_output=True, text=True).stdout.split()
+head = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip()
+print(json.dumps({"messaggio": messaggio, "staged": staged, "sessione": sys.argv[2], "head": head}))
+GIUDIZIO
+)
+ if ! r=$(CHIEDI_TEMPO=45 chiedi POST /api/chiusura/giudica "$corpo"); then
+ _f "$M_chiusura_passa_senza" perche "$(perche_no)" >&2
+ exit 0
+ fi
+ DELMINIO_VERDETTO="$r" python3 - "$file" <<'VERDETTO'
+import json, os, subprocess, sys
+exec(__import__("os").environ["DELMINIO_F_PY"]) # F(): le frasi del client (F665)
+r = json.loads(os.environ["DELMINIO_VERDETTO"])
+if not r.get("ok", True):
+ print(F("chiusura_rifiutata"), file=sys.stderr)
+ for m in r.get("motivi", []):
+ print(f" • {m}", file=sys.stderr)
+ sys.exit(1)
+perche = {"P_TRAILER_TORNATA": F("perche_tornata"), "P_TRAILER_MEMORIA": F("perche_memoria")}
+for k, v in (r.get("aggiungi") or {}).items():
+ subprocess.run(["git", "interpret-trailers", "--in-place", "--trailer", f"{k}: {v}", sys.argv[1]], check=True)
+ spiega = next((x for var, x in perche.items() if k.lower() in os.environ[var].lower().split("|")), "")
+ print(F("aggiunge_trailer_perche", trailer=f"{k}: {v}", perche=spiega) if spiega
+ else F("aggiunge_trailer", trailer=f"{k}: {v}"), file=sys.stderr)
+for a in r.get("avvisi") or []:
+ print(f"⚠️ {a}", file=sys.stderr)
+VERDETTO
+ ;;
+ post-rewrite)
+ coppie=$(awk '$1 != $2 { print $1, $2 }')
+ [ -n "$coppie" ] || exit 0
+ segni=""; [ -f "$STATO/carta" ] && segni=segni
+ f="$STATO/riscritti-$$"; printf '%s\n' "$coppie" > "$f"
+ _staccato bash "$0" post-rewrite-dopo "$f" "$(_remoto)" $segni >/dev/null 2>&1 < /dev/null &
+ ;;
+ post-rewrite-dopo)
+ f=$2
+ corpo=$(python3 "$(dirname "$0")/firme.py" _riscritti ${4:-} < "$f" 2>/dev/null \
+ | python3 -c 'import json, sys; d = json.load(sys.stdin); d["remoto"] = sys.argv[1]; print(json.dumps(d))' "$3") \
+ && chiedi POST /api/repo/riscritti "$corpo" >/dev/null 2>&1
+ rm -f "$f"
+ ;;
+ post-commit)
+ soggetto=$(git log -1 --format=%s 2>/dev/null)
+ pid=$(cli_pid || true); sess=""; [ -n "$pid" ] && sess=$(mia_sessione "$pid")
+ righe=""
+ [ -z "$(git rev-parse -q --verify HEAD^2 2>/dev/null)" ] && righe=$(git show --numstat --format= --diff-filter=d HEAD 2>/dev/null)
+ carta=""
+ [ -f "$(dirname "$0")/firme.py" ] && carta=$(DELMINIO_STATO="$STATO" DELMINIO_URL="$URL" DELMINIO_TOKEN="$TOKEN" \
+ DELMINIO_ACCETTATE="$(accettate_file)" DELMINIO_REMOTO="$(_remoto)" python3 "$(dirname "$0")/firme.py" _commit "$sess")
+ corpo=$(DELMINIO_RIGHE="$righe" DELMINIO_CARTA="$carta" python3 -c '
+import json, os, sys
+d = dict(zip(("remoto", "hash", "sessione", "soggetto"), sys.argv[1:]))
+file = []
+for r in os.environ.get("DELMINIO_RIGHE", "").splitlines():
+ p = r.split("\t", 2)
+ if len(p) == 3 and p[0].isdigit() and p[1].isdigit():
+ file.append((p[2].split("/")[:-1], int(p[0]) + int(p[1])))
+for livelli in (3, 2, 1):
+ righe = {}
+ for cartelle, n in file:
+ k = "/".join(cartelle[:livelli]) or "."
+ righe[k] = righe.get(k, 0) + n
+ if len(righe) <= 150:
+ break
+d["righe"] = righe
+if os.environ.get("DELMINIO_CARTA"):
+ d["carta"] = json.loads(os.environ["DELMINIO_CARTA"])
+print(json.dumps(d))' \
+ "$(_remoto)" "$(git rev-parse HEAD 2>/dev/null)" "$sess" "$soggetto")
+ clone=$(cd "$(dirname "$0")/.." 2>/dev/null && pwd)
+ testa=$(git rev-parse HEAD 2>/dev/null)
+ f="$STATO/commit-$testa.json"; printf '%s' "$corpo" > "$f"
+ _staccato bash "$0" post-commit-dopo "$f" "$testa" "$clone" ${carta:+carta} >/dev/null 2>&1 < /dev/null &
+ e_un_close "$soggetto" || exit 0
+ n=$(printf '%s' "$soggetto" | grep -oE 'S[0-9]+' | head -1)
+ corpo=$(python3 - "$n" "$(_remoto)" <<'CLOSE'
+import json, os, subprocess, sys
+def g(*a):
+ return subprocess.run(["git", *a], capture_output=True, text=True).stdout.strip()
+def chiavi(var): # i nomi di un trailer in ogni lingua (F665), come li vuole git
+ return ",".join("key=" + k for k in os.environ[var].split("|"))
+remoto = sys.argv[2]
+repo = os.path.basename(remoto.rstrip("/"))[:-4] if remoto.rstrip("/").endswith(".git") \
+ else os.path.basename(remoto.rstrip("/"))
+if not repo:
+ repo = os.path.basename(os.path.dirname(os.path.abspath(g("rev-parse", "--git-common-dir"))))
+print(json.dumps({"sessione": sys.argv[1], "close": True, "commit": {
+ "hash": g("rev-parse", "--short=10", "HEAD"), "remoto": remoto, "repo": repo,
+ "tornata": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_TORNATA") + ",valueonly,separator=%x20)"),
+ "audit": g("log", "-1", "--format=%(trailers:" + chiavi("P_TRAILER_AUDIT") + ",valueonly)").strip(),
+ "testo": g("--no-replace-objects", "log", "-1", "--format=%B")}}))
+CLOSE
+)
+ if r=$(chiedi POST /api/canale/sessioni/chiudi "$corpo"); then
+ _f "$M_delminio_chiusa_chi" n "$n" >&2
+ m=$(printf '%s' "$r" | python3 -c 'import json,sys
+try: print(", ".join(json.load(sys.stdin).get("mollate") or []))
+except Exception: print("")')
+ [ -z "$m" ] || _f "$M_opere_avevi_mano" m "$m" >&2
+ else
+ _f "$M_risultera_morta_senza" perche "$(perche_no)" n "$n" >&2
+ fi
+ ;;
+ post-commit-dopo)
+ f=$2; corpo=$(cat "$f" 2>/dev/null); rm -f "$f"
+ [ -n "$corpo" ] || exit 0
+ if [ "${5:-}" = carta ]; then
+ segni=$(python3 "$(dirname "$0")/firme.py" _segni "$3" 2>/dev/null) && con=$(DELMINIO_SEGNI="$segni" python3 -c '
+import json, os, sys
+d = json.loads(sys.stdin.read())
+d["carta"].update(json.loads(os.environ["DELMINIO_SEGNI"]))
+print(json.dumps(d))' <<<"$corpo") && corpo=$con
+ fi
+ r=$(chiedi POST /api/repo/commit "$corpo" 2>/dev/null) \
+ && riaggancia "$(printf '%s' "$r" | campo versione)" "$4" presto
+ ;;
+esac
diff --git a/kit/it/lanciatori-client b/kit/it/lanciatori-client
new file mode 100644
index 0000000..f063f42
--- /dev/null
+++ b/kit/it/lanciatori-client
@@ -0,0 +1,230 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+sonda_sandbox_codex() {
+ python3 - "${DELMINIO_CLI:-codex}" <<'CODEX_SONDA'
+import subprocess, sys
+if sys.platform != 'linux':
+ sys.exit(0)
+cli = sys.argv[1]
+try:
+ r = subprocess.run([cli, 'sandbox', '-c', 'sandbox_mode="read-only"', '--', 'true'],
+ capture_output=True, text=True, timeout=5)
+ print('ok' if r.returncode == 0 else 'rotta')
+except (OSError, subprocess.TimeoutExpired):
+ print('non_verificata')
+CODEX_SONDA
+}
+porta_del_lancio() { # porta_del_lancio <rotta> <frase per chi resta senza agente>
+ local v p
+ f="$STATO/sistema-$$.txt"
+ codice=$( (umask 077; curl -sS -m 30 -G -o "$f" -w '%{http_code}' -K <(_chiave "$TOKEN") \
+ --data-urlencode "ordine=$porta" --data-urlencode "modello=${DELMINIO_MODELLO:-}" \
+ "$URL/api/porte/$1") 2>/dev/null || true)
+ if [ "$codice" != 200 ] || [ ! -s "$f" ]; then
+ _f "$M_delminio_dato_system" url "$URL" porta "$porta" codice "${codice:-000}" >&2
+ [ -s "$f" ] && { head -c 400 "$f" >&2; echo >&2; }
+ echo "$2" >&2
+ rm -f "$f"
+ exit 1
+ fi
+ for v in "$STATO"/sistema-*.txt "$STATO"/qwen-posta-*.jsonl "$STATO"/qwen-mcp-*.json; do
+ [ -e "$v" ] || continue
+ p=${v##*/sistema-}; p=${p##*/qwen-posta-}; p=${p##*/qwen-mcp-}; p=${p%.txt}; p=${p%.jsonl}; p=${p%.json}
+ [ "$p" = "$$" ] || kill -0 "$p" 2>/dev/null || rm -f "$v"
+ done
+}
+case "${1:-}" in
+ claude)
+ shift
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ rotta=nascita; [ "${DELMINIO_NASCITA:-intera}" = porta ] && rotta=sistema
+ porta_del_lancio "$rotta" "$M_agente_parte_meta"
+ export DELMINIO_SISTEMA=1
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/plugin.py" ] \
+ && [ "$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" \
+ = "$(git -C "$(dirname "$0")/.." rev-parse --path-format=absolute --git-common-dir 2>/dev/null)" ]; then
+ DELMINIO_CLAUDE="${DELMINIO_CLI:-claude}" python3 "$(dirname "$0")/plugin.py" claude-al-lancio \
+ "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" >/dev/null 2>&1 || true
+ fi
+ squadra=()
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ while IFS= read -r x; do [ -n "$x" ] && squadra+=("$x"); done < <(python3 "$(dirname "$0")/squadra.py" \
+ lancio claude "$(git rev-parse --show-toplevel 2>/dev/null || pwd)" 2>/dev/null)
+ fi
+ exec "${DELMINIO_CLI:-claude}" --system-prompt-file "$f" ${squadra[@]+"${squadra[@]}"} "$@"
+ ;;
+ codex)
+ shift
+ export DELMINIO_CLI_NOME=codex
+ DELMINIO_SANDBOX_LINUX=$(sonda_sandbox_codex); export DELMINIO_SANDBOX_LINUX
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ [ "${DELMINIO_NASCITA:-intera}" = porta ] && {
+ echo "$M_ruolo_sola_sua" >&2
+ exit 1; }
+ porta_del_lancio nascita "$M_agente_parte_meta_2"
+ export DELMINIO_SISTEMA=1
+ mcp=()
+ if [ -n "${DELMINIO_SENZA_PLUGIN:-}" ] || [ -z "${CODEX_HOME:-}" ] \
+ || ! DELMINIO_CODEX="${DELMINIO_CLI:-codex}" python3 "$(dirname "$0")/plugin.py" codex "$CODEX_HOME" >/dev/null 2>&1; then
+ [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && echo "$M_codex_senza_plugin" >&2
+ export DELMINIO_MCP_TOKEN="$TOKEN"
+ mcp=(-c "mcp_servers.memoria.url=\"$URL/mcp\"" -c 'mcp_servers.memoria.bearer_token_env_var="DELMINIO_MCP_TOKEN"'
+ -c 'mcp_servers.memoria.env_http_headers={"X-Delminio-Modello"="DELMINIO_MODELLO"}'
+ -c 'mcp_servers.memoria.tools.delminio.approval_mode="approve"'
+ -c 'mcp_servers.memoria.tools.delminio_write.approval_mode="approve"')
+ fi
+ squadra=()
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -n "${CODEX_HOME:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ while IFS= read -r x; do [ -n "$x" ] && squadra+=("$x"); done < <(python3 "$(dirname "$0")/squadra.py" \
+ lancio codex "$CODEX_HOME" 2>/dev/null)
+ fi
+ case "${DELMINIO_TETTO_USCITE:-}" in ''|*[!0-9]*) DELMINIO_TETTO_USCITE=25000 ;; esac
+ tetto=(-c "tool_output_token_limit=$DELMINIO_TETTO_USCITE")
+ case "${DELMINIO_MIE:-}" in *"|tool_output_token_limit|"*) tetto=() ;; esac
+ gesto=(-c check_for_update_on_startup=false ${mcp[@]+"${mcp[@]}"} ${squadra[@]+"${squadra[@]}"}
+ ${tetto[@]+"${tetto[@]}"}
+ -c "model_instructions_file=\"$f\"")
+ tutti=()
+ while IFS= read -r -d '' x; do tutti+=("$x"); done < <(python3 -c 'import sys
+n = int(sys.argv[1]); g, a = sys.argv[2:2 + n], sys.argv[2 + n:]
+CON_VALORE = {"-c", "--config", "-m", "--model", "-p", "--profile", "-s", "--sandbox", "-a",
+ "--ask-for-approval", "-C", "--cd", "--add-dir", "-i", "--image", "--enable", "--disable",
+ "--remote", "--remote-auth-token-env", "--local-provider"}
+i, sub = 0, None
+while i < len(a):
+ x = a[i]
+ if x == "--": break
+ if x in CON_VALORE: i += 2; continue
+ if x.startswith("-"): i += 1; continue
+ if x in ("exec", "e", "review", "resume", "fork"): sub = i
+ break
+if sub is None:
+ out = g + a
+else:
+ resto, c, j = [], [], 0
+ while j < sub:
+ if a[j] in ("-c", "--config") and j + 1 < sub: c += a[j:j + 2]; j += 2
+ else: resto.append(a[j]); j += 1
+ out = resto + [a[sub]] + g + c + a[sub + 1:]
+sys.stdout.write("".join(x + "\0" for x in out))' "${#gesto[@]}" "${gesto[@]}" "$@")
+ [ ${#tutti[@]} -ge ${#gesto[@]} ] || { echo "$M_delminio_argomenti_codex" >&2; exit 1; }
+ exec "${DELMINIO_CLI:-codex}" --no-daemon "${tutti[@]}"
+ ;;
+ app-codex)
+ shift
+ p="$(dirname "$0")/plugin.py"
+ case "${1:-}" in
+ "") python3 "$p" app-codex; e=$?
+ case $e in 0) echo "$M_app_codex_fatto" ;; 4) echo "$M_app_codex_assente" ;; *) echo "$M_app_codex_non_riuscito" >&2; exit 1 ;; esac ;;
+ via) python3 "$p" app-codex via && echo "$M_app_codex_tolto" ;;
+ no) python3 "$p" app-codex no && echo "$M_app_codex_no" ;;
+ stato) python3 "$p" app-codex stato ;;
+ *) echo "$M_app_codex_uso" >&2; exit 2 ;;
+ esac
+ ;;
+ qwen)
+ shift
+ export DELMINIO_CLI_NOME=qwen
+ if [ "${1:-}" = --ruolo ] && [ -n "${2:-}" ]; then
+ DELMINIO_PORTA=$2; shift 2
+ fi
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ rotta=nascita; mcp_token="$TOKEN"
+ if [ "${DELMINIO_NASCITA:-intera}" = porta ]; then
+ rotta=sistema
+ mcp_token=$(python3 -c 'import json,sys
+s = json.load(open(sys.argv[1]))["mcpServers"]
+print((s.get("memoria-ruolo") or s["delminio-ruolo"])["headers"]["Authorization"].split(" ", 1)[1])' \
+ "${DELMINIO_CANALE_RUOLO:-}" 2>/dev/null) || mcp_token=""
+ [ -n "$mcp_token" ] || { echo "$M_ruolo_sola_sua_2" >&2; exit 1; }
+ fi
+ posta="$STATO/qwen-posta-$$.jsonl"
+ (umask 077; : > "$posta")
+ porta_del_lancio "$rotta" "$M_agente_parte_meta_2"
+ export QWEN_SYSTEM_MD="$f" DELMINIO_SISTEMA=1 DELMINIO_QWEN_POSTA="$posta"
+ radice=$(git rev-parse --show-toplevel 2>/dev/null || true)
+ if [ -n "$radice" ] && [ ! -e "$radice/.qwen/.env" ]; then
+ (umask 077; mkdir -p "$radice/.qwen" && echo "# delminio" > "$radice/.qwen/.env") 2>/dev/null || true
+ escludi=$(cd "$radice" && git rev-parse --path-format=absolute --git-path info/exclude 2>/dev/null) || escludi=""
+ [ -n "$escludi" ] && { grep -qxF ".qwen/.env" "$escludi" 2>/dev/null || echo ".qwen/.env" >> "$escludi"; } 2>/dev/null
+ fi
+ if [ -n "${QWEN_HOME:-}" ] && [ -f "$(dirname "$0")/plugin.py" ]; then
+ if [ "$rotta" = nascita ] && [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] \
+ && DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" python3 "$(dirname "$0")/plugin.py" qwen "$QWEN_HOME" >/dev/null 2>&1; then
+ exec "${DELMINIO_CLI:-qwen}" --input-file "$posta" "$@"
+ fi
+ DELMINIO_QWEN="${DELMINIO_CLI:-qwen}" python3 "$(dirname "$0")/plugin.py" qwen-via "$QWEN_HOME" >/dev/null 2>&1 || true
+ [ "$rotta" = nascita ] && [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && echo "$M_qwen_senza_plugin" >&2
+ fi
+ mcp="$STATO/qwen-mcp-$$.json"
+ (umask 077; DELMINIO_T="$mcp_token" python3 -c 'import json,os,sys
+print(json.dumps({"mcpServers": {"memoria": {
+ "command": "bash", "args": [sys.argv[2], "ponte-mcp", sys.argv[1]],
+ "env": {"DELMINIO_T": os.environ["DELMINIO_T"],
+ "DELMINIO_MODELLO": os.environ.get("DELMINIO_MODELLO", "")},
+ "timeout": 60000, "trust": True, "alwaysLoadTools": True}}}))' "$URL" "$(cd "$(dirname "$0")" && pwd)/$(basename "$0")" > "$mcp") && [ -s "$mcp" ] \
+ || { echo "$M_delminio_mcp_qwen" >&2; rm -f "$mcp"; exit 1; }
+ exec "${DELMINIO_CLI:-qwen}" --input-file "$posta" --mcp-config "$mcp" "$@"
+ ;;
+ opencode)
+ shift
+ export DELMINIO_CLI_NOME=opencode
+ porta="${DELMINIO_PORTA:-principale}"
+ export DELMINIO_PORTA="$porta"
+ porta_del_lancio nascita "$M_agente_parte_meta_2"
+ export DELMINIO_SISTEMA=1
+ radice=$(git rev-parse --show-toplevel 2>/dev/null || pwd)
+ [ -f "$radice/.opencode/plugins/delminio.js" ] || python3 "$(dirname "$0")/plugin.py" opencode "$radice" >/dev/null 2>&1 || true
+ squadra="{}"
+ if [ -z "${DELMINIO_SENZA_PLUGIN:-}" ] && [ -f "$(dirname "$0")/squadra.py" ]; then
+ squadra=$(python3 "$(dirname "$0")/squadra.py" lancio opencode "$radice" 2>/dev/null) || squadra="{}"
+ fi
+ gratuito=""
+ if [ -n "${DELMINIO_OPENCODE_GRATUITO:-}" ]; then
+ ricordo="${XDG_STATE_HOME:-$HOME/.local/state}/delminio/opencode-gratuito"
+ oggi=$(date +%F)
+ giorno=""; [ -f "$ricordo" ] && read -r giorno gratuito < "$ricordo"
+ if [ "${giorno:-}" != "$oggi" ] || [ -z "$gratuito" ]; then
+ echo "$M_opencode_gratuito_scelgo" >&2
+ gratuito=$(python3 "$(cd "$(dirname "$0")" && pwd)/eseguibili.py" modello-gratuito "${DELMINIO_CLI:-$(command -v opencode)}" 2>/dev/null) || gratuito=""
+ if [ -n "$gratuito" ]; then
+ mkdir -p "$(dirname "$ricordo")" && printf '%s %s\n' "$oggi" "$gratuito" > "$ricordo"
+ else
+ _f "$M_opencode_gratuito_nessuno" nome "$DELMINIO_OPENCODE_GRATUITO" >&2
+ fi
+ fi
+ fi
+ OPENCODE_CONFIG_CONTENT=$(DELMINIO_F="$f" DELMINIO_OPENCODE_SQUADRA="$squadra" DELMINIO_GRATUITO_SCELTO="$gratuito" python3 -c 'import json, os
+c = json.loads(os.environ.get("DELMINIO_OPENCODE_CONFIG") or "{}")
+if os.environ.get("DELMINIO_GRATUITO_SCELTO"):
+ c["model"] = os.environ["DELMINIO_GRATUITO_SCELTO"]
+porta = "{file:" + os.environ["DELMINIO_F"] + "}"
+c.setdefault("agents", {}).setdefault("build", {})["system"] = porta
+def unisci(a, b):
+ for k, v in b.items():
+ if isinstance(v, dict) and isinstance(a.get(k), dict):
+ unisci(a[k], v)
+ elif isinstance(v, list) and isinstance(a.get(k), list):
+ a[k] += [x for x in v if x not in a[k]]
+ else:
+ a.setdefault(k, v)
+try:
+ sq = json.loads(os.environ.get("DELMINIO_OPENCODE_SQUADRA") or "{}")
+except ValueError:
+ sq = {}
+if isinstance(sq, dict):
+ unisci(c, sq)
+print(json.dumps(c))') || { echo "$M_agente_parte_meta_2" >&2; exit 1; }
+ export OPENCODE_CONFIG_CONTENT OPENCODE_DISABLE_AUTOUPDATE=1 OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1
+ exec "${DELMINIO_CLI:-opencode}" --standalone "$@"
+ ;;
+esac
diff --git a/kit/it/opencode-client.js b/kit/it/opencode-client.js
new file mode 100644
index 0000000..cb9cf6a
--- /dev/null
+++ b/kit/it/opencode-client.js
@@ -0,0 +1,174 @@
+/*! © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite. */
+import{spawn}from"node:child_process"
+import fs from"node:fs"
+import os from"node:os"
+import path from"node:path"
+const RITI={"apertura":"apertura","chiusura":"chiusura"}
+const FRASI={"apertura":"","chiusura":"","ciclo":"","fermo":"","v1":"","permesso":"","ammessi":""}
+const nome_server=(ha)=>{const c=ha("memoria")
+return c&&!JSON.stringify(c.command??"").includes("ponte")?"delminio":"memoria"}
+const file=(a)=>a.path
+const COME_CLAUDE={read:["Read",(a)=>({file_path:file(a)})],edit:["Edit",(a)=>({file_path:file(a),old_string:a.oldString,new_string:a.newString})],write:["Write",(a)=>({file_path:file(a),content:a.content})],shell:["Bash",(a)=>({command:a.command,description:a.description})],grep:["Grep",(a)=>({pattern:a.pattern,path:a.path})],glob:["Glob",(a)=>({pattern:a.pattern,path:a.path})],apply_patch:["apply_patch",(a)=>({command:a.patchText})],patch:["apply_patch",(a)=>({command:a.patchText})],opencode_worktree_remove:["Bash",(a)=>({command:`git worktree remove ${a.force ? "--force " : ""}${JSON.stringify(a.directory || "")}`})],opencode_worktree_create:["Bash",(a)=>({command:`git worktree add ${JSON.stringify(a.name || "")}`})],}
+const conMotivo=(errore)=>{const b=errore?.error
+if(b?._tag!=="Permission.BlockedError"||!Array.isArray(b.rules))return null
+const tocca=(schema,testo)=>new RegExp("^"+String(schema).split("*").map((x)=>x.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*")+"$","s").test(String(testo))
+const regola=(r)=>b.rules.findLast((x)=>tocca(x.action,b.permission)&&tocca(x.resource,r))
+const tutti=(b.resources||[]).map(String)
+const vietati=tutti.filter((r)=>regola(r)?.effect!=="allow")
+const ammessi=[...new Set(b.rules.filter((x)=>x.action===b.permission&&x.effect==="allow"&&x.resource!=="*").map((x)=>x.resource))].slice(0,20)
+const elenco=(xs)=>xs.map((x)=>`«${x}»`).join(", ")
+return FRASI.permesso.replace("{permesso}",b.permission||"").replace("{rifiutati}",elenco(vietati.length?vietati:tutti)).replace("{ammessi}",ammessi.length?FRASI.ammessi.replace("{elenco}",elenco(ammessi)):"")}
+const PRIMA=[["tocco",["Write","Edit","apply_patch"]],["guardia",["Read","Grep","Glob","Write","Edit","apply_patch","Bash"]],["condiviso",["Bash"]],["gesto",["*"]],]
+const nucleo=(radice,{ferma=null}={})=>{const gancio=path.join(radice,".claude","delminio.sh")
+if(!fs.existsSync(gancio))return null
+const ancore=new Map()
+const ancora=(id)=>{if(!id)return""
+let a=ancore.get(id)
+if(!a||a.exitCode!==null||a.signalCode){a=spawn("bash",["-c",'while kill -0 "$1" 2>/dev/null; do sleep 20; done',"delminio-opencode",String(process.pid)],{stdio:"ignore"})
+a.on("error",()=>{})
+ancore.set(id,a)}
+return a.pid?String(a.pid):""}
+const chiudi=()=>{for(const a of ancore.values())try{a.kill()}catch{}ancore.clear()}
+const gesto=(nome,evento,argomenti=[],tempo=30000,id=evento?.session_id)=>new Promise((fine)=>{let out="",err="",finito=false
+const pid=ancora(id)
+const p=spawn("bash",[gancio,nome,...argomenti],{cwd:radice,env:{...process.env,DELMINIO_CLI_NOME:"opencode",...(pid?{DELMINIO_CLI_PID:pid}:{})},stdio:["pipe","pipe","pipe"],})
+const basta=(codice)=>{if(!finito){finito=true;clearTimeout(t);fine({codice,out,err})}}
+const t=tempo?setTimeout(()=>{p.kill("SIGTERM");basta(124)},tempo):null
+p.stdout.on("data",(d)=>(out+=d))
+p.stderr.on("data",(d)=>(err+=d))
+p.on("error",()=>basta(127))
+p.on("close",(c)=>basta(c??1))
+p.stdin.on("error",()=>{})
+p.stdin.end(evento===undefined?"":JSON.stringify(evento))})
+const contesto=(r)=>{try{return JSON.parse(r.out).hookSpecificOutput?.additionalContext||""}catch{return""}}
+const rifiuto=(r)=>{if(r.codice===2)return r.err.trim()||"Delminio"
+try{const h=JSON.parse(r.out).hookSpecificOutput||{}
+if(h.permissionDecision==="deny")return h.permissionDecisionReason||"Delminio"}catch{}
+return""}
+const sessioni=new Map()
+const di=(id)=>{if(!sessioni.has(id))sessioni.set(id,{detti:{}});return sessioni.get(id)}
+const CICLO=12
+const FERMATE=3
+const ripete=(s,firma)=>{const uguali=(s.storia||[]).filter((x)=>x.firma===firma)
+return uguali.length>=2&&uguali[uguali.length-1].esito===uguali[uguali.length-2].esito}
+const evento=(id,nome,piu={})=>({session_id:id,hook_event_name:nome,cwd:radice,...piu})
+const nasci=(id,origine)=>{const s=di(id)
+if(s.figlia)return Promise.resolve("")
+if(!s.nascita)
+s.nascita=gesto("apertura",evento(id,"SessionStart",{source:origine}),[],90000).then((r)=>{s.apertura=contesto(r)
+return s.apertura})
+return s.nascita}
+const messaggio=async(id,testo)=>{const s=di(id)
+s.fermate=0
+await nasci(id,"resume")
+const e=evento(id,"UserPromptSubmit",{prompt:testo,model:s.modello||"",coda:(s.coda||"").slice(-1200)})
+const no=rifiuto(await gesto("segreto",e,[],5000))
+if(no)return{no}
+const aggiunte=[]
+for(const[nome,tempo]of[["umano",30000],["memorie",5000]]){const c=contesto(await gesto(nome,e,[],tempo))
+if(c)aggiunte.push(c)}
+return{aggiunte}}
+const rito=async(canonico,dopo,id)=>{dopo=(dopo||"").replace(/^"(.*)"$/s,"$1").trim()
+const r=canonico==="apertura"?await gesto("prompt",undefined,[],30000,id):await gesto("chiusura",undefined,dopo?[dopo]:[],30000,id)
+if(canonico==="chiusura")pulisci(id,true)
+return[r.out.trim(),canonico==="apertura"?dopo:""].filter((x)=>x).join("\n\n")}
+const primaDelTool=async(id,strumento,a,chiamata)=>{const voce=COME_CLAUDE[strumento]||[strumento,(x)=>x]
+const[nome,argomenti]=voce
+a=a||{}
+const firma=`${strumento} ${JSON.stringify(a)}`
+const st=di(id)
+st.firme={...(st.firme||{}),[chiamata]:firma}
+if(ripete(st,firma)){st.fermate=(st.fermate||0)+1
+if(ferma&&st.fermate>=FERMATE){st.fermate=0
+setTimeout(()=>Promise.resolve(ferma(id)).catch(()=>{}),0)
+throw new Error(FRASI.fermo||FRASI.ciclo||"Delminio")}
+throw new Error(FRASI.ciclo||"Delminio")}
+const cwd=nome==="Bash"&&a.workdir?path.resolve(radice,a.workdir):radice
+const e={...evento(id,"PreToolUse"),cwd,tool_name:nome,tool_input:argomenti(a)}
+const s=di(id)
+if(s.figlia)e.agent_id=id
+const detti=[]
+for(const[g,quali]of PRIMA){if(!quali.includes("*")&&!quali.includes(nome))continue
+const r=await gesto(g,e,[],10000)
+const no=rifiuto(r)
+if(no)throw new Error(no)
+const c=contesto(r)
+if(c)detti.push(c)}
+if(detti.length)s.detti[chiamata]=detti.join("\n\n")}
+const db=path.join(process.env.XDG_DATA_HOME||path.join(os.homedir(),".local","share"),"opencode","opencode.db")
+const consumi=(id,nome)=>{if(di(id).figlia||!fs.existsSync(db))return
+gesto(nome,{...evento(id,nome==="consumi"?"Stop":"PostToolUse"),transcript_path:db,cli:"opencode"},[],10000,id)}
+const dopoIlTool=async(id,strumento,chiamata,esito)=>{const s=di(id)
+const firma=(s.firme||{})[chiamata]
+if(firma!==undefined){delete s.firme[chiamata]
+s.storia=[...(s.storia||[]),{firma,esito:String(esito??"").slice(0,4000)}].slice(-CICLO)}
+const prima=s.detti[chiamata]
+delete s.detti[chiamata]
+const e={...evento(id,"PostToolUse"),tool_name:strumento}
+const posta=s.figlia?"":contesto(await gesto("volo",e,[],10000))
+consumi(id,"consumi-tool")
+return[prima,posta].filter((x)=>x).join("\n\n")}
+const conversazioni=process.env.DELMINIO_CONVERSAZIONI||""
+const pulisci=(id,finita)=>{if(conversazioni&&!di(id).figlia)gesto("pulizia",evento(id,finita?"SessionEnd":"Stop"),[],10000,id)}
+const aspetta=(id,sveglia)=>{const s=di(id)
+consumi(id,"consumi")
+pulisci(id,conversazioni==="subito")
+if(s.figlia||s.attesa)return
+s.attesa=gesto("attesa-codex",undefined,[ancora(id)||String(process.pid),id],0,id).then((r)=>{s.attesa=null
+const avviso=r.out.trim()
+if(r.codice===0&&avviso)return Promise.resolve(sveglia(avviso)).catch(()=>{})})}
+return{gancio,di,nasci,messaggio,rito,primaDelTool,dopoIlTool,aspetta,chiudi}}
+const v1=async({client,directory,worktree})=>{const radice=worktree||directory
+if(!fs.existsSync(path.join(radice,".claude","delminio.sh")))return{}
+const detto=new Set()
+const avviso=FRASI.v1||"Delminio: OpenCode 1 is not supported. opencode upgrade --major"
+const mostra=()=>client.tui.showToast({body:{message:avviso,variant:"error",duration:30000}}).catch(()=>{})
+mostra()
+return{"chat.message":async(input,output)=>{if(detto.has(input.sessionID))return
+detto.add(input.sessionID)
+mostra()
+const accanto=(output.parts||[]).find((x)=>x.type==="text")
+if(accanto)
+output.parts.push({id:`${accanto.id}z`,sessionID:accanto.sessionID,messageID:accanto.messageID,type:"text",text:avviso,synthetic:true})},}}
+const v2=async(ctx)=>{const n=nucleo(ctx.location?.directory||ctx.location?.project?.directory||"",{ferma:(id)=>ctx.session.interrupt({sessionID:id}),})
+if(!n)return
+const agente=Boolean(process.env.DELMINIO_PORTA)
+if(agente)
+await ctx.skill.transform((ed)=>{for(const x of ed.list())if(String(x?.path||"").startsWith("skill://"))ed.remove(x.id)}).catch(()=>{})
+const figlia=async(id)=>{const s=n.di(id)
+if(s.figlia===undefined){try{const info=await ctx.session.get({sessionID:id})
+s.figlia=Boolean(info?.parentID??info?.data?.parentID)}catch{s.figlia=false}}
+return s.figlia}
+await ctx.mcp.transform((mcp)=>{const k=nome_server((x)=>mcp.get(x))
+if(!mcp.get(k))
+mcp.set(k,{type:"local",command:["bash",n.gancio,"ponte"],codemode:false,timeout:{execution:120000}})})
+await ctx.command.transform((comandi)=>{for(const[nome,canonico]of Object.entries(RITI))
+comandi.add({name:nome,description:FRASI[canonico]||nome,execute:async({sessionID,prompt})=>{const testo=await n.rito(canonico,prompt?.text,sessionID)
+if(testo)await ctx.session.prompt({sessionID,text:testo})},})})
+await ctx.session.hook("prompt",async(ev)=>{const testo=(ev.prompt?.text||"").trim()
+if(!testo||(await figlia(ev.sessionID)))return
+const r=await n.messaggio(ev.sessionID,testo)
+if(r.no){ev.prompt.text=r.no;return}
+for(const c of r.aggiunte)
+await ctx.session.synthetic({sessionID:ev.sessionID,text:c,delivery:"steer",resume:false})})
+await ctx.session.hook("context",async(ev)=>{if(agente){if(ev.tools?.skill){let elenco=null
+try{const r=await ctx.skill.list();elenco=Array.isArray(r)?r:r?.data}catch{}
+if(Array.isArray(elenco)&&!elenco.some((x)=>!String(x?.path||"").startsWith("skill://")))
+delete ev.tools.skill}
+ev.system=(ev.system||[]).map((x)=>x?.type==="text"&&x.text?.includes("/tmp/opencode")?{...x,text:x.text.split("\n").filter((r)=>!r.includes("/tmp/opencode")).join("\n")}:x)}
+if(await figlia(ev.sessionID))return
+const s=n.di(ev.sessionID)
+if(ev.model)s.modello=`${ev.model.providerID}/${ev.model.id}`
+const apertura=s.apertura??(await n.nasci(ev.sessionID,"resume"))
+if(apertura)ev.system.push({type:"text",text:apertura})})
+await ctx.session.hook("experimental.idle",async(ev)=>{if(await figlia(ev.sessionID))return
+n.aspetta(ev.sessionID,(avviso)=>ctx.session.prompt({sessionID:ev.sessionID,text:avviso}))})
+await ctx.tool.hook("execute.before",async(ev)=>{await figlia(ev.sessionID)
+await n.primaDelTool(ev.sessionID,ev.tool,ev.input,ev.id)})
+await ctx.tool.hook("execute.after",async(ev)=>{const motivo=ev.status==="error"&&FRASI.permesso?conMotivo(ev.error):null
+if(motivo)try{ev.error=new ev.error.constructor({message:motivo})}catch{}
+const piu=await n.dopoIlTool(ev.sessionID,ev.tool,ev.id,JSON.stringify(ev.result?.content??ev.error??""))
+if(piu&&ev.status==="completed")ev.result.content=[...(ev.result.content||[]),{type:"text",text:piu}]});(async()=>{try{for await(const e of ctx.event.subscribe()){const p=e.properties||e.data||{}
+if(e.type==="session.created"&&p.sessionID&&!p.parentID)n.nasci(p.sessionID,"startup")}}catch{}})()
+return()=>n.chiudi()}
+export default{id:"delminio",server:v1,setup:v2}
\ No newline at end of file
diff --git a/kit/it/plugin-client b/kit/it/plugin-client
new file mode 100644
index 0000000..c517267
--- /dev/null
+++ b/kit/it/plugin-client
@@ -0,0 +1,474 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""Il pacchetto di Delminio per le CLI degli agenti (F776): i ganci, /apertura e"""
+from __future__ import annotations
+import hashlib
+import json
+import os
+import re
+import runpy
+import shlex
+import shutil
+import subprocess
+import sys
+NOME = 'delminio'
+ID = f'{NOME}@{NOME}'
+SERVER = 'memoria'
+SERVER_DI_PRIMA = ('delminio', 'delminio-ruolo')
+TOOL = ('delminio', 'delminio_write')
+TOOLS_CLAUDE = tuple((f'mcp__plugin_{NOME}_{SERVER}__{t}' for t in TOOL))
+TOOLS_CLAUDE_PROGETTO = tuple((f'mcp__{SERVER}__{t}' for t in TOOL))
+TOOLS_CLAUDE_DI_PRIMA = tuple((f'mcp__plugin_{NOME}_delminio__{t}' for t in TOOL)) + tuple((f'mcp__{s}__{t}' for s in SERVER_DI_PRIMA for t in TOOL))
+SKILL_CLAUDE = {'dataviz': 'on', 'keybindings-help': 'on', 'update-config': 'on', 'claude-api': 'name-only', 'code-review': 'name-only', 'fewer-permission-prompts': 'name-only', 'init': 'name-only', 'plugin-authoring': 'name-only', 'run': 'name-only', 'security-review': 'name-only', 'simplify': 'name-only', 'workflow-authoring': 'name-only', 'loop': 'name-only', 'schedule': 'name-only'}
+SKILL_CLAUDE_F811 = {**{n: 'user-invocable-only' for n in ('claude-api', 'code-review', 'fewer-permission-prompts', 'init', 'plugin-authoring', 'run', 'security-review', 'simplify')}, 'loop': 'off', 'schedule': 'off'}
+CHIEDI_CLAUDE = ('Agent', 'Workflow')
+SKILL_CODEX_SPENTE = ()
+SKILL_CODEX_F811 = ('imagegen', 'skill-creator', 'skill-installer')
+COMANDI = {
+ "riti": {
+ "apertura": "apertura",
+ "chiusura": "chiusura",
+ "closing": "chiusura",
+ "handoff": "chiusura",
+ "opening": "apertura",
+ "start": "apertura"
+ }
+}
+FRASI = {
+ "descrizione": "Delminio: la memoria del progetto, l'apertura e la chiusura delle sessioni, i messaggi fra gli agenti e i controlli prima di un'azione",
+ "apertura": "Delminio: apri la sessione col briefing del tuo ruolo \u2014 ci\xf2 che scrivi dopo il comando parte come tuo messaggio",
+ "apertura_suggerimento": "[cosa vuoi dirgli subito]",
+ "chiusura": "Delminio: chiudi la sessione \u2014 ci\xf2 che scrivi dopo il comando parte come tuo messaggio",
+ "chiusura_suggerimento": "[cosa fare prima di chiudere]",
+ "ciclo_opencode": "Delminio: \xe8 la terza volta che fai esattamente questa chiamata, e le ultime due hanno avuto la stessa risposta: una quarta non cambier\xe0 niente. Cambia strada, oppure fermati e scrivi a chi ti ha dato il lavoro cosa ti blocca.",
+ "fermo_opencode": "Delminio ha fermato questo giro: il modello ha rifatto la stessa chiamata con la stessa risposta anche dopo tre avvisi. Leggi cosa cercava di fare e riscrivigli cosa vuoi, o cambia modello.",
+ "permesso_opencode": "Delminio: le regole di questo agente non lasciano passare {rifiutati} ({permesso}). In una catena (|, ;, &&) ogni comando si controlla da solo, e ne basta uno fuori dalle regole per fermare tutto; le redirezioni passano.{ammessi} Non riprovare lo stesso comando: lancia da soli quelli che le regole ammettono, o di' a chi ti ha dato il lavoro cosa ti serve.",
+ "ammessi_opencode": " Le regole ammettono: {elenco}.",
+ "opencode_v1": "Delminio non funziona con OpenCode 1: qui non ci sono la memoria del progetto n\xe9 i controlli. Esci e aggiorna a OpenCode 2 con \xabopencode upgrade --major\xbb, poi riapri OpenCode in questo progetto. Al modello: di' alla persona di aggiornare, prima di lavorare.",
+ "uso": "uso: python3 .claude/plugin.py claude|rimuovi|opencode <radice del repo> \xb7 codex|qwen <cartella della CLI> \xb7 app-codex [stato|allinea|via|no|lascia]"
+}
+
+def F(chiave: str, **valori) -> str:
+ testo = FRASI[chiave]
+ for k, v in valori.items():
+ testo = testo.replace('{' + k + '}', str(v))
+ return testo
+
+def cartella() -> str:
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'plugin')
+GANCI_CLAUDE = (('SessionStart', 'apertura', {}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, 'Write|Edit|MultiEdit|NotebookEdit'), ('PreToolUse', 'guardia', {'timeout': 5}, 'Read|Grep|Glob|Write|Edit|MultiEdit|NotebookEdit|Bash'), ('PreToolUse', 'condiviso', {'timeout': 10}, 'Bash'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('PostToolUseFailure', 'errore', {'timeout': 5}, ''), ('Stop', 'attesa', {'asyncRewake': True, 'timeout': 43200}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
+LUNGO = {'additionalContextLimit': 16000}
+FINE_CODEX = {'timeout': 3}
+GANCI_CODEX = (('SessionStart', 'apertura', LUNGO, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30, **LUNGO}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(apply_patch|Edit|Write)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(apply_patch|Edit|Write|Bash)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^Bash$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10, **LUNGO}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', FINE_CODEX, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', FINE_CODEX, ''))
+GANCI_QWEN = (('SessionStart', 'apertura', {'timeout': 60}, ''), ('UserPromptSubmit', 'segreto', {'timeout': 5}, ''), ('UserPromptSubmit', 'rito', {'timeout': 30}, ''), ('UserPromptSubmit', 'umano', {'timeout': 30}, ''), ('UserPromptSubmit', 'memorie', {'timeout': 5}, ''), ('PreToolUse', 'tocco', {'timeout': 5}, '^(edit|write_file|notebook_edit)$'), ('PreToolUse', 'guardia', {'timeout': 5}, '^(read_file|grep_search|edit|write_file|notebook_edit|run_shell_command)$'), ('PreToolUse', 'condiviso', {'timeout': 10}, '^run_shell_command$'), ('PreToolUse', 'gesto', {'timeout': 10}, ''), ('PostToolUse', 'volo', {'timeout': 10}, ''), ('PostToolUse', 'consumi-tool', {'timeout': 10}, ''), ('Stop', 'attesa', {'timeout': 10}, ''), ('Stop', 'pulizia', {'timeout': 10}, ''), ('SessionEnd', 'pulizia', {'timeout': 10}, ''), ('Stop', 'consumi', {'timeout': 10}, ''), ('SessionEnd', 'consumi', {'timeout': 10}, ''))
+QWEN = NOME + '-qwen'
+PERMESSI_CODEX = tuple((f'[plugins."{ID}".mcp_servers.{SERVER}.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
+PERMESSI_CODEX_DI_PRIMA = tuple((f'[plugins."{ID}".mcp_servers.delminio.tools.{t}]\napproval_mode = "approve"\n' for t in TOOL))
+
+def _permessi_codex(conf: str) -> None:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ nuovo = testo
+ for b in PERMESSI_CODEX_DI_PRIMA:
+ nuovo = nuovo.replace('\n' + b, '').replace(b, '')
+ if (mancano := [b for b in PERMESSI_CODEX if b not in nuovo]):
+ nuovo = nuovo.rstrip('\n') + '\n\n' + '\n'.join(mancano)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo)
+ os.replace(conf + '.nuovo', conf)
+LANCIATORE = '#!/usr/bin/env bash\nd=${CLAUDE_PROJECT_DIR:-$PWD}\nr=$(cd "$d" 2>/dev/null && git rev-parse --show-toplevel 2>/dev/null) || exit 0\n[ -f "$r/.claude/delminio.sh" ] || exit 0\nexec bash "$r/.claude/delminio.sh" "$@"\n'
+
+def _skill(nome: str, descrizione: str, suggerimento: str, comando: str) -> str:
+ return f'---\nname: {nome}\ndescription: {json.dumps(descrizione, ensure_ascii=False)}\nargument-hint: {json.dumps(suggerimento, ensure_ascii=False)}\ndisable-model-invocation: true\nallowed-tools: Bash(bash:*)\n---\n!`{comando}`\n\n$ARGUMENTS\n'
+
+def ganci(chiama: str, lista, matcher_sempre: bool=False) -> dict:
+ g: dict = {}
+ for evento, gesto, extra, matcher in lista:
+ g.setdefault(evento, []).append({**({'matcher': matcher} if matcher or matcher_sempre else {}), 'hooks': [{'type': 'command', 'command': f'{chiama} {gesto}', **extra}]})
+ return g
+
+def contenuti(radice_pacchetto: str) -> dict[str, str]:
+ lanciatore = os.path.join(radice_pacchetto, NOME, 'bin', 'delminio')
+ chiama = 'bash ' + shlex.quote(lanciatore)
+ server = {'command': 'bash', 'args': [lanciatore, 'ponte']}
+ f = {os.path.join(NOME, 'bin', 'delminio'): LANCIATORE, os.path.join(NOME, 'hooks', 'hooks.json'): json.dumps({'hooks': ganci(chiama, GANCI_CLAUDE)}, indent=2) + '\n', os.path.join(NOME, '.mcp.json'): json.dumps({'mcpServers': {SERVER: server}}, indent=2) + '\n', os.path.join(NOME, 'hooks', 'codex.json'): json.dumps({'hooks': ganci(chiama, GANCI_CODEX)}, indent=2) + '\n', os.path.join(NOME, 'mcp-codex.json'): json.dumps({'mcpServers': {SERVER: {**server, 'env_vars': ['DELMINIO_MODELLO', 'DELMINIO_CLI_NOME']}}}, indent=2) + '\n'}
+ riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
+ for nome, rito in sorted(riti.items()):
+ f[os.path.join(QWEN, 'commands', nome + '.md')] = f"---\ndescription: {json.dumps(F('apertura') if rito == 'apertura' else F('chiusura'), ensure_ascii=False)}\n---\n{nome}\n"
+ qwen_server = {**server, 'timeout': 60000, 'trust': True, 'alwaysLoadTools': True}
+ apre = (F('apertura'), F('apertura_suggerimento'), f'{chiama} prompt')
+ chiude = (F('chiusura'), F('chiusura_suggerimento'), f'{chiama} chiusura')
+ for nome, rito in sorted(riti.items()):
+ f[os.path.join(NOME, 'skills', nome, 'SKILL.md')] = _skill(nome, *(apre if rito == 'apertura' else chiude))
+ impronta = hashlib.sha256(''.join((k + v for k, v in sorted(f.items()))).encode()).hexdigest()
+ versione = f'1.0.{int(impronta[:7], 16)}'
+ f[os.path.join(NOME, '.claude-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione')}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(QWEN, 'qwen-extension.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'mcpServers': {SERVER: qwen_server}, 'hooks': ganci(chiama, GANCI_QWEN, matcher_sempre=True)}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(NOME, 'skills-codex', '.vuota')] = ''
+ f[os.path.join(NOME, '.codex-plugin', 'plugin.json')] = json.dumps({'name': NOME, 'version': versione, 'description': F('descrizione'), 'skills': './skills-codex/', 'hooks': './hooks/codex.json', 'mcpServers': './mcp-codex.json'}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': NOME, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': NOME, 'source': {'source': 'local', 'path': './' + NOME}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': NOME, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': NOME, 'source': './' + NOME, 'description': F('descrizione'), 'version': versione}]}, ensure_ascii=False, indent=2) + '\n'
+ return f
+
+def scrivi() -> str:
+ radice = cartella()
+ for rel, testo in contenuti(radice).items():
+ p = os.path.join(radice, rel)
+ try:
+ with open(p, encoding='utf-8') as h:
+ if h.read() == testo:
+ continue
+ except OSError:
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ if rel.endswith(os.path.join('bin', 'delminio')):
+ os.chmod(p + '.nuovo', 493)
+ os.replace(p + '.nuovo', p)
+ return radice
+
+def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _acceso(radice: str) -> bool:
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ return (json.load(h).get('enabledPlugins') or {}).get(ID) is True
+ except (OSError, ValueError, AttributeError):
+ return False
+
+def claude(radice: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ return 3
+ try:
+ if _claude('--help', cwd=radice).returncode != 0:
+ return 3
+ pacchetto = scrivi()
+ _claude('marketplace', 'add', pacchetto, '--scope', 'local', cwd=radice)
+ _claude('install', ID, '--scope', 'local', cwd=radice)
+ if not _acceso(radice):
+ _claude('enable', ID, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _acceso(radice) else 3
+
+def _versione() -> str:
+ return json.loads(contenuti(cartella())[os.path.join(NOME, '.codex-plugin', 'plugin.json')])['version']
+
+def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _codex_pronto(casa: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ return False
+ acceso = re.search('^\\[plugins\\."' + re.escape(ID) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
+ return bool(acceso) and all((b in conf for b in PERMESSI_CODEX)) and (not any((b in conf for b in PERMESSI_CODEX_DI_PRIMA))) and os.path.isdir(os.path.join(casa, 'plugins', 'cache', NOME, NOME, _versione()))
+
+def _skill_codex(casa: str) -> None:
+ conf = os.path.join(casa, 'config.toml')
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except FileNotFoundError:
+ testo = ''
+ except OSError:
+ return
+ prima = testo
+ segno = os.path.join(casa, 'delminio-skill-f844')
+ if testo and (not os.path.exists(segno)):
+ for nome in SKILL_CODEX_F811:
+ percorso = json.dumps(os.path.join(casa, 'skills', '.system', nome, 'SKILL.md'))
+ testo = re.sub('(?m)^\\[\\[skills\\.config\\]\\]\\s*\\npath\\s*=\\s*' + re.escape(percorso) + '\\s*\\nenabled\\s*=\\s*false\\s*\\n?\\n?', '', testo)
+ blocchi = []
+ for nome in SKILL_CODEX_SPENTE:
+ percorso = os.path.join(casa, 'skills', '.system', nome, 'SKILL.md')
+ if json.dumps(percorso) not in testo:
+ blocchi.append(f'[[skills.config]]\npath = {json.dumps(percorso)}\nenabled = false\n')
+ try:
+ os.makedirs(casa, exist_ok=True)
+ if blocchi or testo != prima:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write((testo.rstrip('\n') + '\n\n' if testo.strip() else '') + '\n'.join(blocchi) if blocchi else testo)
+ os.replace(conf + '.nuovo', conf)
+ if not os.path.exists(segno):
+ open(segno, 'w').close()
+ except OSError:
+ pass
+
+def codex(casa: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_CODEX') or 'codex'):
+ return 3
+ pacchetto = scrivi()
+ _skill_codex(casa)
+ _squadra('codex', casa)
+ if _codex_pronto(casa):
+ return 0
+ try:
+ os.makedirs(casa, exist_ok=True)
+ _codex(casa, 'marketplace', 'add', pacchetto)
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'add', ID)
+ _permessi_codex(os.path.join(casa, 'config.toml'))
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _codex_pronto(casa) else 3
+APP_CODEX = ('/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '~/Applications/ChatGPT.app/Contents/Resources/codex-cli/bin/codex', '/usr/lib/chatgpt/resources/codex')
+
+def app_codex_cli() -> str:
+ return next((p for p in map(os.path.expanduser, APP_CODEX) if os.access(p, os.X_OK)), '')
+
+def _casa_app() -> str:
+ return os.path.expanduser('~/.codex')
+
+def _no_app() -> str:
+ return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'delminio', 'app-codex-no')
+
+def _app_scelta(casa: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ return bool(re.search('^\\[marketplaces\\.' + re.escape(NOME) + '\\]', h.read(), re.M))
+ except OSError:
+ return False
+
+def app_codex_stato() -> str:
+ if not app_codex_cli():
+ return ''
+ if _app_scelta(_casa_app()):
+ return 'dentro'
+ return 'no' if os.path.exists(_no_app()) else 'manca'
+
+def app_codex() -> int:
+ cli = app_codex_cli()
+ if not cli:
+ return 4
+ casa = _casa_app()
+ vecchio = os.environ.get('DELMINIO_CODEX')
+ os.environ['DELMINIO_CODEX'] = cli
+ try:
+ pacchetto = scrivi()
+ if not _codex_pronto(casa):
+ os.makedirs(casa, exist_ok=True)
+ _codex(casa, 'marketplace', 'add', pacchetto)
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'add', ID)
+ _permessi_codex(os.path.join(casa, 'config.toml'))
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ finally:
+ if vecchio is None:
+ os.environ.pop('DELMINIO_CODEX', None)
+ else:
+ os.environ['DELMINIO_CODEX'] = vecchio
+ try:
+ os.remove(_no_app())
+ except OSError:
+ pass
+ return 0 if _codex_pronto(casa) else 3
+
+def app_codex_allinea() -> int:
+ if app_codex_cli() and _app_scelta(_casa_app()) and (not _codex_pronto(_casa_app())):
+ return app_codex()
+ return 0
+
+def app_codex_via() -> int:
+ casa = _casa_app()
+ cli = app_codex_cli() or shutil.which('codex') or ''
+ if cli:
+ vecchio = os.environ.get('DELMINIO_CODEX')
+ os.environ['DELMINIO_CODEX'] = cli
+ try:
+ _codex(casa, 'remove', ID)
+ _codex(casa, 'marketplace', 'remove', NOME)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ finally:
+ if vecchio is None:
+ os.environ.pop('DELMINIO_CODEX', None)
+ else:
+ os.environ['DELMINIO_CODEX'] = vecchio
+ conf = os.path.join(casa, 'config.toml')
+ try:
+ with open(conf, encoding='utf-8') as h:
+ testo = h.read()
+ except OSError:
+ return 0
+ nuovo = testo
+ for b in PERMESSI_CODEX + PERMESSI_CODEX_DI_PRIMA:
+ nuovo = nuovo.replace('\n' + b, '').replace(b, '')
+ for intestazione in (f'[plugins."{ID}"]', f'[marketplaces.{NOME}]'):
+ nuovo = re.sub('(?ms)^' + re.escape(intestazione) + '\\n.*?(?=^\\[|\\Z)', '', nuovo)
+ if nuovo != testo:
+ with open(conf + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(nuovo.rstrip('\n') + '\n')
+ os.replace(conf + '.nuovo', conf)
+ return 0 if not _app_scelta(casa) else 3
+
+def app_codex_lascia() -> int:
+ try:
+ os.remove(_no_app())
+ except OSError:
+ pass
+ if not _app_scelta(_casa_app()):
+ return 0
+ return 2 if app_codex_via() == 0 else 3
+
+def app_codex_no() -> int:
+ os.makedirs(os.path.dirname(_no_app()), exist_ok=True)
+ with open(_no_app(), 'w', encoding='utf-8') as h:
+ h.write('no\n')
+ return 0
+
+def _qwen_pronto(casa: str, estensione: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'extensions', NOME, '.qwen-extension-install.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ except (OSError, ValueError):
+ return False
+ return d.get('type') == 'link' and os.path.realpath(d.get('source') or '') == os.path.realpath(estensione)
+
+def qwen(casa: str) -> int:
+ if not shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
+ return 3
+ estensione = os.path.join(scrivi(), QWEN)
+ _squadra('qwen', casa)
+ if _qwen_pronto(casa, estensione):
+ return 0
+ try:
+ os.makedirs(casa, exist_ok=True)
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ subprocess.run([q, 'extensions', 'uninstall', NOME], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0 if _qwen_pronto(casa, estensione) else 3
+
+def qwen_via(casa: str) -> int:
+ if os.path.exists(os.path.join(casa, 'extensions', NOME)) and shutil.which(os.environ.get('DELMINIO_QWEN') or 'qwen'):
+ try:
+ subprocess.run([os.environ.get('DELMINIO_QWEN') or 'qwen', 'extensions', 'uninstall', NOME], env={**os.environ, 'QWEN_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 1 if os.path.exists(os.path.join(casa, 'extensions', NOME)) else 0
+
+def claude_al_lancio(radice: str) -> int:
+ if _acceso(radice):
+ scrivi()
+ return 0
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ ganci = json.load(h).get('hooks') or {}
+ if any(('delminio.sh' in x.get('command', '') for l in ganci.values() for b in l for x in b.get('hooks', []))):
+ return 0
+ except (OSError, ValueError, AttributeError):
+ pass
+ return claude(radice)
+
+def _squadra(gesto: str, dove: str) -> None:
+ p = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'squadra.py')
+ if not os.path.isfile(p):
+ return
+ try:
+ runpy.run_path(p)[gesto](dove)
+ except Exception:
+ pass
+
+def rimuovi(radice: str) -> int:
+ _squadra('stacca', radice)
+ opencode_via(radice)
+ if shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ try:
+ _claude('uninstall', ID, '--scope', 'local', cwd=radice)
+ _claude('marketplace', 'remove', NOME, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ return 0
+ cambiato = False
+ if isinstance(s.get('enabledPlugins'), dict) and ID in s['enabledPlugins']:
+ del s['enabledPlugins'][ID]
+ cambiato = True
+ if not s['enabledPlugins']:
+ del s['enabledPlugins']
+ mercati = s.get('extraKnownMarketplaces')
+ for m in [m for m in mercati or {} if m == NOME] if isinstance(mercati, dict) else []:
+ del mercati[m]
+ cambiato = True
+ if isinstance(mercati, dict) and (not mercati):
+ del s['extraKnownMarketplaces']
+ if cambiato:
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ os.replace(p + '.nuovo', p)
+ return 0
+OPENCODE_PLUGIN = os.path.join('.opencode', 'plugins', 'delminio.js')
+OPENCODE_SORGENTE = os.path.join('.claude', 'opencode.js')
+
+def _nostro_opencode(testo: str) -> bool:
+ return 'delminio.sh' in testo and 'attesa-codex' in testo
+
+def opencode(radice: str) -> int:
+ try:
+ with open(os.path.join(radice, OPENCODE_SORGENTE), encoding='utf-8') as h:
+ testo = h.read()
+ except OSError:
+ return 3
+ riti = COMANDI.get('riti') or {'apertura': 'apertura', 'chiusura': 'chiusura'}
+ frasi = {'apertura': F('apertura'), 'chiusura': F('chiusura'), 'ciclo': F('ciclo_opencode'), 'fermo': F('fermo_opencode'), 'v1': F('opencode_v1'), 'permesso': F('permesso_opencode', rifiutati='{rifiutati}', permesso='{permesso}', ammessi='{ammessi}'), 'ammessi': F('ammessi_opencode', elenco='{elenco}')}
+ testo = re.sub('const RITI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const RITI = ' + json.dumps(riti, ensure_ascii=False), testo, count=1)
+ testo = re.sub('const FRASI\\s*=\\s*\\{[^}]*\\}', lambda _m: 'const FRASI = ' + json.dumps(frasi, ensure_ascii=False), testo, count=1)
+ dove = os.path.join(radice, OPENCODE_PLUGIN)
+ try:
+ with open(dove, encoding='utf-8') as h:
+ prima = h.read()
+ except OSError:
+ prima = None
+ if prima == testo:
+ return 0
+ if prima is not None and (not _nostro_opencode(prima)):
+ return 3
+ os.makedirs(os.path.dirname(dove), exist_ok=True)
+ with open(dove + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ os.replace(dove + '.nuovo', dove)
+ return 0
+
+def opencode_via(radice: str) -> None:
+ dove = os.path.join(radice, OPENCODE_PLUGIN)
+ try:
+ with open(dove, encoding='utf-8') as h:
+ if not _nostro_opencode(h.read()):
+ return
+ os.remove(dove)
+ os.rmdir(os.path.dirname(dove))
+ os.rmdir(os.path.dirname(os.path.dirname(dove)))
+ except OSError:
+ pass
+
+def main(argv: list[str]) -> int:
+ if argv[:1] == ['app-codex'] and len(argv) <= 2:
+ quale = argv[1] if len(argv) == 2 else ''
+ if quale == 'stato':
+ print(app_codex_stato())
+ return 0
+ gesti = {'': app_codex, 'allinea': app_codex_allinea, 'via': app_codex_via, 'no': app_codex_no, 'lascia': app_codex_lascia}
+ if quale in gesti:
+ return gesti[quale]()
+ if len(argv) != 2 or argv[0] not in ('claude', 'claude-al-lancio', 'codex', 'qwen', 'qwen-via', 'rimuovi', 'opencode'):
+ print(F('uso'), file=sys.stderr)
+ return 1
+ if argv[0] in ('codex', 'qwen', 'qwen-via'):
+ return {'codex': codex, 'qwen': qwen, 'qwen-via': qwen_via}[argv[0]](os.path.realpath(argv[1]))
+ radice = os.path.realpath(argv[1])
+ return {'claude': claude, 'claude-al-lancio': claude_al_lancio, 'rimuovi': rimuovi, 'opencode': opencode}[argv[0]](radice)
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/it/squadra-client b/kit/it/squadra-client
new file mode 100644
index 0000000..2107725
--- /dev/null
+++ b/kit/it/squadra-client
@@ -0,0 +1,753 @@
+#!/usr/bin/env python3
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+"""La squadra di Delminio su questo computer (F810, F867): ciò che lo spazio dà a ogni suo"""
+from __future__ import annotations
+import hashlib
+import json
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+NOME = 'delminio'
+FRASI = {
+ "uso": "uso: python3 .claude/squadra.py accetta \xb7 lancio <cli> <dove> \xb7 codex|qwen <cartella della CLI> \xb7 stacca <radice del repo>",
+ "squadra_descrizione": "Le skill della squadra, da Delminio",
+ "squadra_mcp_domanda": "\nIl server MCP \xab{nome}\xbb della squadra dello spazio:\n {cosa}\n\nGirer\xe0 su questo computer, coi tuoi permessi, ogni volta che parte un agente. Lo accetti? [s/N] ",
+ "squadra_mcp_locale": "il comando che parte qui: {comando}\n le variabili d'ambiente che riceve: {variabili}",
+ "squadra_mcp_remoto": "l'indirizzo che chiama: {url}\n la variabile d'ambiente che gli manda come chiave: {variabile}",
+ "squadra_mcp_si": "s si s\xec y",
+ "squadra_mcp_accettati": "\u2705 server MCP e plugin della squadra: {nuovi} accettati ora \xb7 {restano} restano fermi (se uno cambia, lo richiedo)",
+ "squadra_plugin_domanda": "\nIl plugin \xab{nome}\xbb della squadra dello spazio:\n dal marketplace {mercato} ({origine}), per {cli}\n\nUn plugin pu\xf2 portare comandi, hook e server che girano su questo computer coi tuoi permessi. Lo installo? [s/N] "
+}
+
+def F(chiave: str, **valori) -> str:
+ testo = FRASI[chiave]
+ for k, v in valori.items():
+ testo = testo.replace('{' + k + '}', str(v))
+ return testo
+
+def _claude(*argomenti: str, cwd: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CLAUDE') or 'claude', 'plugin', *argomenti], cwd=cwd, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+
+def _codex(casa: str, *argomenti: str) -> subprocess.CompletedProcess:
+ return subprocess.run([os.environ.get('DELMINIO_CODEX') or 'codex', 'plugin', *argomenti], env={**os.environ, 'CODEX_HOME': casa}, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+SQUADRA_MKT = NOME + '-squadra-'
+NOME_PLUGIN_OK = re.compile('[a-z0-9]+(?:-[a-z0-9]+)*')
+
+def cartella_squadre() -> str:
+ return os.path.join(os.environ.get('XDG_DATA_HOME') or os.path.expanduser('~/.local/share'), 'delminio', 'squadre')
+
+def _chiave_ok(chiave: str) -> bool:
+ return bool(re.fullmatch('[0-9a-f]{12}', chiave or ''))
+
+def squadra_di(chiave: str) -> dict:
+ d = os.path.join(cartella_squadre(), chiave)
+ try:
+ with open(os.path.join(d, '.claude-plugin', 'marketplace.json'), encoding='utf-8') as h:
+ m = json.load(h)
+ p = m['plugins'][0]
+ with open(os.path.join(d, '.impronta'), encoding='utf-8') as h:
+ impronta = h.read().strip()
+ except (OSError, ValueError, KeyError, IndexError, TypeError):
+ return {}
+ if not _chiave_ok(chiave) or not NOME_PLUGIN_OK.fullmatch(str(p.get('name') or '')):
+ return {}
+ try:
+ with open(os.path.join(d, '.ruoli.json'), encoding='utf-8') as h:
+ di_chi = json.load(h)
+ except (OSError, ValueError):
+ di_chi = {}
+ return {'cartella': d, 'plugin': p['name'], 'versione': str(p.get('version') or ''), 'marketplace': m.get('name') or '', 'impronta': impronta, 'ruoli': di_chi if isinstance(di_chi, dict) else {}}
+
+def _norm_ruolo(nome: str) -> str:
+ return ''.join((c for c in (nome or '').lower() if c.isalnum()))
+
+def _testa(testo: str) -> tuple[dict, str]:
+ m = re.match('^---\\s*\\n(.*?)\\n---\\s*(?:\\n|$)', testo, re.S)
+ if not m:
+ return ({}, testo)
+ campi = {}
+ for riga in m.group(1).splitlines():
+ k, _, v = riga.partition(':')
+ v = v.strip()
+ if v[:1] == '"':
+ try:
+ v = json.loads(v)
+ except ValueError:
+ v = v.strip('"')
+ campi[k.strip()] = v
+ return (campi, testo[m.end():])
+
+def _col_nome(testo: str, nome: str) -> str:
+ m = re.match('^---[ \\t]*\\n(.*?)\\n---[ \\t]*(?:\\n|$)', testo, re.S)
+ if not m:
+ return f'---\nname: {nome}\n---\n' + testo
+ righe = [r for r in m.group(1).splitlines() if not re.match('name[ \\t]*:', r)]
+ return '---\n' + '\n'.join([f'name: {nome}', *righe]) + '\n---\n' + testo[m.end():]
+
+def _mcp_claude(spec: dict) -> dict:
+ if spec.get('tipo') == 'remoto':
+ t = spec.get('token_variabile')
+ return {'type': 'http', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
+ return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})}
+
+def _mcp_qwen(spec: dict) -> dict:
+ if spec.get('tipo') == 'remoto':
+ t = spec.get('token_variabile')
+ return {'httpUrl': spec['url'], **({'headers': {'Authorization': 'Bearer ${' + t + '}'}} if t else {})}
+ return {'command': spec['comando'], 'args': list(spec.get('argomenti') or []), **({'env': {v: '${' + v + '}' for v in spec.get('variabili') or []}} if spec.get('variabili') else {})}
+_TESTA_AMMESSA = frozenset({'name', 'description', 'argument-hint', 'when_to_use', 'disable-model-invocation', 'user-invocable', 'model', 'color', 'tools', 'modelConfig', 'runConfig'})
+_CHIAVE_TESTA = re.compile('([A-Za-z_][\\w-]*)[ \\t]*:(?:[ \\t]|$)')
+
+def _testa_ripulita(testo: str) -> str:
+ m = re.match('^(\\ufeff?\\s*---[ \\t]*\\r?\\n)(.*?)(\\r?\\n---[ \\t]*(?:\\r?\\n|$))', testo, re.S)
+ if not m:
+ return testo
+ tenute, tieni = ([], False)
+ for riga in re.split('\\r\\n|\\r|\\n', m.group(2)):
+ if riga[:1] not in (' ', '\t'):
+ k = _CHIAVE_TESTA.match(riga)
+ tieni = bool(k) and k.group(1) in _TESTA_AMMESSA
+ if tieni:
+ tenute.append(riga)
+ return '---\n' + ''.join((r + '\n' for r in tenute)) + '---\n' + testo[m.end():]
+
+def _stampabile(v) -> bool:
+ if isinstance(v, str):
+ return v.isprintable()
+ if isinstance(v, dict):
+ return all((_stampabile(k) and _stampabile(x) for k, x in v.items()))
+ if isinstance(v, list):
+ return all((_stampabile(x) for x in v))
+ return True
+
+def _visibile(v) -> str:
+ return ''.join((c if c.isprintable() else c.encode('unicode_escape').decode('ascii') for c in str(v)))
+
+def _mcp_impronta(nome: str, spec: dict) -> str:
+ return hashlib.sha256(json.dumps([nome, spec], sort_keys=True, ensure_ascii=False).encode()).hexdigest()[:24]
+
+def _accettati_file(chiave: str) -> str:
+ return os.path.join(cartella_squadre(), chiave + '.mcp-accettati')
+
+def mcp_accettati(chiave: str) -> set[str]:
+ try:
+ with open(_accettati_file(chiave), encoding='utf-8') as h:
+ return set(h.read().split())
+ except OSError:
+ return set()
+
+def _squadra_contenuti(chiave: str, pacco: dict) -> dict[str, str]:
+ plugin = str(pacco.get('plugin') or 'squadra')
+ if not NOME_PLUGIN_OK.fullmatch(plugin):
+ plugin = 'squadra'
+ impronta = str(pacco.get('impronta') or '')
+ descrizione = F('squadra_descrizione')
+ mkt = SQUADRA_MKT + chiave
+ pezzi = pacco.get('pezzi') if isinstance(pacco.get('pezzi'), list) else [{**x, 'tipo': 'skill'} for x in pacco.get('skill') or [] if isinstance(x, dict)]
+ tutti, plugin_squadra = ([], [])
+ for x in pezzi:
+ tipo, nome = (str(x.get('tipo') or ''), str(x.get('nome') or ''))
+ if tipo == 'plugin' and NOME_PLUGIN_OK.fullmatch(nome) and (len(nome) <= 64):
+ if (spec := _plugin_spec((x.get('file') or {}).get('plugin.json'))):
+ plugin_squadra.append({'nome': nome, 'spec': spec, 'impronta': _mcp_impronta(nome, spec), 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})})
+ continue
+ if tipo not in ('skill', 'comando', 'agente', 'mcp') or not NOME_PLUGIN_OK.fullmatch(nome) or len(nome) > 64:
+ continue
+ file = {}
+ for rel, testo in (x.get('file') or {}).items():
+ pezzi_rel = str(rel).replace('\\', '/').split('/')
+ if isinstance(testo, str) and (not any((not q or q.startswith('.') for q in pezzi_rel))):
+ file[os.path.join(*pezzi_rel)] = testo
+ principale = {'skill': 'SKILL.md', 'comando': 'comando.md', 'agente': 'agente.md', 'mcp': 'mcp.json'}[tipo]
+ if principale not in file:
+ continue
+ if tipo != 'mcp':
+ file[principale] = _testa_ripulita(file[principale])
+ spec = {}
+ if tipo == 'mcp':
+ try:
+ spec = json.loads(file[principale])
+ spec = {k: v for k, v in spec.items() if k != 'descrizione'}
+ _mcp_claude(spec)
+ except (ValueError, KeyError, TypeError, AttributeError):
+ continue
+ if not _stampabile(spec):
+ continue
+ tutti.append({'tipo': tipo, 'nome': nome, 'file': file, 'principale': principale, 'spec': spec, 'ruoli': sorted({_norm_ruolo(r) for r in x.get('ruoli') or [] if _norm_ruolo(r)})})
+ accettati = mcp_accettati(chiave)
+ fermi = [{'nome': x['nome'], 'spec': x['spec'], 'impronta': _mcp_impronta(x['nome'], x['spec'])} for x in tutti if x['tipo'] == 'mcp' and _mcp_impronta(x['nome'], x['spec']) not in accettati]
+ via = {x['nome'] for x in fermi}
+ tutti = [x for x in tutti if not (x['tipo'] == 'mcp' and x['nome'] in via)]
+ dentro = sorted((_mcp_impronta(x['nome'], x['spec']) for x in tutti if x['tipo'] == 'mcp'))
+ minore = int(hashlib.sha256(' '.join(dentro).encode()).hexdigest()[:5], 16) + 1 if dentro else 0
+ versione = f"1.{minore}.{int((impronta or '0')[:7], 16)}"
+ f: dict[str, str] = {}
+ manifesto = {'name': plugin, 'version': versione, 'description': descrizione}
+
+ def un_plugin(dove: str, scelti) -> None:
+ mcp_claude, mcp_qwen = ({}, {})
+ for x in scelti:
+ n = x['nome']
+ if x['tipo'] == 'skill':
+ for rel, testo in x['file'].items():
+ f[os.path.join(dove, 'skills', n, rel)] = testo
+ elif x['tipo'] == 'comando':
+ f[os.path.join(dove, 'commands', n + '.md')] = x['file']['comando.md']
+ elif x['tipo'] == 'agente':
+ f[os.path.join(dove, 'agents', n + '.md')] = x['file']['agente.md']
+ else:
+ mcp_claude[n] = _mcp_claude(x['spec'])
+ mcp_qwen[plugin + '-' + n] = _mcp_qwen(x['spec'])
+ f[os.path.join(dove, '.claude-plugin', 'plugin.json')] = json.dumps(manifesto, ensure_ascii=False, indent=2) + '\n'
+ if mcp_claude:
+ f[os.path.join(dove, '.mcp.json')] = json.dumps({'mcpServers': mcp_claude}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join(dove, 'qwen-extension.json')] = json.dumps({**manifesto, **({'mcpServers': mcp_qwen} if mcp_qwen else {})}, ensure_ascii=False, indent=2) + '\n'
+ per_tutti = [x for x in tutti if not x['ruoli']]
+ un_plugin(plugin, per_tutti)
+ for r in sorted({r for x in tutti for r in x['ruoli']}):
+ un_plugin(os.path.join('ruoli', r, plugin), per_tutti + [x for x in tutti if r in x['ruoli']])
+ lancio = {'skill': {}, 'agente': {}, 'mcp': {}}
+ for x in tutti:
+ n = x['nome']
+ if x['tipo'] == 'skill':
+ for rel, testo in x['file'].items():
+ f[os.path.join('codex', plugin, 'skills', n, rel)] = testo
+ lancio['skill'][n] = x['ruoli']
+ if len(plugin) + 1 + len(n) <= 64:
+ for rel, testo in x['file'].items():
+ f[os.path.join('opencode', 'skills', f'{plugin}-{n}', rel)] = _col_nome(testo, f'{plugin}-{n}') if rel == 'SKILL.md' else testo
+ elif x['tipo'] == 'comando':
+ campi, corpo = _testa(x['file']['comando.md'])
+ f[os.path.join('codex', plugin, 'skills', n, 'SKILL.md')] = f"---\nname: {n}\ndescription: {json.dumps(str(campi.get('description') or ''), ensure_ascii=False)}\n---\n" + corpo.lstrip('\n')
+ lancio['skill'][n] = x['ruoli']
+ elif x['tipo'] == 'agente':
+ campi, corpo = _testa(x['file']['agente.md'])
+ f[os.path.join('codex', 'agenti', n + '.toml')] = f'name = {json.dumps(n)}\ndeveloper_instructions = {json.dumps(corpo.strip(), ensure_ascii=False)}\n'
+ lancio['agente'][n] = {'ruoli': x['ruoli'], 'descrizione': str(campi.get('description') or '')}
+ else:
+ lancio['mcp'][n] = {'ruoli': x['ruoli'], 'spec': x['spec']}
+ f[os.path.join('codex', plugin, '.codex-plugin', 'plugin.json')] = json.dumps({**manifesto, 'skills': './skills/'}, ensure_ascii=False, indent=2) + '\n'
+ lancio['conto'] = {t: sum((1 for x in tutti if x['tipo'] == t)) for t in ('skill', 'comando', 'agente', 'mcp')}
+ lancio['conto']['mcp_fermi'] = len(fermi)
+ f['.ruoli.json'] = json.dumps(lancio, indent=2, sort_keys=True, ensure_ascii=False) + '\n'
+ f[os.path.join('.claude-plugin', 'marketplace.json')] = json.dumps({'name': mkt, 'owner': {'name': 'Delminio'}, 'plugins': [{'name': plugin, 'source': './' + plugin, 'description': descrizione, 'version': versione}]}, ensure_ascii=False, indent=2) + '\n'
+ f[os.path.join('.agents', 'plugins', 'marketplace.json')] = json.dumps({'name': mkt, 'interface': {'displayName': 'Delminio'}, 'plugins': [{'name': plugin, 'source': {'source': 'local', 'path': './codex/' + plugin}, 'policy': {'installation': 'AVAILABLE', 'authentication': 'ON_INSTALL'}, 'category': 'Developer Tools'}]}, ensure_ascii=False, indent=2) + '\n'
+ f['.impronta'] = impronta + '\n'
+ f['.pacco.json'] = json.dumps(pacco, ensure_ascii=False, sort_keys=True) + '\n'
+ if fermi:
+ f['.mcp-fermi.json'] = json.dumps(fermi, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ if plugin_squadra:
+ presi = plugin_accettati(chiave)
+ for x in plugin_squadra:
+ x['accettato'] = x['impronta'] in presi
+ f['.plugin.json'] = json.dumps(plugin_squadra, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ if (fermi_p := [x for x in plugin_squadra if not x['accettato']]):
+ f['.plugin-fermi.json'] = json.dumps(fermi_p, ensure_ascii=False, indent=2, sort_keys=True) + '\n'
+ return f
+
+def squadra_accetta_dal_terminale() -> int:
+ radice = cartella_squadre()
+ try:
+ chiavi = sorted((c for c in os.listdir(radice) if _chiave_ok(c)))
+ except OSError:
+ return 0
+ try:
+ tty_in, tty = (open('/dev/tty'), open('/dev/tty', 'w'))
+ except OSError:
+ return 1
+ nuovi = restano = 0
+ for chiave in chiavi:
+ d = os.path.join(radice, chiave)
+ try:
+ with open(os.path.join(d, '.pacco.json'), encoding='utf-8') as h:
+ pacco = json.load(h)
+ except (OSError, ValueError):
+ continue
+ try:
+ with open(os.path.join(d, '.mcp-fermi.json'), encoding='utf-8') as h:
+ fermi = json.load(h)
+ except (OSError, ValueError):
+ fermi = []
+ accettati, presi = (mcp_accettati(chiave), 0)
+ for x in fermi if isinstance(fermi, list) else []:
+ spec, nome = (x.get('spec') or {}, str(x.get('nome') or ''))
+ if not isinstance(spec, dict) or not _stampabile(spec):
+ restano += 1
+ continue
+ if spec.get('tipo') == 'remoto':
+ cosa = F('squadra_mcp_remoto', url=_visibile(spec.get('url') or ''), variabile=_visibile(spec.get('token_variabile') or '—'))
+ else:
+ cosa = F('squadra_mcp_locale', comando=_visibile(shlex.join([str(spec.get('comando') or '')] + [str(a) for a in spec.get('argomenti') or []])), variabili=_visibile(', '.join((str(v) for v in spec.get('variabili') or [])) or '—'))
+ tty.write(F('squadra_mcp_domanda', nome=_visibile(nome), cosa=cosa))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
+ accettati.add(_mcp_impronta(nome, spec))
+ presi += 1
+ else:
+ restano += 1
+ try:
+ with open(os.path.join(d, '.plugin-fermi.json'), encoding='utf-8') as h:
+ plugin_fermi = json.load(h)
+ except (OSError, ValueError):
+ plugin_fermi = []
+ presi_p, plugin_presi = (0, plugin_accettati(chiave))
+ for x in plugin_fermi if isinstance(plugin_fermi, list) else []:
+ spec, nome = (_plugin_spec(json.dumps((x or {}).get('spec'))), str((x or {}).get('nome') or ''))
+ if not spec or not NOME_PLUGIN_OK.fullmatch(nome):
+ restano += 1
+ continue
+ tty.write(F('squadra_plugin_domanda', nome=_visibile(nome), mercato=_visibile(spec['mercato']), origine=_visibile(spec['origine']), cli=', '.join(spec['cli'])))
+ tty.flush()
+ if tty_in.readline().strip().lower() in F('squadra_mcp_si').split():
+ plugin_presi.add(_mcp_impronta(nome, spec))
+ presi_p += 1
+ else:
+ restano += 1
+ if presi_p:
+ os.makedirs(radice, exist_ok=True)
+ with open(_plugin_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(''.join((i + '\n' for i in sorted(plugin_presi))))
+ os.replace(_plugin_accettati_file(chiave) + '.nuovo', _plugin_accettati_file(chiave))
+ presi += presi_p
+ if presi:
+ os.makedirs(radice, exist_ok=True)
+ with open(_accettati_file(chiave) + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(''.join((i + '\n' for i in sorted(accettati))))
+ os.replace(_accettati_file(chiave) + '.nuovo', _accettati_file(chiave))
+ squadra_scrivi(chiave, pacco)
+ nuovi += presi
+ if nuovi or restano:
+ print(F('squadra_mcp_accettati', nuovi=nuovi, restano=restano))
+ return 0
+
+def squadra_scrivi(chiave: str, pacco: dict) -> dict:
+ if not _chiave_ok(chiave):
+ return {}
+ d = os.path.join(cartella_squadre(), chiave)
+ if not (pacco.get('pezzi') or pacco.get('skill')):
+ shutil.rmtree(d, ignore_errors=True)
+ return {}
+ voluti = _squadra_contenuti(chiave, pacco)
+ for rel, testo in voluti.items():
+ p = os.path.join(d, rel)
+ try:
+ with open(p, encoding='utf-8') as h:
+ if h.read() == testo:
+ continue
+ except (OSError, UnicodeDecodeError):
+ pass
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(testo)
+ os.replace(p + '.nuovo', p)
+ for radice, cartelle, nomi in os.walk(d, topdown=False):
+ for n in nomi:
+ rel = os.path.relpath(os.path.join(radice, n), d)
+ if rel not in voluti:
+ os.remove(os.path.join(radice, n))
+ if radice != d and (not os.listdir(radice)):
+ os.rmdir(radice)
+ return squadra_di(chiave)
+
+def _squadra_id(sq: dict) -> str:
+ return f"{sq['plugin']}@{sq['marketplace']}"
+
+def squadra_claude(radice: str, chiave: str) -> int:
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ s = {}
+ accesi = s.get('enabledPlugins') if isinstance(s.get('enabledPlugins'), dict) else {}
+ mkt = SQUADRA_MKT + chiave
+ sq = squadra_di(chiave)
+ voluto = _squadra_id(sq) if sq else ''
+ vecchi = [k for k in accesi if k.endswith('@' + mkt) and k != voluto]
+ if (not voluto or accesi.get(voluto) is True) and (not vecchi):
+ return 0
+ if not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude'):
+ return 3
+ try:
+ for k in vecchi:
+ _claude('uninstall', k, '--scope', 'local', cwd=radice)
+ if voluto:
+ _claude('marketplace', 'add', sq['cartella'], '--scope', 'local', cwd=radice)
+ _claude('install', voluto, '--scope', 'local', cwd=radice)
+ else:
+ _claude('marketplace', 'remove', mkt, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ return 3
+ return 0
+
+def _squadra_codex(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa))
+ if not _chiave_ok(chiave):
+ return
+ sq = squadra_di(chiave)
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ conf = ''
+ mkt = SQUADRA_MKT + chiave
+ if not sq:
+ for m in re.finditer('^\\[plugins\\."([a-z0-9-]+@' + re.escape(mkt) + ')"\\]', conf, re.M):
+ _codex(casa, 'remove', m.group(1))
+ if mkt in conf:
+ _codex(casa, 'marketplace', 'remove', mkt)
+ return
+ pid = _squadra_id(sq)
+ acceso = re.search('^\\[plugins\\."' + re.escape(pid) + '"\\]\\s*\\nenabled\\s*=\\s*true', conf, re.M)
+ if acceso and os.path.isdir(os.path.join(casa, 'plugins', 'cache', mkt, sq['plugin'], sq['versione'])):
+ return
+ _codex(casa, 'marketplace', 'add', sq['cartella'])
+ _codex(casa, 'add', pid)
+
+def _squadra_qwen(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
+ if not _chiave_ok(chiave):
+ return
+ sq = squadra_di(chiave)
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ via = [n for n in (os.listdir(os.path.join(casa, 'extensions')) if os.path.isdir(os.path.join(casa, 'extensions')) else []) if n != NOME and _collegata_a(casa, n, cartella_squadre()) and (not sq or n != sq['plugin'])]
+ for n in via:
+ subprocess.run([q, 'extensions', 'uninstall', n], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ if not sq:
+ return
+ del_ruolo = os.path.join(sq['cartella'], 'ruoli', _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')), sq['plugin'])
+ estensione = del_ruolo if _norm_ruolo(os.environ.get('DELMINIO_PORTA', '')) and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], sq['plugin'])
+ if _collegata_a(casa, sq['plugin'], estensione):
+ return
+ subprocess.run([q, 'extensions', 'uninstall', sq['plugin']], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ subprocess.run([q, 'extensions', 'link', estensione], env=ambiente, capture_output=True, text=True, timeout=120, input='Y\n')
+_PLUGIN_ORIGINE = re.compile('(github:[A-Za-z0-9][\\w.-]*/[\\w.-]+|https://[^\\s@?#]{3,300})')
+
+def _plugin_spec(testo) -> dict:
+ try:
+ d = json.loads(testo) if isinstance(testo, str) else {}
+ except ValueError:
+ return {}
+ if not isinstance(d, dict):
+ return {}
+ mercato, origine = (str(d.get('mercato') or ''), str(d.get('origine') or ''))
+ cli = [c for c in ('claude', 'codex', 'qwen') if c in (d.get('cli') or [])]
+ if not re.fullmatch('[\\w.-]{1,100}', mercato) or not _PLUGIN_ORIGINE.fullmatch(origine) or (not cli) or (not _stampabile({'m': mercato, 'o': origine})):
+ return {}
+ return {'mercato': mercato, 'origine': origine, 'cli': cli}
+
+def _plugin_accettati_file(chiave: str) -> str:
+ return os.path.join(cartella_squadre(), chiave + '.plugin-accettati')
+
+def plugin_accettati(chiave: str) -> set[str]:
+ try:
+ with open(_plugin_accettati_file(chiave), encoding='utf-8') as h:
+ return set(h.read().split())
+ except OSError:
+ return set()
+
+def plugin_squadra(chiave: str, cli: str) -> list[dict]:
+ try:
+ with open(os.path.join(cartella_squadre(), chiave, '.plugin.json'), encoding='utf-8') as h:
+ tutti = json.load(h)
+ except (OSError, ValueError):
+ return []
+ presi = plugin_accettati(chiave)
+ return [x for x in tutti if isinstance(x, dict) and x.get('impronta') in presi and (cli in (x.get('spec') or {}).get('cli', [])) and NOME_PLUGIN_OK.fullmatch(str(x.get('nome') or '')) and _plugin_spec(json.dumps(x.get('spec')))]
+
+def _installati(chiave: str) -> dict:
+ try:
+ with open(os.path.join(cartella_squadre(), chiave + '.plugin-installati.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ return d if isinstance(d, dict) else {}
+ except (OSError, ValueError):
+ return {}
+
+def _installati_scrivi(chiave: str, d: dict) -> None:
+ p = os.path.join(cartella_squadre(), chiave + '.plugin-installati.json')
+ os.makedirs(os.path.dirname(p), exist_ok=True)
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ json.dump(d, h, indent=2, sort_keys=True)
+ os.replace(p + '.nuovo', p)
+
+def _sorgente(origine: str, cli: str) -> str:
+ if origine.startswith('github:'):
+ return origine[7:] if cli != 'qwen' else 'https://github.com/' + origine[7:]
+ return origine
+
+def _claude_installati(radice: str) -> dict:
+ cfg = os.environ.get('CLAUDE_CONFIG_DIR') or os.path.expanduser('~/.claude')
+ try:
+ with open(os.path.join(cfg, 'plugins', 'installed_plugins.json'), encoding='utf-8') as h:
+ d = json.load(h).get('plugins') or {}
+ except (OSError, ValueError, AttributeError):
+ return {}
+ return {pid: str(v.get('installPath') or '') for pid, voci in d.items() if isinstance(voci, list) for v in voci if isinstance(v, dict) and v.get('scope') in ('local', 'project') and (v.get('projectPath') == radice)}
+
+def squadra_plugin_claude(radice: str, chiave: str) -> int:
+ if not radice or not _chiave_ok(chiave) or (not shutil.which(os.environ.get('DELMINIO_CLAUDE') or 'claude')):
+ return 3
+ voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'claude')}
+ stato = _installati(chiave)
+ miei = stato.get('claude:' + radice) or {}
+ c_e = _claude_installati(radice)
+ try:
+ with open(os.path.join(radice, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ accesi = json.load(h).get('enabledPlugins') or {}
+ except (OSError, ValueError, AttributeError):
+ accesi = {}
+ for pid, x in voluti.items():
+ if pid not in c_e:
+ _claude('marketplace', 'add', _sorgente(x['spec']['origine'], 'claude'), '--scope', 'local', cwd=radice)
+ if _claude('install', pid, '--scope', 'local', cwd=radice).returncode != 0:
+ continue
+ miei[pid] = True
+ elif pid not in miei:
+ continue
+ per_tutti = not x['ruoli']
+ if per_tutti and accesi.get(pid) is not True:
+ _claude('enable', pid, '--scope', 'local', cwd=radice)
+ elif not per_tutti and accesi.get(pid) is not False:
+ _claude('disable', pid, '--scope', 'local', cwd=radice)
+ for pid in [k for k in miei if k not in voluti]:
+ _claude('uninstall', pid, '--scope', 'local', cwd=radice)
+ miei.pop(pid)
+ stato['claude:' + radice] = miei
+ _installati_scrivi(chiave, stato)
+ return 0
+
+def _squadra_plugin_codex(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa))
+ if not _chiave_ok(chiave):
+ return
+ voluti = {f"{x['nome']}@{x['spec']['mercato']}": x for x in plugin_squadra(chiave, 'codex') if not x['ruoli']}
+ stato = _installati(chiave)
+ miei = stato.get('codex:' + casa) or {}
+ try:
+ with open(os.path.join(casa, 'config.toml'), encoding='utf-8') as h:
+ conf = h.read()
+ except OSError:
+ conf = ''
+ for pid, x in voluti.items():
+ if f'[plugins."{pid}"]' in conf:
+ continue
+ if f"[marketplaces.{x['spec']['mercato']}]" not in conf:
+ _codex(casa, 'marketplace', 'add', _sorgente(x['spec']['origine'], 'codex'))
+ if _codex(casa, 'add', pid).returncode == 0:
+ miei[pid] = True
+ for pid in [k for k in miei if k not in voluti]:
+ _codex(casa, 'remove', pid)
+ miei.pop(pid)
+ stato['codex:' + casa] = miei
+ _installati_scrivi(chiave, stato)
+
+def _squadra_plugin_qwen(casa: str) -> None:
+ chiave = os.path.basename(os.path.normpath(casa)).split('-', 1)[0]
+ if not _chiave_ok(chiave):
+ return
+ ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
+ voluti = {x['nome']: x for x in plugin_squadra(chiave, 'qwen') if not x['ruoli'] or ruolo in x['ruoli']}
+ stato = _installati(chiave)
+ miei = stato.get('qwen:' + casa) or {}
+ q = os.environ.get('DELMINIO_QWEN') or 'qwen'
+ ambiente = {**os.environ, 'QWEN_HOME': casa}
+ for nome, x in voluti.items():
+ if os.path.isdir(os.path.join(casa, 'extensions', nome)):
+ continue
+ r = subprocess.run([q, 'extensions', 'install', f"{_sorgente(x['spec']['origine'], 'qwen')}:{nome}", '--consent'], env=ambiente, capture_output=True, text=True, timeout=300, stdin=subprocess.DEVNULL)
+ if r.returncode == 0:
+ miei[nome] = True
+ for nome in [k for k in miei if k not in voluti]:
+ subprocess.run([q, 'extensions', 'uninstall', nome], env=ambiente, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
+ miei.pop(nome)
+ stato['qwen:' + casa] = miei
+ _installati_scrivi(chiave, stato)
+
+def squadra_lancio(cli: str, dove: str) -> list[str]:
+ ruolo = _norm_ruolo(os.environ.get('DELMINIO_PORTA', ''))
+ if cli == 'claude':
+ try:
+ with open(os.path.join(dove, '.claude', 'settings.local.json'), encoding='utf-8') as h:
+ accesi = json.load(h).get('enabledPlugins') or {}
+ except (OSError, ValueError, AttributeError):
+ return []
+ chiavi = [m.group(1) for k, v in accesi.items() if v is True for m in [re.search('@' + re.escape(SQUADRA_MKT) + '([0-9a-f]{12})$', k)] if m]
+ sq = squadra_di(chiavi[0]) if chiavi else {}
+ d = os.path.join(sq['cartella'], 'ruoli', ruolo, sq['plugin']) if sq and ruolo else ''
+ out = ['--plugin-dir', d] if d and os.path.isdir(d) else []
+ if chiavi and ruolo:
+ c_e = _claude_installati(dove)
+ for x in plugin_squadra(chiavi[0], 'claude'):
+ cartella = c_e.get(f"{x['nome']}@{x['spec']['mercato']}", '')
+ if ruolo in x['ruoli'] and cartella and os.path.isdir(cartella):
+ out += ['--plugin-dir', cartella]
+ return out
+ if cli == 'codex':
+ chiave = os.path.basename(os.path.normpath(dove))
+ sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
+ if not sq:
+ return []
+ lancio = sq['ruoli']
+ per_me = lambda r: not r or ruolo in r
+ out = []
+ base = os.path.join(dove, 'plugins', 'cache', sq['marketplace'], sq['plugin'], sq['versione'], 'skills')
+ via = [n for n, r in sorted((lancio.get('skill') or {}).items()) if not per_me(r) and NOME_PLUGIN_OK.fullmatch(n)]
+ if via:
+ voci = ','.join(('{path=' + json.dumps(os.path.join(base, n, 'SKILL.md')) + ',enabled=false}' for n in via))
+ out += ['-c', f'skills.config=[{voci}]']
+ for n, a in sorted((lancio.get('agente') or {}).items()):
+ toml = os.path.join(sq['cartella'], 'codex', 'agenti', n + '.toml')
+ if NOME_PLUGIN_OK.fullmatch(n) and per_me(a.get('ruoli')) and os.path.isfile(toml):
+ out += ['-c', f"agents.{n}.description={json.dumps(a.get('descrizione') or n, ensure_ascii=False)}", '-c', f'agents.{n}.config_file={json.dumps(toml)}']
+ for n, m in sorted((lancio.get('mcp') or {}).items()):
+ spec, k = (m.get('spec') or {}, f"{sq['plugin']}-{n}")
+ if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
+ continue
+ if spec.get('tipo') == 'remoto' and spec.get('url'):
+ out += ['-c', f"mcp_servers.{k}.url={json.dumps(spec['url'])}"]
+ if spec.get('token_variabile'):
+ out += ['-c', f"mcp_servers.{k}.bearer_token_env_var={json.dumps(spec['token_variabile'])}"]
+ elif spec.get('comando'):
+ out += ['-c', f"mcp_servers.{k}.command={json.dumps(spec['comando'])}", '-c', f"mcp_servers.{k}.args={json.dumps(list(spec.get('argomenti') or []))}"]
+ if spec.get('variabili'):
+ out += ['-c', f"mcp_servers.{k}.env_vars={json.dumps(list(spec['variabili']))}"]
+ return out
+ if cli == 'opencode':
+ return [json.dumps(_squadra_opencode(ruolo), ensure_ascii=False)]
+ return []
+
+def _squadra_opencode(ruolo: str) -> dict:
+ chiave = os.environ.get('DELMINIO_SQUADRA', '')
+ sq = squadra_di(chiave) if _chiave_ok(chiave) else {}
+ if not sq:
+ return {}
+ lancio, plugin = (sq['ruoli'], sq['plugin'])
+ per_me = lambda r: not r or ruolo in r
+ skill = [os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}') for n, r in sorted((lancio.get('skill') or {}).items()) if per_me(r) and NOME_PLUGIN_OK.fullmatch(n) and os.path.isfile(os.path.join(sq['cartella'], 'opencode', 'skills', f'{plugin}-{n}', 'SKILL.md'))]
+ del_ruolo = os.path.join(sq['cartella'], 'ruoli', ruolo, plugin)
+ base = del_ruolo if ruolo and os.path.isdir(del_ruolo) else os.path.join(sq['cartella'], plugin)
+ comandi, agenti = ({}, {})
+ for cartella, dove in (('commands', comandi), ('agents', agenti)):
+ try:
+ nomi = sorted(os.listdir(os.path.join(base, cartella)))
+ except OSError:
+ nomi = []
+ for x in nomi:
+ n = x[:-3] if x.endswith('.md') else ''
+ if not NOME_PLUGIN_OK.fullmatch(n):
+ continue
+ try:
+ with open(os.path.join(base, cartella, x), encoding='utf-8') as h:
+ campi, corpo = _testa(h.read())
+ except OSError:
+ continue
+ descrizione = str(campi.get('description') or n)
+ if cartella == 'commands':
+ dove[f'{plugin}:{n}'] = {'template': corpo.strip() or '$ARGUMENTS', 'description': descrizione}
+ else:
+ dove[f'{plugin}-{n}'] = {'mode': 'subagent', 'description': descrizione, 'system': corpo.strip()}
+ server = {}
+ for n, m in sorted((lancio.get('mcp') or {}).items()):
+ spec = m.get('spec') or {}
+ if not NOME_PLUGIN_OK.fullmatch(n) or not per_me(m.get('ruoli')):
+ continue
+ if spec.get('tipo') == 'remoto' and spec.get('url'):
+ t = spec.get('token_variabile')
+ s = {'type': 'remote', 'url': spec['url'], **({'headers': {'Authorization': 'Bearer {env:' + t + '}'}} if t else {})}
+ elif spec.get('comando'):
+ s = {'type': 'local', 'command': [str(spec['comando'])] + [str(a) for a in spec.get('argomenti') or []], **({'environment': {v: '{env:' + v + '}' for v in spec['variabili']}} if spec.get('variabili') else {})}
+ else:
+ continue
+ server[f'{plugin}-{n}'] = s
+ out: dict = {}
+ if skill:
+ out['skills'] = skill
+ if comandi:
+ out['commands'] = comandi
+ if agenti:
+ out['agents'] = agenti
+ if server:
+ out['mcp'] = {'servers': server}
+ return out
+
+def _collegata_a(casa: str, nome: str, dove: str) -> bool:
+ try:
+ with open(os.path.join(casa, 'extensions', nome, '.qwen-extension-install.json'), encoding='utf-8') as h:
+ d = json.load(h)
+ except (OSError, ValueError):
+ return False
+ sorgente = os.path.realpath(d.get('source') or '')
+ dove = os.path.realpath(dove)
+ return d.get('type') == 'link' and (sorgente == dove or sorgente.startswith(dove + os.sep))
+
+def codex(casa: str) -> int:
+ try:
+ _squadra_codex(casa)
+ _squadra_plugin_codex(casa)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 0
+
+def qwen(casa: str) -> int:
+ try:
+ _squadra_qwen(casa)
+ _squadra_plugin_qwen(casa)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return 0
+
+def stacca(radice: str) -> int:
+ d = cartella_squadre()
+ for nome in sorted(os.listdir(d)) if os.path.isdir(d) else []:
+ if nome.endswith('.plugin-installati.json') and _chiave_ok(nome.split('.', 1)[0]):
+ chiave = nome.split('.', 1)[0]
+ stato = _installati(chiave)
+ miei = stato.pop('claude:' + radice, None) or {}
+ for pid in miei:
+ try:
+ _claude('uninstall', pid, '--scope', 'local', cwd=radice)
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ if miei:
+ _installati_scrivi(chiave, stato)
+ p = os.path.join(radice, '.claude', 'settings.local.json')
+ try:
+ with open(p, encoding='utf-8') as h:
+ s = json.load(h)
+ except (OSError, ValueError):
+ return 0
+ cambiato = False
+ for k in [k for k in s.get('enabledPlugins') or {} if k.split('@', 1)[-1].startswith(SQUADRA_MKT)]:
+ del s['enabledPlugins'][k]
+ cambiato = True
+ if isinstance(s.get('enabledPlugins'), dict) and (not s['enabledPlugins']):
+ del s['enabledPlugins']
+ mercati = s.get('extraKnownMarketplaces')
+ for m in [m for m in mercati or {} if m.startswith(SQUADRA_MKT)] if isinstance(mercati, dict) else []:
+ del mercati[m]
+ cambiato = True
+ if isinstance(mercati, dict) and (not mercati):
+ del s['extraKnownMarketplaces']
+ if cambiato:
+ with open(p + '.nuovo', 'w', encoding='utf-8') as h:
+ h.write(json.dumps(s, indent=2, ensure_ascii=False) + '\n')
+ os.replace(p + '.nuovo', p)
+ return 0
+
+def main(argv: list[str]) -> int:
+ if argv == ['accetta']:
+ return squadra_accetta_dal_terminale()
+ if len(argv) == 3 and argv[0] == 'lancio':
+ for x in squadra_lancio(argv[1], os.path.realpath(argv[2])):
+ print(x)
+ return 0
+ if len(argv) == 2 and argv[0] in ('codex', 'qwen', 'stacca'):
+ return {'codex': codex, 'qwen': qwen, 'stacca': stacca}[argv[0]](os.path.realpath(argv[1]))
+ print(F('uso'), file=sys.stderr)
+ return 1
+if __name__ == '__main__':
+ sys.exit(main(sys.argv[1:]))
diff --git a/kit/it/worktree-client b/kit/it/worktree-client
new file mode 100644
index 0000000..b20c45c
--- /dev/null
+++ b/kit/it/worktree-client
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+# © 2026 Delminio — tutti i diritti riservati. Software proprietario, concesso in licenza d'uso (LICENZA.md, o i Termini del servizio del cloud): copia, modifica e redistribuzione fuori dall'uso con Delminio non sono consentite.
+case "${1:-}" in
+ nuovo|merge|smonta)
+ principale=$(cd "$(dirname "$(_assoluto "$0")")/.." && pwd)
+ if f=$(chiedi GET /api/funzioni); then
+ perche=$(printf '%s' "$f" | python3 -c 'import json,sys
+x = next((x for x in json.load(sys.stdin)["funzioni"] if x["id"] == "agenti"), {})
+print("" if x.get("accesa", True) else "licenza" if x.get("concessa") is False else "spenta")' 2>/dev/null || true)
+ case "$perche" in
+ licenza) echo "$M_piu_agenti_non_concessa" >&2; exit 1 ;;
+ spenta) echo "$M_piu_agenti_insieme" >&2; exit 1 ;;
+ esac
+ fi
+ remoto=$(git -C "$principale" remote get-url origin 2>/dev/null || true)
+ pid=$(cli_pid || true); nome="${2:-}"; [ -z "$nome" ] && [ -n "$pid" ] && nome=$(mia_sessione "$pid")
+ [ -n "$nome" ] || { _f "$M_chi_sei_bash" gesto "$1" >&2; exit 1; }
+ qui=$(git rev-parse --show-toplevel 2>/dev/null || echo "$principale")
+ if [ -z "${DELMINIO_WORKTREE_DEL_PROGETTO:-}" ] && [ -x "$qui/.delminio/worktree" ]; then
+ DELMINIO_WORKTREE_DEL_PROGETTO=1 exec "$qui/.delminio/worktree" "$1" "$nome"
+ fi
+ ramo="sessione/$nome"; wt="$(dirname "$principale")/$(basename "$principale")-$nome"
+ case "$1" in
+ nuovo)
+ [ -e "$wt" ] && { _f "$M_gia_entraci_smontalo" wt "$wt" >&2; exit 1; }
+ [ -z "$remoto" ] || git -C "$principale" pull -q --ff-only 2>/dev/null || echo "$M_principale_aggiorna_remoto" >&2
+ git -C "$principale" worktree add -q "$wt" -b "$ramo" || exit 1
+ for f in $KIT_FILE; do
+ [ -e "$principale/$f" ] && mkdir -p "$wt/$(dirname "$f")" && ln -sfn "$principale/$f" "$wt/$f"
+ done
+ _f "$M_ramo" wt "$wt" ramo "$ramo"
+ case "$( [ -n "$pid" ] && cli_di "$pid")" in
+ codex)
+ _f "$M_codex_resta_dov" wt "$wt" ;;
+ claude)
+ echo "$M_entraci_col_tool"
+ echo "$M_lavoro_tocca_altro" ;;
+ *)
+ _f "$M_tua_cli_modo" wt "$wt" ;;
+ esac
+ ;;
+ merge)
+ dove=$(git rev-parse --show-toplevel)
+ [ "$dove" = "$wt" ] || { _f "$M_merge_lancia_tuo" wt "$wt" dove "$dove" >&2; exit 1; }
+ [ -z "$(git status --porcelain --untracked-files=no)" ] || { echo "$M_hai_lavoro_committato" >&2; git status --short | head -10 >&2; exit 1; }
+ exec 9>"$(git rev-parse --git-common-dir)/delminio-merge.lock"
+ _lucchetto 600 || { echo "$M_altro_merge_corso" >&2; exit 1; }
+ staged=$(git -C "$principale" diff --cached --name-only)
+ [ -z "$staged" ] || { echo "$M_principale_lavoro_staging" >&2; echo "$staged" | head -10 >&2; exit 1; }
+ [ -z "$remoto" ] || git -C "$principale" pull -q --ff-only 2>/dev/null || { echo "$M_principale_aggiorna_remoto_2" >&2; exit 1; }
+ collisione=$(comm -12 <(git -C "$principale" diff --name-only | sort -u) <(git diff --name-only "$(git merge-base HEAD "$(git -C "$principale" rev-parse HEAD)")" HEAD | sort -u))
+ [ -z "$collisione" ] || { echo "$M_merge_toccherebbe_file" >&2; echo "$collisione" | head -10 >&2; exit 1; }
+ git -C "$principale" merge -q --no-edit "$ramo" || { git -C "$principale" merge --abort 2>/dev/null; ramo_principale=$(git -C "$principale" rev-parse --abbrev-ref HEAD); _f "$M_merge_non_pulito" ramo "$ramo_principale" >&2; exit 1; }
+ if [ -z "$remoto" ]; then
+ _f "$M_principale_senza_remoto" ramo "$ramo"
+ else
+ git -C "$principale" push -q origin HEAD || { echo "$M_mergiato_locale_push" >&2; exit 1; }
+ _f "$M_principale_remoto" ramo "$ramo"
+ fi
+ ;;
+ smonta)
+ [ -d "$wt" ] || { _f "$M_nessun_worktree" wt "$wt"; exit 0; }
+ sporchi=$(git -C "$wt" status --porcelain 2>/dev/null)
+ [ -z "$sporchi" ] || { _f "$M_file_committati_smonta" wt "$wt" >&2; exit 1; }
+ git -C "$principale" merge-base --is-ancestor "$ramo" HEAD \
+ || { _f "$M_principale_prima_merge" ramo "$ramo" >&2; exit 1; }
+ git -C "$principale" worktree remove "$wt" && git -C "$principale" branch -q -d "$ramo" && _f "$M_smontato_tolto" wt "$wt" ramo "$ramo"
+ ;;
+ esac
+ ;;
+esac