@letsrebase/verify 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/.claude/commands/rebase-verify.md +118 -0
  2. package/LICENSE +21 -0
  3. package/PRIVACY.md +113 -0
  4. package/README.md +210 -2
  5. package/SECURITY.md +33 -0
  6. package/bin/rebase-verify.mjs +700 -0
  7. package/package.json +38 -4
  8. package/share/practices.json +224 -0
  9. package/share/tech-labels.json +57 -0
  10. package/share/tech-lexicon.json +62 -0
  11. package/src/adapters/claude-code.mjs +225 -0
  12. package/src/adapters/codex.mjs +476 -0
  13. package/src/adapters/cursor.mjs +584 -0
  14. package/src/adapters/kimi.mjs +594 -0
  15. package/src/adapters/omp.mjs +59 -0
  16. package/src/adapters/opencode.mjs +439 -0
  17. package/src/adapters/pi.mjs +414 -0
  18. package/src/adapters/tool-vocab.mjs +15 -0
  19. package/src/agent-run.mjs +10 -0
  20. package/src/agentic-literacy.mjs +211 -0
  21. package/src/agents/acp.mjs +364 -0
  22. package/src/agents/json-answer.mjs +72 -0
  23. package/src/agents/registry.mjs +370 -0
  24. package/src/agents/run.mjs +131 -0
  25. package/src/ai-relationship.mjs +95 -0
  26. package/src/consistency.mjs +382 -0
  27. package/src/days.mjs +45 -0
  28. package/src/digest.mjs +501 -0
  29. package/src/distribution.mjs +54 -0
  30. package/src/enrich.mjs +118 -0
  31. package/src/fingerprint.mjs +134 -0
  32. package/src/forensics.mjs +178 -0
  33. package/src/groundedness.mjs +347 -0
  34. package/src/hub.mjs +136 -0
  35. package/src/intensity.mjs +132 -0
  36. package/src/live-status.mjs +79 -0
  37. package/src/practices-llm.mjs +90 -0
  38. package/src/practices-rules.mjs +295 -0
  39. package/src/practices-sample.mjs +111 -0
  40. package/src/practices.mjs +279 -0
  41. package/src/profile-llm.mjs +249 -0
  42. package/src/profile.mjs +497 -0
  43. package/src/redact.mjs +97 -0
  44. package/src/sources.mjs +91 -0
  45. package/src/submit.mjs +65 -0
  46. package/src/system-text.mjs +3 -0
  47. package/src/tech-usage.mjs +88 -0
  48. package/src/trajectory.mjs +264 -0
  49. package/src/wizard.mjs +411 -0
package/src/hub.mjs ADDED
@@ -0,0 +1,136 @@
1
+ // Sign-in against the rebase hub: the device authorization of the hub's
2
+ // work profile design (a small RFC 8628). The CLI asks for a code, the person
3
+ // approves it in the browser, and the CLI polls until it holds an access token.
4
+ // The token is returned to the caller and lives only in memory: it can send one
5
+ // profile and is spent by it, so there is nothing to store and nothing to revoke.
6
+
7
+ import { spawn } from "node:child_process";
8
+ import { readFileSync } from "node:fs";
9
+
10
+ // The hub reads the tool version from this header on every request.
11
+ const { version: TOOL_VERSION } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
12
+ export const USER_AGENT = `rebase-verify/${TOOL_VERSION}`;
13
+
14
+ export const DEFAULT_HUB = "https://letsrebase.com";
15
+ export const PREVIEW_HUB = "https://preview.letsrebase.com";
16
+
17
+ // --hub <url>, else REBASE_VERIFY_HUB_URL, else production. `preview` is a
18
+ // shorthand for the preview host.
19
+ export function resolveHub(flagValue, env = process.env) {
20
+ const raw = (flagValue || env.REBASE_VERIFY_HUB_URL || DEFAULT_HUB).trim();
21
+ const url = raw === "preview" ? PREVIEW_HUB : raw;
22
+ return url.replace(/\/+$/, "");
23
+ }
24
+
25
+ // The address the opener may be given: https (http only for a local hub), on the hub's own
26
+ // origin, and free of characters a shell would treat specially. Returns the href, or null.
27
+ export function safeBrowserUrl(raw, hub) {
28
+ if (typeof raw !== "string" || /[\s|<>^"`]/.test(raw)) return null;
29
+ let u;
30
+ let base;
31
+ try {
32
+ u = new URL(raw);
33
+ base = new URL(hub);
34
+ } catch {
35
+ return null;
36
+ }
37
+ const local = u.hostname === "localhost" || u.hostname === "127.0.0.1";
38
+ if (u.protocol !== "https:" && !(u.protocol === "http:" && local)) return null;
39
+ if (u.origin !== base.origin) return null;
40
+ return u.href;
41
+ }
42
+
43
+ // Opens a URL with the platform's opener, never through a shell. Resolves true when the opener
44
+ // started, false when there is none; never throws.
45
+ export function openInBrowser(url, { platform = process.platform, spawnFn = spawn } = {}) {
46
+ const [cmd, args] =
47
+ platform === "darwin" ? ["open", [url]]
48
+ : platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
49
+ : ["xdg-open", [url]];
50
+ return new Promise((resolve) => {
51
+ try {
52
+ const child = spawnFn(cmd, args, { stdio: "ignore", detached: true });
53
+ child.once("error", () => resolve(false));
54
+ child.once("spawn", () => { child.unref?.(); resolve(true); });
55
+ } catch {
56
+ resolve(false);
57
+ }
58
+ });
59
+ }
60
+
61
+ const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
62
+
63
+ // `parsed` is the JSON body or null when there was none; `data` is the same with {} for null.
64
+ async function postJson(fetchFn, url, body) {
65
+ const res = await fetchFn(url, {
66
+ method: "POST",
67
+ headers: { "content-type": "application/json", accept: "application/json", "user-agent": USER_AGENT },
68
+ body: JSON.stringify(body),
69
+ });
70
+ const parsed = await res.json().catch(() => null);
71
+ return { res, data: parsed ?? {}, parsed };
72
+ }
73
+
74
+ // Runs the device flow and resolves with the access token. Everything that
75
+ // touches the outside is injectable so the flow tests without network or timers.
76
+ export async function signIn(hub, {
77
+ fetchFn = fetch,
78
+ open = openInBrowser,
79
+ sleep = sleepMs,
80
+ now = Date.now,
81
+ log = console.log,
82
+ } = {}) {
83
+ const start = await postJson(fetchFn, `${hub}/api/hub/cli/device`, { scope: "work_profile" });
84
+ if (!start.res.ok) {
85
+ 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
+ const { device_code, user_code, verification_uri, verification_uri_complete } = start.data;
88
+ if (!device_code || !user_code) throw new Error("the hub answered the sign-in start without a code");
89
+ let interval = Number(start.data.interval) || 5;
90
+ const expiresIn = Number(start.data.expires_in) || 600;
91
+
92
+ log(`\nSign in to rebase to send your profile.`);
93
+ log(`Your code: ${user_code}`);
94
+ const link = verification_uri_complete || verification_uri;
95
+ // Only a link on the hub's own origin is handed to the system opener; anything else is printed.
96
+ const href = safeBrowserUrl(link, hub);
97
+ const opened = href ? await open(href) : false;
98
+ if (opened) {
99
+ log(`A browser tab should have opened. Check the code matches, then press «Autorizza».`);
100
+ log(`If it did not open, go to: ${href}`);
101
+ } else {
102
+ log(`Open this address in a browser, check the code matches, then press «Autorizza»:`);
103
+ log(` ${link}`);
104
+ }
105
+ log(`Waiting for you to approve (the code is valid ${Math.round(expiresIn / 60)} minutes)...`);
106
+
107
+ 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"}`);
133
+ }
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
+ }
136
+ }
@@ -0,0 +1,132 @@
1
+ // Practice intensity: how deeply Claude is embedded in the candidate's daily
2
+ // workflow. Pure counts from session timestamps and message volumes — no PII.
3
+ //
4
+ // Five signals, all deterministic:
5
+ // - activeDays / observedDays / activeDaysRatio
6
+ // - medianSessionsPerActiveDay
7
+ // - medianSessionToolCalls (proxy for session depth)
8
+ // - longestStreak (consecutive active days)
9
+ // - peakDayToolCalls
10
+ //
11
+ // A daily-driver candidate ends up around: ≥60% active days, ≥1 session/day
12
+ // median, ≥30 tool calls median session, ≥10 day streak. An occasional user
13
+ // looks the opposite on all five.
14
+ //
15
+ // activeDays uses the SHARED definition in src/days.mjs (message-activity days,
16
+ // no interpolation) so it can never diverge from the fingerprint. The timezone
17
+ // the days are bucketed in is recorded on the result so the count reproduces.
18
+
19
+ import { activeDayKeys, dayKeyFor, DEFAULT_TZ } from "./days.mjs";
20
+
21
+ const DAY_MS = 86_400_000;
22
+ const median = (arr) => {
23
+ if (!arr.length) return 0;
24
+ const s = [...arr].sort((a, b) => a - b);
25
+ return s[Math.floor(s.length / 2)];
26
+ };
27
+
28
+ export function computeIntensity(parsed, { tz = DEFAULT_TZ } = {}) {
29
+ const sessions = parsed?.sessions ?? [];
30
+ if (sessions.length === 0) return null;
31
+
32
+ const dayKey = dayKeyFor(tz);
33
+
34
+ // Per-session aggregates
35
+ const perSession = [];
36
+ const perDaySessions = new Map(); // active day → # sessions active that day
37
+ const perDayToolCalls = new Map(); // session-open day → tool calls
38
+ const allMsgTs = []; // every message timestamp — the active-day source, shared with the fingerprint
39
+ let firstTs = Infinity;
40
+ let lastTs = -Infinity;
41
+
42
+ for (const s of sessions) {
43
+ const start = s.firstTs ? Date.parse(s.firstTs) : null;
44
+ const end = s.lastTs ? Date.parse(s.lastTs) : start;
45
+ if (!Number.isFinite(start)) continue;
46
+ let toolCalls = 0;
47
+ // A session is "active" on every day it actually had a message — this
48
+ // recovers days spent only continuing an existing session, while leaving
49
+ // genuinely idle days idle (no interpolation across a resume gap).
50
+ const dayHits = new Set();
51
+ for (const m of s.messages ?? []) {
52
+ toolCalls += (m.toolUses?.length ?? 0);
53
+ const mt = m.ts ? Date.parse(m.ts) : NaN;
54
+ if (Number.isFinite(mt)) { allMsgTs.push(mt); dayHits.add(dayKey(mt)); }
55
+ }
56
+ perSession.push({ start, end, toolCalls });
57
+ // NO session-open fallback. firstTs can come from a non-message record
58
+ // (system row, file-history snapshot), but the fingerprint counts message
59
+ // timestamps only — so a timestamped, message-empty session must contribute
60
+ // zero active days here too, or the two diverge.
61
+ for (const d of dayHits) perDaySessions.set(d, (perDaySessions.get(d) ?? 0) + 1);
62
+ // Tool-call volume is attributed to the day the session opened (peak-day proxy).
63
+ const openDay = dayKey(start);
64
+ perDayToolCalls.set(openDay, (perDayToolCalls.get(openDay) ?? 0) + toolCalls);
65
+ if (start < firstTs) firstTs = start;
66
+ if (end > lastTs) lastTs = end;
67
+ }
68
+ if (!perSession.length) return null;
69
+
70
+ // activeDays via the SHARED definition: the exact call the fingerprint makes,
71
+ // over message timestamps. The two cannot diverge.
72
+ const activeDayKeySet = activeDayKeys(allMsgTs, tz);
73
+ const activeDaysCount = activeDayKeySet.size;
74
+
75
+ // observedDays from inclusive day KEYS in the same recorded zone — not a raw-ms
76
+ // window, which can round below the day-bucket count (a 90-min session across
77
+ // midnight is 2 active days in 1 rounded ms-day -> 200%). This makes
78
+ // activeDays <= observedDays hold by construction in every zone.
79
+ const dayCount = (a, b) => Math.round((Date.parse(b + "T00:00:00Z") - Date.parse(a + "T00:00:00Z")) / DAY_MS) + 1;
80
+ const observedDays = Math.max(1, dayCount(dayKey(firstTs), dayKey(lastTs)));
81
+ const activeDaysRatio = +(activeDaysCount / observedDays).toFixed(2);
82
+
83
+ // Median sessions per active day (NOT per observed day — we want the cadence
84
+ // on the days they actually showed up).
85
+ const sessionsPerActiveDay = [...perDaySessions.values()];
86
+ const medianSessionsPerActiveDay = median(sessionsPerActiveDay);
87
+
88
+ // Median session tool calls (proxy for session depth).
89
+ const toolCallsPerSession = perSession.map((s) => s.toolCalls);
90
+ const medianSessionToolCalls = median(toolCallsPerSession);
91
+
92
+ // Longest consecutive-active-days streak.
93
+ const dayStamps = [...activeDayKeySet].sort();
94
+ let longestStreak = 0;
95
+ let currentStreak = 0;
96
+ let prev = null;
97
+ for (const d of dayStamps) {
98
+ const t = Date.parse(d + "T00:00:00Z");
99
+ if (prev != null && (t - prev) === DAY_MS) currentStreak++;
100
+ else currentStreak = 1;
101
+ if (currentStreak > longestStreak) longestStreak = currentStreak;
102
+ prev = t;
103
+ }
104
+
105
+ // Peak day by tool calls.
106
+ let peakDayToolCalls = 0;
107
+ for (const v of perDayToolCalls.values()) if (v > peakDayToolCalls) peakDayToolCalls = v;
108
+
109
+ // Cadence band — purely for the LLM narrative, not a grade.
110
+ let cadence = "occasional";
111
+ if (activeDaysRatio >= 0.6) cadence = "daily driver";
112
+ else if (activeDaysRatio >= 0.3) cadence = "heavy regular";
113
+ else if (activeDaysRatio >= 0.1) cadence = "weekly";
114
+
115
+ let sessionShape = "short bursts";
116
+ if (medianSessionToolCalls >= 200) sessionShape = "marathon sessions";
117
+ else if (medianSessionToolCalls >= 50) sessionShape = "deep sessions";
118
+ else if (medianSessionToolCalls >= 20) sessionShape = "focused sessions";
119
+
120
+ return {
121
+ observedDays,
122
+ activeDays: activeDaysCount,
123
+ activeDaysRatio,
124
+ medianSessionsPerActiveDay,
125
+ medianSessionToolCalls,
126
+ longestStreak,
127
+ peakDayToolCalls,
128
+ cadence,
129
+ sessionShape,
130
+ timezone: tz, // recorded so activeDays/streak reproduce on any machine
131
+ };
132
+ }
@@ -0,0 +1,79 @@
1
+ // A one-line live status for the phases where an agent process is alive.
2
+ // @clack's spinner puts stdin in raw mode and exits the process with code 0
3
+ // on Ctrl-C, which would leave the agent running and its temp dir and
4
+ // transcript behind. This one looks the same (gray bar, magenta frame) but
5
+ // hands Ctrl-C to `onCancel`, so the caller can abort the run and clean up.
6
+ import { styleText } from "node:util";
7
+
8
+ const FRAMES = process.platform === "win32" ? ["•", "o", "O", "0"] : ["◒", "◐", "◓", "◑"];
9
+ const DELAY_MS = 80;
10
+ const CTRL_C = "\x03";
11
+
12
+ /**
13
+ * @param {{ onCancel: () => void, input?: object, output?: object, style?: Function, frames?: string[], delay?: number }} o
14
+ * `input` is stdin-like (isTTY, setRawMode, resume, pause, on/off "data"); `output` has write().
15
+ */
16
+ export function liveStatus({ onCancel, input = process.stdin, output = process.stdout, style = styleText, frames = FRAMES, delay = DELAY_MS }) {
17
+ let message = "";
18
+ let frame = 0;
19
+ let timer = null;
20
+ let active = false;
21
+ let wasRaw = false;
22
+ let resumed = false;
23
+
24
+ const clear = () => output.write("\r\x1b[2K");
25
+ const draw = () => {
26
+ clear();
27
+ // never wider than the terminal, or the redraw would wrap and stack lines
28
+ const room = Math.max(10, (output.columns || 80) - 4);
29
+ const text = message.length > room ? `${message.slice(0, room - 1)}…` : message;
30
+ output.write(`${style("magenta", frames[frame % frames.length])} ${text}`);
31
+ };
32
+ const onData = (chunk) => {
33
+ if (String(chunk).includes(CTRL_C)) onCancel();
34
+ };
35
+ const release = () => {
36
+ if (!active) return false;
37
+ active = false;
38
+ clearInterval(timer);
39
+ timer = null;
40
+ input.off?.("data", onData);
41
+ if (input.isTTY && typeof input.setRawMode === "function") input.setRawMode(wasRaw);
42
+ if (resumed) input.pause?.();
43
+ output.write("\x1b[?25h");
44
+ clear();
45
+ return true;
46
+ };
47
+
48
+ return {
49
+ start(msg = "") {
50
+ if (active) return;
51
+ active = true;
52
+ message = msg;
53
+ output.write(`${style("gray", "│")}\n\x1b[?25l`);
54
+ if (input.isTTY && typeof input.setRawMode === "function") {
55
+ wasRaw = Boolean(input.isRaw);
56
+ input.setRawMode(true);
57
+ }
58
+ resumed = Boolean(input.isPaused?.());
59
+ input.resume?.();
60
+ input.on("data", onData);
61
+ draw();
62
+ timer = setInterval(() => {
63
+ frame++;
64
+ draw();
65
+ }, delay);
66
+ timer.unref?.();
67
+ },
68
+ message(msg = "") {
69
+ message = msg;
70
+ if (active) draw();
71
+ },
72
+ stop(msg = "") {
73
+ if (release()) output.write(`${style("green", "◇")} ${msg}\n`);
74
+ },
75
+ error(msg = "") {
76
+ if (release()) output.write(`${style("red", "■")} ${msg}\n`);
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,90 @@
1
+ // The API-key path of the model practices: the person's own messages, already
2
+ // redacted in out/practices-input.json, go to the person's own Anthropic key in
3
+ // batches; the answers are checked before anything is written.
4
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { join } from "node:path";
6
+ import { firstJsonObject } from "./agents/json-answer.mjs";
7
+ import { TONE_RULE } from "./practices-rules.mjs";
8
+ import { validateModelAnswers } from "./practices.mjs";
9
+
10
+ export const PRACTICES_BATCH = 10;
11
+
12
+ // What the person is told before their messages go to the API.
13
+ export const PRACTICES_WARN_WHAT = "the person's own messages from the sampled sessions (already redacted)";
14
+
15
+ export function practicesPrompt(practices) {
16
+ const list = practices.map((p) => {
17
+ const lines = [`- ${p.id}: ${p.definition}`];
18
+ if (p.positive?.length) lines.push(` yes, for example: ${p.positive.map((x) => JSON.stringify(x)).join("; ")}`);
19
+ if (p.negative?.length) lines.push(` no, for example: ${p.negative.map((x) => JSON.stringify(x)).join("; ")}`);
20
+ return lines.join("\n");
21
+ });
22
+ return [
23
+ "You classify work sessions between a person and an AI coding agent. For each session you get only the person's own messages, in order.",
24
+ "For each practice below, answer true when the person's messages in that session show it, and false otherwise.",
25
+ "",
26
+ "Practices:",
27
+ ...list,
28
+ "",
29
+ "Judge only what the messages say. When in doubt, answer false.",
30
+ TONE_RULE,
31
+ "",
32
+ "Reply with JSON only: an object keyed by the given session ids, each value an object with exactly the given practice ids as keys and true or false as values. Nothing else: no reasons, no quotes, no other keys, no text around it.",
33
+ ].join("\n");
34
+ }
35
+
36
+ // input: { practices: [{ id, definition, ... }], sessions: [{ id, messages }] }
37
+ // `retries`: how many times a batch is asked again when its answer holds no JSON
38
+ // object or does not fit. `onBatch({ batch, total, retry })` fires before each ask.
39
+ // A failure of `call` itself passes through when it carries its own name (tool
40
+ // use, login, abort); a plain one is prefixed with the batch as before.
41
+ export async function classifyPractices(input, { call, retries = 0, onBatch } = {}) {
42
+ const system = practicesPrompt(input.practices);
43
+ const ids = input.practices.map((p) => p.id);
44
+ const answers = {};
45
+ const total = Math.ceil(input.sessions.length / PRACTICES_BATCH);
46
+ for (let i = 0; i < input.sessions.length; i += PRACTICES_BATCH) {
47
+ const sessions = input.sessions.slice(i, i + PRACTICES_BATCH);
48
+ const n = i / PRACTICES_BATCH + 1;
49
+ const batch = `batch ${n} of ${total}`;
50
+ const user = JSON.stringify({ practices: ids, sessions });
51
+ let parsed;
52
+ for (let attempt = 0; ; attempt++) {
53
+ onBatch?.({ batch: n, total, retry: attempt > 0 });
54
+ let text;
55
+ try {
56
+ text = await call({ system, user });
57
+ } catch (e) {
58
+ throw e instanceof Error && e.name !== "Error" ? e : new Error(`practices ${batch}: ${e.message}`);
59
+ }
60
+ let failure = null;
61
+ try {
62
+ parsed = firstJsonObject(text);
63
+ const v = validateModelAnswers(parsed, sessions, ids);
64
+ if (!v.ok) failure = v.error;
65
+ } catch (e) {
66
+ failure = e.message;
67
+ }
68
+ if (!failure) break;
69
+ if (attempt >= retries) throw new Error(`practices ${batch}: ${failure}`);
70
+ }
71
+ Object.assign(answers, parsed);
72
+ }
73
+ return answers;
74
+ }
75
+
76
+ // The generate step. Returns "written", "hint" (no key) or "none" (no input).
77
+ export async function runPracticesStep(out, { key, call, warn, log = console.log }) {
78
+ const inputFile = join(out, "practices-input.json");
79
+ if (!existsSync(inputFile)) return "none";
80
+ if (!key) {
81
+ log(" model practices not classified yet (no API key).");
82
+ log(" From a clone, inside Claude Code: /rebase-verify (your own model classifies them and finalizes)");
83
+ return "hint";
84
+ }
85
+ warn?.();
86
+ const input = JSON.parse(readFileSync(inputFile, "utf8"));
87
+ const answers = await classifyPractices(input, { call });
88
+ writeFileSync(join(out, "practices.json"), JSON.stringify(answers, null, 2));
89
+ return "written";
90
+ }