#!/usr/bin/env python3 # © 2026 Delminio — tutti i diritti riservati. Software proprietario: l'uso con Delminio è regolato dal contratto con cui si usa il servizio; la lettura e la verifica da LICENCE. """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 the full card\n {cmd} search \"\" the closest semantically, done ones included (a number: that one)\n \u26d4 open needs --asked \"\", or at the session end --half-done \"\"\n {cmd} open --title \"...\" --risk \"...\" --done-when \"...\" --domain \\\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 \"\"]\n [--wait-for B] optional: created on hold until B is done\n {cmd} open --decision --title \"...\" --risk \"...\" --to-decide \"which decision is missing\" --domain \n {cmd} open --follow-up --title \"...\" --when \\\n --must-be-true \"what must be true that day\" --domain [--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 [\"why\"] looked at, not yet decidable\n {cmd} link [--memory \"X\"] [--remove \"X\"] the memories to read before touching it\n {cmd} take \xb7 release \xb7 reopen \n {cmd} answer \"\" 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 \"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 the admin gives a task to a person (without a login it frees it)\n {cmd} note \"\" what you found out, without closing it (--replace to rewrite)\n {cmd} edit [--title ..] [--risk ..] [--done-when ..] [--priority 1-4|none] [--autocheck \"cmd\"|none]\n [--owner ..] [--question \"..\"|none] [--type decision|action]\n {cmd} close [\"how\"] it's done, and how \u2014 an item to decide: the decision and why\n {cmd} hold \"\" not debt: it's waiting for something\n {cmd} wait B [B] waits for other tasks: it goes on hold, and when the last one is done\n it reopens by itself \xb7 --remove B 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 {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 \"$()\" -eq 0 \xb7 | grep -q ''\nWhat it answered:\n", "argomento_sconosciuto": "\u274c unknown argument: {argomento}", "vuole_valore": "\u274c {argomento} needs a value", "uso_mostra": "usage: {cmd} show ", "uso_cerca": "usage: {cmd} search \"\"", "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 B [B] \xb7 --remove B", "uso_rinvia": "usage: {cmd} postpone [\"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 \"\"", "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)