@legios/quartermaster 0.1.6 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -36,7 +36,54 @@ function finDelDia(ahora) {
36
36
  const d = new Date(ahora);
37
37
  return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1, 0, 0, 0, 0).getTime();
38
38
  }
39
- export function presupuestoDiario(ventanas, ahora = Date.now()) {
39
+ /**
40
+ * Lo que subió esta barra desde la medianoche local.
41
+ *
42
+ * Se suman sólo los saltos HACIA ARRIBA. Una ventana se puede reiniciar en
43
+ * medio del día —pasó el 2026-09-13: una semanal fue de 84 % a 6 % a las pocas
44
+ * horas— y ahí el porcentaje no es monótono. Restar la primera lectura de la
45
+ * última daría −78 puntos, que además de absurdo es la clase de número que se
46
+ * muestra con confianza. Sumando deltas positivos, el reinicio aporta 0 y lo
47
+ * que se gastó después se cuenta igual.
48
+ *
49
+ * Devuelve null si el historial no cubre el arranque del día. Es la regla de
50
+ * siempre: lo que no se puede medir es null, no cero. Con una primera lectura a
51
+ * las 03:10 no se sabe qué pasó entre la medianoche y esa hora, y suponer que
52
+ * no pasó nada es inventar.
53
+ */
54
+ export function gastadoDesdeMedianoche(lecturas, ahora = Date.now()) {
55
+ const d = new Date(ahora);
56
+ const medianoche = new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
57
+ const deHoy = lecturas.filter((l) => l.t >= medianoche && l.t <= ahora).sort((a, b) => a.t - b.t);
58
+ if (deHoy.length < 2)
59
+ return null;
60
+ // El día tiene que estar cubierto desde el principio. Sin una lectura cerca
61
+ // de la medianoche —o una de ayer que diga con cuánto se llegó— el tramo
62
+ // inicial es un agujero.
63
+ const anterior = lecturas.filter((l) => l.t < medianoche).sort((a, b) => a.t - b.t).pop();
64
+ const arranque = anterior ?? deHoy[0];
65
+ const huecoMs = deHoy[0].t - arranque.t;
66
+ if (anterior === undefined || huecoMs > TOLERANCIA_ARRANQUE_MS) {
67
+ if (deHoy[0].t - medianoche > TOLERANCIA_ARRANQUE_MS)
68
+ return null;
69
+ }
70
+ let subida = 0;
71
+ let previo = (anterior ?? deHoy[0]).porcentaje;
72
+ for (const l of deHoy) {
73
+ if (l.porcentaje > previo)
74
+ subida += l.porcentaje - previo;
75
+ previo = l.porcentaje;
76
+ }
77
+ return Math.round(subida * 10) / 10;
78
+ }
79
+ /**
80
+ * Cuánto puede faltar entre la medianoche y la primera lectura del día para
81
+ * seguir dando el total por bueno. Media hora: el sondeo corre cada 5 minutos
82
+ * como mucho, así que un hueco mayor es la máquina apagada o suspendida, y ahí
83
+ * no se sabe qué pasó.
84
+ */
85
+ export const TOLERANCIA_ARRANQUE_MS = 30 * 60_000;
86
+ export function presupuestoDiario(ventanas, ahora = Date.now(), lecturas = []) {
40
87
  const v = semanal(ventanas);
41
88
  if (v === null) {
42
89
  return { estado: 'sin-datos', motivo: 'esta cuenta no informa una ventana larga que repartir' };
@@ -56,20 +103,39 @@ export function presupuestoDiario(ventanas, ahora = Date.now()) {
56
103
  const porDia = restante / (horasRestantes / 24);
57
104
  // El día se corta donde corte primero: la medianoche o el reinicio.
58
105
  const horasHoy = Math.min(finDelDia(ahora) - ahora, msRestantes) / 3600_000;
106
+ const gastadoHoy = gastadoDesdeMedianoche(lecturas, ahora);
59
107
  return {
60
108
  estado: 'ok',
61
109
  ventana: v,
62
110
  porDia,
63
111
  quedaHoy: porDia * (horasHoy / 24),
112
+ gastadoHoy,
113
+ restanteHoy: gastadoHoy === null ? null : Math.max(0, porDia - gastadoHoy),
64
114
  restante,
65
115
  horasRestantes,
66
116
  horasHoy,
67
117
  };
68
118
  }
69
- /** «podés gastar 12.3 %/día · hoy te queda 4.1 %». La misma frase en todas las pantallas. */
119
+ /**
120
+ * La misma frase en todas las pantallas, y dice lo que calcula.
121
+ *
122
+ * Antes decía «hoy te queda 4.1 %» para un número que NO le restaba lo gastado:
123
+ * era el reparto a ritmo parejo de las horas que faltaban del día. Con la
124
+ * cuota quieta bajaba de 10,5 a 0,5 a lo largo del día sin que nadie gastara
125
+ * nada — «te queda» prometía una resta que no ocurría, y siempre para abajo.
126
+ *
127
+ * Ahora hay dos frases porque hay dos cosas distintas:
128
+ *
129
+ * - con historial que cubra el día: lo gastado y lo que queda DE VERDAD;
130
+ * - sin él: el reparto por hora, dicho como lo que es.
131
+ */
70
132
  export function frasePresupuesto(p) {
71
133
  if (p.estado === 'sin-datos')
72
134
  return `presupuesto diario: ${p.motivo}`;
73
- return `podés gastar ${p.porDia.toFixed(1)} %/día · hoy te queda ${p.quedaHoy.toFixed(1)} %`;
135
+ const dia = `podés gastar ${p.porDia.toFixed(1)} %/día`;
136
+ if (p.gastadoHoy !== null && p.restanteHoy !== null) {
137
+ return `${dia} · gastaste ${p.gastadoHoy.toFixed(1)} % hoy · te queda ${p.restanteHoy.toFixed(1)} %`;
138
+ }
139
+ return `${dia} · de acá a medianoche te toca ${p.quedaHoy.toFixed(1)} %`;
74
140
  }
75
141
  //# sourceMappingURL=presupuesto.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"presupuesto.js","sourceRoot":"","sources":["../../src/core/presupuesto.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,4EAA4E;AAC5E,gFAAgF;AAChF,+EAA+E;AAC/E,+EAA+E;AAC/E,2EAA2E;AAC3E,EAAE;AACF,yEAAyE;AACzE,EAAE;AACF,8DAA8D;AAC9D,6DAA6D;AAC7D,EAAE;AACF,8EAA8E;AAC9E,yEAAyE;AACzE,+EAA+E;AAC/E,gFAAgF;AAChF,6EAA6E;AAC7E,2EAA2E;AAC3E,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,8EAA8E;AAC9E,0DAA0D;AAE1D,OAAO,EAAE,OAAO,EAAqB,MAAM,YAAY,CAAC;AAoBxD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AAE9B,kFAAkF;AAClF,SAAS,SAAS,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AM,UAAU,gBAAgB,CAAC,CAAc;IAC7C,IAAI,CAAC,CAAC,MAAM,KAAK,WAAW;QAAE,OAAO,uBAAuB,CAAC,CAAC,MAAM,EAAE,CAAC;IACvE,MAAM,GAAG,GAAG,gBAAgB,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,QAAQ,CAAC;IACxD,IAAI,CAAC,CAAC,UAAU,KAAK,IAAI,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI,EAAE,CAAC;QACpD,OAAO,GAAG,GAAG,eAAe,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IACvG,CAAC;IACD,OAAO,GAAG,GAAG,kCAAkC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;AAC3E,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@legios/quartermaster",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Cuánta cuota te queda en TODOS los perfiles de Claude Code de la máquina, más Codex y los proveedores de opencode. Sin red y sin credenciales: el número sale del cache que Claude Code deja en disco.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -53,8 +53,8 @@ def funcion(nombre: str) -> str:
53
53
  return cuerpo
54
54
 
55
55
 
56
- ambito: dict = {"datetime": datetime, "timezone": timezone}
57
- for nombre in ("faltan", "_tope", "_ya_reinicio", "_vale_preguntar"):
56
+ ambito: dict = {"datetime": datetime, "timezone": timezone, "ACTIVA_SEGUNDOS": 600}
57
+ for nombre in ("faltan", "_tope", "_ya_reinicio", "_activa_hace_poco", "_vale_preguntar"):
58
58
  exec(compile(funcion(nombre), "qm-indicator", "exec"), ambito) # noqa: S102
59
59
 
60
60
  # `_vale_preguntar` es un método y llama a `self._tope` y a `self._ya_reinicio`,
@@ -63,6 +63,7 @@ for nombre in ("faltan", "_tope", "_ya_reinicio", "_vale_preguntar"):
63
63
  class Indicador:
64
64
  _tope = staticmethod(ambito["_tope"])
65
65
  _ya_reinicio = staticmethod(ambito["_ya_reinicio"])
66
+ _activa_hace_poco = staticmethod(ambito["_activa_hace_poco"])
66
67
  _vale_preguntar = ambito["_vale_preguntar"]
67
68
 
68
69
 
@@ -73,10 +74,11 @@ def iso(delta_horas: float) -> str:
73
74
  return (datetime.now(timezone.utc) + timedelta(hours=delta_horas)).isoformat()
74
75
 
75
76
 
76
- def pieza(sesion=None, semanal=None, r_sesion=None, r_semanal=None) -> dict:
77
+ def pieza(sesion=None, semanal=None, r_sesion=None, r_semanal=None, uso=None) -> dict:
77
78
  return {
78
79
  "perfil": ".claude", "sesion": sesion, "semanal": semanal,
79
80
  "reinicia_sesion": r_sesion, "reinicia_semanal": r_semanal,
81
+ "ultimo_uso": uso,
80
82
  }
81
83
 
82
84
 
@@ -94,6 +96,14 @@ CASOS = [
94
96
  pieza(sesion=9, semanal=9, r_sesion=iso(-1), r_semanal=iso(50)), True),
95
97
  ("sin fecha de reinicio no se puede afirmar que venció",
96
98
  pieza(sesion=100, semanal=100, r_sesion=None, r_semanal=None), False),
99
+
100
+ # La cuenta que estás usando ahora, esté donde esté el nivel.
101
+ ("una cuenta al 2 % que se está usando AHORA: sí — es el caso del segundo bug",
102
+ pieza(sesion=2, semanal=5, r_sesion=iso(3), r_semanal=iso(50), uso=iso(-0.02)), True),
103
+ ("la misma cuenta al 2 %, sin tocar hace dos horas: no",
104
+ pieza(sesion=2, semanal=5, r_sesion=iso(3), r_semanal=iso(50), uso=iso(-2)), False),
105
+ ("una cuenta al 2 % sin dato de último uso: no se inventa actividad",
106
+ pieza(sesion=2, semanal=5, r_sesion=iso(3), r_semanal=iso(50), uso=None), False),
97
107
  ]
98
108
 
99
109
  fallas = 0
@@ -113,6 +123,42 @@ if re.search(r"mueven\s*=.*<\s*100", FUENTE):
113
123
  file=sys.stderr)
114
124
  fallas += 1
115
125
 
126
+ # ── que el lazo no se pueda matar solo ────────────────────────────────────
127
+ #
128
+ # `calentar()` empieza soltando `self.reloj`. Si después devuelve False sin
129
+ # reprogramar, la fuente de GLib se quita y nadie la vuelve a armar: el
130
+ # indicador no le pregunta más al endpoint en lo que le queda de vida.
131
+ #
132
+ # Pasó de verdad el 2026-09-13, después de una suspensión de 4,1 h: proceso
133
+ # vivo, dibujando cada pocos minutos, con la cuota leída hacía 5,2 horas.
134
+ cuerpo_calentar = funcion("calentar")
135
+ rama = cuerpo_calentar.split("if self.calentando:", 1)
136
+ if len(rama) != 2:
137
+ print("✗ no encontré la guarda `if self.calentando:` en calentar()", file=sys.stderr)
138
+ fallas += 1
139
+ else:
140
+ # Hasta el siguiente `args =`, que es donde sigue el camino normal.
141
+ guarda = rama[1].split("args =", 1)[0]
142
+ if "programar_calentado" not in guarda:
143
+ print("✗ calentar() sale de `if self.calentando:` sin reprogramar: "
144
+ "el lazo se muere y no vuelve a preguntar nunca más", file=sys.stderr)
145
+ fallas += 1
146
+ elif "CALENTADO_PLAZO_US" not in guarda:
147
+ print("✗ la bandera `calentando` no tiene plazo: si el callback no llega "
148
+ "—una suspensión en el medio— se queda pegada para siempre", file=sys.stderr)
149
+ fallas += 1
150
+ else:
151
+ print(" ✓ un calentado en vuelo reprograma el lazo, y la bandera tiene plazo")
152
+
153
+ # ── que se entere de la suspensión ────────────────────────────────────────
154
+ if "PrepareForSleep" not in FUENTE or "vigilar_suspension()" not in FUENTE:
155
+ print("✗ el indicador no escucha PrepareForSleep: al volver de suspender muestra "
156
+ "los números de antes de dormir hasta el próximo sondeo, y el sondeo corre "
157
+ "contra un reloj que no avanzó", file=sys.stderr)
158
+ fallas += 1
159
+ else:
160
+ print(" ✓ escucha PrepareForSleep y pregunta al volver")
161
+
116
162
  if fallas:
117
163
  print(f"\ngate de calentado: ROJO ({fallas})", file=sys.stderr)
118
164
  raise SystemExit(1)
@@ -0,0 +1,189 @@
1
+ #!/usr/bin/env node
2
+ // El PR a microsoft/winget-pkgs, desde el fork de la ORGANIZACIÓN.
3
+ //
4
+ // Por qué no lo hace `wingetcreate submit`, que es la herramienta que Microsoft
5
+ // publica justo para esto: wingetcreate forkea a la cuenta del token y no tiene
6
+ // forma de decirle otra cosa (ver `wingetcreate submit --help`: hay --prtitle,
7
+ // --replace, --token, --no-open, y nada de fork). O sea que la rama de una
8
+ // release de Legios quedaba colgando de la cuenta personal de quien tuviera el
9
+ // token. La 0.1.6 salió así y hubo que rehacerla a mano.
10
+ //
11
+ // Lo que sí hacía wingetcreate y acá no se pierde: normalizar los manifests.
12
+ // No hace falta —`scripts/hacer-manifests.mjs` ya los emite con la forma del
13
+ // esquema, y se comprobó que los dos árboles son EQUIVALENTES cargándolos como
14
+ // YAML: mismas claves, mismos valores, distinto orden y un comentario de
15
+ // cabecera. Lo que valida `winget validate` es el contenido, y pasa con los
16
+ // nuestros: eso ya corría en el job antes de este cambio.
17
+ //
18
+ // Todo por la API, sin clonar: winget-pkgs son cientos de miles de archivos y
19
+ // un clone en cada release sería minutos de runner para tocar cuatro YAML.
20
+
21
+ import { readdirSync, readFileSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+
24
+ const TOKEN = process.env.GITHUB_TOKEN;
25
+ const V = process.env.V;
26
+ const DIR = process.env.DIR;
27
+ const ARRIBA = process.env.UPSTREAM ?? 'microsoft/winget-pkgs';
28
+ const FORK = process.env.FORK ?? 'legiosai/winget-pkgs';
29
+ const SECO = process.argv.includes('--en-seco');
30
+
31
+ // DIR sólo hace falta cuando de verdad se va a mandar algo: --en-seco existe
32
+ // para poder preguntar «¿este token llega a la organización?» sin haber armado
33
+ // los manifests, que es lo que hay que poder contestar ANTES de tirar un tag.
34
+ for (const [k, v] of Object.entries({ GITHUB_TOKEN: TOKEN, V, ...(SECO ? {} : { DIR }) })) {
35
+ if (!v) { console.error(`falta ${k}`); process.exit(2); }
36
+ }
37
+
38
+ const [ORG] = FORK.split('/');
39
+ const RAMA = `Legios.Quartermaster-${V}`;
40
+ const RUTA = `manifests/l/Legios/Quartermaster/${V}`;
41
+
42
+ async function api(metodo, ruta, cuerpo) {
43
+ const r = await fetch(`https://api.github.com/${ruta}`, {
44
+ method: metodo,
45
+ headers: {
46
+ authorization: `Bearer ${TOKEN}`,
47
+ accept: 'application/vnd.github+json',
48
+ 'x-github-api-version': '2022-11-28',
49
+ 'user-agent': 'quartermaster-release',
50
+ ...(cuerpo ? { 'content-type': 'application/json' } : {}),
51
+ },
52
+ ...(cuerpo ? { body: JSON.stringify(cuerpo) } : {}),
53
+ });
54
+ const texto = await r.text();
55
+ let datos = null;
56
+ try { datos = texto ? JSON.parse(texto) : null; } catch { /* no era json */ }
57
+ return { ok: r.ok, estado: r.status, datos, texto };
58
+ }
59
+
60
+ function morir(que, r) {
61
+ console.error(`::error::winget: ${que} — HTTP ${r.estado}`);
62
+ console.error(`::error::${(r.datos?.message ?? r.texto ?? '').slice(0, 300)}`);
63
+ if (DIR) console.error(`::error::Los manifests quedaron en ${DIR} y se pueden mandar a mano.`);
64
+ process.exit(1);
65
+ }
66
+
67
+ // ── que el token llegue, y que llegue a la ORG ────────────────────────
68
+ // Un classic con public_repo alcanza para forkear y abrir el PR, pero sólo
69
+ // entra a los repos de una organización si la org no restringe los classic
70
+ // (Settings → Third-party Access → Personal access tokens). Eso no se ve por
71
+ // API hasta que se intenta, así que se intenta ACÁ, antes de tocar nada de
72
+ // Microsoft, y con un mensaje que dice dónde mirar.
73
+ const yo = await api('GET', 'user');
74
+ if (!yo.ok) morir('el token no valida (¿venció?)', yo);
75
+ console.log(`· token de ${yo.datos.login}`);
76
+
77
+ const org = await api('GET', `orgs/${ORG}`);
78
+ if (!org.ok) {
79
+ console.error(`::error::winget: el token no llega a la organización ${ORG}.`);
80
+ console.error('::error::Un PAT classic entra a los repos de una org sólo si la org no los restringe:');
81
+ console.error(`::error::https://github.com/organizations/${ORG}/settings/personal-access-tokens`);
82
+ process.exit(1);
83
+ }
84
+
85
+ // ── el fork de la org ─────────────────────────────────────────────────
86
+ let fork = await api('GET', `repos/${FORK}`);
87
+ if (!fork.ok) {
88
+ console.log(`· ${FORK} no existe: forkeando ${ARRIBA} a la organización`);
89
+ const hecho = await api('POST', `repos/${ARRIBA}/forks`, {
90
+ organization: ORG, default_branch_only: true,
91
+ });
92
+ if (!hecho.ok) morir(`no pude forkear ${ARRIBA} a ${ORG}`, hecho);
93
+ for (let i = 0; i < 30 && !fork.ok; i++) {
94
+ await new Promise((r) => setTimeout(r, 4000));
95
+ fork = await api('GET', `repos/${FORK}`);
96
+ }
97
+ if (!fork.ok) morir('el fork se pidió pero GitHub no terminó de copiarlo', fork);
98
+ }
99
+ if (!fork.datos.permissions?.push) {
100
+ console.error(`::error::winget: el token no puede escribir en ${FORK}.`);
101
+ console.error('::error::Tiene que ser un PAT CLASSIC con public_repo, y la org no puede restringirlo.');
102
+ process.exit(1);
103
+ }
104
+ const base = fork.datos.default_branch;
105
+ console.log(`· fork: ${FORK} (rama base ${base})`);
106
+
107
+ // Ponerlo al día con Microsoft antes de ramificar. Sin esto el fork se queda
108
+ // donde quedó la release anterior y el PR arrastra la diferencia.
109
+ const aldia = await api('POST', `repos/${FORK}/merge-upstream`, { branch: base });
110
+ console.log(aldia.ok
111
+ ? `· ${base} al día con ${ARRIBA}: ${aldia.datos.merge_type}`
112
+ : `· no pude sincronizar ${base} (HTTP ${aldia.estado}); sigo igual`);
113
+
114
+ if (SECO) { console.log('· --en-seco: hasta acá llego'); process.exit(0); }
115
+
116
+ // ── la rama con los cuatro manifests ──────────────────────────────────
117
+ const ref = await api('GET', `repos/${FORK}/git/ref/heads/${base}`);
118
+ if (!ref.ok) morir(`no pude leer ${base} del fork`, ref);
119
+ const shaBase = ref.datos.object.sha;
120
+
121
+ const archivos = readdirSync(DIR).filter((f) => f.endsWith('.yaml')).sort();
122
+ if (archivos.length === 0) { console.error(`::error::no hay .yaml en ${DIR}`); process.exit(1); }
123
+
124
+ const arbol = [];
125
+ for (const f of archivos) {
126
+ const blob = await api('POST', `repos/${FORK}/git/blobs`, {
127
+ content: readFileSync(join(DIR, f)).toString('base64'), encoding: 'base64',
128
+ });
129
+ if (!blob.ok) morir(`no pude subir ${f}`, blob);
130
+ arbol.push({ path: `${RUTA}/${f}`, mode: '100644', type: 'blob', sha: blob.datos.sha });
131
+ console.log(` · ${f}`);
132
+ }
133
+
134
+ const tree = await api('POST', `repos/${FORK}/git/trees`, { base_tree: shaBase, tree: arbol });
135
+ if (!tree.ok) morir('no pude armar el árbol', tree);
136
+
137
+ const commit = await api('POST', `repos/${FORK}/git/commits`, {
138
+ message: `New package: Legios.Quartermaster version ${V}`,
139
+ tree: tree.datos.sha, parents: [shaBase],
140
+ });
141
+ if (!commit.ok) morir('no pude armar el commit', commit);
142
+
143
+ // force: un rerun del job tiene que poder repetirse sin dejar la rama a medias.
144
+ let rama = await api('PATCH', `repos/${FORK}/git/refs/heads/${RAMA}`, { sha: commit.datos.sha, force: true });
145
+ if (!rama.ok) rama = await api('POST', `repos/${FORK}/git/refs`, { ref: `refs/heads/${RAMA}`, sha: commit.datos.sha });
146
+ if (!rama.ok) morir(`no pude dejar la rama ${RAMA}`, rama);
147
+ console.log(`· rama ${ORG}:${RAMA} en ${commit.datos.sha.slice(0, 10)}`);
148
+
149
+ // ── el PR ─────────────────────────────────────────────────────────────
150
+ // Si ya hay uno abierto con esta misma cabeza, el push de arriba ya lo
151
+ // actualizó: abrir otro sería ruido en el repo de otro.
152
+ const abiertos = await api('GET', `repos/${ARRIBA}/pulls?head=${ORG}:${RAMA}&state=open`);
153
+ if (abiertos.ok && abiertos.datos.length > 0) {
154
+ console.log(`::notice::winget: el PR ya estaba abierto y se actualizó: ${abiertos.datos[0].html_url}`);
155
+ process.exit(0);
156
+ }
157
+
158
+ const cuerpo = [
159
+ '## 📖 Description',
160
+ '',
161
+ `New package: **Legios.Quartermaster** version ${V} — a CLI that reports how much`,
162
+ 'quota is left across every Claude Code profile on the machine, plus Codex and',
163
+ 'opencode. MIT, source at https://github.com/legiosai/quartermaster',
164
+ '',
165
+ 'Two things worth flagging for the reviewer:',
166
+ '',
167
+ '- The installer declares `OpenJS.NodeJS.LTS` as a dependency. The package is a',
168
+ ' Node CLI and does nothing without a Node ≥ 22.6 runtime.',
169
+ '- Our installer is per-user and does **not** request elevation (`InstallerType:',
170
+ ' inno`, `Scope: user`). The Node dependency\'s MSI does, so a machine without',
171
+ ' Node will see one UAC prompt that is not ours.',
172
+ '',
173
+ '## ✅ Checklist',
174
+ '',
175
+ '- [ ] Signed the [Contributor License Agreement](https://cla.opensource.microsoft.com)',
176
+ '',
177
+ '## 📦 Manifest Checklist',
178
+ '',
179
+ '- [x] This PR only modifies one (1) manifest',
180
+ '- [x] Validated manifest locally with `winget validate --manifest <path>`',
181
+ '- [ ] Tested manifest locally with `winget install --manifest <path>`',
182
+ ].join('\n');
183
+
184
+ const pr = await api('POST', `repos/${ARRIBA}/pulls`, {
185
+ title: `New package: Legios.Quartermaster version ${V}`,
186
+ head: `${ORG}:${RAMA}`, base, body: cuerpo, maintainer_can_modify: true,
187
+ });
188
+ if (!pr.ok) morir('no pude abrir el PR', pr);
189
+ console.log(`::notice::winget: PR abierto — ${pr.datos.html_url}`);