@letsrebase/verify 0.1.3 → 0.2.1

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.
@@ -63,20 +63,41 @@ const COGNITIVE_TAGS = [
63
63
  "research-first","decomposer","orchestrator","verification-heavy","risk-calibrated",
64
64
  ];
65
65
 
66
+ // How a language writes numbers: the thousands separator and the decimal mark.
67
+ // A profile with no `language` predates the field and was written in English.
68
+ const NUMBER_FORMATS = {
69
+ it: { group: ".", decimal: "," },
70
+ en: { group: ",", decimal: "." },
71
+ };
72
+ const DEFAULT_NUMBER_LANGUAGE = "en";
73
+
74
+ // Read one numeric token ("1.168", "12,5") the way `language` writes it.
75
+ // Returns NaN for a token that is not a number in that language.
76
+ function parseNumber(raw, language) {
77
+ const { group, decimal } = NUMBER_FORMATS[language] ?? NUMBER_FORMATS[DEFAULT_NUMBER_LANGUAGE];
78
+ const esc = (c) => `\\${c}`;
79
+ const grouped = new RegExp(`^\\d{1,3}(?:${esc(group)}\\d{3})+(?:${esc(decimal)}\\d+)?$`);
80
+ let t = raw;
81
+ if (grouped.test(t)) t = t.split(group).join("");
82
+ t = t.replace(decimal, ".");
83
+ return /^\d+(?:\.\d+)?$/.test(t) ? Number(t) : NaN;
84
+ }
85
+
66
86
  // Extract candidate ANCHORS from a chunk of prose.
67
- function extractAnchors(text) {
87
+ function extractAnchors(text, language = DEFAULT_NUMBER_LANGUAGE) {
68
88
  if (!text || typeof text !== "string") return [];
69
89
  const anchors = [];
70
90
 
71
91
  // Numbers that look meaningful (>1 digit OR followed by a unit/word).
72
- for (const m of text.matchAll(/\b\d{1,5}(?:[.,]\d+)?\b/g)) {
73
- const n = Number(m[0].replace(",", "."));
92
+ for (const m of text.matchAll(/\b\d{1,5}(?:[.,]\d+)*\b/g)) {
93
+ const n = parseNumber(m[0], language);
74
94
  if (Number.isFinite(n) && n >= 2) anchors.push({ kind: "number", value: n, raw: m[0] });
75
95
  }
76
96
 
77
97
  // Percentages.
78
- for (const m of text.matchAll(/(\d{1,3})\s*%/g)) {
79
- anchors.push({ kind: "percent", value: Number(m[1]) / 100, raw: m[0] });
98
+ for (const m of text.matchAll(/(?<![\d.,])(\d{1,3}(?:[.,]\d+)?)\s*%/g)) {
99
+ const n = parseNumber(m[1], language);
100
+ if (Number.isFinite(n)) anchors.push({ kind: "percent", value: n / 100, raw: m[0] });
80
101
  }
81
102
 
82
103
  // Year-months (2026-03, 2026-Q1).
@@ -301,13 +322,14 @@ function classifyTextFields(profile) {
301
322
  export function assessGroundedness(profile) {
302
323
  const pool = collectSupportPool(profile);
303
324
  const fields = classifyTextFields(profile);
325
+ const language = profile?.language ?? DEFAULT_NUMBER_LANGUAGE;
304
326
 
305
327
  let total = 0;
306
328
  let supported = 0;
307
329
  const anomalies = [];
308
330
 
309
331
  for (const f of fields) {
310
- const anchors = extractAnchors(f.text);
332
+ const anchors = extractAnchors(f.text, language);
311
333
  for (const a of anchors) {
312
334
  total++;
313
335
  let ok = false;
package/src/hub.mjs CHANGED
@@ -79,8 +79,9 @@ export async function signIn(hub, {
79
79
  sleep = sleepMs,
80
80
  now = Date.now,
81
81
  log = console.log,
82
+ around = (_label, fn) => fn(),
82
83
  } = {}) {
83
- const start = await postJson(fetchFn, `${hub}/api/hub/cli/device`, { scope: "work_profile" });
84
+ const start = await around("Asking rebase for a sign-in code", () => postJson(fetchFn, `${hub}/api/hub/cli/device`, { scope: "work_profile" }));
84
85
  if (!start.res.ok) {
85
86
  throw new Error(`could not start the sign-in (${start.res.status}): ${start.data.detail || start.data.error || "no answer from the hub"}`);
86
87
  }
@@ -105,32 +106,34 @@ export async function signIn(hub, {
105
106
  log(`Waiting for you to approve (the code is valid ${Math.round(expiresIn / 60)} minutes)...`);
106
107
 
107
108
  const deadline = now() + expiresIn * 1000 + 30_000;
108
- for (;;) {
109
- await sleep(interval * 1000);
110
- let data = null;
111
- try {
112
- const answer = await postJson(fetchFn, `${hub}/api/hub/cli/token`, { device_code });
113
- if (answer.res.status < 500) data = answer.parsed;
114
- } catch {
115
- data = null;
116
- }
117
- // A network error, a 5xx or a non-JSON answer is a hiccup, not a verdict (RFC 8628 § 3.5):
118
- // back off and keep polling until the code expires.
119
- if (!data) data = { error: "slow_down" };
120
- if (data.access_token) return data.access_token;
121
- switch (data.error) {
122
- case "authorization_pending":
123
- break;
124
- case "slow_down":
125
- interval += 5;
126
- break;
127
- case "access_denied":
128
- throw new Error("you pressed «Annulla» in the browser, so nothing was sent. Run submit again when you want to send the profile.");
129
- case "expired_token":
130
- throw new Error("the code expired before it was approved, so nothing was sent. Run submit again for a new code.");
131
- default:
132
- throw new Error(`the hub answered the sign-in with an error: ${data.error || data.detail || "unknown"}`);
109
+ return around("Waiting for you to approve the sign-in in your browser", async () => {
110
+ for (;;) {
111
+ await sleep(interval * 1000);
112
+ let data = null;
113
+ try {
114
+ const answer = await postJson(fetchFn, `${hub}/api/hub/cli/token`, { device_code });
115
+ if (answer.res.status < 500) data = answer.parsed;
116
+ } catch {
117
+ data = null;
118
+ }
119
+ // A network error, a 5xx or a non-JSON answer is a hiccup, not a verdict (RFC 8628 § 3.5):
120
+ // back off and keep polling until the code expires.
121
+ if (!data) data = { error: "slow_down" };
122
+ if (data.access_token) return data.access_token;
123
+ switch (data.error) {
124
+ case "authorization_pending":
125
+ break;
126
+ case "slow_down":
127
+ interval += 5;
128
+ break;
129
+ case "access_denied":
130
+ throw new Error("you pressed «Annulla» in the browser, so nothing was sent. Run submit again when you want to send the profile.");
131
+ case "expired_token":
132
+ throw new Error("the code expired before it was approved, so nothing was sent. Run submit again for a new code.");
133
+ default:
134
+ throw new Error(`the hub answered the sign-in with an error: ${data.error || data.detail || "unknown"}`);
135
+ }
136
+ if (now() > deadline) throw new Error("the sign-in took too long, so nothing was sent. Run submit again for a new code.");
133
137
  }
134
- if (now() > deadline) throw new Error("the sign-in took too long, so nothing was sent. Run submit again for a new code.");
135
- }
138
+ });
136
139
  }
@@ -0,0 +1,250 @@
1
+ // The languages a profile can be written in.
2
+ //
3
+ // A language is one entry in LANGUAGES: its code, its English name (the prompt
4
+ // tells the model "write in <name>"), and the label table `profile.md` is
5
+ // rendered from. Adding a language is one entry here and nothing else.
6
+ //
7
+ // The payload never changes with the language: enum values stay the English
8
+ // codes the detectors emit ("daily driver", "deep focus", ...). Only what a
9
+ // person reads goes through `labels`: headings, fixed phrases, and the display
10
+ // name of each code. A code with no label shows as itself.
11
+
12
+ export const DEFAULT_LANGUAGE = "it";
13
+
14
+ const plural = (n, one, many) => (n === 1 ? one : many);
15
+
16
+ const EN = {
17
+ title: (name) => `Agentic profile${name ? ` — ${name}` : ""}`,
18
+ window: (p) => `Window: ${p.window.from} → ${p.window.to} · ${p.volume.sessions} sessions · ${p.volume.instructions} instructions · ${p.volume.products} products`,
19
+ screen: (score, note) => `Log consistency screen: ${score == null ? "n/a" : `${score}/100`} (${note})`,
20
+ sources: (list) => `Sources: ${list}`,
21
+ source: (s) => `${s.source} (${s.captureLevel} capture${s.backend ? `, ${s.backend}` : ""}) · ${s.sessions} sessions read`,
22
+ lowerBounds: "Window and counts are lower bounds: logs rotate and old sessions are pruned.",
23
+ domains: "Domains",
24
+ domainLine: (d, note) => `- **${d.label}** · ${d.products} products · ${d.sessions} sessions${note ? ` — ${note}` : ""}`,
25
+ representative: "Representative projects",
26
+ domainFallback: "(domain)",
27
+ projectLine: (pr, landing) => `${pr.span.from ?? "n/a"}→${pr.span.to ?? "n/a"} · ${pr.sessions} sessions · ${landing}`,
28
+ landing: (l) => `commits ${l.commits} · reverts ${l.reverts} · churn ${l.revertChurn}${l.checksRun ? " · checks passed" : ""}`,
29
+ stack: (list) => `stack: ${list}`,
30
+ orchestration: (bits) => `orchestration: ${bits}`,
31
+ sessionsByTool: (tools, disjoint) => `sessions by tool: ${tools}${disjoint ? " (different periods)" : ""}`,
32
+ dispatches: (n) => `${n} agent dispatches`,
33
+ delegations: (n) => `${n} sub-agent delegations`,
34
+ whyRepresentative: "why representative:",
35
+ artifact: (a) => `artifact: ${a ? a.label : "— (none attached)"}`,
36
+ otherProjects: "Other projects (inventory)",
37
+ otherLine: (o, types, tag) => `- ${types} · ${o.span.from ?? "n/a"}→${o.span.to ?? "n/a"} · ${o.sessions} sess${tag}`,
38
+ cognitive: "Cognitive profile",
39
+ tags: "tags:",
40
+ aiHeading: "How they work with the AI",
41
+ aiLine: (a, mode) => `${a.directing}% directing · ${a.coThinking}% co-thinking · ${mode}`,
42
+ intensity: "Practice intensity",
43
+ daysNote: (tz) => ` (days counted in ${tz})`,
44
+ activeDays: (i, note) => `- Active days: ${i.activeDays} / ${i.observedDays} (${Math.round(i.activeDaysRatio * 100)}%)${note}`,
45
+ medianSessionsPerDay: (n) => `- Median sessions per active day: ${n}`,
46
+ medianDepth: (n) => `- Median session depth: ${n} tool calls`,
47
+ streak: (n) => `- Longest streak: ${n} consecutive days`,
48
+ peakDay: (n) => `- Peak day: ${n} tool calls`,
49
+ cadence: (cadence, shape) => `Cadence: ${cadence} · ${shape}`,
50
+ distribution: "Work distribution",
51
+ perProduct: (d) => `- Sessions per product: median ${d.medianSessionsPerProduct} · mean ${d.meanSessionsPerProduct}`,
52
+ top3: (d) => `- Top 3 products: ${Math.round(d.top3Share * 100)}% of all sessions`,
53
+ multiMonth: (d) => `- Multi-month products: ${d.multiMonthProducts} / ${d.products} (${Math.round(d.multiMonthShare * 100)}%)`,
54
+ shape: (shape) => `Shape: ${shape}`,
55
+ techUsage: "Technology usage",
56
+ monthsNote: (tz) => ` (months counted in ${tz})`,
57
+ techIntro: (note) => `Counts per technology detected in the stack, across all products${note}. Sessions are those of the products where it was detected. The band only labels the month counts.`,
58
+ techLine: (t, band, span) => `- ${t.name}: ${band} · ${t.sessions} sessions · ${t.products} ${plural(t.products, "product", "products")} · ${t.months} ${plural(t.months, "month", "months")} (${span})`,
59
+ to: "to",
60
+ practices: "How the work is done",
61
+ practicesIntro: (note) => `Counts of sessions where a practice was seen, out of the sessions where it could have been${note}. Each row says how it was counted: by code, or by the person's own model.`,
62
+ practiceLine: (t, name, how) => `- ${name}: in ${t.seen} of ${t.of} ${plural(t.of, "session", "sessions")} · ${t.products} ${plural(t.products, "product", "products")} · ${t.months} ${plural(t.months, "month", "months")} · ${how}`,
63
+ byModel: "classified by the person's model",
64
+ byCode: "counted by code",
65
+ literacy: "Agentic literacy",
66
+ uses: "Uses",
67
+ builds: "Builds",
68
+ designs: "Designs",
69
+ subagentDelegations: (n) => `- Sub-agent delegations: ${n}`,
70
+ taskTracking: (n) => `- Task tracking events: ${n}`,
71
+ builtinSlash: (n) => `- Built-in slash commands invoked: ${n}`,
72
+ customSkills: (c) => `- Custom skills/commands: ${c.distinct} distinct, ${c.invocations} invocations`,
73
+ publicMcp: (m) => `- Public MCP servers: ${m.servers} · ${m.calls} calls`,
74
+ customMcp: (m) => `- Custom MCP servers: ${m.servers} · ${m.tools} tools · ${m.calls} calls`,
75
+ skillsAuthored: (n) => `- Skills authored: ${n}`,
76
+ commandsAuthored: (n) => `- Commands authored: ${n}`,
77
+ agentsAuthored: (n) => `- Agents authored: ${n}`,
78
+ hooksEdited: (n) => `- Hooks edited: ${n}`,
79
+ memoryFiles: (n) => `- Project memory files (CLAUDE.md): ${n}`,
80
+ plansFirst: (n) => `- Plans-first (ExitPlanMode): ${n}`,
81
+ subtaskTracking: (n) => `- Subtask tracking (TodoWrite): ${n}`,
82
+ clarifies: (n) => `- Clarifies (AskUserQuestion): ${n}`,
83
+ trajectory: "Trajectory",
84
+ shifts: (midpoint) => `Behavioral shifts (early → late half${midpoint ? `, split at ${midpoint}` : ""}):`,
85
+ topics: "Topics explored, by quarter:",
86
+ vocabulary: (list) => `New vocabulary adopted: ${list}`,
87
+ principles: "Principles codified:",
88
+ stackAdopted: "Stack adopted",
89
+ stackNote: "_Stack as currently declared in the repo: from package.json dependencies (npm manifests only) and the files touched. Dependencies are unavailable if the project folder no longer exists, and services used only over REST (no package) are not auto-detected._",
90
+ // Display names of the payload's codes. A code missing here shows as itself.
91
+ codes: {},
92
+ };
93
+
94
+ const IT = {
95
+ title: (name) => `Profilo agentico${name ? ` — ${name}` : ""}`,
96
+ window: (p) => `Periodo: ${p.window.from} → ${p.window.to} · ${p.volume.sessions} sessioni · ${p.volume.instructions} istruzioni · ${p.volume.products} prodotti`,
97
+ screen: (score, note) => `Controllo di coerenza dei log: ${score == null ? "n/d" : `${score}/100`} (${note})`,
98
+ sources: (list) => `Fonti: ${list}`,
99
+ source: (s) => `${s.source} (cattura ${s.captureLevel}${s.backend ? `, ${s.backend}` : ""}) · ${s.sessions} sessioni lette`,
100
+ lowerBounds: "Periodo e conteggi sono stime per difetto: i log ruotano e le sessioni vecchie vengono eliminate.",
101
+ domains: "Ambiti",
102
+ domainLine: (d, note) => `- **${d.label}** · ${d.products} prodotti · ${d.sessions} sessioni${note ? ` — ${note}` : ""}`,
103
+ representative: "Progetti rappresentativi",
104
+ domainFallback: "(ambito)",
105
+ projectLine: (pr, landing) => `${pr.span.from ?? "n/d"}→${pr.span.to ?? "n/d"} · ${pr.sessions} sessioni · ${landing}`,
106
+ landing: (l) => `commit ${l.commits} · revert ${l.reverts} · rimaneggiamento ${l.revertChurn}${l.checksRun ? " · controlli superati" : ""}`,
107
+ stack: (list) => `stack: ${list}`,
108
+ orchestration: (bits) => `orchestrazione: ${bits}`,
109
+ sessionsByTool: (tools, disjoint) => `sessioni per strumento: ${tools}${disjoint ? " (periodi diversi)" : ""}`,
110
+ dispatches: (n) => `${n} lanci di agenti`,
111
+ delegations: (n) => `${n} deleghe a sub-agent`,
112
+ whyRepresentative: "perché rappresentativo:",
113
+ artifact: (a) => `allegato: ${a ? a.label : "— (nessuno)"}`,
114
+ otherProjects: "Altri progetti (inventario)",
115
+ otherLine: (o, types, tag) => `- ${types} · ${o.span.from ?? "n/d"}→${o.span.to ?? "n/d"} · ${o.sessions} sess.${tag}`,
116
+ cognitive: "Profilo cognitivo",
117
+ tags: "tag:",
118
+ aiHeading: "Come lavorano con l'AI",
119
+ aiLine: (a, mode) => `${a.directing}% guida · ${a.coThinking}% ragionamento condiviso · ${mode}`,
120
+ intensity: "Intensità della pratica",
121
+ daysNote: (tz) => ` (giorni contati in ${tz})`,
122
+ activeDays: (i, note) => `- Giorni attivi: ${i.activeDays} / ${i.observedDays} (${Math.round(i.activeDaysRatio * 100)}%)${note}`,
123
+ medianSessionsPerDay: (n) => `- Sessioni mediane per giorno attivo: ${n}`,
124
+ medianDepth: (n) => `- Profondità mediana della sessione: ${n} chiamate a strumenti`,
125
+ streak: (n) => `- Serie più lunga: ${n} giorni consecutivi`,
126
+ peakDay: (n) => `- Giorno di picco: ${n} chiamate a strumenti`,
127
+ cadence: (cadence, shape) => `Cadenza: ${cadence} · ${shape}`,
128
+ distribution: "Distribuzione del lavoro",
129
+ perProduct: (d) => `- Sessioni per prodotto: mediana ${d.medianSessionsPerProduct} · media ${d.meanSessionsPerProduct}`,
130
+ top3: (d) => `- Primi 3 prodotti: ${Math.round(d.top3Share * 100)}% di tutte le sessioni`,
131
+ multiMonth: (d) => `- Prodotti su più mesi: ${d.multiMonthProducts} / ${d.products} (${Math.round(d.multiMonthShare * 100)}%)`,
132
+ shape: (shape) => `Forma: ${shape}`,
133
+ techUsage: "Uso delle tecnologie",
134
+ monthsNote: (tz) => ` (mesi contati in ${tz})`,
135
+ techIntro: (note) => `Conteggi per tecnologia rilevata nello stack, su tutti i prodotti${note}. Le sessioni sono quelle dei prodotti in cui è stata rilevata. La fascia etichetta solo i conteggi dei mesi.`,
136
+ techLine: (t, band, span) => `- ${t.name}: ${band} · ${t.sessions} sessioni · ${t.products} ${plural(t.products, "prodotto", "prodotti")} · ${t.months} ${plural(t.months, "mese", "mesi")} (${span})`,
137
+ to: "a",
138
+ practices: "Come si lavora",
139
+ practicesIntro: (note) => `Conteggi delle sessioni in cui una pratica è stata vista, sul totale delle sessioni in cui poteva esserlo${note}. Ogni riga dice come è stata contata: dal codice o dal modello della persona.`,
140
+ practiceLine: (t, name, how) => `- ${name}: in ${t.seen} su ${t.of} ${plural(t.of, "sessione", "sessioni")} · ${t.products} ${plural(t.products, "prodotto", "prodotti")} · ${t.months} ${plural(t.months, "mese", "mesi")} · ${how}`,
141
+ byModel: "classificata dal modello della persona",
142
+ byCode: "contata dal codice",
143
+ literacy: "Competenza agentica",
144
+ uses: "Usa",
145
+ builds: "Costruisce",
146
+ designs: "Progetta",
147
+ subagentDelegations: (n) => `- Deleghe a sub-agent: ${n}`,
148
+ taskTracking: (n) => `- Eventi di tracciamento attività: ${n}`,
149
+ builtinSlash: (n) => `- Comandi slash integrati usati: ${n}`,
150
+ customSkills: (c) => `- Skill/comandi personalizzati: ${c.distinct} distinti, ${c.invocations} invocazioni`,
151
+ publicMcp: (m) => `- Server MCP pubblici: ${m.servers} · ${m.calls} chiamate`,
152
+ customMcp: (m) => `- Server MCP personalizzati: ${m.servers} · ${m.tools} strumenti · ${m.calls} chiamate`,
153
+ skillsAuthored: (n) => `- Skill scritte: ${n}`,
154
+ commandsAuthored: (n) => `- Comandi scritti: ${n}`,
155
+ agentsAuthored: (n) => `- Agenti scritti: ${n}`,
156
+ hooksEdited: (n) => `- Hook modificati: ${n}`,
157
+ memoryFiles: (n) => `- File di memoria del progetto (CLAUDE.md): ${n}`,
158
+ plansFirst: (n) => `- Prima il piano (ExitPlanMode): ${n}`,
159
+ subtaskTracking: (n) => `- Tracciamento dei sotto-compiti (TodoWrite): ${n}`,
160
+ clarifies: (n) => `- Chiede chiarimenti (AskUserQuestion): ${n}`,
161
+ trajectory: "Traiettoria",
162
+ shifts: (midpoint) => `Cambiamenti di comportamento (prima → seconda metà${midpoint ? `, divisione a ${midpoint}` : ""}):`,
163
+ topics: "Temi esplorati, per trimestre:",
164
+ vocabulary: (list) => `Nuovo vocabolario adottato: ${list}`,
165
+ principles: "Principi codificati:",
166
+ stackAdopted: "Stack adottato",
167
+ stackNote: "_Stack come dichiarato oggi nel repo: dalle dipendenze di package.json (solo manifest npm) e dai file toccati. Le dipendenze non sono disponibili se la cartella del progetto non esiste più, e i servizi usati solo via REST (senza pacchetto) non vengono rilevati._",
168
+ codes: {
169
+ // intensity.cadence
170
+ "daily driver": "uso quotidiano",
171
+ "heavy regular": "uso regolare e intenso",
172
+ weekly: "settimanale",
173
+ occasional: "occasionale",
174
+ // intensity.sessionShape
175
+ "marathon sessions": "sessioni maratona",
176
+ "deep sessions": "sessioni profonde",
177
+ "focused sessions": "sessioni mirate",
178
+ "short bursts": "brevi interventi",
179
+ // distribution.shape
180
+ "deep focus": "focus profondo",
181
+ balanced: "equilibrata",
182
+ portfolio: "portafoglio",
183
+ // aiRelationship.mode
184
+ "directing-leaning": "orientata alla guida",
185
+ "co-thinking-leaning": "orientata al ragionamento condiviso",
186
+ // techUsage band
187
+ continuous: "continuo",
188
+ recurring: "ricorrente",
189
+ // trajectory metrics
190
+ "median prompt words": "parole mediane per prompt",
191
+ "delegation rate": "tasso di delega",
192
+ "research:mutation": "ricerca:modifica",
193
+ "verification rate": "tasso di verifica",
194
+ // trajectory topics
195
+ "agent architecture": "architettura degli agenti",
196
+ "design & UI": "design e UI",
197
+ "security & auth": "sicurezza e autenticazione",
198
+ "dev tooling": "strumenti di sviluppo",
199
+ "data & schema": "dati e schema",
200
+ "AI patterns": "pattern di AI",
201
+ "business & domain": "business e dominio",
202
+ // project type tags
203
+ "product-build": "sviluppo di prodotto",
204
+ "audit-research": "audit e ricerca",
205
+ "agent-tooling": "strumenti per agenti",
206
+ "static-site": "sito statico",
207
+ "ai-platform": "piattaforma AI",
208
+ "data-migration": "migrazione dati",
209
+ "feature-work": "lavoro su funzionalità",
210
+ testing: "test",
211
+ "quality-gating": "controllo di qualità",
212
+ orchestrated: "orchestrato",
213
+ "design-research": "ricerca di design",
214
+ exploration: "esplorazione",
215
+ // cognitive tags
216
+ "research-first": "prima la ricerca",
217
+ decomposer: "scompone i problemi",
218
+ orchestrator: "orchestra",
219
+ "verification-heavy": "verifica molto",
220
+ "risk-calibrated": "rischio calibrato",
221
+ // practices
222
+ checks_before_commit: "controlli prima del commit",
223
+ tests_with_changes: "test insieme alle modifiche",
224
+ failure_reproduced_before_fix: "errore riprodotto prima della correzione",
225
+ plan_before_edit: "piano prima della modifica",
226
+ reviews_changes: "rilegge le modifiche",
227
+ design_documents: "documenti di progettazione",
228
+ security_checks: "controlli di sicurezza",
229
+ asks_for_alternatives: "chiede alternative",
230
+ pushes_back_with_reason: "contesta con una ragione",
231
+ states_done_criteria: "dichiara i criteri di completamento",
232
+ limits_scope: "limita il perimetro",
233
+ },
234
+ };
235
+
236
+ // name: the English name the prompt gives the model.
237
+ export const LANGUAGES = {
238
+ it: { code: "it", name: "Italian", labels: IT },
239
+ en: { code: "en", name: "English", labels: EN },
240
+ };
241
+
242
+ export const SUPPORTED_LANGUAGES = Object.keys(LANGUAGES);
243
+
244
+ export const isSupportedLanguage = (code) => Object.hasOwn(LANGUAGES, code);
245
+
246
+ // A profile with no `language` predates the field and was written in English.
247
+ export const labelsFor = (code) => (LANGUAGES[code] ?? LANGUAGES.en).labels;
248
+
249
+ // The display name of a payload code, or the code itself when the language has none.
250
+ export const codeLabel = (labels, code) => labels.codes[code] ?? code;
@@ -0,0 +1,56 @@
1
+ // The main-thread side of src/pipeline-worker.mjs: one worker for the whole wizard, one promise
2
+ // per task, progress passed to the caller as it arrives. Nothing here blocks, so the spinner
3
+ // the wizard shows keeps moving for as long as the worker computes.
4
+ import { Worker } from "node:worker_threads";
5
+
6
+ const WORKER_URL = new URL("./pipeline-worker.mjs", import.meta.url);
7
+
8
+ /**
9
+ * @param {{ claudeRoot: string, sources: object, out: string, tz: string, top: string|null, language: string, outDir: string, cmd: string }} data
10
+ */
11
+ export function startPipeline(data, { workerUrl = WORKER_URL } = {}) {
12
+ const worker = new Worker(workerUrl, { workerData: data });
13
+ const pending = new Map();
14
+ let seq = 0;
15
+ let stopped = null;
16
+
17
+ const settle = (id, how, value) => {
18
+ const p = pending.get(id);
19
+ if (!p) return;
20
+ pending.delete(id);
21
+ p[how](value);
22
+ };
23
+ const stop = (error) => {
24
+ stopped ??= error;
25
+ for (const id of [...pending.keys()]) settle(id, "reject", stopped);
26
+ };
27
+
28
+ worker.on("message", (m) => {
29
+ if ("progress" in m) pending.get(m.id)?.onProgress?.(m.progress);
30
+ else if (m.error) settle(m.id, "reject", Object.assign(new Error(m.error.message), { name: m.error.name }));
31
+ else settle(m.id, "resolve", m.ok);
32
+ });
33
+ worker.on("error", (e) => stop(e));
34
+ worker.on("exit", (code) => stop(new Error(`the log reader stopped unexpectedly (exit code ${code})`)));
35
+
36
+ const call = (task, args, onProgress) =>
37
+ new Promise((resolve, reject) => {
38
+ if (stopped) return reject(stopped);
39
+ const id = ++seq;
40
+ pending.set(id, { resolve, reject, onProgress });
41
+ worker.postMessage({ id, task, args });
42
+ });
43
+
44
+ return {
45
+ /** Reads one source; resolves with `{ sessions }` (null when it is turned off). `onProgress({ done, total })` as files are read. */
46
+ read: (id, { onProgress } = {}) => call("read", { id }, onProgress),
47
+ /** Derives the profile inputs from the sources read; resolves with what the agent is given. `onStep(label)`. */
48
+ prepare: (ids, { onStep } = {}) => call("prepare", { ids }, (p) => p.step && onStep?.(p.step)),
49
+ /** Merges the agent's answers, assembles and saves the profile; resolves with the numbers to show. */
50
+ finish: (run, { onStep } = {}) => call("finish", { run }, (p) => p.step && onStep?.(p.step)),
51
+ /** submit's check of the profile against the logs as they are now. `onStep(label)`, `onProgress({ source, done, total })`. */
52
+ preflight: (profile, { onStep, onProgress } = {}) =>
53
+ call("preflight", { profile }, (p) => (p.step ? onStep?.(p.step) : onProgress?.(p))),
54
+ close: () => worker.terminate(),
55
+ };
56
+ }
@@ -0,0 +1,96 @@
1
+ // The wizard's heavy work, in a worker thread: reading the logs of each harness, deriving the
2
+ // profile inputs, assembling the profile and the pre-flight against the logs take seconds of
3
+ // synchronous CPU and file reads each. On the main thread they stop @clack's spinner (it
4
+ // animates on a timer), so they run here and the main thread only paints.
5
+ //
6
+ // The worker holds the parsed logs between tasks (they are large and never leave it); a task
7
+ // answers with small, cloneable values. Driven by src/pipeline-client.mjs; the tasks are the
8
+ // functions of src/pipeline.mjs, so the sub-commands and the wizard compute the same thing.
9
+ import { parentPort, workerData } from "node:worker_threads";
10
+ import { existsSync, readFileSync, rmSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { performance } from "node:perf_hooks";
13
+ import { readSource, combineSources } from "./sources.mjs";
14
+ import { narrativeInputFor } from "./profile-llm.mjs";
15
+ import {
16
+ applyAgentRun, assembleWithGroundedness, checkAgainstLogs, deriveInputs, ensureOutDir,
17
+ narrativeOptionsOf, profileSummary, saveProfile, writePracticesInput,
18
+ } from "./pipeline.mjs";
19
+
20
+ const { claudeRoot, sources, out, tz, top, language, outDir, cmd } = workerData;
21
+ const ctx = { tz, top, language, outDir, cmd };
22
+
23
+ const PROGRESS_EVERY_MS = 100;
24
+ const state = { bundles: new Map(), inputs: null };
25
+
26
+ // A task's progress goes out at most every PROGRESS_EVERY_MS, so a loop over thousands of files
27
+ // does not flood the main thread.
28
+ function reporter(id) {
29
+ let last = -Infinity;
30
+ const post = (progress) => parentPort.postMessage({ id, progress });
31
+ return {
32
+ step: (label) => post({ step: label }),
33
+ onProgress: (p) => {
34
+ const t = performance.now();
35
+ if (t - last < PROGRESS_EVERY_MS) return;
36
+ last = t;
37
+ post(p);
38
+ },
39
+ };
40
+ }
41
+
42
+ const EMPTY_CLAUDE = { source: "claude-code", files: [], sessions: [], compactionSummaries: [], redaction: { hits: 0, charsRemoved: 0 } };
43
+
44
+ const tasks = {
45
+ read({ id }, { onProgress }) {
46
+ const bundle = id === "claude-code" && !existsSync(claudeRoot) ? EMPTY_CLAUDE : readSource(id, { claudeRoot, sources, onProgress });
47
+ if (!bundle) return null;
48
+ state.bundles.set(id, bundle);
49
+ return { sessions: bundle.sessions.length };
50
+ },
51
+
52
+ prepare({ ids }, { step }) {
53
+ step("Merging the sources");
54
+ const parsed = combineSources(ids.map((id) => state.bundles.get(id)));
55
+ ensureOutDir(out);
56
+ rmSync(join(out, "agent-log.jsonl"), { force: true });
57
+ const inputs = deriveInputs(parsed, out, { ...ctx, step });
58
+ writePracticesInput(out, parsed, ctx);
59
+ state.inputs = inputs;
60
+ const inputFile = join(out, "practices-input.json");
61
+ return {
62
+ narrativeInput: narrativeInputFor(inputs.selected, inputs.enrichments, narrativeOptionsOf(inputs, language)),
63
+ practicesInput: existsSync(inputFile) ? JSON.parse(readFileSync(inputFile, "utf8")) : null,
64
+ };
65
+ },
66
+
67
+ finish({ run }, { step }) {
68
+ const inputs = state.inputs;
69
+ if (!inputs) throw new Error("the profile inputs are not ready");
70
+ step("Merging the practices");
71
+ const { practices, narrative, generatedBy } = applyAgentRun(out, inputs.practices, run, ctx);
72
+ step("Checking the prose against the data");
73
+ const profile = assembleWithGroundedness(
74
+ { ...inputs, narrative, practices, generatedBy, manifestHash: inputs.fingerprint.manifest.bundleHash },
75
+ { language },
76
+ );
77
+ step("Saving the profile");
78
+ saveProfile(out, profile);
79
+ // Nothing reads the parsed logs again from here, and the pre-flight reads them afresh.
80
+ state.bundles.clear();
81
+ state.inputs = null;
82
+ return profileSummary(profile);
83
+ },
84
+
85
+ preflight({ profile }, { step, onProgress }) {
86
+ return checkAgainstLogs(profile, { claudeRoot, sources, step, onProgress });
87
+ },
88
+ };
89
+
90
+ parentPort.on("message", ({ id, task, args }) => {
91
+ try {
92
+ parentPort.postMessage({ id, ok: tasks[task](args, reporter(id)) ?? null });
93
+ } catch (e) {
94
+ parentPort.postMessage({ id, error: { name: e?.name ?? "Error", message: e?.message ?? String(e) } });
95
+ }
96
+ });