#!/usr/bin/env node
// verify.mjs — the checks behind the stratum "The Parable of the 38 Witnesses"
// (/strata/the-parable-of-38-witnesses/).
//
// The page makes two things operable:
//   (1) a RECORD-CORRECTION of the Kitty Genovese "38 witnesses" story, and
//   (2) a live demonstration that Darley & Latané's 1968 bystander effect runs
//       OPPOSITE to the safety-in-numbers intuition.
//
// This file is the ground truth the in-browser instrument's live numbers are
// checked against. It (a) restates the sourced figures the page shows, and
// (b) RE-DERIVES the one computation the argument turns on — that if witnesses
// helped independently at the lone-witness rate, adding bystanders would make
// help MORE certain, so the measured decline cannot be independence; it is
// diffusion of responsibility.
//
// ---- What is reproduced vs. cited ------------------------------------------
//   [derived]  arithmetic re-computed here (the independence model; slopes).
//   [cited]    reported figures we restate faithfully but did NOT re-run
//              (the 1968 trial percentages/latencies; the meta-analytic and
//              CCTV headline numbers). Every [cited] value names its source.
//
// ---- Sources ----------------------------------------------------------------
//   [DL68]   Darley, J. M., & Latané, B. (1968). "Bystander intervention in
//            emergencies: Diffusion of responsibility." J. Personality & Social
//            Psychology 8(4), 377-383. Table 1 (p. 380) read from the original
//            article PDF. Group-size conditions defined p. 379.
//   [MLC07]  Manning, R., Levine, M., & Collins, A. (2007). "The Kitty Genovese
//            murder and the social psychology of helping: The parable of the 38
//            witnesses." American Psychologist 62(6), 555-562.
//   [NYT64]  Gansberg, M. "37 Who Saw Murder Didn't Call the Police." The New
//            York Times, March 27, 1964 (headline "37"; body text "38").
//   [Fis11]  Fischer, P., et al. (2011). "The bystander-effect: A meta-analytic
//            review..." Psychological Bulletin 137(4), 517-537.
//   [Phi20]  Philpot, R., et al. (2020). "Would I be helped? Cross-national CCTV
//            footage shows that intervention is the norm in public conflicts."
//            American Psychologist 75(1), 66-75.
//
// Run:  node research/bystander/verify.mjs
'use strict';

let pass = 0, fail = 0;
const checks = [];
function ok(name, cond, detail) {
  checks.push({ name, cond: !!cond, detail });
  if (cond) pass++; else fail++;
}
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

// ===========================================================================
// 1.  Darley & Latané (1968), Table 1 — the exact reported figures  [cited]
//     These are the constants the in-browser instrument uses verbatim.
// ===========================================================================
// Each row: b = number of OTHER bystanders the subject believed present.
// groupSize = b + 2 (subject + victim + b others), matching the paper's label.
const DL68 = [
  { b: 0, groupSize: 2, N: 13, pctByEndOfFit: 85, meanTimeSec: 52,  speedScore: 0.87, pctEver: 100 },
  { b: 1, groupSize: 3, N: 26, pctByEndOfFit: 62, meanTimeSec: 93,  speedScore: 0.72, pctEver: 85  }, // pctEver 85 is from Fig.1, not Table 1 — flagged below
  { b: 4, groupSize: 6, N: 13, pctByEndOfFit: 31, meanTimeSec: 166, speedScore: 0.51, pctEver: 62  },
];
// Provenance flag: only the 2- and 6-person "ever responded" figures (100, 62)
// are stated numerically in [DL68] text; the 3-person 85 is read off Figure 1.
const PCT_EVER_STATED_IN_TEXT = { 2: true, 3: false, 6: true };

ok('[cited] DL68 by-end-of-fit rates are 85 / 62 / 31',
   DL68.map(r => r.pctByEndOfFit).join('/') === '85/62/31',
   DL68.map(r => r.pctByEndOfFit).join('/'));
ok('[cited] DL68 mean latencies are 52 / 93 / 166 s (not the mis-copied 96 s for the 3-person)',
   DL68.map(r => r.meanTimeSec).join('/') === '52/93/166',
   DL68.map(r => r.meanTimeSec).join('/'));
ok('[cited] DL68 per-condition N are 13 / 26 / 13 (female subjects, Table 1)',
   DL68.map(r => r.N).join('/') === '13/26/13', DL68.map(r => r.N).join('/'));
ok('[cited] DL68 speed scores are .87 / .72 / .51',
   DL68.map(r => r.speedScore).join('/') === '0.87/0.72/0.51',
   DL68.map(r => r.speedScore).join('/'));
ok('provenance: 3-person "ever responded" (85) is Fig.1-derived, not a stated table value',
   PCT_EVER_STATED_IN_TEXT[3] === false, 'flagged so the page does not over-assert it');

// ===========================================================================
// 2.  The measured effect: helping DECLINES as the crowd grows  [derived]
// ===========================================================================
const rates = DL68.map(r => r.pctByEndOfFit);
const strictlyDecreasing = rates.every((v, i) => i === 0 || v < rates[i - 1]);
ok('measured individual response rate strictly DECLINES with group size (85 > 62 > 31)',
   strictlyDecreasing, rates.join(' > '));

const times = DL68.map(r => r.meanTimeSec);
const latencyRises = times.every((v, i) => i === 0 || v > times[i - 1]);
ok('measured mean latency strictly RISES with group size (52 < 93 < 166 s)',
   latencyRises, times.join(' < '));

// ===========================================================================
// 3.  The independence model — the safety-in-numbers intuition  [derived]
//     If every witness were as ready to help as a LONE witness (base rate a),
//     and acted independently, the chance that AT LEAST ONE of N witnesses
//     helps is 1 - (1-a)^N. This is what intuition assumes a crowd buys you.
// ===========================================================================
const a = DL68[0].pctByEndOfFit / 100;            // lone-witness base rate = 0.85
const someoneHelps = (N) => 1 - Math.pow(1 - a, N); // N = total potential helpers

// Values at the three tested conditions (N = b + 1 people who could help):
const indep = DL68.map(r => someoneHelps(r.b + 1));
ok('independence base rate a = 0.85 (the lone-witness rate)', approx(a, 0.85), String(a));
ok('[derived] independence: chance SOMEONE helps at b=0,1,4 ≈ 0.850 / 0.978 / 1.000',
   approx(indep[0], 0.85, 1e-9) && approx(indep[1], 0.9775, 1e-9) && approx(indep[2], 0.9999240625, 1e-9),
   indep.map(x => x.toFixed(6)).join(' / '));

// The crux: under independence, adding bystanders makes help MORE certain —
// the opposite sign of the measured individual decline.
const indepRises = indep.every((v, i) => i === 0 || v > indep[i - 1]);
ok('[derived] independence prediction RISES with group size (opposite of what was measured)',
   indepRises, indep.map(x => (x * 100).toFixed(2) + '%').join(' < '));
ok('[derived] the sign flip is the effect: d(independence)/dN > 0 while d(measured)/dN < 0',
   indepRises && strictlyDecreasing,
   'intuition says help gets more certain; the data says each witness gets less likely to act');

// The gap the instrument shades, at the largest tested crowd (b=4):
const gapAt4 = indep[2] - DL68[2].pctByEndOfFit / 100;
ok('[derived] at 4 other bystanders the intuition/reality gap is ~0.69 (≈100% vs 31%)',
   approx(gapAt4, 0.6899240625, 1e-9), gapAt4.toFixed(4));

// ===========================================================================
// 4.  The record-correction figures  [cited]
// ===========================================================================
const GENOVESE = {
  date: '1964-03-13', place: 'Kew Gardens, Queens',
  nytHeadlineNumber: 37, nytBodyNumber: 38,       // [NYT64] headline 37, body 38
  nytArticleDate: '1964-03-27', reporter: 'Martin Gansberg',
  attacker: 'Winston Moseley', attackerAge: 29,
  nytAttackCount: 3, correctedAttackCount: 2,      // NYT said 3; corrected history: 2
  neighborWhoCameToHer: 'Sophia Farrar',
  moseleyDied: '2016-03-28',
};
ok('[cited] NYT headline said 37, body said 38 (the 37/38 split is real)',
   GENOVESE.nytHeadlineNumber === 37 && GENOVESE.nytBodyNumber === 38,
   `${GENOVESE.nytHeadlineNumber} / ${GENOVESE.nytBodyNumber}`);
ok('[cited] NYT claimed 3 attacks; corrected historical account is 2',
   GENOVESE.nytAttackCount === 3 && GENOVESE.correctedAttackCount === 2, '3 → 2');
// [MLC07] three claims with "no evidence": (i) 38 witnesses, (ii) witnesses saw
// the murder, (iii) witnesses stayed inactive. And: >=2 contacted police; a
// neighbour (Sophia Farrar) came and held her — she did not die alone.
const MLC07_debunked = ['thirty-eight witnesses', 'witnesses observed the murder', 'witnesses remained inactive'];
ok('[cited] Manning-Levine-Collins 2007 found no evidence for 3 central claims',
   MLC07_debunked.length === 3, MLC07_debunked.join('; '));
ok('[cited] a neighbour (Sophia Farrar) came to Genovese — she did not die alone',
   GENOVESE.neighborWhoCameToHer === 'Sophia Farrar', GENOVESE.neighborWhoCameToHer);

// ===========================================================================
// 5.  The modern nuance — named, not hidden  [cited]
// ===========================================================================
const FISCHER11 = { effectSizes: 105, participantsOver: 7700, g: -0.35, dangerous: 'attenuated' };
ok('[cited] Fischer 2011: 105 effect sizes, >7,700 participants, overall g = -0.35',
   FISCHER11.effectSizes === 105 && FISCHER11.participantsOver === 7700 && approx(FISCHER11.g, -0.35),
   `g=${FISCHER11.g}`);
ok('[cited] Fischer 2011: the effect is ATTENUATED (not reversed) in dangerous emergencies',
   FISCHER11.dangerous === 'attenuated', FISCHER11.dangerous);

const PHILPOT20 = { interventionPct: 90.9, incidents: 219, cities: ['Amsterdam', 'Lancaster', 'Cape Town'], meanInterveners: 3.76 };
ok('[cited] Philpot 2020: at least one bystander intervened in 90.9% of 219 public conflicts',
   approx(PHILPOT20.interventionPct, 90.9) && PHILPOT20.incidents === 219, `${PHILPOT20.interventionPct}% of ${PHILPOT20.incidents}`);
ok('[cited] Philpot 2020: three cities — Amsterdam, Lancaster, Cape Town',
   PHILPOT20.cities.length === 3, PHILPOT20.cities.join(', '));
// The honest individual-vs-aggregate distinction: aggregate help rises with
// crowd size (Philpot), yet the per-individual odds can still fall — so the
// aggregate CCTV finding does not by itself overturn diffusion of responsibility.
ok('nuance recorded: Philpot measures AGGREGATE "someone helps", not per-individual odds',
   true, 'the page states this so the CCTV result is not oversold as a full refutation');

// ===========================================================================
// Report
// ===========================================================================
console.log('\n  The Parable of the 38 Witnesses — verification\n');
for (const c of checks) {
  console.log(`  ${c.cond ? 'PASS' : 'FAIL'}  ${c.name}${c.detail ? '  ·  ' + c.detail : ''}`);
}
console.log(`\n  ${pass}/${pass + fail} checks pass.\n`);
process.exit(fail ? 1 : 0);
