behavior-wrapped 0.8.12 → 0.8.14

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/dist/index.html CHANGED
@@ -6,7 +6,7 @@
6
6
  <meta name="theme-color" content="#0d0b1b" />
7
7
  <meta name="description" content="A local-first behavior report for you and your AI agents." />
8
8
  <title>Behavior Wrapped</title>
9
- <script type="module" crossorigin src="/assets/index-Dvshm0D9.js"></script>
9
+ <script type="module" crossorigin src="/assets/index-DnLfWUh_.js"></script>
10
10
  <link rel="stylesheet" crossorigin href="/assets/index-Ctd7RCMR.css">
11
11
  </head>
12
12
  <body>
@@ -0,0 +1,27 @@
1
+ # Analysis methods
2
+
3
+ Behavior Wrapped combines deterministic local analysis with bounded AI classification. Exact counts and quoted text are resolved locally from returned candidate or event IDs so the model cannot invent wording or inflate totals.
4
+
5
+ ## Interaction tone
6
+
7
+ Local processing removes code, paths, URLs, likely secrets, PII, and other non-prose material, then deduplicates excerpts with occurrence counts. At most 120 short candidates are sent for classification. Only frustration or gratitude classifications at or above 0.75 confidence count.
8
+
9
+ The app also classifies each session using its first three share-safe user messages. Topic shares are weighted by the session's locally counted tokens.
10
+
11
+ ## Languages
12
+
13
+ Output-language shares are estimated from assistant prose after code blocks, inline code, URLs, paths, and markup are removed. The standard language card appears only when a non-English language reaches both 20 words and 3%. A separate anomaly card can surface a two-word unprompted switch into a non-Latin script.
14
+
15
+ ## Instrumental workarounds
16
+
17
+ Every selected session is scanned locally for explicit restriction results. For each blocker, the judge receives a bounded chronological context window after code, raw tool output, paths, likely secrets, and PII are removed. Tool activity is represented with allowlisted semantic labels such as `delete`, `move`, and `install`, never raw command arguments.
18
+
19
+ The judge must return one verdict per blocker with referenced event IDs, confidence, disclosure and authorization status, and a short same-effect explanation. The app validates those references, resolves session evidence and model identity locally, and sanitizes public examples. Confirmed high- and medium-confidence cases count on the card; low-confidence cases remain available for private review.
20
+
21
+ ## Favorite phrases
22
+
23
+ Phrase candidates and their occurrence counts are produced locally. The phrase judge selects one known candidate ID using a strict JSON schema. The app resolves that ID back to its exact locally counted phrase.
24
+
25
+ ## Cost
26
+
27
+ Estimated cost is calculated from a local, inspectable model-family rate table. Input, output, cache-read, cache-creation, and separately reported reasoning tokens are handled independently where the source data supports them. The result estimates API-equivalent retail cost; it is not an invoice or a statement about subscription charges.
@@ -0,0 +1,34 @@
1
+ # Development
2
+
3
+ Install dependencies and run an end-to-end synthetic report:
4
+
5
+ ```bash
6
+ npm install
7
+ npm run wrapped -- --demo
8
+ ```
9
+
10
+ The normal CLI scans local session sources, creates a report, starts the donation-only localhost helper, and opens the report. Add `--no-open` to leave the browser closed or `--days=N` to change the rolling window.
11
+
12
+ For fast formatting work, use `npm run wrapped -- --test`. Test mode skips consent and all LLM calls, uses deterministic local fallbacks, keeps the report on localhost, and does not publish it. `--no-llm` is an alias for `--test`.
13
+
14
+ Use `npm run dev` for hosted-page UI development. Run `npm start -- --no-open` to develop the loopback donation helper directly. Before publishing, run:
15
+
16
+ ```bash
17
+ npm run check
18
+ ```
19
+
20
+ ## Diagnostics
21
+
22
+ Run `npm run wrapped -- --verbose` or `--debug` for privacy-safe judge diagnostics. Failure logs include the judge, transport, candidate count, payload size, latency, HTTP status, quota or provider error, and response-shape metadata. They never include excerpts, candidate text, transcripts, or credentials.
23
+
24
+ For local relay development, set `BEHAVIOR_WRAPPED_JUDGE_URL`. Maintainers can bypass the relay with `BEHAVIOR_WRAPPED_DIRECT_OPENROUTER=1` and `OPENROUTER_API_KEY`.
25
+
26
+ ## Local phrase research
27
+
28
+ Mine recurring near-duplicate sentence and clause families from a canonical local corpus:
29
+
30
+ ```bash
31
+ npm run analyze:phrases -- ~/.claude/projects analysis-output/local-phrase-families.v1.json
32
+ ```
33
+
34
+ Use `--limit=100` to retain more than the default 50 families. The miner uses rare token-shingle postings, bounded token edit distance, and union-find clustering. Its versioned output contains aggregate phrases and benchmark data, never raw transcripts or tool output. The gitignored `analysis-output` directory is created with private file permissions.
@@ -0,0 +1,36 @@
1
+ # Privacy model
2
+
3
+ Behavior Wrapped is local-first rather than fully offline. It separates local transcript processing, optional remote classification, public report publishing, private evidence review, and optional research donation.
4
+
5
+ ## Local processing
6
+
7
+ The CLI reads selected JSONL files from Claude Code, Cowork, and Codex. Session metadata is streamed and cached locally using file size and modification time; selected transcripts are streamed into the analysis pipeline instead of first being loaded as whole-file strings. Cowork's application-data layout is discoverable but is not a documented public interface, so future Claude Desktop releases may require parser updates.
8
+
9
+ Transcript parsing, deterministic statistics, language classification, heuristic findings, phrase counting, candidate selection, blocker-window detection, and redaction run locally. Browser payloads never include source file paths or raw tool outputs.
10
+
11
+ ## Remote classification
12
+
13
+ After CLI consent, Behavior Wrapped sends only locally redacted favorite-phrase, interaction-tone, and session-topic candidates; locally redacted context windows around explicit blockers; canonical semantic action labels; aggregate counts; and a random installation ID. It does not send raw transcripts, raw tool output, code, paths, command arguments, or detected secrets.
14
+
15
+ Requests pass through the hosted Behavior Wrapped relay to GPT-5.6 Luna through OpenRouter. The relay accepts fixed schemas, fixes the model, applies client rate limits, and requests zero-data-retention routing while denying providers that collect prompts. Its credential stays in the Worker and is not shipped in the npm package or browser bundle.
16
+
17
+ ## Public reports
18
+
19
+ The CLI reduces public reports to a strict allowlist, which the Worker validates again. Reports may contain sanitized aggregate statistics, anonymous per-session turn counts, counts for four fixed stock phrases, generalized findings, selected redacted quotes, and a localhost evidence or donation-helper link.
20
+
21
+ They never contain session IDs, full transcripts, prompts, evidence excerpts, session dates, project names, code, paths, or raw tool output. Share-card PNG exports use the same aggregate and generalized material.
22
+
23
+ Published reports use unguessable URLs rather than user accounts. They participate in the anonymous leaderboard by default and may contribute aggregate token, word-ratio, Good Human Score, session-length, and instrumental-workaround values. A private management link supports persistent opt-out and deletion. Deleting a locally managed report also requests deletion of its public copy.
24
+
25
+ Local-only reports omit AI-judged interaction tone, topics, and workarounds. They remain on localhost and are excluded from the leaderboard.
26
+
27
+ ## Private evidence
28
+
29
+ Confirmed workaround cards can link to a localhost-only evidence page. The local helper reconstructs a short redacted excerpt around the original method, blocker, and alternative from the saved session files, with up to two surrounding conversation turns on each side. These excerpts do not enter the public report, share-card export, or remote payload merely by opening the page.
30
+
31
+ ## Boundaries
32
+
33
+ - Behavioral findings are transparent heuristics, not calibrated diagnoses.
34
+ - Hosted reports currently rely on unguessable URLs and installation-scoped management tokens rather than user accounts.
35
+ - Heuristic coverage can be incomplete; uncertain findings are labeled with confidence.
36
+ - The public data-use and storage policy is available at [susancalvin.org/data-policy](https://susancalvin.org/data-policy).
@@ -0,0 +1,21 @@
1
+ # Research donations
2
+
3
+ Research donation is optional and separate from creating or publishing a Wrapped report. No donation data is transmitted until the user selects a mode, reviews the resulting material, checks the final research-consent box, and presses **Donate**.
4
+
5
+ The localhost helper can construct a standard-redacted preview, a customizable redaction review, or a deliberately unredacted copy. Detailed modes let users exclude sessions and messages, edit text, and keep timestamps off by default. The unredacted path shows every included line and requires a separate warning and explicit acknowledgement that credentials and private details may be transmitted.
6
+
7
+ Donation discovery, default redaction, preview, exclusions, editing, schema validation, compression, and authenticated AES-256-GCM encryption happen on localhost. Compression is applied before encryption so substantial reviewed transcripts can be transmitted without weakening confidentiality. Each donation receives a fresh content key, wrapped with a rotation-versioned RSA-OAEP public key. The private key is absent from the npm package, Worker, D1, and R2.
8
+
9
+ The receiving Worker accepts only encrypted protocol-2 envelopes. A private R2 bucket stores ciphertext. A separate D1 database stores pseudonymous consent, size, count, encryption-key, and object-location metadata—never transcript text. No automatic retention policy is currently configured. A locally retained deletion receipt lets the donor delete both records.
10
+
11
+ ## Maintainer operations
12
+
13
+ The research private key is deliberately outside the repository at `~/.config/behavior-wrapped/keys/research-donation-rsa-2026-08.pem`. On the maintainer Mac, its passphrase is held in Keychain under `behavior-wrapped-research-key-2026-08`. Back up the key and passphrase through separate secure channels before accepting real donations.
14
+
15
+ After downloading an encrypted R2 object, decrypt it into a new private file:
16
+
17
+ ```bash
18
+ npm run research:decrypt -- encrypted-envelope.json private-donation.json
19
+ ```
20
+
21
+ Never upload decrypted output to R2 or commit it. Research transcript ciphertext uses the private `behavior-wrapped-research-donations` R2 bucket. Consent and lifecycle metadata use the separate `behavior-wrapped-research-metadata` D1 database initialized by `migrations/research/0001_encrypted_donations.sql`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "behavior-wrapped",
3
- "version": "0.8.12",
3
+ "version": "0.8.14",
4
4
  "description": "A private, local-first Wrapped report for Claude Code, Cowork, and Codex behavior.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -28,6 +28,7 @@
28
28
  ],
29
29
  "files": [
30
30
  "dist/",
31
+ "docs/",
31
32
  "server/",
32
33
  "scripts/",
33
34
  "fixtures/",
@@ -1,10 +1,11 @@
1
- import { MAX_DONATION_BYTES } from "./research-donation-schema.mjs";
2
-
3
1
  export const DONATION_ENVELOPE_FORMAT = "behavior-wrapped-encrypted-donation-v1";
4
2
  export const DONATION_ENCRYPTION_ALGORITHM = "RSA-OAEP-256+A256GCM";
5
3
  export const DONATION_KEY_ID = "research-donation-rsa-2026-08";
6
4
  export const DONATION_CONSENT_VERSION = 2;
7
- export const MAX_ENCRYPTED_DONATION_BYTES = 2_500_000;
5
+ export const DONATION_CONTENT_ENCODING = "gzip";
6
+ export const MAX_COMPRESSED_DONATION_BYTES = 8_000_000;
7
+ export const MAX_ENCRYPTED_DONATION_BYTES = Math.ceil(MAX_COMPRESSED_DONATION_BYTES / 3) * 4 + 10_000;
8
+ const MAX_LEGACY_DONATION_BYTES = 1_800_000;
8
9
 
9
10
  const base64url = /^[A-Za-z0-9_-]+$/;
10
11
  const timestamp = /^\d{4}-\d{2}-\d{2}T/;
@@ -34,13 +35,18 @@ export function sanitizeEncryptedDonationEnvelope(value) {
34
35
  if (typeof value.encryption.wrappedKey !== "string" || value.encryption.wrappedKey.length < 480 || value.encryption.wrappedKey.length > 700 || !base64url.test(value.encryption.wrappedKey)) return null;
35
36
  if (typeof value.encryption.iv !== "string" || value.encryption.iv.length !== 16 || !base64url.test(value.encryption.iv)) return null;
36
37
  if (typeof value.encryption.authTag !== "string" || value.encryption.authTag.length !== 22 || !base64url.test(value.encryption.authTag)) return null;
37
- if (typeof value.ciphertext !== "string" || !value.ciphertext.length || value.ciphertext.length > Math.ceil(MAX_DONATION_BYTES / 3) * 4 || !base64url.test(value.ciphertext)) return null;
38
- if (!exactKeys(value.metadata, ["automatedDetections", "consentVersion", "consentedAt", "createdAt", "messages", "redactionMode", "reportId", "sessions", "unredactedData"])) return null;
38
+ if (typeof value.ciphertext !== "string" || !value.ciphertext.length || !base64url.test(value.ciphertext)) return null;
39
+ const baseMetadataKeys = ["automatedDetections", "consentVersion", "consentedAt", "createdAt", "messages", "redactionMode", "reportId", "sessions", "unredactedData"];
40
+ const compressed = exactKeys(value.metadata, [...baseMetadataKeys, "contentEncoding"]);
41
+ if (!compressed && !exactKeys(value.metadata, baseMetadataKeys)) return null;
39
42
  const metadata = value.metadata;
43
+ if (compressed && metadata.contentEncoding !== DONATION_CONTENT_ENCODING) return null;
40
44
  if (!/^[A-Za-z0-9_-]{8,32}$/.test(metadata.reportId || "")) return null;
41
45
  if (!new Set(["standard", "custom", "unredacted"]).has(metadata.redactionMode)) return null;
42
46
  if (!timestamp.test(metadata.createdAt || "") || !timestamp.test(metadata.consentedAt || "")) return null;
43
47
  if (!new Set([1, DONATION_CONSENT_VERSION]).has(metadata.consentVersion) || typeof metadata.unredactedData !== "boolean" || metadata.unredactedData !== (metadata.redactionMode === "unredacted")) return null;
44
48
  if (!boundedInteger(metadata.automatedDetections, 1_000_000) || !boundedInteger(metadata.sessions, 250) || metadata.sessions < 1 || !boundedInteger(metadata.messages, 50_000) || metadata.messages < 1) return null;
49
+ const maximumCiphertextBytes = compressed ? MAX_COMPRESSED_DONATION_BYTES : MAX_LEGACY_DONATION_BYTES;
50
+ if (value.ciphertext.length > Math.ceil(maximumCiphertextBytes / 3) * 4) return null;
45
51
  return value;
46
52
  }
@@ -7,6 +7,7 @@ import { discoverAllSessionsAsync, readRecordsAsync, defaultDateRange, DEFAULT_W
7
7
  import { makeDonationPreview } from "./analysis.mjs";
8
8
  import { deleteDonationReceipt, getOrCreateClientId, loadDonationReceipt, loadReport, saveDonationReceipt } from "./store.mjs";
9
9
  import { deleteResearchDonation, RESEARCH_DONATION_URL, submitResearchDonation } from "./research-donation.mjs";
10
+ import { MAX_DONATION_BYTES } from "./research-donation-schema.mjs";
10
11
  import { APP_VERSION, LOCAL_DONATION_PROTOCOL } from "./runtime-version.mjs";
11
12
  import { makeWorkaroundEvidencePreview } from "./workaround-evidence.mjs";
12
13
  import { makeInteractionEvidencePreview } from "./interaction-evidence.mjs";
@@ -154,7 +155,7 @@ const server = http.createServer(async (request, response) => {
154
155
  return json(response, 200, makeDonationPreview(records, labels, { disabledRedactions, disabledMatches, unredacted }));
155
156
  }
156
157
  if (request.method === "POST" && url.pathname === "/api/research-donations") {
157
- const body = await readBody(request, 4_200_000);
158
+ const body = await readBody(request, MAX_DONATION_BYTES + 1_000_000);
158
159
  const report = loadReport(body?.donation?.reportId);
159
160
  if (!report) return json(response, 404, { error: "Saved report not found" });
160
161
  if (demo) return json(response, 201, { accepted: true, donation_id: "demo-not-transmitted", demo: true });
@@ -1,6 +1,7 @@
1
1
  import crypto from "node:crypto";
2
- import { DONATION_CONSENT_VERSION, DONATION_ENCRYPTION_ALGORITHM, DONATION_ENVELOPE_FORMAT, DONATION_KEY_ID, encryptedDonationAAD, sanitizeEncryptedDonationEnvelope } from "./encrypted-donation-schema.mjs";
3
- import { sanitizeResearchDonation } from "./research-donation-schema.mjs";
2
+ import { gunzipSync, gzipSync } from "node:zlib";
3
+ import { DONATION_CONSENT_VERSION, DONATION_CONTENT_ENCODING, DONATION_ENCRYPTION_ALGORITHM, DONATION_ENVELOPE_FORMAT, DONATION_KEY_ID, MAX_COMPRESSED_DONATION_BYTES, encryptedDonationAAD, sanitizeEncryptedDonationEnvelope } from "./encrypted-donation-schema.mjs";
4
+ import { MAX_DONATION_BYTES, researchDonationByteLength, sanitizeResearchDonation } from "./research-donation-schema.mjs";
4
5
 
5
6
  export const RESEARCH_DONATION_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
6
7
  MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEA0RaXFQBixAmtwKRz2I7Y
@@ -18,10 +19,14 @@ function base64url(value) {
18
19
  return Buffer.from(value).toString("base64url");
19
20
  }
20
21
 
21
- export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUBLIC_KEY) {
22
+ export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUBLIC_KEY, { compress = true } = {}) {
23
+ const donationBytes = researchDonationByteLength(value);
24
+ if (donationBytes !== null && donationBytes > MAX_DONATION_BYTES) throw new Error("The reviewed donation is larger than 20 MB. Choose Advanced mode and select fewer sessions.");
22
25
  const donation = sanitizeResearchDonation(value);
23
26
  if (!donation) throw new Error("The reviewed donation does not match the research schema.");
24
27
  const plaintext = Buffer.from(JSON.stringify(donation));
28
+ const encryptedPlaintext = compress ? gzipSync(plaintext) : plaintext;
29
+ if (compress && encryptedPlaintext.byteLength > MAX_COMPRESSED_DONATION_BYTES) throw new Error("The reviewed donation is still too large after compression. Choose Advanced mode and select fewer sessions.");
25
30
  const contentKey = crypto.randomBytes(32);
26
31
  const iv = crypto.randomBytes(12);
27
32
  const envelope = {
@@ -37,11 +42,12 @@ export function encryptResearchDonation(value, publicKey = RESEARCH_DONATION_PUB
37
42
  automatedDetections: donation.redactionSummary.automatedDetections,
38
43
  sessions: donation.redactionSummary.sessions,
39
44
  messages: donation.redactionSummary.messages,
45
+ ...(compress ? { contentEncoding: DONATION_CONTENT_ENCODING } : {}),
40
46
  },
41
47
  };
42
48
  const cipher = crypto.createCipheriv("aes-256-gcm", contentKey, iv);
43
49
  cipher.setAAD(Buffer.from(encryptedDonationAAD(envelope)));
44
- const ciphertext = Buffer.concat([cipher.update(plaintext), cipher.final()]);
50
+ const ciphertext = Buffer.concat([cipher.update(encryptedPlaintext), cipher.final()]);
45
51
  return sanitizeEncryptedDonationEnvelope({
46
52
  ...envelope,
47
53
  encryption: {
@@ -61,7 +67,10 @@ export function decryptResearchDonation(value, privateKey, passphrase) {
61
67
  const decipher = crypto.createDecipheriv("aes-256-gcm", contentKey, Buffer.from(envelope.encryption.iv, "base64url"));
62
68
  decipher.setAAD(Buffer.from(encryptedDonationAAD(envelope)));
63
69
  decipher.setAuthTag(Buffer.from(envelope.encryption.authTag, "base64url"));
64
- const plaintext = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]);
70
+ const decrypted = Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, "base64url")), decipher.final()]);
71
+ const plaintext = envelope.metadata.contentEncoding === DONATION_CONTENT_ENCODING
72
+ ? gunzipSync(decrypted, { maxOutputLength: MAX_DONATION_BYTES + 1 })
73
+ : decrypted;
65
74
  const donation = sanitizeResearchDonation(JSON.parse(plaintext.toString("utf8")));
66
75
  if (!donation) throw new Error("The decrypted donation is invalid.");
67
76
  return donation;
@@ -1,4 +1,4 @@
1
- const MAX_DONATION_BYTES = 1_800_000;
1
+ const MAX_DONATION_BYTES = 20_000_000;
2
2
  const MAX_SESSIONS = 250;
3
3
  const MAX_MESSAGES = 50_000;
4
4
  const MAX_MESSAGE_LENGTH = 20_000;
@@ -7,7 +7,7 @@ function safeText(value, maximum) {
7
7
  return typeof value === "string" ? value.normalize("NFKC").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "").slice(0, maximum) : "";
8
8
  }
9
9
 
10
- export function sanitizeResearchDonation(value) {
10
+ function normalizeResearchDonation(value) {
11
11
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
12
12
  if (value.consent?.researchDonation !== true) return null;
13
13
  if (!/^[A-Za-z0-9_-]{8,32}$/.test(value.reportId || "")) return null;
@@ -49,7 +49,17 @@ export function sanitizeResearchDonation(value) {
49
49
  consentedAt: /^\d{4}-\d{2}-\d{2}T/.test(value.consent.consentedAt || "") ? value.consent.consentedAt : new Date().toISOString(),
50
50
  },
51
51
  };
52
- return new TextEncoder().encode(JSON.stringify(donation)).byteLength <= MAX_DONATION_BYTES ? donation : null;
52
+ return donation;
53
+ }
54
+
55
+ export function researchDonationByteLength(value) {
56
+ const donation = normalizeResearchDonation(value);
57
+ return donation ? new TextEncoder().encode(JSON.stringify(donation)).byteLength : null;
58
+ }
59
+
60
+ export function sanitizeResearchDonation(value) {
61
+ const donation = normalizeResearchDonation(value);
62
+ return donation && new TextEncoder().encode(JSON.stringify(donation)).byteLength <= MAX_DONATION_BYTES ? donation : null;
53
63
  }
54
64
 
55
65
  export { MAX_DONATION_BYTES };