@letsrebase/verify 0.2.0 → 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.
package/README.md CHANGED
@@ -18,7 +18,7 @@ Node 20.12 or newer, one coding agent installed and signed in (or an Anthropic A
18
18
  npx @letsrebase/verify
19
19
  ```
20
20
 
21
- On a terminal this starts a short wizard. It lists the sources it found in your logs, asks which coding agent should write the narrative and classify the practices (the default is the tested agent with most sessions in your logs, on that agent's current model), shows a consent note, then runs with live progress. It asks nothing about who you are. Two files come out in `out/`: `profile.md` for humans, `candidate.json` for agents (plus working files described under "Work practices" and "Commands"). The wizard ends with a summary and a choice: submit now or later. You can keep the profile for yourself.
21
+ On a terminal this starts a short wizard. It lists the sources it found in your logs, asks which coding agent should write the narrative and classify the practices (the default is the tested agent with most sessions in your logs, on that agent's current model), shows a consent note, then runs with live progress. It asks nothing about who you are. Two files come out in `out/`: `profile.md` for humans, `candidate.json` for agents (plus working files described under "Work practices" and "Commands"). The wizard ends with a summary, a screen that says who receives what and for how long, and one question: send (the first option, so Enter sends) or not. Answering no, or pressing Ctrl-C, sends nothing; you can keep the profile for yourself and send it later with `submit --yes`. Every wait shows a spinner that names its step.
22
22
 
23
23
  To submit later:
24
24
 
@@ -183,7 +183,7 @@ If you spot something we should change, [open an issue](https://github.com/letsr
183
183
 
184
184
  | | |
185
185
  |---|---|
186
- | `npx @letsrebase/verify` | on a terminal, the wizard: finds your sources, lets you pick the agent and the model, writes and classifies the profile, shows a summary, then submits now or later |
186
+ | `npx @letsrebase/verify` | on a terminal, the wizard: finds your sources, lets you pick the agent and the model, writes and classifies the profile, shows a summary and who receives it, then asks once whether to send |
187
187
  | `generate --agent <id> --model <id>` | the same without the wizard, for scripts; add `--yes` to skip every prompt |
188
188
  | `generate` *(default)* | full profile, locally; with `ANTHROPIC_API_KEY` set, the key sends the practices sample, and the narrative input unless `--narrative-file` is given, to Anthropic |
189
189
  | `prepare` | `out/narrative-input.json`, for writing the narrative manually, and `out/practices-input.json` with `out/practices-sample.json` for the model practices; `finalize` must get the same `--tz` |
@@ -39,29 +39,16 @@
39
39
  import { homedir } from "node:os";
40
40
  import { join } from "node:path";
41
41
  import { fileURLToPath } from "node:url";
42
- import { writeFileSync, existsSync, readFileSync, mkdirSync, rmSync } from "node:fs";
43
- import { readClaudeCode } from "../src/adapters/claude-code.mjs";
44
- import { SOURCES, readSource, combineSources, readAllSources } from "../src/sources.mjs";
45
- import { computeFingerprint } from "../src/fingerprint.mjs";
46
- import { computeForensics } from "../src/forensics.mjs";
47
- import { buildDigest } from "../src/digest.mjs";
48
- import { practicesFiles } from "../src/practices-sample.mjs";
42
+ import { writeFileSync, existsSync, readFileSync, rmSync } from "node:fs";
43
+ import { SOURCES, readAllSources } from "../src/sources.mjs";
44
+ import * as pipeline from "../src/pipeline.mjs";
49
45
  import { PRACTICES_WARN_WHAT, runPracticesStep } from "../src/practices-llm.mjs";
50
- import { enrichRepo, describeContextGaps } from "../src/enrich.mjs";
51
46
  import { MODEL, anthropicCall, generateNarrative, narrativeInputFor, warnApiKey } from "../src/profile-llm.mjs";
52
- import { selectRepresentatives, assembleProfile, renderMarkdown, summarizeSources } from "../src/profile.mjs";
53
47
  import { resolveHub } from "../src/hub.mjs";
54
- import { submitProfile, buildPayload } from "../src/submit.mjs";
55
- import { buildTrajectory } from "../src/trajectory.mjs";
48
+ import { submitProfile, buildPayload, sendNotice } from "../src/submit.mjs";
56
49
  import { DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES, isSupportedLanguage } from "../src/languages.mjs";
57
50
  import { assessGroundedness } from "../src/groundedness.mjs";
58
- import { assessStructure, assessAgainstLogs, submitBlockers } from "../src/consistency.mjs";
59
- import { computeAiRelationship } from "../src/ai-relationship.mjs";
60
- import { computeAgenticLiteracy } from "../src/agentic-literacy.mjs";
61
- import { computeIntensity } from "../src/intensity.mjs";
62
- import { computeDistribution } from "../src/distribution.mjs";
63
- import { computeTechUsage, recordedTechUsageTz } from "../src/tech-usage.mjs";
64
- import { computeCodePractices, mergeModelPractices, practicesBlock, recordedPracticesTz } from "../src/practices.mjs";
51
+ import { assessStructure, submitBlockers } from "../src/consistency.mjs";
65
52
  import { DEFAULT_TZ } from "../src/days.mjs";
66
53
  import { invocation } from "../src/invocation.mjs";
67
54
 
@@ -139,13 +126,7 @@ const OUT_DIR = "out";
139
126
  const CMD = invocation();
140
127
  const outPath = () => join(process.cwd(), OUT_DIR);
141
128
  // Created only once logs were found. A `*` .gitignore inside keeps every file in it out of a commit.
142
- const ensureOut = () => {
143
- const out = outPath();
144
- mkdirSync(out, { recursive: true });
145
- const ignore = join(out, ".gitignore");
146
- if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
147
- return out;
148
- };
129
+ const ensureOut = () => pipeline.ensureOutDir(outPath());
149
130
 
150
131
  // The wizard, the agent runner and their dependencies load only where they are used, so the
151
132
  // sub-commands work in a clone that never ran npm ci.
@@ -176,10 +157,8 @@ const die = (msg, code = 2) => {
176
157
  process.exit(code);
177
158
  };
178
159
 
179
- // The wizard owns the terminal while it runs: the pipeline's progress lines stay quiet then.
180
- let QUIET = false;
181
- const say = (...a) => { if (!QUIET) console.log(...a); };
182
- const warn = (...a) => { if (!QUIET) console.error(...a); };
160
+ const say = (...a) => console.log(...a);
161
+ const warn = (...a) => console.error(...a);
183
162
 
184
163
  // The agent behind `generate --agent <id>`, checked before any log is read.
185
164
  async function resolveAgent() {
@@ -279,89 +258,38 @@ async function loadProfileInputs() {
279
258
  return deriveInputs(parsed, ensureOut());
280
259
  }
281
260
 
282
- // Everything computed from the parsed logs; the wizard passes the sources the person chose.
283
- function deriveInputs(parsed, out) {
284
- // Timezone the day-based counts (activeDays, streak) are bucketed in. Default
285
- // UTC (machine-independent); recorded in the profile so the count reproduces.
286
- // Validated at startup (tzFlag) before any logs are read.
287
- const tz = tzFlag;
288
-
289
- say(`[2/5] Fingerprint, manifest, consistency ...`);
290
- const fingerprint = computeFingerprint(parsed, { tz });
291
- const forensics = computeForensics(parsed);
292
-
293
- say(`[3/5] Deep digest + per-repo clustering (PII redacted: ${parsed.redaction.hits}) ...`);
294
- const digest = buildDigest(parsed, { tz });
295
- const projects = selectRepresentatives(digest.projects, flag("top") ? +flag("top") : "auto");
296
- const selected = projects.filter((p) => p.selected);
297
- say(` ${digest.projectCount} products, ${selected.length}${flag("top") ? "" : " (adaptive 3-5)"} representative: ${selected.map((p) => `${p.repo}[${p.type[0]}]`).join(", ")}`);
298
-
299
- const enrichments = selected.map((p) => enrichRepo(p.cwdRaw));
300
- const contextGap = describeContextGaps(enrichments);
301
- if (contextGap) warn(` note: ${contextGap}`);
302
- const trajectory = buildTrajectory(parsed);
303
- const aiRelationship = computeAiRelationship(parsed);
304
- const agenticLiteracy = computeAgenticLiteracy(parsed);
305
- const intensity = computeIntensity(parsed, { tz });
306
- const distribution = computeDistribution(projects);
307
- const techUsage = computeTechUsage(projects, { tz });
308
- const practices = practicesBlock(computeCodePractices(parsed, { tz })?.items, { tz });
309
- const sources = summarizeSources(parsed);
310
- return { parsed, fingerprint, forensics, projects, selected, enrichments, trajectory, aiRelationship, agenticLiteracy, intensity, distribution, techUsage, practices, sources, out };
261
+ // The profile pipeline lives in src/pipeline.mjs, shared with the wizard's worker thread; these
262
+ // bind it to this run's flags and to the terminal.
263
+ const pipelineCtx = () => ({ tz: tzFlag, top: flag("top"), language: langFlag, outDir: OUT_DIR, cmd: CMD, say, warn });
264
+ const deriveInputs = (parsed, out) => pipeline.deriveInputs(parsed, out, pipelineCtx());
265
+ const writePracticesInput = (out, parsed) => pipeline.writePracticesInput(out, parsed, pipelineCtx());
266
+ const assembleWithGroundedness = (args) => pipeline.assembleWithGroundedness(args, pipelineCtx());
267
+
268
+ // Answers that cannot be used stop the step with the reason; nothing is saved.
269
+ function stopOnBadAnswers(fn) {
270
+ try {
271
+ return fn();
272
+ } catch (e) {
273
+ if (!(e instanceof pipeline.PracticesAnswersError)) throw e;
274
+ console.error(e.message);
275
+ process.exit(2);
276
+ }
311
277
  }
278
+ const mergePracticesAnswers = (out, codeBlock, classifiedBy) => stopOnBadAnswers(() => pipeline.mergePracticesAnswers(out, codeBlock, classifiedBy, pipelineCtx()));
279
+ const applyAgentRun = (out, codePractices, run) => stopOnBadAnswers(() => pipeline.applyAgentRun(out, codePractices, run, pipelineCtx()));
312
280
 
313
- function writeProfile(out, profile, { print = true } = {}) {
314
- writeFileSync(join(out, "candidate.json"), JSON.stringify(profile, null, 2));
315
- const md = renderMarkdown(profile);
316
- writeFileSync(join(out, "profile.md"), md);
317
- if (!print) return;
318
- console.log(md);
281
+ function writeProfile(out, profile) {
282
+ console.log(pipeline.saveProfile(out, profile));
319
283
  console.log(`Saved: ${OUT_DIR}/candidate.json + ${OUT_DIR}/profile.md`);
320
284
  console.log(`To send it to rebase when ready: ${CMD} submit`);
321
285
  }
322
286
 
323
- // What the agent run adds to the profile: the answers merged into the practices block, who
324
- // wrote the narrative. The answers stay in practices-detail.json, so a later finalize never
325
- // reads them as the slash command's.
326
- function applyAgentRun(out, codePractices, run) {
327
- if (run.practicesAnswers) writeFileSync(join(out, "practices.json"), JSON.stringify(run.practicesAnswers, null, 2));
328
- const practices = run.practicesAnswers ? mergePracticesAnswers(out, codePractices, run.used) : codePractices;
329
- rmSync(join(out, "practices.json"), { force: true });
330
- return { practices, narrative: run.narrative, generatedBy: { narrative: run.used } };
331
- }
332
-
333
- const narrativeOptionsOf = (i) => ({
334
- trajectory: i.trajectory,
335
- aiRelationship: i.aiRelationship,
336
- agenticLiteracy: i.agenticLiteracy,
337
- intensity: i.intensity,
338
- distribution: i.distribution,
339
- allProjects: i.projects,
340
- compactionSummaries: i.parsed.compactionSummaries,
341
- language: langFlag,
342
- });
343
-
344
- // The model-classified practices: written only when some are published and
345
- // there is something to read. Both files stay local; the sample file maps the
346
- // opaque ids back to real sessions and is never sent.
347
- function writePracticesInput(out, parsed, tz) {
348
- // A stale sample from an earlier run must never be read by finalize.
349
- for (const f of ["practices-input.json", "practices-sample.json", "practices-detail.json", "practices.json"]) rmSync(join(out, f), { force: true });
350
- const shared = JSON.parse(readFileSync(new URL("../share/practices.json", import.meta.url), "utf8"));
351
- const practices = (shared.practices ?? []).filter((p) => p.method === "model");
352
- const files = practicesFiles(parsed, { tz, practices });
353
- if (!files) return;
354
- writeFileSync(join(out, "practices-input.json"), JSON.stringify(files.input, null, 2));
355
- writeFileSync(join(out, "practices-sample.json"), JSON.stringify(files.sample, null, 2));
356
- say(`Wrote ${OUT_DIR}/practices-input.json (${files.sample.length} sessions of your own messages, for your model to classify) and ${OUT_DIR}/practices-sample.json (local only).`);
357
- }
358
-
359
287
  async function cmdGenerate() {
360
288
  const entry = await resolveAgent();
361
289
  console.log(`\nrebase-verify generate\n`);
362
290
  const { parsed, fingerprint, forensics, projects, selected, enrichments, trajectory, aiRelationship, agenticLiteracy, intensity, distribution, techUsage, practices: codePractices, sources, out } = await loadProfileInputs();
363
291
  if (entry) rmSync(join(out, "agent-log.jsonl"), { force: true });
364
- writePracticesInput(out, parsed, tzFlag);
292
+ writePracticesInput(out, parsed);
365
293
  const narrativeOptions = {
366
294
  trajectory,
367
295
  aiRelationship,
@@ -408,25 +336,10 @@ async function cmdGenerate() {
408
336
  }));
409
337
  }
410
338
 
411
- // Assemble + compute groundedness on the assembled draft + re-assemble with
412
- // the score embedded. Centralised so generate and finalize share it.
413
- function assembleWithGroundedness(args) {
414
- // The raw vocabularyCandidates never enter the profile (they can carry
415
- // client names), so a narrative that omitted its filtered pick leaves
416
- // newVocabulary empty. Say so instead of failing silently.
417
- if (args.narrative && args.trajectory?.vocabularyCandidates?.length && !args.narrative.trajectory?.vocabulary_adopted?.length) {
418
- warn(` note: the narrative has no trajectory.vocabulary_adopted, newVocabulary stays empty (raw candidates are never used; re-run the narrative step to fill it)`);
419
- }
420
- const withLanguage = { language: langFlag, ...args };
421
- const draft = assembleProfile(withLanguage);
422
- const groundedness = assessGroundedness(draft);
423
- return assembleProfile({ ...withLanguage, groundedness });
424
- }
425
-
426
339
  async function cmdPrepare() {
427
340
  console.log(`\nrebase-verify prepare\n`);
428
341
  const { parsed, projects, selected, enrichments, trajectory, aiRelationship, agenticLiteracy, intensity, distribution, out } = await loadProfileInputs();
429
- writePracticesInput(out, parsed, tzFlag);
342
+ writePracticesInput(out, parsed);
430
343
  const input = narrativeInputFor(selected, enrichments, {
431
344
  trajectory,
432
345
  aiRelationship,
@@ -442,32 +355,6 @@ async function cmdPrepare() {
442
355
  console.log(`Next: write ${OUT_DIR}/narrative.json (rules in the slash command), then ${CMD} finalize`);
443
356
  }
444
357
 
445
- // The model's answers, when the person's model wrote out/practices.json: checked
446
- // against the sample file written at prepare (never resampled), then merged into
447
- // the block, with who classified them. A bad or unreadable file stops the step;
448
- // nothing is saved.
449
- function mergePracticesAnswers(out, codeBlock, classifiedBy) {
450
- const answersFile = join(out, "practices.json");
451
- if (!existsSync(answersFile)) return codeBlock;
452
- const sampleFile = join(out, "practices-sample.json");
453
- const fail = (msg) => { console.error(`${msg} Fix it, or delete ${OUT_DIR}/practices.json to leave the model practices out.`); process.exit(2); };
454
- const read = (file) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return undefined; } };
455
- const sample = read(sampleFile);
456
- if (!Array.isArray(sample)) fail(`Missing or unreadable ${sampleFile}: run ${CMD} prepare again.`);
457
- const answers = read(answersFile);
458
- if (answers === undefined) fail(`${answersFile} is not valid JSON.`);
459
- const shared = JSON.parse(readFileSync(new URL("../share/practices.json", import.meta.url), "utf8"));
460
- const ids = (shared.practices ?? []).filter((p) => p.method === "model").map((p) => p.id);
461
- try {
462
- const { block, detail } = mergeModelPractices(codeBlock, answers, sample, ids, { tz: tzFlag, classifiedBy });
463
- writeFileSync(join(out, "practices-detail.json"), JSON.stringify(detail, null, 2));
464
- say(`Merged the model's answers for ${sample.length} sessions (per-session detail in ${OUT_DIR}/practices-detail.json, local only).`);
465
- return block;
466
- } catch (e) {
467
- return fail(`${answersFile}: ${e.message}.`);
468
- }
469
- }
470
-
471
358
  function preparedLanguage(out) {
472
359
  try {
473
360
  const code = JSON.parse(readFileSync(join(out, "narrative-input.json"), "utf8")).language;
@@ -507,7 +394,10 @@ async function cmdFinalize() {
507
394
  }));
508
395
  }
509
396
 
510
- async function cmdSubmit({ yes = false } = {}) {
397
+ // `checkLogs(profile, spin)` and `around(label, fn)` are the wizard's: the pre-flight against the
398
+ // logs runs in its worker and every wait is shown with its own spinner. Without them (the
399
+ // sub-command) the same steps run in place and print their own progress.
400
+ async function cmdSubmit({ yes = false, noticeShown = false, checkLogs = null, around = (_label, fn) => fn({ message() {} }) } = {}) {
511
401
  // Profiles live in ./out; fall back to the repo root for profiles
512
402
  // generated by a version that still wrote there.
513
403
  let profilePath = join(process.cwd(), OUT_DIR, "candidate.json");
@@ -521,20 +411,11 @@ async function cmdSubmit({ yes = false } = {}) {
521
411
  }
522
412
  const profile = JSON.parse(readFileSync(profilePath, "utf8"));
523
413
  const hub = resolveHub(flag("hub"));
524
- const links = (profile.projects || []).filter((p) => p.artifact).length;
525
-
526
- console.log(`\nrebase-verify submit\n`);
527
- console.log(`About to send to rebase (${hub}):`);
528
- console.log(` profile: ${profile.volume?.sessions} sessions, ${profile.volume?.products} products`);
529
- console.log(` artifact links: ${links}`);
530
- console.log(`\nYou sign in in the browser first, so rebase knows it is you; no name, email or city is sent with the profile.`);
531
- console.log(`A person at rebase reads it before it counts. If they approve it, your profile gets «Verificato da rebase»,`);
532
- console.log(`companies rebase works with can see its summary, its domains of work and the sectors of its representative projects, next to your name and your card (written by your model, reviewed by you), for example in the talent cloud or when rebase proposes you for a project, and its text is used to write your anonymous card.`);
533
- console.log(`It is kept at most 12 months, and you can delete it from your member area.`);
534
- console.log(`Controller: Rebase S.r.l. (VAT IT 14971460960). Details: https://letsrebase.com/privacy and PRIVACY.md.`);
535
- console.log(`NOT sent: raw logs, local repo context, third-party proper names.`);
536
- console.log(`Repository names (repoLabel) are stripped from the payload before it leaves your machine.`);
537
- console.log(`Inspect the exact outgoing payload: ${CMD} submit --dry-run`);
414
+
415
+ if (!noticeShown) {
416
+ console.log(`\nrebase-verify submit\n`);
417
+ console.log(sendNotice({ hub, profile, cmd: CMD }).join("\n"));
418
+ }
538
419
 
539
420
  // Pre-flight groundedness: how much of the prose is anchored in the data.
540
421
  // Recomputed on the file as it is NOW, not trusted from the embedded score.
@@ -560,23 +441,14 @@ async function cmdSubmit({ yes = false } = {}) {
560
441
  console.log(`\nConsistency check`);
561
442
  const issues = [...assessStructure(profile).issues];
562
443
  let excessClaims = 0;
563
- let root = flag("root", join(homedir(), ".claude", "projects"));
564
- if (flag("project")) root = join(root, flag("project"));
444
+ const root = logsRoot();
565
445
  if (existsSync(root)) {
566
446
  // Re-derive from the SAME source mix the profile was generated from
567
447
  // (see sourceFlags()'s comment for why this must never drift).
568
- const parsed = readAllSources({ claudeRoot: root, sources: sourceFlags() });
569
- // Re-derive day-based intensity and tech-usage months in the zone the
570
- // profile RECORDED, never the machine zone, so the comparison measures
571
- // the data, not the bucketing.
572
- const techTz = recordedTechUsageTz(profile);
573
- const digest = buildDigest(parsed, { tz: techTz });
574
- const intensity = computeIntensity(parsed, { tz: profile.intensity?.timezone || DEFAULT_TZ });
575
- const techUsage = computeTechUsage(digest.projects, { tz: techTz });
576
- const practices = computeCodePractices(parsed, { tz: recordedPracticesTz(profile) });
577
- const logs = assessAgainstLogs(profile, digest.projects, { intensity, techUsage, practices });
448
+ const logs = await around("Checking the profile against your logs", (spin) =>
449
+ (checkLogs ?? ((p) => pipeline.checkAgainstLogs(p, { claudeRoot: root, sources: sourceFlags() })))(profile, spin));
578
450
  issues.push(...logs.issues);
579
- excessClaims = logs.excessClaims || 0;
451
+ excessClaims = logs.excessClaims;
580
452
  for (const w of logs.warnings) console.log(` ~ ${w}`);
581
453
  } else {
582
454
  console.log(` ~ no logs at ${root}, skipping log re-derivation (pass --root if they live elsewhere)`);
@@ -645,7 +517,7 @@ async function cmdSubmit({ yes = false } = {}) {
645
517
  }
646
518
 
647
519
  try {
648
- const res = await submitProfile(profilePath, { hub: flag("hub") });
520
+ const res = await submitProfile(profilePath, { hub: flag("hub"), around });
649
521
  console.log(`\nSent. Your profile is waiting as a draft: a person at rebase will read it before it counts.`);
650
522
  if (res.review_url) console.log(`See its status here: ${res.review_url}`);
651
523
  } catch (e) {
@@ -661,11 +533,12 @@ if (sub !== "generate" && (has("agent") || has("model"))) die("--agent and --mod
661
533
  const interactive = !(argv[0] && !argv[0].startsWith("--")) && process.stdin.isTTY && process.stdout.isTTY && !has("yes");
662
534
 
663
535
  async function cmdWizard() {
664
- const { wizard, clack, live, agents } = await loadOptional(async () => ({
536
+ const { wizard, clack, live, agents, pipelineClient } = await loadOptional(async () => ({
665
537
  wizard: await import("../src/wizard.mjs"),
666
538
  clack: await import("@clack/prompts"),
667
539
  live: await import("../src/live-status.mjs"),
668
540
  agents: await loadAgents(),
541
+ pipelineClient: await import("../src/pipeline-client.mjs"),
669
542
  }));
670
543
  const rejected = wizard.rejectedFlags(has);
671
544
  if (rejected) die(rejected);
@@ -675,52 +548,51 @@ async function cmdWizard() {
675
548
  const root = logsRoot();
676
549
  const flags = sourceFlags();
677
550
  const pkg = JSON.parse(readFileSync(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
678
- const code = await wizard.runWizard({
679
- ui: { ...clack, live: live.liveStatus },
680
- out,
681
- flags: { version: pkg.version, agent: entry?.id, model: flag("model") ?? undefined },
682
- deps: {
683
- sources: SOURCES.filter((s) => s.id === "claude-code" || !flags[s.id]?.disabled),
684
- readSource: (id) =>
685
- id === "claude-code" && !existsSync(root)
686
- ? { source: "claude-code", files: [], sessions: [], compactionSummaries: [], redaction: { hits: 0, charsRemoved: 0 } }
687
- : readSource(id, { claudeRoot: root, sources: flags }),
688
- combine: combineSources,
689
- availableAgents: (sessionsBySource) => availableAgents({ sessionsBySource }),
690
- defaultAgent,
691
- prepare: (parsed) => {
692
- QUIET = true;
693
- ensureOut();
694
- rmSync(join(out, "agent-log.jsonl"), { force: true });
695
- const inputs = deriveInputs(parsed, out);
696
- writePracticesInput(out, parsed, tzFlag);
697
- const inputFile = join(out, "practices-input.json");
698
- return {
699
- inputs,
700
- narrativeInput: narrativeInputFor(inputs.selected, inputs.enrichments, narrativeOptionsOf(inputs)),
701
- practicesInput: existsSync(inputFile) ? JSON.parse(readFileSync(inputFile, "utf8")) : null,
702
- };
703
- },
704
- startAgent: agents.acp.startAgent,
705
- runWithAgent: agents.run.runWithAgent,
706
- finish: ({ inputs }, run) => {
707
- const { practices, narrative, generatedBy } = applyAgentRun(out, inputs.practices, run);
708
- const profile = assembleWithGroundedness({
709
- ...inputs, narrative, practices, generatedBy,
710
- manifestHash: inputs.fingerprint.manifest.bundleHash,
711
- });
712
- writeProfile(out, profile, { print: false });
713
- QUIET = false;
714
- return {
715
- sessions: profile.volume?.sessions ?? 0,
716
- products: profile.volume?.products ?? 0,
717
- practices: profile.practices?.items ?? [],
718
- summary: profile.summary ?? null,
719
- };
551
+ // Reading the logs and deriving the profile take seconds of synchronous work: they run in a
552
+ // worker thread, so the main thread only paints the spinner that says which step it is.
553
+ const work = pipelineClient.startPipeline({ claudeRoot: root, sources: flags, out, tz: tzFlag, top: flag("top"), language: langFlag, outDir: OUT_DIR, cmd: CMD });
554
+ const sourceLabel = (id) => SOURCES.find((s) => s.id === id)?.label ?? id;
555
+ // One spinner per wait that submit has, with the step it is on; its last line is the label itself.
556
+ const around = async (label, fn) => {
557
+ const s = clack.spinner();
558
+ s.start(label);
559
+ try {
560
+ const v = await fn({ message: (m) => s.message(m) });
561
+ s.stop(label);
562
+ return v;
563
+ } catch (e) {
564
+ s.error(label);
565
+ throw e;
566
+ }
567
+ };
568
+ const checkLogs = (profile, spin) =>
569
+ work.preflight(profile, {
570
+ onStep: (m) => spin.message(m),
571
+ onProgress: (p) => spin.message(`Reading your logs again: ${sourceLabel(p.source)}, ${p.done} of ${p.total} files`),
572
+ });
573
+ let code;
574
+ try {
575
+ code = await wizard.runWizard({
576
+ ui: { ...clack, live: live.liveStatus },
577
+ out,
578
+ flags: { version: pkg.version, agent: entry?.id, model: flag("model") ?? undefined },
579
+ deps: {
580
+ sources: SOURCES.filter((s) => s.id === "claude-code" || !flags[s.id]?.disabled),
581
+ readSource: (id, o) => work.read(id, o),
582
+ availableAgents: (sessionsBySource) => availableAgents({ sessionsBySource }),
583
+ defaultAgent,
584
+ prepare: (ids, o) => work.prepare(ids, o),
585
+ startAgent: agents.acp.startAgent,
586
+ runWithAgent: agents.run.runWithAgent,
587
+ finish: (run, o) => work.finish(run, o),
588
+ // the profile finish() has just written, read back as submit will read it
589
+ sendNotice: () => sendNotice({ hub: resolveHub(flag("hub")), profile: JSON.parse(readFileSync(join(out, "candidate.json"), "utf8")), cmd: CMD }).join("\n"),
590
+ submit: () => cmdSubmit({ yes: true, noticeShown: true, checkLogs, around }),
720
591
  },
721
- submit: () => cmdSubmit({ yes: true }),
722
- },
723
- });
592
+ });
593
+ } finally {
594
+ await work.close();
595
+ }
724
596
  process.exit(code);
725
597
  }
726
598
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@letsrebase/verify",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Work profile: build a tamper-evident, PII-redacted work profile from your coding-agent logs and send it to rebase for review.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -84,11 +84,13 @@ function extractContent(content) {
84
84
  return { text, thinkingChars, signatureChars, toolUses, toolResults };
85
85
  }
86
86
 
87
- export function readClaudeCode(root) {
87
+ export function readClaudeCode(root, { onProgress } = {}) {
88
88
  const files = [];
89
89
  const records = [];
90
90
 
91
- for (const path of walk(root)) {
91
+ const paths = [...walk(root)];
92
+ for (const [i, path] of paths.entries()) {
93
+ onProgress?.({ done: i, total: paths.length });
92
94
  const buf = readFileSync(path);
93
95
  const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
94
96
  let malformed = 0;
@@ -232,7 +232,7 @@ const EMPTY = (root) => ({
232
232
  stats: { originatorCounts: {}, malformedLines: 0 },
233
233
  });
234
234
 
235
- export function readCodex(root) {
235
+ export function readCodex(root, { onProgress } = {}) {
236
236
  if (!root || !existsSync(root)) return EMPTY(root);
237
237
 
238
238
  const files = [];
@@ -242,7 +242,9 @@ export function readCodex(root) {
242
242
  const originatorCounts = {};
243
243
  let malformedLinesTotal = 0;
244
244
 
245
- for (const path of walk(root)) {
245
+ const paths = [...walk(root)];
246
+ for (const [i, path] of paths.entries()) {
247
+ onProgress?.({ done: i, total: paths.length });
246
248
  const buf = readFileSync(path);
247
249
  const relPath = relative(root, path);
248
250
  const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
@@ -54,6 +54,6 @@ function isTopLevelSession(relPath) {
54
54
  return parts.length === 2 && !parts[1].includes("__advisor");
55
55
  }
56
56
 
57
- export function readOmp(root) {
58
- return readPiFormat(root, { source: "omp", mapTool: mapOmpTool, includeFile: isTopLevelSession });
57
+ export function readOmp(root, { onProgress } = {}) {
58
+ return readPiFormat(root, { source: "omp", mapTool: mapOmpTool, includeFile: isTopLevelSession, onProgress });
59
59
  }
@@ -235,14 +235,14 @@ const EMPTY = (root, source = "pi") => ({
235
235
  stats: { malformedLines: 0, projectDirCount: 0 },
236
236
  });
237
237
 
238
- export function readPi(root) {
239
- return readPiFormat(root, { source: "pi" });
238
+ export function readPi(root, { onProgress } = {}) {
239
+ return readPiFormat(root, { source: "pi", onProgress });
240
240
  }
241
241
 
242
242
  // pi's on-disk format is shared by oh-my-pi (omp), a pi fork. The omp adapter
243
243
  // calls this with its own source label, tool-name mapper and file filter; real
244
244
  // pi goes through readPi above with the defaults, behaviour unchanged.
245
- export function readPiFormat(root, { source = "pi", mapTool = piMapTool, includeFile = () => true } = {}) {
245
+ export function readPiFormat(root, { source = "pi", mapTool = piMapTool, includeFile = () => true, onProgress } = {}) {
246
246
  if (!root || !existsSync(root)) return EMPTY(root, source);
247
247
 
248
248
  const files = [];
@@ -253,8 +253,9 @@ export function readPiFormat(root, { source = "pi", mapTool = piMapTool, include
253
253
  let malformedLinesTotal = 0;
254
254
  const projectDirs = new Set();
255
255
 
256
- for (const path of walk(root)) {
257
- if (!includeFile(relative(root, path))) continue;
256
+ const paths = [...walk(root)].filter((path) => includeFile(relative(root, path)));
257
+ for (const [i, path] of paths.entries()) {
258
+ onProgress?.({ done: i, total: paths.length });
258
259
  const buf = readFileSync(path);
259
260
  const relPath = relative(root, path);
260
261
  const lines = buf.toString("utf8").split("\n").filter((l) => l.trim());
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,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
+ });
@@ -0,0 +1,194 @@
1
+ // The steps between the logs and the profile, as plain functions of their inputs, so the
2
+ // sub-commands run them in place and the wizard runs the same ones in a worker thread
3
+ // (src/pipeline-worker.mjs), where a long synchronous stretch cannot freeze its spinner.
4
+ // Nothing here prints or exits: output goes through the `ctx` callbacks and a failure is thrown.
5
+ //
6
+ // `ctx` = { tz, top, language, outDir, cmd, say, warn, step }:
7
+ // tz, language the profile's timezone and language
8
+ // top the forced number of representative projects, or null for adaptive
9
+ // outDir, cmd how the person's own messages name the output folder and this command
10
+ // say, warn progress and notes for the sub-commands' terminal output (default: silent)
11
+ // step a short label of the stretch about to start, for the wizard's spinner
12
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { readAllSources } from "./sources.mjs";
15
+ import { computeFingerprint } from "./fingerprint.mjs";
16
+ import { computeForensics } from "./forensics.mjs";
17
+ import { buildDigest } from "./digest.mjs";
18
+ import { enrichRepo, describeContextGaps } from "./enrich.mjs";
19
+ import { selectRepresentatives, assembleProfile, renderMarkdown, summarizeSources } from "./profile.mjs";
20
+ import { narrativeInputFor } from "./profile-llm.mjs";
21
+ import { practicesFiles } from "./practices-sample.mjs";
22
+ import { buildTrajectory } from "./trajectory.mjs";
23
+ import { computeAiRelationship } from "./ai-relationship.mjs";
24
+ import { computeAgenticLiteracy } from "./agentic-literacy.mjs";
25
+ import { computeIntensity } from "./intensity.mjs";
26
+ import { computeDistribution } from "./distribution.mjs";
27
+ import { computeTechUsage, recordedTechUsageTz } from "./tech-usage.mjs";
28
+ import { computeCodePractices, mergeModelPractices, practicesBlock, recordedPracticesTz } from "./practices.mjs";
29
+ import { assessGroundedness } from "./groundedness.mjs";
30
+ import { assessAgainstLogs } from "./consistency.mjs";
31
+ import { DEFAULT_TZ } from "./days.mjs";
32
+
33
+ const quiet = () => {};
34
+
35
+ /** The model's answers could not be used; the message says what to fix. */
36
+ export class PracticesAnswersError extends Error {
37
+ name = "PracticesAnswersError";
38
+ }
39
+
40
+ /** The output folder, created once logs were found. A `*` .gitignore inside keeps every file in it out of a commit. */
41
+ export function ensureOutDir(out) {
42
+ mkdirSync(out, { recursive: true });
43
+ const ignore = join(out, ".gitignore");
44
+ if (!existsSync(ignore)) writeFileSync(ignore, "*\n");
45
+ return out;
46
+ }
47
+
48
+ // Everything computed from the parsed logs; the wizard passes the sources the person chose.
49
+ export function deriveInputs(parsed, out, { tz, top = null, say = quiet, warn = quiet, step = quiet }) {
50
+ step("Fingerprinting the logs");
51
+ say(`[2/5] Fingerprint, manifest, consistency ...`);
52
+ const fingerprint = computeFingerprint(parsed, { tz });
53
+ const forensics = computeForensics(parsed);
54
+
55
+ step("Grouping the work into projects");
56
+ say(`[3/5] Deep digest + per-repo clustering (PII redacted: ${parsed.redaction.hits}) ...`);
57
+ const digest = buildDigest(parsed, { tz });
58
+ const projects = selectRepresentatives(digest.projects, top ? +top : "auto");
59
+ const selected = projects.filter((p) => p.selected);
60
+ say(` ${digest.projectCount} products, ${selected.length}${top ? "" : " (adaptive 3-5)"} representative: ${selected.map((p) => `${p.repo}[${p.type[0]}]`).join(", ")}`);
61
+
62
+ step("Reading the representative projects");
63
+ const enrichments = selected.map((p) => enrichRepo(p.cwdRaw));
64
+ const contextGap = describeContextGaps(enrichments);
65
+ if (contextGap) warn(` note: ${contextGap}`);
66
+ step("Measuring how the work changed over time");
67
+ const trajectory = buildTrajectory(parsed);
68
+ const aiRelationship = computeAiRelationship(parsed);
69
+ const agenticLiteracy = computeAgenticLiteracy(parsed);
70
+ const intensity = computeIntensity(parsed, { tz });
71
+ const distribution = computeDistribution(projects);
72
+ const techUsage = computeTechUsage(projects, { tz });
73
+ step("Counting the work practices");
74
+ const practices = practicesBlock(computeCodePractices(parsed, { tz })?.items, { tz });
75
+ const sources = summarizeSources(parsed);
76
+ return { parsed, fingerprint, forensics, projects, selected, enrichments, trajectory, aiRelationship, agenticLiteracy, intensity, distribution, techUsage, practices, sources, out };
77
+ }
78
+
79
+ export const narrativeOptionsOf = (i, language) => ({
80
+ trajectory: i.trajectory,
81
+ aiRelationship: i.aiRelationship,
82
+ agenticLiteracy: i.agenticLiteracy,
83
+ intensity: i.intensity,
84
+ distribution: i.distribution,
85
+ allProjects: i.projects,
86
+ compactionSummaries: i.parsed.compactionSummaries,
87
+ language,
88
+ });
89
+
90
+ const sharedPractices = () => JSON.parse(readFileSync(new URL("../share/practices.json", import.meta.url), "utf8"));
91
+
92
+ // The model-classified practices: written only when some are published and
93
+ // there is something to read. Both files stay local; the sample file maps the
94
+ // opaque ids back to real sessions and is never sent.
95
+ export function writePracticesInput(out, parsed, { tz, outDir, say = quiet }) {
96
+ // A stale sample from an earlier run must never be read by finalize.
97
+ for (const f of ["practices-input.json", "practices-sample.json", "practices-detail.json", "practices.json"]) rmSync(join(out, f), { force: true });
98
+ const practices = (sharedPractices().practices ?? []).filter((p) => p.method === "model");
99
+ const files = practicesFiles(parsed, { tz, practices });
100
+ if (!files) return;
101
+ writeFileSync(join(out, "practices-input.json"), JSON.stringify(files.input, null, 2));
102
+ writeFileSync(join(out, "practices-sample.json"), JSON.stringify(files.sample, null, 2));
103
+ say(`Wrote ${outDir}/practices-input.json (${files.sample.length} sessions of your own messages, for your model to classify) and ${outDir}/practices-sample.json (local only).`);
104
+ }
105
+
106
+ // The model's answers, when the person's model wrote out/practices.json: checked
107
+ // against the sample file written at prepare (never resampled), then merged into
108
+ // the block, with who classified them. A bad or unreadable file stops the step;
109
+ // nothing is saved.
110
+ export function mergePracticesAnswers(out, codeBlock, classifiedBy, { tz, outDir, cmd, say = quiet }) {
111
+ const answersFile = join(out, "practices.json");
112
+ if (!existsSync(answersFile)) return codeBlock;
113
+ const sampleFile = join(out, "practices-sample.json");
114
+ const fail = (msg) => {
115
+ throw new PracticesAnswersError(`${msg} Fix it, or delete ${outDir}/practices.json to leave the model practices out.`);
116
+ };
117
+ const read = (file) => { try { return JSON.parse(readFileSync(file, "utf8")); } catch { return undefined; } };
118
+ const sample = read(sampleFile);
119
+ if (!Array.isArray(sample)) fail(`Missing or unreadable ${sampleFile}: run ${cmd} prepare again.`);
120
+ const answers = read(answersFile);
121
+ if (answers === undefined) fail(`${answersFile} is not valid JSON.`);
122
+ const ids = (sharedPractices().practices ?? []).filter((p) => p.method === "model").map((p) => p.id);
123
+ try {
124
+ const { block, detail } = mergeModelPractices(codeBlock, answers, sample, ids, { tz, classifiedBy });
125
+ writeFileSync(join(out, "practices-detail.json"), JSON.stringify(detail, null, 2));
126
+ say(`Merged the model's answers for ${sample.length} sessions (per-session detail in ${outDir}/practices-detail.json, local only).`);
127
+ return block;
128
+ } catch (e) {
129
+ return fail(`${answersFile}: ${e.message}.`);
130
+ }
131
+ }
132
+
133
+ // What the agent run adds to the profile: the answers merged into the practices block, who
134
+ // wrote the narrative. The answers stay in practices-detail.json, so a later finalize never
135
+ // reads them as the slash command's.
136
+ export function applyAgentRun(out, codePractices, run, ctx) {
137
+ if (run.practicesAnswers) writeFileSync(join(out, "practices.json"), JSON.stringify(run.practicesAnswers, null, 2));
138
+ const practices = run.practicesAnswers ? mergePracticesAnswers(out, codePractices, run.used, ctx) : codePractices;
139
+ rmSync(join(out, "practices.json"), { force: true });
140
+ return { practices, narrative: run.narrative, generatedBy: { narrative: run.used } };
141
+ }
142
+
143
+ // Assemble + compute groundedness on the assembled draft + re-assemble with
144
+ // the score embedded. Centralised so generate, finalize and the wizard share it.
145
+ export function assembleWithGroundedness(args, { language, warn = quiet }) {
146
+ // The raw vocabularyCandidates never enter the profile (they can carry
147
+ // client names), so a narrative that omitted its filtered pick leaves
148
+ // newVocabulary empty. Say so instead of failing silently.
149
+ if (args.narrative && args.trajectory?.vocabularyCandidates?.length && !args.narrative.trajectory?.vocabulary_adopted?.length) {
150
+ warn(` note: the narrative has no trajectory.vocabulary_adopted, newVocabulary stays empty (raw candidates are never used; re-run the narrative step to fill it)`);
151
+ }
152
+ const withLanguage = { language, ...args };
153
+ const draft = assembleProfile(withLanguage);
154
+ const groundedness = assessGroundedness(draft);
155
+ return assembleProfile({ ...withLanguage, groundedness });
156
+ }
157
+
158
+ /** Writes candidate.json and profile.md; returns the markdown. */
159
+ export function saveProfile(out, profile) {
160
+ writeFileSync(join(out, "candidate.json"), JSON.stringify(profile, null, 2));
161
+ const md = renderMarkdown(profile);
162
+ writeFileSync(join(out, "profile.md"), md);
163
+ return md;
164
+ }
165
+
166
+ /** The numbers the wizard shows after a run. */
167
+ export const profileSummary = (profile) => ({
168
+ sessions: profile.volume?.sessions ?? 0,
169
+ products: profile.volume?.products ?? 0,
170
+ practices: profile.practices?.items ?? [],
171
+ summary: profile.summary ?? null,
172
+ });
173
+
174
+ /**
175
+ * submit's pre-flight against the logs as they are now: re-reads the SAME source mix the
176
+ * profile was generated from (see sourceFlags() in the bin for why this must never drift),
177
+ * then re-derives what the profile claims.
178
+ * @returns {{ issues: string[], excessClaims: number, warnings: string[] }}
179
+ */
180
+ export function checkAgainstLogs(profile, { claudeRoot, sources, step = quiet, onProgress }) {
181
+ step("Reading your logs again");
182
+ const parsed = readAllSources({ claudeRoot, sources, onProgress });
183
+ step("Re-deriving what the profile claims");
184
+ // Re-derive day-based intensity and tech-usage months in the zone the
185
+ // profile RECORDED, never the machine zone, so the comparison measures
186
+ // the data, not the bucketing.
187
+ const techTz = recordedTechUsageTz(profile);
188
+ const digest = buildDigest(parsed, { tz: techTz });
189
+ const intensity = computeIntensity(parsed, { tz: profile.intensity?.timezone || DEFAULT_TZ });
190
+ const techUsage = computeTechUsage(digest.projects, { tz: techTz });
191
+ const practices = computeCodePractices(parsed, { tz: recordedPracticesTz(profile) });
192
+ const logs = assessAgainstLogs(profile, digest.projects, { intensity, techUsage, practices });
193
+ return { issues: logs.issues, excessClaims: logs.excessClaims || 0, warnings: logs.warnings };
194
+ }
package/src/sources.mjs CHANGED
@@ -53,9 +53,11 @@ export const SOURCES = [
53
53
  /**
54
54
  * Read one source by its id (see SOURCES) with agent-run transcripts dropped,
55
55
  * or null when `sources.<id>.disabled`. Same roots and flags as readAllSources.
56
+ * `onProgress({ done, total })` is called as the files of the source are read, for the
57
+ * sources that are files (the sqlite ones are read in one query).
56
58
  */
57
- export function readSource(id, { claudeRoot, sources }) {
58
- if (id === "claude-code") return dropAgentRuns(readClaudeCode(claudeRoot));
59
+ export function readSource(id, { claudeRoot, sources, onProgress }) {
60
+ if (id === "claude-code") return dropAgentRuns(readClaudeCode(claudeRoot, { onProgress }));
59
61
  const o = sources?.[id] ?? {};
60
62
  if (o.disabled) return null;
61
63
  switch (id) {
@@ -66,9 +68,9 @@ export function readSource(id, { claudeRoot, sources }) {
66
68
  const root = o.root ?? defaultOpencodeRoot();
67
69
  return dropAgentRuns(o.json ? readOpencodeJson(root) : readOpencode(root));
68
70
  }
69
- case "codex": return dropAgentRuns(readCodex(o.root ?? defaultCodexRoot()));
70
- case "pi": return dropAgentRuns(readPi(o.root ?? defaultPiRoot()));
71
- case "omp": return dropAgentRuns(readOmp(o.root ?? defaultOmpRoot()));
71
+ case "codex": return dropAgentRuns(readCodex(o.root ?? defaultCodexRoot(), { onProgress }));
72
+ case "pi": return dropAgentRuns(readPi(o.root ?? defaultPiRoot(), { onProgress }));
73
+ case "omp": return dropAgentRuns(readOmp(o.root ?? defaultOmpRoot(), { onProgress }));
72
74
  case "cursor": return dropAgentRuns(readCursor(o.root ?? defaultCursorRoot()));
73
75
  case "kimi": return dropAgentRuns(readKimi(o.root ?? defaultKimiRoot()));
74
76
  default: throw new Error(`unknown source: ${id}`);
@@ -80,10 +82,10 @@ export function combineSources(bundles) {
80
82
  return bundles.length > 1 ? mergeSources(...bundles) : bundles[0];
81
83
  }
82
84
 
83
- export function readAllSources({ claudeRoot, sources }) {
85
+ export function readAllSources({ claudeRoot, sources, onProgress }) {
84
86
  const bundles = [];
85
87
  for (const { id } of SOURCES) {
86
- const b = readSource(id, { claudeRoot, sources });
88
+ const b = readSource(id, { claudeRoot, sources, onProgress: onProgress && ((p) => onProgress({ ...p, source: id })) });
87
89
  // claude-code is always part of the result; the others only when they have sessions.
88
90
  if (b && (id === "claude-code" || b.sessions.length)) bundles.push(b);
89
91
  }
package/src/submit.mjs CHANGED
@@ -28,24 +28,46 @@ export function buildPayload(profile) {
28
28
  return payload;
29
29
  }
30
30
 
31
- // Signs in, then posts. `fetchFn`, `open`, `sleep` and `log` are injectable.
32
- export async function submitProfile(profilePath, { hub, fetchFn = fetch, ...flow } = {}) {
31
+ // What the person is told before anything is sent: who receives it, what it holds, what a person at
32
+ // rebase does with it, how long it is kept, what never leaves the machine. One text for the
33
+ // sub-command and for the wizard, so the screen before the last question is the same in both.
34
+ export function sendNotice({ hub, profile, cmd }) {
35
+ const links = (profile.projects || []).filter((p) => p.artifact).length;
36
+ return [
37
+ `About to send to rebase (${hub}):`,
38
+ ` profile: ${profile.volume?.sessions} sessions, ${profile.volume?.products} products`,
39
+ ` artifact links: ${links}`,
40
+ ``,
41
+ `You sign in in the browser first, so rebase knows it is you; no name, email or city is sent with the profile.`,
42
+ `A person at rebase reads it before it counts. If they approve it, your profile gets «Verificato da rebase»,`,
43
+ `companies rebase works with can see its summary, its domains of work and the sectors of its representative projects, next to your name and your card (written by your model, reviewed by you), for example in the talent cloud or when rebase proposes you for a project, and its text is used to write your anonymous card.`,
44
+ `It is kept at most 12 months, and you can delete it from your member area.`,
45
+ `Controller: Rebase S.r.l. (VAT IT 14971460960). Details: https://letsrebase.com/privacy and PRIVACY.md.`,
46
+ `NOT sent: raw logs, local repo context, third-party proper names.`,
47
+ `Repository names (repoLabel) are stripped from the payload before it leaves your machine.`,
48
+ `Inspect the exact outgoing payload: ${cmd} submit --dry-run`,
49
+ ];
50
+ }
51
+
52
+ // Signs in, then posts. `fetchFn`, `open`, `sleep` and `log` are injectable; `around(label, fn)`
53
+ // wraps each wait (the sign-in code, the approval in the browser, the upload) so a caller can show it.
54
+ export async function submitProfile(profilePath, { hub, fetchFn = fetch, around = (_label, fn) => fn(), ...flow } = {}) {
33
55
  if (!existsSync(profilePath)) throw new Error(`profile not found: ${profilePath}`);
34
56
  // Refuse before signing in: no point asking for a browser round trip for a payload the hub would reject.
35
57
  const payload = buildPayload(JSON.parse(readFileSync(profilePath, "utf8")));
36
58
 
37
59
  const base = resolveHub(hub);
38
- const token = await signIn(base, { fetchFn, ...flow });
60
+ const token = await signIn(base, { fetchFn, around, ...flow });
39
61
 
40
62
  const form = new FormData();
41
63
  form.append("profile", new Blob([JSON.stringify(payload)], { type: "application/json" }), "candidate.json");
42
64
  let res;
43
65
  try {
44
- res = await fetchFn(`${base}/api/hub/work-profiles`, {
66
+ res = await around("Sending your profile to rebase", () => fetchFn(`${base}/api/hub/work-profiles`, {
45
67
  method: "POST",
46
68
  headers: { authorization: `Bearer ${token}`, "user-agent": USER_AGENT },
47
69
  body: form,
48
- });
70
+ }));
49
71
  } catch (e) {
50
72
  throw new Error(`could not reach the hub to send the profile (${e.message}). The sign-in is spent by the first attempt, so run submit again and sign in anew.`);
51
73
  }
package/src/wizard.mjs CHANGED
@@ -11,7 +11,6 @@ import { AgentAuthError, AgentStartError, ModelNotOfferedError, ToolUseError } f
11
11
  import { RUN_SYSTEM } from "./agents/run.mjs";
12
12
 
13
13
  const REDRAW_MS = 100;
14
- const tick = () => new Promise((r) => setImmediate(r));
15
14
  const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
16
15
  const kilo = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
17
16
 
@@ -104,8 +103,11 @@ const NO_AGENT_NOTE = [
104
103
  /**
105
104
  * @param {object} p
106
105
  * @param {object} p.ui clack: intro, outro, cancel, note, log, spinner, multiselect, select, confirm, isCancel
107
- * @param {object} p.deps sources, readSource, combine, availableAgents, defaultAgent, prepare,
108
- * startAgent, runWithAgent, finish, submit
106
+ * @param {object} p.deps sources, availableAgents, defaultAgent, startAgent, runWithAgent, submit,
107
+ * sendNotice() -> the text of the screen shown before the question about sending, and the
108
+ * steps that read and compute, all async so the spinner keeps moving while they work:
109
+ * readSource(id, { onProgress }) -> { sessions } | null, prepare(ids, { onStep }) -> { narrativeInput, practicesInput },
110
+ * finish(run, { onStep }) -> { sessions, products, practices, summary }
109
111
  * @param {{ version?: string, agent?: string, model?: string }} p.flags
110
112
  * @returns {Promise<number>} the process exit code
111
113
  */
@@ -165,21 +167,23 @@ export async function runWizard({ ui, deps, flags = {}, out, proc = process, now
165
167
 
166
168
  ui.intro(`rebase-verify${flags.version ? ` ${flags.version}` : ""}`);
167
169
 
168
- // 1. Sources, one spinner each so the counts appear as they finish.
170
+ // 1. Sources, one spinner each so the counts appear as they finish. The reading runs off the
171
+ // main thread (deps.readSource is async), so the spinner keeps moving and shows the files so far.
169
172
  const found = [];
170
173
  for (const src of deps.sources) {
171
174
  const s = ui.spinner();
172
175
  s.start(`Reading ${src.label}`);
173
- await tick();
174
- let bundle = null;
176
+ let read = null;
175
177
  try {
176
- bundle = deps.readSource(src.id);
178
+ read = await deps.readSource(src.id, {
179
+ onProgress: ({ done, total }) => s.message(`Reading ${src.label} (${done} of ${plural(total, "file")})`),
180
+ });
177
181
  } catch {
178
- bundle = null;
182
+ read = null;
179
183
  }
180
- const n = bundle?.sessions?.length ?? 0;
181
- s.stop(bundle ? `${src.label}: ${plural(n, "session")}` : `${src.label}: could not be read`);
182
- if (n > 0) found.push({ ...src, bundle, count: n });
184
+ const n = read?.sessions ?? 0;
185
+ s.stop(read ? `${src.label}: ${plural(n, "session")}` : `${src.label}: could not be read`);
186
+ if (n > 0) found.push({ ...src, count: n });
183
187
  }
184
188
  if (!found.length) {
185
189
  ui.cancel("No sessions found in your logs, so there is nothing to build a profile from. Nothing was sent.");
@@ -198,10 +202,9 @@ export async function runWizard({ ui, deps, flags = {}, out, proc = process, now
198
202
  const sessionsBySource = Object.fromEntries(found.map((f) => [f.id, f.count]));
199
203
  const ps = ui.spinner();
200
204
  ps.start("Building your profile from the logs");
201
- await tick();
202
205
  let prepared;
203
206
  try {
204
- prepared = deps.prepare(deps.combine(picked.map((f) => f.bundle)));
207
+ prepared = await deps.prepare(picked.map((f) => f.id), { onStep: (m) => ps.message(`Building your profile: ${m.toLowerCase()}`) });
205
208
  } catch (e) {
206
209
  ps.error(`Could not build the profile: ${e.message}`);
207
210
  return 1;
@@ -366,7 +369,16 @@ export async function runWizard({ ui, deps, flags = {}, out, proc = process, now
366
369
  session = null;
367
370
 
368
371
  // 6. The profile.
369
- const done = deps.finish(prepared, result);
372
+ const assembling = ui.spinner();
373
+ assembling.start("Assembling your profile");
374
+ let done;
375
+ try {
376
+ done = await deps.finish(result, { onStep: (m) => assembling.message(`Assembling your profile: ${m.toLowerCase()}`) });
377
+ } catch (e) {
378
+ assembling.error("Could not assemble your profile");
379
+ return await fail(e);
380
+ }
381
+ assembling.stop("Your profile is ready");
370
382
  const rows = (done.practices ?? []).map((p) => ` ${p.id}: seen in ${p.seen} of ${p.of}`);
371
383
  ui.note(
372
384
  [
@@ -378,27 +390,23 @@ export async function runWizard({ ui, deps, flags = {}, out, proc = process, now
378
390
  ].join("\n"),
379
391
  "Your profile",
380
392
  );
381
- let next;
382
- for (;;) {
383
- next = await ui.select({
384
- message: "What next?",
385
- options: [
386
- { value: "submit", label: "Send it to rebase now" },
387
- { value: "exit", label: "Exit", hint: "send later with: npx @letsrebase/verify submit --yes" },
388
- ],
389
- initialValue: "exit",
390
- });
391
- if (await cancelled(next)) return 130;
392
- if (next !== "submit") break;
393
- const read = await ui.confirm({ message: "Have you read out/profile.md? It is what rebase will see.", initialValue: false });
394
- if (await cancelled(read)) return 130;
395
- if (read) break;
396
- }
397
- if (next === "submit") {
393
+ // The screen that says who receives what comes first and is never skipped; then one question,
394
+ // whose first and default answer is to send. Anything but that answer (no, Ctrl-C) sends nothing.
395
+ ui.note(deps.sendNotice(), "What leaves your machine, and who receives it");
396
+ const choice = await ui.select({
397
+ message: `Send this profile to rebase? It is what rebase will see (${join(out, "profile.md")}).`,
398
+ options: [
399
+ { value: "send", label: "Send it to rebase" },
400
+ { value: "exit", label: "Do not send", hint: "send later with: npx @letsrebase/verify submit --yes" },
401
+ ],
402
+ initialValue: "send",
403
+ });
404
+ if (await cancelled(choice)) return 130;
405
+ if (choice === "send") {
398
406
  await deps.submit();
399
407
  ui.outro("Sent.");
400
408
  } else {
401
- ui.outro("Done. Nothing was sent.");
409
+ ui.outro("Done. Nothing was sent. To send it later: npx @letsrebase/verify submit --yes");
402
410
  }
403
411
  return 0;
404
412
  } finally {