@heyramzi/lint 2.5.0 → 2.6.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.
package/README.md CHANGED
@@ -305,11 +305,62 @@ failure says what to do instead. It reads the staged blob, so it judges what the
305
305
  scripts, the `fallow` reference in `vibekit.json`, no tracked `.fallow/*.bin`), an
306
306
  `.oxlintrc.json` that doesn't extend the shared base, and a `lint` block in `vite.config`.
307
307
  - **Compose:** an `image:` that's `:latest` or untagged, unless the service builds it.
308
+ - **Untracked imports:** a staged code file whose relative or `#alias` import resolves to a file
309
+ that's on disk but not in the commit and not ignored. `@heyramzi/ui` 2.15.0 shipped that way
310
+ without `lib/motion.ts`.
308
311
  - **Fossil names:** an added path named `-old`, `-v2`, `-final` or `copy`, or under `misc/` or
309
312
  `temp/`.
310
313
 
311
314
  No allowlist, no config.
312
315
 
316
+ ### Slop Gate and Jev
317
+
318
+ `heyramzi-slop <file|dir|->` runs the exact patterns, and `--register=<name>` adds the rates of a
319
+ voice. `--jev` also asks TypeSafe Jev (`jev.js`) to score each sentence and paragraph against the
320
+ humanizer shapes. Those scores are a report unless `--shape-block=<0.6-1>` names a bar. Jev reads
321
+ `JEV_BASE_URL` and `JEV_API_KEY` from the env, else Proton Pass (Dev vault, item `AI endpoints`).
322
+ A base ending in `/ai/run` is Cloudflare Workers AI, which also reads `JEV_GATEWAY_ID`.
323
+
324
+ `--register=forum` is the Reddit gate, and `reddit lint` in upsys/app runs it. It's built from the
325
+ Reddit bench below, because the humanizer checks refused 151 of 157 human replies there:
326
+
327
+ - **AI signals** (`register.js`): no I, hedge or question; short even sentences; orders to the
328
+ reader; chopped into short paragraphs; no question or aside. Three or more of the 5 fails a reply
329
+ of 25 words or more. `aiSignalNames(text)` lists them.
330
+ - **Ramzi's two rules**: no em or en dash, and no single block over 95 words.
331
+ - **Jev** asks one whole-reply question (`FORUM_SHAPES` in `jev-core.js`) in place of the sentence
332
+ shapes, and refuses at 0.75. The forum register always asks it, and when Jev can't answer the
333
+ reply fails with `jev unscored`. A reply under 25 words asks Jev nothing.
334
+
335
+ `jev-core.js` (`@heyramzi/lint/jev-core`) is the same Jev pass with no Node import, for a Worker:
336
+ `auditShapesWith(text, { post: jevPost({ baseUrl, key, gatewayId }), block: FAIL, register: "forum" })`.
337
+ `jev.js` wraps it for Node with the env, Proton Pass and a disk cache.
338
+
339
+ #### The Reddit bench
340
+
341
+ `data/reddit-bench.json` holds u/heyramzi comments that went badly (`bad: true`) and the top human
342
+ replies in the same threads (`bad: false`). A comment is bad when it was reported (`reported`, by
343
+ id), removed (a mod-team, AutoModerator or BotBouncer notice, or the app's removal record), scored
344
+ 0 or less, sits in a sub that banned us or that the app marked cold, or was posted on a day in
345
+ `badDays`. A row, once bad, stays bad. The file stays out of the npm tarball.
346
+
347
+ - `node scripts/reddit-bench.mjs` runs the CLI exactly as `reddit lint` does on every row. It prints
348
+ recall (bad comments refused), the false positive rate (humans refused) and which check caught
349
+ what. It exits 1 when a bad comment outside `knownMisses` passes, or more than 17% of humans are
350
+ refused. After a gate change you've reviewed, `--accept` writes today's misses to `knownMisses`.
351
+ - `scripts/reddit-bench-harvest.mjs` pulls new bad comments and fresh human replies through the
352
+ logged-in Orca tab, one read every 6 seconds, writes them to the bench, then runs the bench and
353
+ exits with its code:
354
+
355
+ ```sh
356
+ cd ~/Studio/vibe-kit && bun ./CLIs/scripts/secrets.mjs run --mode development \
357
+ --file 'CLIs/.env' --shell "bun packages/lint/scripts/reddit-bench-harvest.mjs"
358
+ ```
359
+
360
+ `--no-bench` stops after the harvest. A new report from a mod or a bot: add the comment id to
361
+ `reported`, then run it. When it fails, change the AI signals or `FORUM_SHAPES` against the whole
362
+ bench, never the one comment, and keep the false positive rate under the bar.
363
+
313
364
  ### Commit Message Gate
314
365
 
315
366
  `heyramzi-commit-msg <file>` is a `commit-msg` hook. It refuses an em or en dash anywhere in the
@@ -23,10 +23,15 @@ const git = (args) =>
23
23
  const all = process.argv.includes("--all");
24
24
 
25
25
  const tracked = git(["ls-files", "-z"]).toString("utf8").split("\0").filter(Boolean);
26
+ const untracked = git(["ls-files", "--others", "--exclude-standard", "-z"])
27
+ .toString("utf8")
28
+ .split("\0")
29
+ .filter(Boolean);
26
30
  const changes = all ? { touched: tracked, added: tracked } : staged();
27
31
  const tree = createTree({
28
32
  ...changes,
29
33
  tracked,
34
+ untracked,
30
35
  read: all ? readWorking : readStaged,
31
36
  readBefore: all ? undefined : readHead,
32
37
  });
@@ -48,7 +48,7 @@
48
48
  */
49
49
 
50
50
  /*
51
- * With the model unreachable the exact patterns still run, stderr says the model check didn't, and the exit code is theirs.
51
+ * With the model unreachable the exact patterns still run, stderr says the model check didn't, and the exit code is theirs. `--register=forum` is the exception: it always asks Jev and fails when Jev can't answer.
52
52
  */
53
53
 
54
54
  import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
@@ -56,7 +56,8 @@ import { join } from "node:path";
56
56
  import { shapes } from "#lint/data/slop-words.js";
57
57
  import { patterns } from "#lint/data/slop/patterns.js";
58
58
  import { titleTells } from "#lint/data/slop/title-tells.js";
59
- import { REVIEW, auditShapes, isUnavailable, jevKey as readJevKey, proseOf } from "#lint/jev.js";
59
+ import { FAIL, REVIEW, isUnavailable, proseOf } from "#lint/jev-core.js";
60
+ import { auditShapes, jevKey as readJevKey } from "#lint/jev.js";
60
61
  import { slopGate } from "#lint/slop.js";
61
62
 
62
63
  // =========================
@@ -149,7 +150,7 @@ async function modelShapes(file, raw) {
149
150
  try {
150
151
  jevKey ??= readJevKey();
151
152
  const text = /\.(html?|svelte|vue)$/i.test(file) ? proseOf(raw) : raw;
152
- return await auditShapes(text, { key: jevKey, block: shapeBlock });
153
+ return await auditShapes(text, { key: jevKey, block: shapeBlock, register });
153
154
  } catch (err) {
154
155
  if (!isUnavailable(err)) throw err;
155
156
  jevDown = err.message;
@@ -211,12 +212,17 @@ if (onlyFlag && !onlyFlag.includes("=")) {
211
212
  }
212
213
  const only = onlyFlag ? new Set(onlyFlag.split("=")[1].split(",").filter(Boolean)) : null;
213
214
 
215
+ // The reply BotBouncer reported on 30 Oct 2026 passed every exact pattern. So forum always asks
216
+ // Jev, refuses at FAIL, and fails a reply Jev couldn't score.
217
+ const forum = register === "forum";
218
+ const askJev = flags.has("--jev") || forum;
219
+
214
220
  // The opt-in bar. Below REVIEW would promise to block scores the model check never keeps.
215
221
  const blockFlag = args.find((a) => a.startsWith("--shape-block"));
216
- let shapeBlock = Infinity;
222
+ let shapeBlock = forum ? FAIL : Infinity;
217
223
  if (blockFlag) {
218
224
  shapeBlock = blockFlag.includes("=") ? Number(blockFlag.split("=")[1]) : Number.NaN;
219
- if (!(shapeBlock >= REVIEW && shapeBlock <= 1) || !flags.has("--jev")) {
225
+ if (!(shapeBlock >= REVIEW && shapeBlock <= 1) || !askJev) {
220
226
  process.stderr.write(
221
227
  `--shape-block takes a score from ${REVIEW} to 1 and needs --jev: --jev --shape-block=0.85\n`,
222
228
  );
@@ -238,7 +244,7 @@ for (const file of files) {
238
244
  result.review = [];
239
245
  result.ok = result.findings.length === 0;
240
246
  }
241
- if (flags.has("--jev") && !jevDown) {
247
+ if (askJev && !jevDown) {
242
248
  const found = await modelShapes(file, raw);
243
249
  if (found) {
244
250
  result.findings.push(...found.findings);
@@ -246,7 +252,15 @@ for (const file of files) {
246
252
  result.ok = result.ok && found.findings.length === 0;
247
253
  }
248
254
  }
249
- if (flags.has("--jev")) result.jev = jevDown ? { ran: false, reason: jevDown } : { ran: true };
255
+ if (askJev) result.jev = jevDown ? { ran: false, reason: jevDown } : { ran: true };
256
+ if (forum && jevDown) {
257
+ result.findings.push({
258
+ kind: "jev",
259
+ id: "unscored",
260
+ detail: `a forum reply needs Jev: ${jevDown}`,
261
+ });
262
+ result.ok = false;
263
+ }
250
264
  results.push({ file, raw, result });
251
265
 
252
266
  if (flags.has("--fix") && result.removed.length > 0) {
@@ -279,7 +293,9 @@ const ok = results.every((r) => r.result.ok) && !ledger;
279
293
  // Said on stderr in every mode, so a quiet or JSON run never reads as a full pass.
280
294
  if (jevDown)
281
295
  process.stderr.write(
282
- `model check did not run: ${jevDown}. Exact patterns only; the exit code is theirs alone.\n`,
296
+ forum
297
+ ? `model check did not run: ${jevDown}. A forum reply fails without it.\n`
298
+ : `model check did not run: ${jevDown}. Exact patterns only; the exit code is theirs alone.\n`,
283
299
  );
284
300
 
285
301
  if (flags.has("--json")) {
package/data/jev-bench.js CHANGED
@@ -93,6 +93,14 @@ export const SENTENCES = [
93
93
  { shape: null, text: "Does Friday at 10am still work for you and your accountant?" },
94
94
  { shape: null, text: "Thanks for sending the floor plan so fast." },
95
95
  { shape: null, text: "We'd love to have you at the tasting next week." },
96
+ {
97
+ shape: "reassurance",
98
+ text: "Every photo of the bread here is my own loaf, straight from my oven.",
99
+ },
100
+ { shape: "reassurance", text: "The payroll numbers below are real, nothing rounded up." },
101
+ { shape: "reassurance", text: "These are real reviews from real gym members, no paid ones." },
102
+ { shape: null, text: "I own the bakery that sells this flour." },
103
+ { shape: null, text: "The supplier sent me the mixer for free to review." },
96
104
  ];
97
105
 
98
106
  export const PARAGRAPHS = [
@@ -56,6 +56,13 @@ export const shapesFraming = [
56
56
  example:
57
57
  '"If you are coming from traditional automation: instead of registering handlers, you describe conditions." / "The rule is simple: write it down." / "Here is the tradeoff: speed against accuracy."',
58
58
  },
59
+ {
60
+ id: "unprompted-reassurance",
61
+ name: "Unprompted reassurance",
62
+ rule: 'A sentence whose only job is to fend off a suspicion nobody has raised: that the content is fake, staged, mocked up, written by AI, sponsored, edited or dishonest. It reads as a bot pre-empting the exact accusation, so it plants the doubt it was meant to settle. Ramzi, 2 Nov 2026, on a Reddit launch post that said every screen in the video was the real app: "saying this is so stupid in the 1st place because it sounds AI generated", and "They focus on details instead of looking at the big picture of things." Cut the sentence, or show the proof instead of asserting it: a link to the build, the changelog, a release count the reader can check. A disclosure the venue asks for ("I\'m the developer", "they sent me a review unit") states a relationship and stays. Jev judges it as `reassurance`. Not in `patterns` because the same words are literal elsewhere: "the designer sent no mockups" and "no fluff in the sauce" describe a thing, not the writing.',
63
+ example:
64
+ '"Everything in the video is the real app, no mockups." / "This isn\'t an ad, I just love it." / "100% real footage." / "Real numbers, no cherry-picking." / "Screenshots are unedited, I promise." / "No fluff, just what worked."',
65
+ },
59
66
  {
60
67
  id: "abstract-metaphor-noun",
61
68
  name: "Abstract metaphor noun",
package/jev-code.js CHANGED
@@ -2,7 +2,8 @@
2
2
  * Coding guidelines as tiny Jev questions, judged on the edited code alone after each edit.
3
3
  * Only rules a reader can settle from the snippet, no repo context. Bench: scripts/jev-code-bench.mjs.
4
4
  */
5
- import { JEV_OFF, jevKey, judge, q } from "#lint/jev.js";
5
+ import { q } from "#lint/jev-core.js";
6
+ import { JEV_OFF, jevKey, judge } from "#lint/jev.js";
6
7
 
7
8
  // =========================
8
9
  // CONSTANTS
package/jev-core.d.ts ADDED
@@ -0,0 +1,93 @@
1
+ /** One Jev yes/no question, scored 0 to 1 as the chance the answer is yes. */
2
+ export type JevQuestion = {
3
+ type: "noul";
4
+ instructions: string;
5
+ criteria: { true: string; false: string };
6
+ };
7
+
8
+ /** What a caller's `post` sends to Jev: items keyed `i<n>`, questions keyed `i<n>_<shape>`. */
9
+ export type JevRequest = {
10
+ state: Record<string, Record<string, string>>;
11
+ questions: Record<string, JevQuestion>;
12
+ };
13
+
14
+ /** Jev's `answers`, keyed like the questions. `post` returns this object, unwrapped from any envelope. */
15
+ export type JevAnswers = Record<string, { noul?: number }>;
16
+
17
+ /** Sends one request to Jev. Throw `unavailable(message)` when it can't answer. */
18
+ export type JevPost = (request: JevRequest) => Promise<JevAnswers>;
19
+
20
+ /** Optional score store: `read` returns earlier worst scores or undefined, `write` keeps them. */
21
+ export type JevCache = {
22
+ read: (
23
+ item: Record<string, string>,
24
+ field: string,
25
+ shapes: Record<string, JevQuestion>,
26
+ ) => Record<string, number> | undefined;
27
+ write: (
28
+ item: Record<string, string>,
29
+ field: string,
30
+ shapes: Record<string, JevQuestion>,
31
+ scores: Record<string, number>,
32
+ ) => void;
33
+ };
34
+
35
+ export type ShapeHit = { p: number; kind: "shape"; id: string; detail: string };
36
+ export type ShapeResult = { findings: ShapeHit[]; review: ShapeHit[] };
37
+
38
+ /** Jev's moving id on TypeSafe-compatible gateways, and on Cloudflare Workers AI. */
39
+ export const MODEL: "typesafe-ai/jev";
40
+ export const CLOUDFLARE_MODEL: "typesafe/jev";
41
+
42
+ /** A base URL ending in `/ai/run` is Cloudflare; anything else gets `/v1/systemone`. */
43
+ export function jevRoute(baseUrl: string): { url: string; model: string; cloudflare: boolean };
44
+
45
+ /**
46
+ * A `JevPost` over fetch for any runtime, a Worker included. `gatewayId` is the Cloudflare AI
47
+ * Gateway id; `fetch` defaults to the global one. Retries a 429 or 5xx 4 times, then throws.
48
+ */
49
+ export function jevPost(options: {
50
+ baseUrl: string;
51
+ key: string;
52
+ gatewayId?: string;
53
+ fetch?: typeof fetch;
54
+ }): JevPost;
55
+
56
+ /** The bar a gate refuses at, and the floor a score is reported from. */
57
+ export const FAIL: 0.75;
58
+ export const REVIEW: 0.6;
59
+ /** A forum reply shorter than this gets no whole-reply questions. */
60
+ export const FORUM_MIN_WORDS: number;
61
+
62
+ export function q(instructions: string, yes: string, no: string): JevQuestion;
63
+
64
+ /** Asked of every sentence (`sentence`, with its paragraph as `context`). */
65
+ export const SHAPES: Record<string, JevQuestion>;
66
+ /** Asked of every paragraph of 3 sentences or more (`paragraph`). */
67
+ export const PARAGRAPH_SHAPES: Record<string, JevQuestion>;
68
+ /** Asked once of a whole forum reply (`reply`) under `register: "forum"`, in place of the other two. */
69
+ export const FORUM_SHAPES: Record<string, JevQuestion>;
70
+
71
+ export function sentences(text: string): { sentence: string; context: string }[];
72
+ export function paragraphs(text: string): { paragraph: string }[];
73
+ export function replies(text: string): { reply: string }[];
74
+ export function proseOf(html: string): string;
75
+
76
+ export function unavailable(message: string): Error;
77
+ export function isUnavailable(err: unknown): boolean;
78
+
79
+ export function judgeWith(
80
+ items: Record<string, string>[],
81
+ shapes: Record<string, JevQuestion>,
82
+ field: string,
83
+ options: { post: JevPost; cache?: JevCache; block?: number },
84
+ ): Promise<ShapeResult>;
85
+
86
+ /**
87
+ * The CLI's Jev pass with your transport. `block: FAIL` and `register: "forum"` is the Reddit gate;
88
+ * a finding means refuse. Throws when `post` throws.
89
+ */
90
+ export function auditShapesWith(
91
+ text: string,
92
+ options: { post: JevPost; cache?: JevCache; block?: number; register?: string },
93
+ ): Promise<ShapeResult>;
package/jev-core.js ADDED
@@ -0,0 +1,344 @@
1
+ /**
2
+ * The Jev questions and judging loop with no Node import, so a Worker runs the CLI's gate.
3
+ */
4
+
5
+ /*
6
+ * The caller brings `post`: `{ state, questions }` in, Jev's `answers` out. jev.js is the Node one.
7
+ */
8
+
9
+ // =========================
10
+ // CONSTANTS
11
+ // =========================
12
+ /** The gateway's moving latest, never a version, so each Jev release reaches the gate (TECHLOG.md). */
13
+ export const MODEL = "typesafe-ai/jev";
14
+ /** The same moving id in Workers AI's naming, for a base URL on Cloudflare's `/ai/run`. */
15
+ export const CLOUDFLARE_MODEL = "typesafe/jev";
16
+ /** upsys/app's env since 27 Oct 2026: `.../accounts/<id>/ai/run`, which takes `{ model, input }`. */
17
+ const CLOUDFLARE_RUN = /\/ai\/run$/;
18
+ /** One request that hangs must not hang a draft: past this it counts as unreachable. */
19
+ const TIMEOUT_MS = 30_000;
20
+ export const FAIL = 0.75;
21
+ export const REVIEW = 0.6;
22
+ /** Scores drift about 0.05 between identical calls, so each item is asked RUNS times and its worst score counts. */
23
+ const RUNS = 3;
24
+ /** Items per request: 4 sentences, each asked every shape in the same request. */
25
+ const BATCH = 4;
26
+ const CONCURRENCY = 8;
27
+ /** The Reddit bench holds no human reply under this, so a shorter reply is never asked. */
28
+ export const FORUM_MIN_WORDS = 25;
29
+
30
+ /** One question per root cause, not per pattern: humanizer references/patterns.md maps each pattern to one. */
31
+ export const q = (instructions, yes, no) => ({
32
+ type: "noul",
33
+ instructions,
34
+ criteria: { true: yes, false: no },
35
+ });
36
+ const PLAIN =
37
+ "A plain, literal sentence: a step the reader takes, a named thing, a number, or a fact that carries its own meaning.";
38
+
39
+ /** Asked of every sentence, with its paragraph as `context`. */
40
+ export const SHAPES = {
41
+ inflated: q(
42
+ "Does `sentence` tell the reader that something matters, impresses or feels a certain way, instead of giving the fact, number or mechanism that would show it, or is it generic enough to move unchanged to another company, product or person?",
43
+ "Praise, significance, emotion or quality asserted, not shown, or a line with nothing only this subject could say.",
44
+ `${PLAIN} Or a letter's courtesy to its reader: a thanks, a greeting, an invitation.`,
45
+ ),
46
+ aphorism: q(
47
+ "Is `sentence` a slogan or maxim: a quotable general truth stated in abstract terms instead of a concrete step, number or fact?",
48
+ "Could be printed on a poster, often a flip or an 'only', and the next sentence has to explain it.",
49
+ PLAIN,
50
+ ),
51
+ law: q(
52
+ "Does `sentence` describe how a tool, setting or system behaves as a general rule, with the thing as the subject and no person acting, where it could tell the reader what to do and what they will see?",
53
+ "The subject is an object or an idea, the verb is a state or a spread, and the reader has no step to copy. Often it ends on 'it' or 'them'.",
54
+ "A person does something, a literal step (where to click, what appears), a measured result of what happened, with its number, or a plain fact or rule about one specific thing said the way a person would ('the back door doesn't lock', 'a cancelled ticket is never refunded').",
55
+ ),
56
+ vague: q(
57
+ "Does `sentence` point at content instead of stating it: it announces, promises, sets up or labels a point that the sentence itself does not give?",
58
+ "A teaser, signpost or label: the reader learns that there is a reason, a tip, a rule or a next step, but not what it is.",
59
+ "The sentence gives the content itself, the paragraph gives it right after, or it starts with 'Link:' and names what the reader does when they click.",
60
+ ),
61
+ hedge: q(
62
+ "Does `sentence` pad itself with a hedge, a reassurance, a propping adverb (really, basically, actually), an unnamed source, or a line about the conversation instead of the subject?",
63
+ "It contains padding of that kind, or talks about the writing instead of the subject.",
64
+ "No hedge, prop or talk about the conversation. A thanks, a greeting or a question to the reader is not padding.",
65
+ ),
66
+ filler: q(
67
+ "Can one word or phrase in `sentence` be deleted, or swapped for a shorter one, and the sentence still say exactly the same thing?",
68
+ "At least one word can go or shrink ('in order to', 'each and every', a word the rest already implies) with no loss of meaning.",
69
+ "Every word carries meaning the sentence would lose. Warmth to the reader in a letter counts as meaning.",
70
+ ),
71
+ contrast: q(
72
+ "Does `sentence` stage a contrast to make its point: 'not X, it's Y' denying a claim nobody made, an either-or where one side is a strawman, a 'from X to Y' span with no real range, or one claim said twice in other words?",
73
+ "The denied half, the strawman side, the span or the repeat is there for effect. Delete it and the point stands alone.",
74
+ "A real comparison between two named options, or a single plain claim.",
75
+ ),
76
+ stilted: q(
77
+ "Does `sentence` sound awkward or unnatural, like a clumsy translation or a forced rewrite, so a native English speaker would phrase it differently or need to reread it?",
78
+ "Awkward phrasing: a person made the subject of find, meet or get where people would say 'there is' or 'X has'; an odd verb; an unexplained code or label; a clumsy word order.",
79
+ "Natural, clear English a person would say out loud.",
80
+ ),
81
+ pitch: q(
82
+ "Is `sentence` an ad line that promises an effortless result: a dramatic command plus an outcome said to be already true, or a lone word used as a verdict, instead of saying what happens when the reader takes an action?",
83
+ "Reads like a tagline: 'Do X, and Y is already done', or a one-word fragment as the punchline.",
84
+ `${PLAIN} Or a literal step with what happens next, in the product's own terms.`,
85
+ ),
86
+ personified: q(
87
+ "Does `sentence` use a figure where a literal word exists: a non-human thing doing what only a person does, or an abstract idea dressed as a physical object?",
88
+ "A tool that knows, wants, saves or gives; an idea that is a lever, a ceiling, a moat or a muscle.",
89
+ "The thing does something mechanical and literal, or a person does the acting.",
90
+ ),
91
+ thingdoer: q(
92
+ "Does `sentence` make a tool, automation, checklist, script or system the grammatical subject of what a person sets up or does, where a person as the subject ('we', 'you', or an imperative) would be plainer?",
93
+ "A noun leads and acts: 'An automation creates it and assigns it', 'A checklist catches this', 'The script only posts what is approved'. It reads like a description of a machine, with nobody behind it. Ramzi, 30 Sep 2026.",
94
+ "A person is the subject or the sentence is an instruction ('Have an automation create it'), or the thing genuinely is the subject of a literal fact ('The API returns JSON').",
95
+ ),
96
+ stagey: q(
97
+ "Does `sentence` describe an action or a rule as a small scene where a plain verb and object would do: 'waits for someone to say go' for 'needs your approval', 'gets you most of the way' for 'covers most of it', 'does its sweep' for 'runs'?",
98
+ "A phrase that acts out the idea (waits, says go, gets you there, takes the wheel) when one plain verb says the same thing. Ramzi, 30 Sep 2026: 'Claude Code on a timer requires you' is simpler and means the same.",
99
+ "The sentence already uses the plain verb and object a person would say out loud.",
100
+ ),
101
+ reassurance: q(
102
+ "Does `sentence` vouch for what the reader is shown (a demo, screenshot, photo, number, review or the text itself) when nothing in the text doubted it: insist it is real, genuine, untouched, or the product's or the writer's own, or deny it is fake, staged, mocked up, written by AI, sponsored, cherry-picked or padded?",
103
+ "An unasked claim of authenticity or honesty with no proof beside it. A demo that shows the product, a photo that shows the dish and a review nobody paid for are what any reader already assumes, so saying so only fends off a doubt, and raising the doubt is what plants it. Ramzi, 2 Nov 2026.",
104
+ "A plain fact about the thing or what it does, a disclosure of who the writer is or what they were given ('I'm the developer', 'they sent me a free unit'), or an answer to a doubt someone in the text raised.",
105
+ ),
106
+ };
107
+
108
+ /** Asked once per paragraph of 3 or more sentences: the shapes no single sentence shows. */
109
+ export const PARAGRAPH_SHAPES = {
110
+ rhythm: q(
111
+ "Does `paragraph` repeat one structure instead of varying it: sentences of one length or one opening, items forced into threes, a punchy closer on every beat, a word reused where no new idea arrived, or a transition that asserts a link the facts do not show?",
112
+ "A reader could predict the shape of the next sentence before reading it.",
113
+ "Sentence lengths and openings vary with the thought, and each link between sentences is shown by what they say.",
114
+ ),
115
+ };
116
+
117
+ /**
118
+ * Asked once of a whole forum reply, in place of SHAPES and PARAGRAPH_SHAPES: those refused 151 of
119
+ * 157 human Reddit replies (scripts/reddit-bench.mjs, 2 Nov 2026). Of 10 whole-reply questions tried,
120
+ * this one alone refused a bad comment at FAIL without refusing a human. The rest live in TECHLOG.md.
121
+ */
122
+ export const FORUM_SHAPES = {
123
+ tutorial: q(
124
+ "`reply` is a comment on a Reddit thread. Does it read as a complete tutorial or help-article answer: the whole procedure laid out step by step from start to finish, each step an instruction, rather than what one person typed from their own experience?",
125
+ "A tidy walkthrough: select this, then open that, pick this, then hit that. Every step covered in order, like documentation or a support bot.",
126
+ "A person talking: a partial answer, a pointer, an opinion, a story about what they did, a question back, or one tip with their reason.",
127
+ ),
128
+ };
129
+
130
+ // =========================
131
+ // FUNCTIONS
132
+ // =========================
133
+ /** Short unpunctuated lines are glance copy (subjects, headlines); Ramzi, 23 Sep 2026, on a subject Jev never saw. */
134
+ const GLANCE = /^[^\n]{1,60}$/;
135
+
136
+ /** Prose sentences with their paragraph, plus glance lines of 4+ words as their own item. */
137
+ export function sentences(text) {
138
+ return text.split(/\n\s*\n|\n(?=\s*[-*]\s)/).flatMap((para) => {
139
+ const lines = para
140
+ .split("\n")
141
+ .map((l) => l.replace(/^\s*(?:#+|[-*])\s*/, "").trim())
142
+ .filter(Boolean);
143
+ if (lines.every((l) => GLANCE.test(l)) && lines.some((l) => !/[.!?]["')\]]*$/.test(l))) {
144
+ return lines
145
+ .filter((l) => l.split(" ").length >= 4)
146
+ .map((l) => ({ sentence: l, context: l }));
147
+ }
148
+ // An unpunctuated line is a heading: end it, so it isn't glued to the next sentence.
149
+ const flat = para.replace(/\s+/g, " ").trim();
150
+ const ended = lines.map((l) => (/[.!?:]["')\]]*$/.test(l) ? l : `${l}.`)).join(" ");
151
+ // A stop only ends a sentence before a space, so "1.5" stays whole.
152
+ return (ended.match(/.+?[.!?]+["')\]]*(?=\s|$)/g) ?? [])
153
+ .map((s) => s.trim())
154
+ .filter((s) => s.split(" ").length >= 3)
155
+ .map((sentence) => ({ sentence, context: flat }));
156
+ });
157
+ }
158
+
159
+ /** Markup as Jev reads it: a block ends a paragraph, and link text says it's a link. */
160
+ export function proseOf(html) {
161
+ return html
162
+ .replace(/<(script|style)[\s\S]*?<\/\1>|<!--[\s\S]*?-->/gi, " ")
163
+ .replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, "\n\nLink: $1\n\n")
164
+ .replace(/<\/(p|li|h[1-6]|div|td|blockquote)>|<br\s*\/?>/gi, "\n\n")
165
+ .replace(/<[^>]+>/g, " ")
166
+ .replace(/&rarr;|&[a-z]+;|&#\d+;/gi, " ")
167
+ .replace(/[ \t]+/g, " ")
168
+ .replace(/\n\s*\n\s*/g, "\n\n")
169
+ .trim();
170
+ }
171
+
172
+ /** Paragraphs long enough to have a rhythm: 3 sentences or more. */
173
+ export function paragraphs(text) {
174
+ return text
175
+ .split(/\n\s*\n/)
176
+ .map((para) => para.replace(/\s+/g, " ").trim())
177
+ .filter((para) => (para.match(/[.!?]+["')\]]*(?=\s|$)/g) ?? []).length >= 3)
178
+ .map((paragraph) => ({ paragraph }));
179
+ }
180
+
181
+ /** A forum reply as one item. Under FORUM_MIN_WORDS it's a quick answer, which humans give bare too. */
182
+ export function replies(text) {
183
+ const reply = text.replace(/\s+/g, " ").trim();
184
+ return reply.split(" ").length >= FORUM_MIN_WORDS ? [{ reply }] : [];
185
+ }
186
+
187
+ /** The model check could not run: network, key, credits, timeout or a bad answer. Callers skip it, not crash. */
188
+ export function unavailable(message) {
189
+ return Object.assign(new Error(message), { name: "JevUnavailable" });
190
+ }
191
+
192
+ export const isUnavailable = (err) => err instanceof Error && err.name === "JevUnavailable";
193
+
194
+ /** Where a base URL sends a question: TypeSafe's own route, or Cloudflare's `/ai/run`. */
195
+ export function jevRoute(baseUrl) {
196
+ const base = (baseUrl ?? "").trim().replace(/\/+$/, "");
197
+ if (!CLOUDFLARE_RUN.test(base))
198
+ return { url: `${base}/v1/systemone`, model: MODEL, cloudflare: false };
199
+ return { url: base, model: CLOUDFLARE_MODEL, cloudflare: true };
200
+ }
201
+
202
+ function why(err) {
203
+ if (err?.name === "TimeoutError") return `timed out after ${TIMEOUT_MS / 1000}s`;
204
+ return err?.cause?.code ?? err?.cause?.message ?? err?.message ?? String(err);
205
+ }
206
+
207
+ /**
208
+ * A `post` over fetch, for any runtime: the caller passes the base URL, the key and, on Cloudflare,
209
+ * the AI Gateway id. A 429 or 5xx is retried 4 times; anything else throws `unavailable`.
210
+ */
211
+ export function jevPost({
212
+ baseUrl,
213
+ key,
214
+ gatewayId,
215
+ fetch: send = (...a) => globalThis.fetch(...a),
216
+ }) {
217
+ const { url, model, cloudflare } = jevRoute(baseUrl);
218
+ const headers = { Authorization: `Bearer ${key}`, "Content-Type": "application/json" };
219
+ if (cloudflare && gatewayId) headers["cf-aig-gateway-id"] = gatewayId;
220
+ return async function post(body, attempt = 0) {
221
+ if (!baseUrl?.trim() || !key) throw unavailable("Jev is off: no base URL or key");
222
+ let res;
223
+ try {
224
+ res = await send(url, {
225
+ method: "POST",
226
+ headers,
227
+ body: JSON.stringify(cloudflare ? { model, input: body } : { model, ...body }),
228
+ signal: AbortSignal.timeout(TIMEOUT_MS),
229
+ });
230
+ } catch (err) {
231
+ throw unavailable(`${new URL(url).host} unreachable (${why(err)})`);
232
+ }
233
+ if ((res.status === 429 || res.status >= 500) && attempt < 4) {
234
+ await new Promise((r) => setTimeout(r, 1000 * 2 ** attempt));
235
+ return post(body, attempt + 1);
236
+ }
237
+ if (!res.ok) throw unavailable(`Jev HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`);
238
+ const parsed = await res.json().catch(() => ({}));
239
+ const run = cloudflare ? parsed.result : parsed;
240
+ if (cloudflare && run?.state !== "Completed")
241
+ throw unavailable(`Cloudflare ended the Jev run as ${run?.state ?? "unknown"}`);
242
+ const answers = cloudflare ? run.result?.answers : run?.answers;
243
+ if (!answers) throw unavailable("Jev answered without scores");
244
+ return answers;
245
+ };
246
+ }
247
+
248
+ /** One request for every shape of up to BATCH items; item `i` is `i<n>` in state, so `field` becomes `i<n>.field`. */
249
+ async function askBatch(items, post, shapes, field) {
250
+ const state = Object.fromEntries(items.map((it, n) => [`i${n}`, it]));
251
+ const questions = {};
252
+ items.forEach((_, n) => {
253
+ for (const [id, q] of Object.entries(shapes)) {
254
+ questions[`i${n}_${id}`] = {
255
+ ...q,
256
+ instructions: q.instructions.replaceAll(`\`${field}\``, `\`i${n}.${field}\``),
257
+ };
258
+ }
259
+ });
260
+ const answers = await post({ state, questions });
261
+ return items.map((_, n) =>
262
+ Object.fromEntries(
263
+ Object.keys(shapes).map((id) => {
264
+ const score = answers[`i${n}_${id}`]?.noul;
265
+ if (typeof score !== "number") throw unavailable(`Jev left out the score for ${id}`);
266
+ return [id, score];
267
+ }),
268
+ ),
269
+ );
270
+ }
271
+
272
+ async function pooled(jobs) {
273
+ const out = [];
274
+ for (let i = 0; i < jobs.length; i += CONCURRENCY)
275
+ out.push(...(await Promise.all(jobs.slice(i, i + CONCURRENCY).map((job) => job()))));
276
+ return out;
277
+ }
278
+
279
+ /** Every item's worst score per shape over RUNS calls, kept from REVIEW up. A cached item costs no request. */
280
+ async function askAll(items, shapes, field, { post, cache }) {
281
+ if (Object.keys(shapes).length === 0) return [];
282
+ const worst = items.map((it) => cache?.read(it, field, shapes));
283
+ const pending = items.flatMap((_, i) => (worst[i] ? [] : [i]));
284
+ const chunks = [];
285
+ for (let i = 0; i < pending.length; i += BATCH) chunks.push(pending.slice(i, i + BATCH));
286
+ const runs = await pooled(
287
+ chunks.flatMap((chunk) =>
288
+ Array.from({ length: RUNS }, () => async () => ({
289
+ chunk,
290
+ scores: await askBatch(
291
+ chunk.map((i) => items[i]),
292
+ post,
293
+ shapes,
294
+ field,
295
+ ),
296
+ })),
297
+ ),
298
+ );
299
+ for (const { chunk, scores } of runs) {
300
+ scores.forEach((byShape, n) => {
301
+ const seen = (worst[chunk[n]] ??= {});
302
+ for (const [id, p] of Object.entries(byShape)) seen[id] = Math.max(seen[id] ?? 0, p);
303
+ });
304
+ }
305
+ for (const i of pending) cache?.write(items[i], field, shapes, worst[i]);
306
+ return items.flatMap((it, i) =>
307
+ Object.entries(worst[i])
308
+ .filter(([, p]) => p >= REVIEW)
309
+ .map(([id, p]) => ({ p, kind: "shape", id, detail: `${p.toFixed(2)} "${it[field]}"` })),
310
+ );
311
+ }
312
+
313
+ /**
314
+ * Every item asked every shape: `findings` at `block` and up (FAIL by default), `review` from REVIEW
315
+ * to `block`. `cache` is optional: `read(item, field, shapes)` returns scores or undefined, `write`
316
+ * stores them.
317
+ */
318
+ export async function judgeWith(items, shapes, field, { post, cache, block = FAIL }) {
319
+ const hits = await askAll(items, shapes, field, { post, cache });
320
+ return { findings: hits.filter((h) => h.p >= block), review: hits.filter((h) => h.p < block) };
321
+ }
322
+
323
+ /**
324
+ * Shapes Jev reads in a text: each sentence and each paragraph of 3 or more, or under the forum
325
+ * register the whole reply alone. A report (`review`) unless `block` names a bar; a hit at or above it is
326
+ * a `finding`. Throws JevUnavailable when `post` can't get an answer.
327
+ */
328
+ export async function auditShapesWith(text, { post, cache, block = Infinity, register } = {}) {
329
+ const passes =
330
+ register === "forum"
331
+ ? [[replies(text), FORUM_SHAPES, "reply"]]
332
+ : [
333
+ [sentences(text), SHAPES, "sentence"],
334
+ [paragraphs(text), PARAGRAPH_SHAPES, "paragraph"],
335
+ ];
336
+ const out = { findings: [], review: [] };
337
+ // One pass at a time, so a draft never sends the gateway more than CONCURRENCY requests at once.
338
+ for (const [items, shapes, field] of passes) {
339
+ const { findings, review } = await judgeWith(items, shapes, field, { post, cache, block });
340
+ out.findings.push(...findings);
341
+ out.review.push(...review);
342
+ }
343
+ return out;
344
+ }