Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 2x 1x 2x 2x 2x 2x 1x 4x 4x 4x 4x 4x 1x 3x 3x 1x 2x 1x 1x 1x 2x 1x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | // Admin ops for Restrict Direct Contact (spec: restrict_direct_contact).
//
// Enforcement core: per-pro activate/rollback, cohort creation, prerequisite
// gate checks, and gate-blocked cohort activation. Mounted under
// /api/admin/restriction — the parent admin router already applies
// contextMiddleware + requirePlatformAdmin. The time/vendor-driven
// orchestration (30-day WhatsApp notices, observation-window cron, churn
// detection) is out of scope; ops drive these endpoints manually.
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { z } from "zod";
import { NotFoundError, ValidationError } from "../../lib/errors";
import { handleError, success } from "../../lib/response";
import type { ContextVariables } from "../../middleware";
type Env = { Bindings: CloudflareBindings; Variables: ContextVariables };
const app = new Hono<Env>();
// Prerequisite gates (spec P0). responseRate is a fraction (0.6 = 60%).
const GATE_MIN_RESPONSE_RATE = 0.6;
const GATE_MIN_COMPARISONS = 50;
// NOTE: cohort routes are registered BEFORE the `/:proId` routes — Hono matches
// in registration order and `/:proId` would otherwise swallow `/cohorts`.
// POST /api/admin/restriction/cohorts — create a rollout cohort
const createCohortSchema = z.object({
cohortNumber: z.number().int().positive(),
proIds: z.array(z.string().min(1)).min(1).max(500),
});
app.post("/cohorts", zValidator("json", createCohortSchema), async (c) => {
try {
const dal = c.get("dal");
const { cohortNumber, proIds } = c.req.valid("json");
const cohort = await dal.restrictionCohorts.create({
id: crypto.randomUUID(),
cohortNumber,
proIds,
status: "pending",
});
return success(c, cohort, 201);
} catch (err) {
return handleError(c, err);
}
});
// GET /api/admin/restriction/cohorts — list cohorts
app.get("/cohorts", async (c) => {
try {
const dal = c.get("dal");
return success(c, await dal.restrictionCohorts.list());
} catch (err) {
return handleError(c, err);
}
});
// POST /api/admin/restriction/cohorts/:id/check-gates — run a prerequisite
// gate check. Measured inputs are supplied by ops where the platform cannot
// compute them yet (response rate, comparisons); `logLive` is computed — the
// Communication History Log ships with this codebase and writes on every
// inquiry, so it is verified by reading the table.
const gateCheckSchema = z.object({
responseRate: z.number().min(0).max(1).optional(),
comparisonsDone: z.number().int().min(0).optional(),
legalSignoff: z.boolean().optional(),
});
app.post(
"/cohorts/:id/check-gates",
zValidator("json", gateCheckSchema),
async (c) => {
try {
const dal = c.get("dal");
const cohortId = c.req.param("id");
const cohort = await dal.restrictionCohorts.get(cohortId);
Iif (!cohort) {
throw new NotFoundError("Cohort", cohortId);
}
const { responseRate, comparisonsDone, legalSignoff } =
c.req.valid("json");
// Log is "live" when the table is reachable and logging works.
const logLive = await dal.communicationLogs
.listAll(1)
.then(() => true)
.catch(() => false);
const failures: string[] = [];
if ((responseRate ?? 0) < GATE_MIN_RESPONSE_RATE) {
failures.push(
`response_rate ${responseRate ?? 0} < ${GATE_MIN_RESPONSE_RATE}`,
);
}
if ((comparisonsDone ?? 0) < GATE_MIN_COMPARISONS) {
failures.push(
`comparisons_done ${comparisonsDone ?? 0} < ${GATE_MIN_COMPARISONS}`,
);
}
Iif (!logLive) failures.push("communication_logs not live");
if (!legalSignoff) failures.push("legal_signoff missing");
const check = await dal.prerequisiteGateChecks.create({
cohortId,
responseRate: responseRate ?? null,
comparisonsDone: comparisonsDone ?? null,
logLive,
legalSignoff: legalSignoff ?? false,
allGatesMet: failures.length === 0,
blockedBy: failures.length > 0 ? failures.join("; ") : null,
});
return success(c, check, 201);
} catch (err) {
return handleError(c, err);
}
},
);
// POST /api/admin/restriction/cohorts/:id/activate — activate restriction for
// every pro in the cohort. BLOCKED unless the latest gate check passed all
// gates (spec: "system blocks activation and displays which gates are unmet").
// Gates are re-checked per cohort — each cohort needs its own passing check.
app.post("/cohorts/:id/activate", async (c) => {
try {
const dal = c.get("dal");
const cohortId = c.req.param("id");
const cohort = await dal.restrictionCohorts.get(cohortId);
if (!cohort) {
throw new NotFoundError("Cohort", cohortId);
}
const latestCheck =
await dal.prerequisiteGateChecks.latestForCohort(cohortId);
if (!latestCheck) {
throw new ValidationError(
"Cohort activation blocked: no prerequisite gate check has been run. Run check-gates first.",
);
}
if (!latestCheck.allGatesMet) {
throw new ValidationError(
`Cohort activation blocked by unmet gates: ${latestCheck.blockedBy ?? "unknown"}`,
);
}
const now = new Date();
for (const proId of cohort.proIds) {
await dal.proRestrictionStatus.setActive(proId, true, { cohortId });
}
const updated = await dal.restrictionCohorts.update(cohortId, {
status: "active",
activatedAt: now,
});
return success(c, updated);
} catch (err) {
return handleError(c, err);
}
});
// POST /api/admin/restriction/cohorts/:id/rollback — roll a cohort back
const rollbackSchema = z.object({ reason: z.string().max(500).optional() });
app.post(
"/cohorts/:id/rollback",
zValidator("json", rollbackSchema),
async (c) => {
try {
const dal = c.get("dal");
const cohortId = c.req.param("id");
const cohort = await dal.restrictionCohorts.get(cohortId);
Iif (!cohort) {
throw new NotFoundError("Cohort", cohortId);
}
const { reason } = c.req.valid("json");
for (const proId of cohort.proIds) {
await dal.proRestrictionStatus.setActive(proId, false, { cohortId });
}
const updated = await dal.restrictionCohorts.update(cohortId, {
status: "rolled_back",
rollbackAt: new Date(),
rollbackReason: reason ?? null,
});
return success(c, updated);
} catch (err) {
return handleError(c, err);
}
},
);
// GET /api/admin/restriction — list pros with restriction currently active
app.get("/", async (c) => {
try {
const dal = c.get("dal");
const rows = await dal.proRestrictionStatus.listActive();
return success(c, rows);
} catch (err) {
return handleError(c, err);
}
});
// GET /api/admin/restriction/:proId — a single pro's restriction status
app.get("/:proId", async (c) => {
try {
const dal = c.get("dal");
const proId = c.req.param("proId");
const status = await dal.proRestrictionStatus.get(proId);
return success(c, status ?? { proId, restrictionActive: false });
} catch (err) {
return handleError(c, err);
}
});
// POST /api/admin/restriction/:proId/activate — turn restriction ON for one pro
// (early opt-in / ops override path; cohort activation is the gated path).
app.post("/:proId/activate", async (c) => {
try {
const dal = c.get("dal");
const proId = c.req.param("proId");
const pro = await dal.pros.findById(proId);
if (!pro) {
throw new NotFoundError("Pro", proId);
}
const status = await dal.proRestrictionStatus.setActive(proId, true);
return success(c, status);
} catch (err) {
return handleError(c, err);
}
});
// POST /api/admin/restriction/:proId/rollback — turn restriction OFF for a pro
app.post("/:proId/rollback", async (c) => {
try {
const dal = c.get("dal");
const proId = c.req.param("proId");
const pro = await dal.pros.findById(proId);
Iif (!pro) {
throw new NotFoundError("Pro", proId);
}
const status = await dal.proRestrictionStatus.setActive(proId, false);
return success(c, status);
} catch (err) {
return handleError(c, err);
}
});
export default app;
|