cyborg-hunter 0.7.5 → 0.9.0

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 (46) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/CITATION.cff +2 -2
  3. package/README.md +22 -7
  4. package/dist/cyborg-hunter-replay.js +3 -3
  5. package/dist/cyborg-hunter.esm.js +5 -2
  6. package/dist/cyborg-hunter.min.js +3 -3
  7. package/dist/extension-cyborg-hunter.js +1 -1
  8. package/package.json +10 -2
  9. package/src/cli/analyzers/score-weights.js +145 -0
  10. package/src/cli/analyzers/triage.js +55 -39
  11. package/src/cli/config.js +15 -0
  12. package/src/cli/ingest.js +311 -57
  13. package/src/cli/renderers/html-index-core.js +88 -22
  14. package/src/cli/renderers/html-index.js +7 -5
  15. package/src/cli/renderers/replay-assets.js +61 -7
  16. package/src/cli/renderers/replay-client-source.js +102 -0
  17. package/src/cli/renderers/replay-viewer.client.js +1750 -595
  18. package/src/cli/renderers/score-weights.js +16 -0
  19. package/src/cli/renderers/summary-csv.js +2 -0
  20. package/src/cli/renderers/trajectories-core.js +2 -1
  21. package/src/cli/renderers/triage-md.js +9 -2
  22. package/src/cli/report.js +16 -3
  23. package/src/core/monitor.js +12 -13
  24. package/src/jspsych/extension-cyborg-hunter-replay.js +64 -3
  25. package/src/jspsych/extension-cyborg-hunter.js +1 -1
  26. package/src/replay/capture-dom.js +470 -458
  27. package/src/replay/capture-trace.js +688 -271
  28. package/src/replay/delivery.js +82 -0
  29. package/src/replay/dom-instantiate.js +779 -0
  30. package/src/replay/index.js +88 -5
  31. package/src/replay/initial-state.js +295 -0
  32. package/src/replay/mutations.js +668 -0
  33. package/src/replay/node-registry.js +116 -0
  34. package/src/replay/persistence.js +19 -6
  35. package/src/replay/recorder.js +342 -73
  36. package/src/replay/redaction.js +165 -0
  37. package/src/replay/serializer.js +148 -43
  38. package/src/replay/snapshot.js +409 -0
  39. package/src/replay/span.js +55 -0
  40. package/src/replay/viewer-model.js +293 -102
  41. package/src/shared/constants.js +1 -1
  42. package/src/shared/inline-safe.js +80 -0
  43. package/src/shared/schema-v2-validator.js +595 -0
  44. package/src/shared/schema.js +1 -0
  45. package/src/shared/validation.js +1 -1
  46. package/tools/convert/jspsych-v1-to-v2.mjs +432 -0
@@ -0,0 +1,145 @@
1
+ // src/cli/analyzers/score-weights.js
2
+ // The report score's signal table and its weights (config.scoreWeights).
3
+ //
4
+ // The report score orders participants WITHIN a tier (see triage.js). Each
5
+ // signal below contributes min(count, max) × weight. The default weights
6
+ // reproduce the fixed 0.8.0 score: 5×paste + 5×copy + 3×sidebar + 1×tab-away
7
+ // (tab-aways longer than the participant's threshold). Every other signal
8
+ // defaults to 0 and can be switched on from cyborg-hunter.config.json:
9
+ //
10
+ // "scoreWeights": { "synthetic": 1, "copy": { "weight": 5, "max": 3 } }
11
+ //
12
+ // A user's scoreWeights is merged PER KEY onto the defaults (the config loader
13
+ // merges top-level keys only), so writing one key never zeroes the others.
14
+ // The hard/soft/clean tier does not depend on these weights.
15
+
16
+ import { findClosestKey } from '../../shared/validation.js';
17
+
18
+ // Order matters: the first four are the 0.8.0 terms in their 0.8.0 order, so
19
+ // default output (breakdown, totals) is unchanged. Counts copy the 0.8.0
20
+ // expressions, including the sidebar fallback for pre-count data.
21
+ export const SCORE_SIGNALS = [
22
+ { key: 'paste', weight: 5, count: s => s.totalPasteEvents || 0 },
23
+ { key: 'copy', weight: 5, count: s => s.totalCopyEvents || 0 },
24
+ { key: 'sidebar', weight: 3, count: s => s.sidebarEventCount ?? (s.sidebarDetected ? 1 : 0) },
25
+ { key: 'tabaway', weight: 1, count: s => (s.tabAwayLongCount || 0) + (s.tabAwayMediumCount || 0) },
26
+ { key: 'tabawayLong', weight: 0, count: s => s.tabAwayLongCount || 0 },
27
+ { key: 'tabawayMedium', weight: 0, count: s => s.tabAwayMediumCount || 0 },
28
+ { key: 'flicker', weight: 0, count: s => s.tabAwayFlickerCount || 0 },
29
+ { key: 'drop', weight: 0, count: s => s.totalDropEvents || 0 },
30
+ { key: 'fastTyping', weight: 0, count: s => s.trialsWithFastTyping || 0 },
31
+ { key: 'synthetic', weight: 0, count: s => s.totalSyntheticInsertions || 0 },
32
+ { key: 'foreignInput', weight: 0, count: s => s.totalForeignInputEvents || 0 },
33
+ { key: 'aiExtensions', weight: 0, count: s => (s.aiExtensionsFound || s.extensionsDetected || []).length },
34
+ { key: 'kbShortcuts', weight: 0, count: s => s.keyboardShortcutCount || 0 },
35
+ { key: 'viewportShifts', weight: 0, count: s => s.layoutShiftCount || 0 },
36
+ { key: 'zoom', weight: 0, count: s => s.zoomChangeCount || 0 },
37
+ // Edge exits are computed per trial by edge-exit.js and summed on the
38
+ // triage row; they are not a summary field.
39
+ { key: 'edgeExits', weight: 0, count: (s, edgeExitCount) => edgeExitCount || 0 },
40
+ ];
41
+
42
+ const KEYS = SCORE_SIGNALS.map(s => s.key);
43
+
44
+ export const DEFAULT_SCORE_WEIGHTS = Object.fromEntries(SCORE_SIGNALS.map(s => [s.key, s.weight]));
45
+
46
+ const show = v => {
47
+ if (typeof v === 'string') return JSON.stringify(v);
48
+ if (typeof v === 'number' || v == null || typeof v === 'boolean') return String(v);
49
+ try { return JSON.stringify(v); } catch (e) { return typeof v; }
50
+ };
51
+ const isPlainObject = v => v !== null && typeof v === 'object' && !Array.isArray(v);
52
+ const validWeight = w => typeof w === 'number' && Number.isFinite(w) && w >= 0;
53
+ const validMax = m => Number.isInteger(m) && m >= 0;
54
+
55
+ // Returns { weights: { key: { weight, max|null } }, isDefault, warnings }.
56
+ // Invalid entries warn and keep that key's default; nothing here throws.
57
+ export function resolveScoreWeights(user) {
58
+ const weights = Object.fromEntries(SCORE_SIGNALS.map(s => [s.key, { weight: s.weight, max: null }]));
59
+ const warnings = [];
60
+
61
+ if (user != null && !isPlainObject(user)) {
62
+ warnings.push(`scoreWeights must be an object of signal weights (got ${show(user)}); using the default weights.`);
63
+ } else if (user != null) {
64
+ for (const [key, value] of Object.entries(user)) {
65
+ if (key.toLowerCase() === 'devtools') {
66
+ warnings.push('scoreWeights.devTools is ignored: the DevTools count is always 0. DevTools hotkeys are counted under "kbShortcuts".');
67
+ continue;
68
+ }
69
+ if (!KEYS.includes(key)) {
70
+ const guess = findClosestKey(key, KEYS);
71
+ warnings.push(`scoreWeights: unknown signal "${key}"${guess ? ` (did you mean "${guess}"?)` : ''}; it is ignored. Keys are case-sensitive.`);
72
+ continue;
73
+ }
74
+ const slot = weights[key];
75
+ const def = DEFAULT_SCORE_WEIGHTS[key];
76
+ const obj = isPlainObject(value) ? value : null;
77
+ const hasWeight = obj ? obj.weight !== undefined : true;
78
+ // `max: null` means "no cap" — the shape score-weights.json writes — so a
79
+ // copy of that file used as scoreWeights resolves without warnings.
80
+ const hasMax = !!obj && obj.max != null;
81
+ const w = obj ? obj.weight : value;
82
+
83
+ if (obj) {
84
+ const extra = Object.keys(obj).filter(k => k !== 'weight' && k !== 'max');
85
+ if (extra.length) warnings.push(`scoreWeights.${key}: unknown field${extra.length > 1 ? 's' : ''} ${extra.map(k => `"${k}"`).join(', ')} ignored; only "weight" and "max" are read.`);
86
+ }
87
+ if (obj && !hasWeight) {
88
+ if (hasMax) warnings.push(`scoreWeights.${key} has a max but no weight; the default weight ${def} applies.`);
89
+ else if (!('max' in obj)) warnings.push(`scoreWeights.${key}: the weight must be a finite number ≥ 0 (got ${show(obj)}); using the default ${def}.`);
90
+ } else if (!validWeight(w)) {
91
+ warnings.push(`scoreWeights.${key}: the weight must be a finite number ≥ 0 (got ${show(obj ? w : value)}); using the default ${def}.`);
92
+ } else {
93
+ slot.weight = w;
94
+ }
95
+
96
+ if (hasMax) {
97
+ if (validMax(obj.max)) slot.max = obj.max;
98
+ else warnings.push(`scoreWeights.${key}.max must be a whole number ≥ 0 (got ${show(obj.max)}); no cap is applied.`);
99
+ }
100
+ }
101
+ }
102
+
103
+ if (weights.tabaway.weight !== 0 && (weights.tabawayLong.weight !== 0 || weights.tabawayMedium.weight !== 0)) {
104
+ warnings.push('scoreWeights: "tabaway" already counts long + medium tab-aways, so weighting "tabawayLong" or "tabawayMedium" as well double counts them. Set "tabaway": 0 to use the split keys.');
105
+ }
106
+ if (KEYS.every(k => weights[k].weight === 0)) {
107
+ warnings.push('scoreWeights: every weight is 0, so every report score will be 0.');
108
+ }
109
+
110
+ const isDefault = KEYS.every(k => !differsFromDefault(weights, k));
111
+ return { weights, isDefault, warnings };
112
+ }
113
+
114
+ // A cap on a zero-weight signal changes nothing, so it does not make the
115
+ // weights custom.
116
+ function differsFromDefault(weights, k) {
117
+ const { weight, max } = weights[k];
118
+ return weight !== DEFAULT_SCORE_WEIGHTS[k] || (max != null && weight !== 0);
119
+ }
120
+
121
+ export const DEFAULT_RESOLVED_WEIGHTS = resolveScoreWeights(null).weights;
122
+
123
+ // "5×copy + 3×sidebar + 1×synthetic (max 3)": the weighted signals, in table
124
+ // order, for prose that states the formula (triage.md, the console summary).
125
+ // Callers keep their own verbatim wording for the default weights.
126
+ export function formulaText(weights, times = '×') {
127
+ return KEYS.filter(k => weights[k].weight !== 0)
128
+ .map(k => `${weights[k].weight}${times}${k}${weights[k].max != null ? ` (max ${weights[k].max})` : ''}`)
129
+ .join(' + ') || '0';
130
+ }
131
+
132
+ // "copy 5 max 3, synthetic 1": only the keys that differ from the defaults,
133
+ // in table order. Empty string when nothing differs.
134
+ export function customWeightsText(weights) {
135
+ return KEYS.filter(k => differsFromDefault(weights, k))
136
+ .map(k => `${k} ${weights[k].weight}${weights[k].max != null ? ` max ${weights[k].max}` : ''}`)
137
+ .join(', ');
138
+ }
139
+
140
+ // The one formatter for displayed scores. Integers (every score under integer
141
+ // weights, i.e. all default output) pass through unchanged, type included;
142
+ // fractional scores print to one decimal; non-numbers pass through.
143
+ export function formatScore(n) {
144
+ return typeof n === 'number' && !Number.isInteger(n) ? n.toFixed(1) : n;
145
+ }
@@ -5,24 +5,36 @@
5
5
  //
6
6
  // Ranking has two parts (see rankTriage + decomposeScore below):
7
7
  // - tier: hard-triggered → soft-flagged → clean (primary sort key)
8
- // - score: 5×paste + 5×copy + 3×sidebar-open + 1×tab-away (within a tier),
9
- // where a "tab-away" is one longer than the participant's tab-away
10
- // threshold (3s by default, 5s for the strict preset)
11
- // Other signals (AI extensions, keyboard shortcuts, layout/zoom, edge-exits,
12
- // synthetic insertions, foreign inputs, honeypot disclosure) are surfaced in the
13
- // reason and detail panes but do NOT contribute to the score.
8
+ // - score: by default 5×paste + 5×copy + 3×sidebar-open + 1×tab-away (within
9
+ // a tier), where a "tab-away" is one longer than the participant's
10
+ // tab-away threshold (3s by default, 5s for the strict preset).
11
+ // config.scoreWeights can reweight these and switch on any other
12
+ // signal (see score-weights.js); the tier never depends on it.
13
+ // Signals with weight 0 (by default: AI extensions, keyboard shortcuts,
14
+ // layout/zoom, edge-exits, synthetic insertions, foreign inputs) and honeypot
15
+ // disclosure are surfaced in the reason and detail panes but do not contribute
16
+ // to the score.
17
+
18
+ import { SCORE_SIGNALS, DEFAULT_RESOLVED_WEIGHTS, resolveScoreWeights } from './score-weights.js';
14
19
 
15
20
  export function rankTriage(summaries, edgeExits, config) {
21
+ // Resolved once per run. Warnings are not printed here: config.js
22
+ // (cliConfigWarnings) is the single place they reach the console.
23
+ const { weights } = resolveScoreWeights(config?.scoreWeights);
16
24
  const triageList = summaries.map((s, i) => {
17
25
  const ee = edgeExits[i];
18
26
  const totalEdgeExits = ee.edgeExits.reduce((sum, t) => sum + t.edgeExitCount, 0);
19
27
 
20
- const score = computeTriageScore(s, totalEdgeExits);
28
+ const terms = decomposeScore(s, totalEdgeExits, s.hardTriggered, weights);
29
+ const score = sumTerms(terms);
21
30
  const reason = generateTriageReason(s, totalEdgeExits);
22
31
 
23
32
  return {
24
33
  participantId: s.participantId,
25
34
  score,
35
+ // The applied [signal, contribution] pairs; renderers draw these so the
36
+ // breakdown always matches the score that was ranked on.
37
+ terms,
26
38
  reason,
27
39
  hardTriggered: s.hardTriggered,
28
40
  // Threshold precedence: an explicit analyst-side CLI override
@@ -40,8 +52,8 @@ export function rankTriage(summaries, edgeExits, config) {
40
52
  // Sort tier-first (hard, then soft, then clean), and by score descending
41
53
  // within a tier. A hard-triggered participant (paste/drop over its count
42
54
  // threshold) is categorically more actionable than a high soft-signal count,
43
- // so they must lead the "start here" triage.md even though the four-term
44
- // score (paste/copy/sidebar/tab-away) no longer includes a hard-trigger term.
55
+ // so they must lead the "start here" triage.md even though the score (by
56
+ // default paste/copy/sidebar/tab-away) includes no hard-trigger term.
45
57
  // This matches the HTML index's "Tier" sort (hard:0, soft:1, clean:2; score
46
58
  // desc within tier).
47
59
  const tierRank = (t) => (t.hardTriggered ? 0 : t.softFlagged ? 1 : 2);
@@ -54,47 +66,51 @@ export function rankTriage(summaries, edgeExits, config) {
54
66
  }
55
67
 
56
68
  // Decomposes the composite triage score into [label, contribution] pairs.
57
- // Used by both computeTriageScore (sums them) and the HTML renderer (displays them
69
+ // Used by both rankTriage (sums them, and keeps them on the row as `terms`) and the
70
+ // HTML renderer (displays them
58
71
  // with bars). Keeping the formula here means the score breakdown in the report can
59
72
  // never silently disagree with the ranked score it explains.
60
73
  //
61
- // Scoring policy (fixed 2026-06-01): only four signals contribute to the
62
- // score —
74
+ // Each signal in SCORE_SIGNALS (score-weights.js) contributes
75
+ // min(count, max) × weight; signals whose weight is 0 are left out of the list
76
+ // (a weighted signal with a count of 0 stays in, as `[key, 0]`). The DEFAULT
77
+ // weights are the 2026-06-01 policy, so without config.scoreWeights the result
78
+ // is the 0.8.0 four-term list:
63
79
  // 5 × paste events
64
80
  // 5 × copy events
65
81
  // 3 × sidebar events (open cycles)
66
82
  // 1 × tab-aways longer than the participant's tab-away threshold (3s default,
67
83
  // 5s strict) — excludes at-or-below-cutoff flickers, which are mostly noise
68
84
  // from brief URL-bar focus / window edge clicks
69
- // Hard-trigger, AI extensions, layout shifts, zoom changes, keyboard shortcuts,
70
- // edge exits, synthetic insertions, and foreign inputs no longer affect the
71
- // *score*. They are NOT hidden from review: every event list still renders in
72
- // the per-participant detail panes, and hard-triggered participants are still
73
- // surfaced via the hard/soft/clean tier (which is independent of this score).
74
- // edgeExitCount and hardTriggered remain in the signature for the renderer's
75
- // call site but are unused under this policy.
76
- export function decomposeScore(summary, edgeExitCount, hardTriggered) {
77
- const sidebarCount = summary.sidebarEventCount ?? (summary.sidebarDetected ? 1 : 0);
78
- const tabAwayMeaningful =
79
- (summary.tabAwayLongCount || 0) + (summary.tabAwayMediumCount || 0);
80
- return [
81
- ['paste', (summary.totalPasteEvents || 0) * 5],
82
- ['copy', (summary.totalCopyEvents || 0) * 5],
83
- ['sidebar', sidebarCount * 3],
84
- ['tabaway', tabAwayMeaningful],
85
- ];
85
+ // Every other signal (AI extensions, layout shifts, zoom, keyboard shortcuts,
86
+ // edge exits, synthetic insertions, foreign inputs, …) defaults to 0 and can be
87
+ // weighted through config.scoreWeights. Nothing here affects the hard/soft/clean
88
+ // tier, and unweighted signals still render in the per-participant detail panes.
89
+ // hardTriggered stays in the signature for the renderer's call site; it is unused.
90
+ export function decomposeScore(summary, edgeExitCount, hardTriggered, weights = DEFAULT_RESOLVED_WEIGHTS) {
91
+ const terms = [];
92
+ for (const sig of SCORE_SIGNALS) {
93
+ const { weight, max } = weights[sig.key];
94
+ if (weight === 0) continue;
95
+ const count = sig.count(summary, edgeExitCount);
96
+ terms.push([sig.key, (max == null ? count : Math.min(count, max)) * weight]);
97
+ }
98
+ return terms;
86
99
  }
87
100
 
88
- // computeTriageScore stays an internal helper. It accumulates the decomposition
89
- // in the original iteration order, starting from the soft base directly (NOT
90
- // from a defensive 0) — same `let score = base; score += hardTerm; score +=
91
- // edgeTerm; …` behaviour as the pre-refactor inline version. For malformed data
92
- // where `base` is a non-number (e.g. an object), every subsequent `+=` becomes
93
- // a string concat — exactly as it did before this refactor.
94
- function computeTriageScore(summary, edgeExitCount) {
95
- const terms = decomposeScore(summary, edgeExitCount, summary.hardTriggered);
96
- let score = terms[0][1];
101
+ // sumTerms stays an internal helper. It sums the decomposition in order,
102
+ // starting from the first term rather than a defensive 0, as the pre-refactor
103
+ // inline version did. With every weight set to 0 the list is empty and the
104
+ // score is 0. (Since 0.9.0 every term is multiplied by its weight, so malformed
105
+ // string counts are coerced to numbers rather than string-concatenated as they
106
+ // could be for the unmultiplied 0.8.0 tab-away term.)
107
+ function sumTerms(terms) {
108
+ let score = terms.length ? terms[0][1] : 0;
97
109
  for (let i = 1; i < terms.length; i++) score += terms[i][1];
110
+ // Deliberately unrounded: ordering uses the exact sum, so no configured
111
+ // contribution, however small, can be erased. Binary noise from fractional
112
+ // weights (0.1 × 3 = 0.30000000000000004) is removed only where scores are
113
+ // displayed, by formatScore (score-weights.js).
98
114
  return score;
99
115
  }
100
116
 
@@ -141,7 +157,7 @@ export function generateTriageReason(summary, edgeExitCount = 0) {
141
157
  if (summary.totalSyntheticInsertions > 0) parts.push(`${summary.totalSyntheticInsertions} synthetic insertions`);
142
158
  if (summary.totalForeignInputEvents > 0) parts.push(`${summary.totalForeignInputEvents} foreign inputs`);
143
159
  // Guard-honeypot self-disclosure — a strong corroborating signal, surfaced in
144
- // the reason though it does not feed the four-term score.
160
+ // the reason though it does not feed the score (it has no scoreWeights key).
145
161
  if (summary.honeypotAiUse) parts.push('self-reported AI use (honeypot)');
146
162
  if (parts.length === 0) parts.push('clean');
147
163
  return parts.join('; ');
package/src/cli/config.js CHANGED
@@ -10,6 +10,7 @@ import { readFileSync, existsSync } from 'fs';
10
10
  import { resolve, join } from 'path';
11
11
  import { DEFAULT_CLI_CONFIG } from '../shared/schema.js';
12
12
  import { validateConfig } from '../shared/validation.js';
13
+ import { resolveScoreWeights } from './analyzers/score-weights.js';
13
14
 
14
15
  export function loadConfig(cliArgs) {
15
16
  // Parse CLI flags into a simple key-value object
@@ -67,6 +68,20 @@ export function cliConfigWarnings(config) {
67
68
  `soft-flagged. Set it to a number.`
68
69
  );
69
70
  }
71
+ // The browser library's scoring rules look like they belong here too, but
72
+ // the CLI reads only scoring.softScoreThreshold; the report score's weights
73
+ // live in scoreWeights. Say so rather than ignore them silently.
74
+ const scoring = config?.scoring;
75
+ if (scoring && typeof scoring === 'object' && (scoring.soft != null || scoring.hard != null)) {
76
+ warnings.push(
77
+ 'scoring.soft / scoring.hard configure the browser library, not the report; ' +
78
+ 'the CLI ignores them (only scoring.softScoreThreshold is read). To weight ' +
79
+ 'signals in the report score, use "scoreWeights".'
80
+ );
81
+ }
82
+ // This is the single place scoreWeights warnings reach the console
83
+ // (rankTriage resolves the same weights silently).
84
+ warnings.push(...resolveScoreWeights(config?.scoreWeights).warnings);
70
85
  return warnings;
71
86
  }
72
87