@litfamily/litcodex 1.0.7 → 1.0.8

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 (25) hide show
  1. package/README.md +105 -71
  2. package/dist/install/doctor-render.js +1 -0
  3. package/dist/install/doctor.js +8 -0
  4. package/dist/install/types.d.ts +3 -0
  5. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  6. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  7. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  8. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  9. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +8 -1
  10. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +36 -4
  11. package/marketplace/plugins/litcodex/components/lit-loop/dist/jev-hint.d.ts +112 -0
  12. package/marketplace/plugins/litcodex/components/lit-loop/dist/jev-hint.js +522 -0
  13. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  14. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  15. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  16. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  17. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  18. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  19. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +8 -1
  20. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +36 -4
  21. package/node_modules/@litcodex/lit-loop/dist/jev-hint.d.ts +112 -0
  22. package/node_modules/@litcodex/lit-loop/dist/jev-hint.js +522 -0
  23. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  24. package/package.json +3 -3
  25. package/readme-assets/badge-version.svg +1 -1
@@ -0,0 +1,522 @@
1
+ // src/jev-hint.ts — optional Jev skill hint for the UserPromptSubmit hook.
2
+ //
3
+ // Off by default. Active only when `LITCODEX_JEV=1` AND a non-empty `TYPESAFE_API_KEY` are both in
4
+ // the hook's environment. On an eligible turn (not a slash command, not an explicit `$skill` mention,
5
+ // not already routed by the deterministic lit router, at least 4 non-space characters) it sends the
6
+ // redacted, truncated prompt text to Jev with one Choice question over this plugin's own implicitly
7
+ // invocable skills, and returns at most one fixed advisory sentence naming a validated skill id.
8
+ //
9
+ // The response is untrusted: only an exact catalog id (or `none`) with a numeric confidence at or
10
+ // above the threshold is accepted, and no response text ever reaches the model context. Every
11
+ // failure falls back to today's behavior, with one short visible note per session. With
12
+ // `LITCODEX_JEV_SHOW=1` as well, a hinted turn also shows one visible line naming the skill id and
13
+ // latency. Whenever the hint is on, the first prompt of each session the router leaves alone also shows
14
+ // a once-per-session plain-text banner (`JEV_ON_BANNER`). The key is read from the environment only and is never written to output, errors, state,
15
+ // or the trace.
16
+ import { createHash, randomBytes } from "node:crypto";
17
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, unlinkSync, writeSync, } from "node:fs";
18
+ import { dirname, isAbsolute, join } from "node:path";
19
+ import { isExactBrowserDrivePrompt } from "./browser-drive-route.js";
20
+ import { isExactBareHandoffPrompt } from "./handoff-route.js";
21
+ import { resolveSkillPath } from "./modes.js";
22
+ import { isExactBareScientificVisualizationPrompt } from "./scientific-visualization-route.js";
23
+ import { matchRenamedSkillInvocation } from "./skill-renames.js";
24
+ import { normalizeSessionId } from "./state-paths.js";
25
+ import { maskMarkdownCode, matchLitTrigger } from "./trigger.js";
26
+ export const JEV_FLAG_ENV = "LITCODEX_JEV";
27
+ export const JEV_KEY_ENV = "TYPESAFE_API_KEY";
28
+ export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
29
+ export const JEV_DEFAULT_MODEL = "jev-1.13.0";
30
+ export const JEV_DEFAULT_TIMEOUT_MS = 1_500;
31
+ export const JEV_MAX_TIMEOUT_MS = 3_000;
32
+ export const JEV_DEFAULT_MAX_CALLS = 200;
33
+ export const JEV_DEFAULT_MIN_CONFIDENCE = 0.35;
34
+ export const JEV_MAX_PROMPT_CHARS = 2_000;
35
+ export const JEV_REDACTION_WINDOW_CHARS = 8_000;
36
+ export const JEV_MAX_DESCRIPTION_CHARS = 300;
37
+ export const JEV_MAX_BODY_BYTES = 64 * 1024;
38
+ export const JEV_STATE_DIR = ".litcodex/jev";
39
+ const QUESTION_INSTRUCTIONS = "Which one skill, if any, is the best fit for the user's request? Choose none when no catalog skill fits.";
40
+ const NONE_CRITERION = "No specialized skill in this catalog fits; answer the user directly.";
41
+ const SKILL_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
42
+ const FRONTMATTER_READ_BYTES = 16 * 1024;
43
+ /** The doctor/status state. Never reveals the key or its length. */
44
+ export function jevSwitchState(env) {
45
+ if (env[JEV_FLAG_ENV] !== "1")
46
+ return "off";
47
+ return (env[JEV_KEY_ENV]?.trim() ?? "") !== "" ? "on" : "flag on but TYPESAFE_API_KEY missing";
48
+ }
49
+ // ── Redaction ────────────────────────────────────────────────────────────────
50
+ // The user name runs to the next separator and never ends in a dot, so `/Users/alice.` keeps its full stop.
51
+ const HOME_PATHS = [
52
+ /\/(?:Users|home)\/[^/\\\s,;:"'`()[\]<>{}]*[^/\\\s,;:"'`()[\]<>{}.](\/)?/g,
53
+ /[A-Za-z]:\\Users\\[^/\\\s,;:"'`()[\]<>{}]*[^/\\\s,;:"'`()[\]<>{}.](\\)?/gi,
54
+ ];
55
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g;
56
+ const TOKEN_SHAPES = [
57
+ /-----BEGIN [A-Z0-9 ]+-----[\s\S]*?(?:-----END [A-Z0-9 ]+-----|$)/g,
58
+ /\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]*)?/g,
59
+ /\bsk-ant-[A-Za-z0-9_-]{8,}/g,
60
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
61
+ /\bgh[op]_[A-Za-z0-9]{16,}/g,
62
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/g,
63
+ /\bnpm_[A-Za-z0-9]{16,}/g,
64
+ /\bapikey_[A-Za-z0-9_-]{8,}/gi,
65
+ /\bxox[abprs]-[A-Za-z0-9-]{8,}/g,
66
+ /\bAKIA[A-Z0-9]{16}\b/g,
67
+ /\bAIza[A-Za-z0-9_-]{20,}/g,
68
+ /[A-Za-z0-9+/_-]{32,}={0,2}/g,
69
+ ];
70
+ const TRAILING_TOKEN_RUN = /[A-Za-z0-9+/_-]{8,}={0,2}$/;
71
+ /**
72
+ * Redact an 8,000-character window (home paths, e-mail addresses, the literal key and token-shaped
73
+ * strings, in that order), then cut to 2,000 characters. A run of 8 or more token characters left at
74
+ * the cut is part of something the cut split, so it becomes `[secret]` too.
75
+ */
76
+ export function redactJevPrompt(prompt, key = "") {
77
+ let text = Array.from(prompt).slice(0, JEV_REDACTION_WINDOW_CHARS).join("");
78
+ for (const pattern of HOME_PATHS)
79
+ text = text.replace(pattern, (_match, separator) => (separator ? "~/" : "~"));
80
+ text = text.replace(EMAIL, "[email]");
81
+ if (key !== "")
82
+ text = text.split(key).join("[secret]");
83
+ for (const pattern of TOKEN_SHAPES)
84
+ text = text.replace(pattern, "[secret]");
85
+ const chars = Array.from(text);
86
+ if (chars.length <= JEV_MAX_PROMPT_CHARS)
87
+ return text;
88
+ return chars.slice(0, JEV_MAX_PROMPT_CHARS).join("").replace(TRAILING_TOKEN_RUN, "[secret]");
89
+ }
90
+ /** The installed plugin's `skills/` directory, resolved the same way the mode router finds bodies. */
91
+ export function defaultJevSkillsRoot() {
92
+ return dirname(dirname(resolveSkillPath("lit-loop")));
93
+ }
94
+ function readHead(path) {
95
+ let fd;
96
+ try {
97
+ fd = openSync(path, "r");
98
+ const buffer = Buffer.alloc(FRONTMATTER_READ_BYTES);
99
+ const read = readSync(fd, buffer, 0, buffer.length, 0);
100
+ return buffer.subarray(0, read).toString("utf8");
101
+ }
102
+ catch {
103
+ return null;
104
+ }
105
+ finally {
106
+ if (fd !== undefined)
107
+ closeSync(fd);
108
+ }
109
+ }
110
+ function frontmatterValue(raw) {
111
+ const value = raw.trim();
112
+ if (value.startsWith('"') && value.endsWith('"') && value.length >= 2) {
113
+ try {
114
+ const parsed = JSON.parse(value);
115
+ if (typeof parsed === "string")
116
+ return parsed;
117
+ }
118
+ catch {
119
+ return value.slice(1, -1);
120
+ }
121
+ }
122
+ if (value.startsWith("'") && value.endsWith("'") && value.length >= 2)
123
+ return value.slice(1, -1).replace(/''/g, "'");
124
+ return value;
125
+ }
126
+ function readFrontmatter(text) {
127
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
128
+ if (match?.[1] === undefined)
129
+ return {};
130
+ const out = {};
131
+ for (const line of match[1].split(/\r?\n/)) {
132
+ const field = /^(name|description):\s*(.*)$/.exec(line);
133
+ if (field?.[1] === "name" && field[2] !== undefined)
134
+ out.name = frontmatterValue(field[2]);
135
+ if (field?.[1] === "description" && field[2] !== undefined)
136
+ out.description = frontmatterValue(field[2]);
137
+ }
138
+ return out;
139
+ }
140
+ function implicitInvocationDisabled(skillDir) {
141
+ try {
142
+ return /^\s*allow_implicit_invocation:\s*false\s*$/m.test(readFileSync(join(skillDir, "agents", "openai.yaml"), "utf8"));
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ /**
149
+ * This plugin's own skills that the host may load on the model's initiative: every `skills/<id>/SKILL.md`
150
+ * whose frontmatter `name` equals its directory, minus skills whose `agents/openai.yaml` sets
151
+ * `allow_implicit_invocation: false` (those run only on an explicit user invocation).
152
+ */
153
+ export function loadJevCatalog(skillsRoot = defaultJevSkillsRoot()) {
154
+ let names;
155
+ try {
156
+ names = readdirSync(skillsRoot).sort();
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ const catalog = [];
162
+ for (const id of names) {
163
+ if (!SKILL_ID.test(id) || id === "none")
164
+ continue;
165
+ const head = readHead(join(skillsRoot, id, "SKILL.md"));
166
+ if (head === null)
167
+ continue;
168
+ const frontmatter = readFrontmatter(head);
169
+ const description = frontmatter.description?.trim() ?? "";
170
+ if (frontmatter.name !== id || description === "")
171
+ continue;
172
+ if (implicitInvocationDisabled(join(skillsRoot, id)))
173
+ continue;
174
+ catalog.push({ id, description: Array.from(description).slice(0, JEV_MAX_DESCRIPTION_CHARS).join("") });
175
+ }
176
+ return catalog;
177
+ }
178
+ /** Why this turn gets no Jev request, or null when it is eligible. Pure. */
179
+ export function jevSkipReason(prompt, catalogIds = new Set()) {
180
+ if (/^\s*\//u.test(prompt))
181
+ return "slash-command";
182
+ for (const mention of prompt.matchAll(/(?:^|\s)\$([A-Za-z0-9_-]+)(:[A-Za-z0-9_-]+)?/gu)) {
183
+ if (mention[2] !== undefined || catalogIds.has((mention[1] ?? "").toLowerCase()))
184
+ return "skill-mention";
185
+ }
186
+ if (matchLitTrigger(prompt) !== null ||
187
+ matchRenamedSkillInvocation(maskMarkdownCode(prompt), Number.POSITIVE_INFINITY) !== null ||
188
+ isExactBareHandoffPrompt(prompt) ||
189
+ isExactBareScientificVisualizationPrompt(prompt) ||
190
+ isExactBrowserDrivePrompt(prompt)) {
191
+ return "routed";
192
+ }
193
+ if (Array.from(prompt.replace(/\s+/gu, "")).length < 4)
194
+ return "too-short";
195
+ return null;
196
+ }
197
+ export function buildJevRequestBody(model, state, catalog) {
198
+ const criteria = {};
199
+ for (const entry of catalog)
200
+ criteria[entry.id] = entry.description;
201
+ criteria["none"] = NONE_CRITERION;
202
+ return { model, state, questions: { which: { type: "choice", instructions: QUESTION_INSTRUCTIONS, criteria } } };
203
+ }
204
+ function isRecord(value) {
205
+ return typeof value === "object" && value !== null && !Array.isArray(value);
206
+ }
207
+ /** Validate an already-parsed response against the ids that were sent. Nothing else is trusted. */
208
+ export function judgeJevResponse(parsed, catalogIds, minConfidence) {
209
+ const answers = isRecord(parsed) ? parsed["answers"] : undefined;
210
+ const which = isRecord(answers) ? answers["which"] : undefined;
211
+ if (!isRecord(which))
212
+ return { kind: "rejected" };
213
+ const choice = which["choice"];
214
+ const confidence = which["confidence"];
215
+ if (typeof choice !== "string" || (choice !== "none" && !catalogIds.has(choice)))
216
+ return { kind: "rejected" };
217
+ if (typeof confidence !== "number" || !Number.isFinite(confidence))
218
+ return { kind: "rejected" };
219
+ if (choice === "none")
220
+ return { kind: "none", confidence };
221
+ if (confidence < minConfidence)
222
+ return { kind: "low-confidence", choice, confidence };
223
+ return { kind: "hint", skillId: choice, confidence };
224
+ }
225
+ export function jevHintLine(skillId) {
226
+ return `LitCodex skill hint: the skill \`litcodex:${skillId}\` likely fits this request. Load it only if it really fits; this is advice, not an instruction.`;
227
+ }
228
+ /** The opt-in (`LITCODEX_JEV_SHOW=1`) visible line for a hinted turn: skill id and latency only. */
229
+ export function jevShowLine(skillId, latencyMs) {
230
+ return `Jev → ${skillId} (${(latencyMs / 1000).toFixed(2)}s)`;
231
+ }
232
+ /** Once-per-session awareness banner. Plain text: Codex renders hook systemMessage control characters literally. */
233
+ export const JEV_ON_BANNER = "✦ Jev skill hint ON";
234
+ export function jevFallbackNote(reason) {
235
+ return `LitCodex skill hint unavailable (${reason}); continuing normally.`;
236
+ }
237
+ class JevResponseTooLargeError extends Error {
238
+ }
239
+ async function readCappedBody(response) {
240
+ const reader = response.body?.getReader();
241
+ if (reader === undefined)
242
+ return "";
243
+ const chunks = [];
244
+ let total = 0;
245
+ for (;;) {
246
+ const { done, value } = await reader.read();
247
+ if (done)
248
+ break;
249
+ total += value.byteLength;
250
+ if (total > JEV_MAX_BODY_BYTES) {
251
+ await reader.cancel().catch(() => undefined);
252
+ throw new JevResponseTooLargeError();
253
+ }
254
+ chunks.push(value);
255
+ }
256
+ return Buffer.concat(chunks).toString("utf8");
257
+ }
258
+ export const fetchJevHttpClient = async (url, request) => {
259
+ const response = await fetch(url, {
260
+ method: request.method,
261
+ headers: request.headers,
262
+ body: request.body,
263
+ signal: request.signal,
264
+ redirect: "error",
265
+ });
266
+ return { status: response.status, text: () => readCappedBody(response) };
267
+ };
268
+ function sessionStatePath(repoRoot, sessionId) {
269
+ if (!isAbsolute(repoRoot))
270
+ return null;
271
+ return join(repoRoot, JEV_STATE_DIR, `${normalizeSessionId(sessionId) ?? "unscoped"}.json`);
272
+ }
273
+ function readSessionState(path) {
274
+ try {
275
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
276
+ if (isRecord(parsed) && typeof parsed["calls"] === "number" && typeof parsed["noted"] === "boolean") {
277
+ return { version: 1, calls: parsed["calls"], noted: parsed["noted"], announced: parsed["announced"] === true };
278
+ }
279
+ }
280
+ catch {
281
+ // Missing or malformed state starts a fresh session record.
282
+ }
283
+ return { version: 1, calls: 0, noted: false, announced: false };
284
+ }
285
+ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
286
+ /**
287
+ * Create `.litcodex/jev` one level at a time. False when either level is a symlink or not a directory,
288
+ * so a checked-in link can never redirect state or trace writes elsewhere.
289
+ */
290
+ function ensureStateDir(dir) {
291
+ for (const level of [dirname(dir), dir]) {
292
+ try {
293
+ if (!lstatSync(level).isDirectory())
294
+ return false;
295
+ }
296
+ catch {
297
+ try {
298
+ mkdirSync(level);
299
+ }
300
+ catch {
301
+ return false;
302
+ }
303
+ }
304
+ }
305
+ return true;
306
+ }
307
+ /** False when `path` exists as anything but a regular file (a symlink included). */
308
+ function isRegularOrAbsent(path) {
309
+ return lstatSync(path, { throwIfNoEntry: false })?.isFile() ?? true;
310
+ }
311
+ function writeSessionState(path, state) {
312
+ if (!ensureStateDir(dirname(path)))
313
+ return false;
314
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
315
+ try {
316
+ if (!isRegularOrAbsent(path))
317
+ return false;
318
+ const fd = openSync(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | NO_FOLLOW);
319
+ try {
320
+ writeSync(fd, `${JSON.stringify(state)}\n`);
321
+ }
322
+ finally {
323
+ closeSync(fd);
324
+ }
325
+ renameSync(tmp, path);
326
+ return true;
327
+ }
328
+ catch {
329
+ try {
330
+ unlinkSync(tmp);
331
+ }
332
+ catch {
333
+ // Nothing was created.
334
+ }
335
+ return false;
336
+ }
337
+ }
338
+ function writeTrace(repoRoot, env, now, record) {
339
+ if (env[`${JEV_FLAG_ENV}_TRACE`] !== "1" || !isAbsolute(repoRoot))
340
+ return;
341
+ try {
342
+ const path = join(repoRoot, JEV_STATE_DIR, "trace.jsonl");
343
+ if (!ensureStateDir(dirname(path)) || !isRegularOrAbsent(path))
344
+ return;
345
+ const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | NO_FOLLOW);
346
+ try {
347
+ writeSync(fd, `${JSON.stringify({ ts: new Date(now()).toISOString(), ...record })}\n`);
348
+ }
349
+ finally {
350
+ closeSync(fd);
351
+ }
352
+ }
353
+ catch {
354
+ // The trace is an optional debug aid; a write failure never affects the turn.
355
+ }
356
+ }
357
+ // ── Settings ─────────────────────────────────────────────────────────────────
358
+ function positiveInt(raw, fallback) {
359
+ const value = raw === undefined ? Number.NaN : Number(raw.trim());
360
+ return Number.isInteger(value) && value > 0 ? value : fallback;
361
+ }
362
+ function nonNegativeInt(raw, fallback) {
363
+ const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw.trim());
364
+ return Number.isInteger(value) && value >= 0 ? value : fallback;
365
+ }
366
+ function unitInterval(raw, fallback) {
367
+ const value = raw === undefined || raw.trim() === "" ? Number.NaN : Number(raw.trim());
368
+ return Number.isFinite(value) && value >= 0 && value <= 1 ? value : fallback;
369
+ }
370
+ function modelName(raw) {
371
+ const value = raw?.trim() ?? "";
372
+ return /^[A-Za-z0-9._:-]{1,64}$/.test(value) ? value : JEV_DEFAULT_MODEL;
373
+ }
374
+ const NOTHING = Object.freeze({});
375
+ async function exchange(http, key, body, timeoutMs) {
376
+ const controller = new AbortController();
377
+ let timer;
378
+ const timeout = new Promise((resolve) => {
379
+ timer = setTimeout(() => {
380
+ controller.abort();
381
+ resolve({ kind: "failed", reason: "timeout" });
382
+ }, timeoutMs);
383
+ });
384
+ const call = (async () => {
385
+ try {
386
+ const response = await http(JEV_ENDPOINT, {
387
+ method: "POST",
388
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json", accept: "application/json" },
389
+ body,
390
+ signal: controller.signal,
391
+ });
392
+ if (response.status !== 200)
393
+ return { kind: "response", status: response.status, body: null };
394
+ const text = await response.text();
395
+ if (Buffer.byteLength(text, "utf8") > JEV_MAX_BODY_BYTES)
396
+ return { kind: "failed", reason: "response-too-large" };
397
+ return { kind: "response", status: 200, body: text };
398
+ }
399
+ catch (error) {
400
+ if (controller.signal.aborted)
401
+ return { kind: "failed", reason: "timeout" };
402
+ return {
403
+ kind: "failed",
404
+ reason: error instanceof JevResponseTooLargeError ? "response-too-large" : "network",
405
+ };
406
+ }
407
+ })();
408
+ try {
409
+ return await Promise.race([call, timeout]);
410
+ }
411
+ finally {
412
+ clearTimeout(timer);
413
+ }
414
+ }
415
+ /**
416
+ * Decide the optional hint for one UserPromptSubmit turn. Never throws; every failure resolves to at
417
+ * most one visible fallback note per session and otherwise to nothing.
418
+ */
419
+ export async function runJevSkillHint(input) {
420
+ const { env, repoRoot } = input;
421
+ const now = input.now ?? Date.now;
422
+ const switchState = jevSwitchState(env);
423
+ if (switchState === "off")
424
+ return NOTHING;
425
+ if (jevSkipReason(input.prompt) !== null)
426
+ return NOTHING;
427
+ const statePath = sessionStatePath(repoRoot, input.sessionId);
428
+ if (statePath === null)
429
+ return NOTHING;
430
+ const session = readSessionState(statePath);
431
+ const fail = (reason, record) => {
432
+ writeTrace(repoRoot, env, now, { ...record, fallback: reason });
433
+ if (session.noted)
434
+ return NOTHING;
435
+ const current = readSessionState(statePath);
436
+ if (!writeSessionState(statePath, { ...current, noted: true }))
437
+ return NOTHING;
438
+ return { systemMessage: jevFallbackNote(reason) };
439
+ };
440
+ const blank = { promptSha256: "", choice: null, confidence: null, latencyMs: null, httpStatus: null };
441
+ const catalog = loadJevCatalog(input.skillsRoot);
442
+ const catalogIds = new Set(catalog.map((entry) => entry.id));
443
+ if (jevSkipReason(input.prompt, catalogIds) !== null)
444
+ return NOTHING;
445
+ if (switchState !== "on")
446
+ return fail("key-missing", blank);
447
+ if (catalog.length === 0)
448
+ return fail("catalog-unavailable", blank);
449
+ if (session.calls >= nonNegativeInt(env[`${JEV_FLAG_ENV}_MAX_CALLS`], JEV_DEFAULT_MAX_CALLS)) {
450
+ return fail("cap-reached", blank);
451
+ }
452
+ const key = env[JEV_KEY_ENV]?.trim() ?? "";
453
+ const state = redactJevPrompt(input.prompt, key);
454
+ const promptSha256 = createHash("sha256").update(state).digest("hex");
455
+ const body = JSON.stringify(buildJevRequestBody(modelName(env[`${JEV_FLAG_ENV}_MODEL`]), state, catalog));
456
+ if (Buffer.byteLength(body, "utf8") > JEV_MAX_BODY_BYTES)
457
+ return fail("request-too-large", { ...blank, promptSha256 });
458
+ // Count the call before sending it, so a state write failure can never lift the per-session cap.
459
+ if (!writeSessionState(statePath, { ...session, calls: session.calls + 1 }))
460
+ return NOTHING;
461
+ const timeoutMs = Math.min(positiveInt(env[`${JEV_FLAG_ENV}_TIMEOUT_MS`], JEV_DEFAULT_TIMEOUT_MS), JEV_MAX_TIMEOUT_MS);
462
+ const started = now();
463
+ const result = await exchange(input.http ?? fetchJevHttpClient, key, body, timeoutMs);
464
+ const latencyMs = Math.max(0, now() - started);
465
+ const sent = { ...blank, promptSha256, latencyMs };
466
+ if (result.kind === "failed")
467
+ return fail(result.reason, sent);
468
+ if (result.status !== 200 || result.body === null) {
469
+ return fail(`http-${result.status}`, { ...sent, httpStatus: result.status });
470
+ }
471
+ let parsed;
472
+ try {
473
+ parsed = JSON.parse(result.body);
474
+ }
475
+ catch {
476
+ return fail("invalid-json", { ...sent, httpStatus: 200 });
477
+ }
478
+ const minConfidence = unitInterval(env[`${JEV_FLAG_ENV}_MIN_CONFIDENCE`], JEV_DEFAULT_MIN_CONFIDENCE);
479
+ const verdict = judgeJevResponse(parsed, catalogIds, minConfidence);
480
+ const choice = verdict.kind === "hint" ? verdict.skillId : verdict.kind === "none" ? "none" : null;
481
+ const confidence = verdict.kind === "rejected" ? null : verdict.confidence;
482
+ writeTrace(repoRoot, env, now, { ...sent, httpStatus: 200, choice, confidence, fallback: null });
483
+ if (verdict.kind !== "hint")
484
+ return NOTHING;
485
+ const additionalContext = jevHintLine(verdict.skillId);
486
+ if (env[`${JEV_FLAG_ENV}_SHOW`] !== "1")
487
+ return { additionalContext };
488
+ return { additionalContext, systemMessage: jevShowLine(verdict.skillId, latencyMs) };
489
+ }
490
+ /**
491
+ * The once-per-session banner, or null. Only when the hint is fully on (flag and key); it is claimed in
492
+ * the session state before it is shown, so a state write failure shows nothing rather than repeating.
493
+ */
494
+ export function claimJevOnBanner(repoRoot, sessionId, env) {
495
+ if (jevSwitchState(env) !== "on")
496
+ return null;
497
+ const statePath = sessionStatePath(repoRoot, sessionId);
498
+ if (statePath === null)
499
+ return null;
500
+ const session = readSessionState(statePath);
501
+ if (session.announced)
502
+ return null;
503
+ return writeSessionState(statePath, { ...session, announced: true }) ? JEV_ON_BANNER : null;
504
+ }
505
+ /** Put the banner (when claimed) on its own line ahead of any other visible Jev line. */
506
+ export function withJevBanner(result, banner) {
507
+ if (banner === null)
508
+ return result;
509
+ const systemMessage = result.systemMessage === undefined ? banner : `${banner}\n${result.systemMessage}`;
510
+ return { ...result, systemMessage };
511
+ }
512
+ /** Codex UserPromptSubmit output for a hint and/or visible line; "" when there is nothing to say. */
513
+ export function formatJevHookOutput(result) {
514
+ if (result.additionalContext === undefined && result.systemMessage === undefined)
515
+ return "";
516
+ return `${JSON.stringify({
517
+ ...(result.systemMessage === undefined ? {} : { systemMessage: result.systemMessage }),
518
+ ...(result.additionalContext === undefined
519
+ ? {}
520
+ : { hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: result.additionalContext } }),
521
+ })}\n`;
522
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lit-loop",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex Lit-Loop runtime: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/lsp",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex LSP hook (inert placeholder): post-edit diagnostics + cache reset, no-op until an LSP daemon is provided.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/rules",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex rules: injects project rule files (AGENTS.md etc.) into model context through lifecycle hooks.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/start-work-continuation",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex Start-Work continuation hook: resumes in-flight start-work state on root Stop.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/telemetry",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "LitCodex telemetry: a deliberately inert, local-only SessionStart hook (NO network, NO data collection).",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@litcodex/wikify-knowledge",
3
- "version": "1.0.7",
3
+ "version": "1.0.8",
4
4
  "description": "Local review-gated knowledge records for the LitCodex Wikify surface.",
5
5
  "type": "module",
6
6
  "private": true,
@@ -1,3 +1,4 @@
1
+ import { type JevHttpClient } from "./jev-hint.js";
1
2
  /** Hard cap on stdin to bound memory / ReDoS exposure inside the 5 s Codex hook budget. 8 MB. */
2
3
  export declare const MAX_STDIN_BYTES = 8000000;
3
4
  /** Machine-readable error envelope emitted to stderr on a NON-zero exit. */
@@ -14,7 +15,13 @@ export type LitHookErrorCode = "LIT_HOOK_STDIN_INVALID_JSON" | "LIT_HOOK_STDIN_T
14
15
  * NEVER throws. Writes the camelCase activation line to stdout (empty on no-op), or a LitHookError
15
16
  * line to stderr on malformed / oversized stdin.
16
17
  */
17
- export declare function runUserPromptSubmitHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string): Promise<number>;
18
+ export declare function runUserPromptSubmitHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string, jev?: JevHookOptions): Promise<number>;
19
+ /** Injectable Jev dependencies; production uses the process environment and built-in `fetch`. */
20
+ export interface JevHookOptions {
21
+ readonly env?: NodeJS.ProcessEnv;
22
+ readonly http?: JevHttpClient;
23
+ readonly skillsRoot?: string;
24
+ }
18
25
  /** Enforce lit-plan persistence when a Stop hook event arrives. */
19
26
  export declare function runStopPlanPersistenceHookCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream, repoRoot?: string): Promise<number>;
20
27
  export declare function runPreToolUseCreateGoalGuardCli(stdin: NodeJS.ReadableStream, stdout: NodeJS.WritableStream, stderr: NodeJS.WritableStream): Promise<number>;
@@ -5,9 +5,12 @@
5
5
  // hands the parsed value to the pure engine, and writes the decision. Exit map: any structurally
6
6
  // valid event → 0 (no-op writes zero bytes); unparseable or oversized stdin → 2 with a
7
7
  // machine-readable LitHookError JSON line on stderr. NEVER calls process.exit (the dispatcher does)
8
- // and NEVER throws.
8
+ // and NEVER throws. A UserPromptSubmit turn the router leaves alone may carry the opt-in Jev skill
9
+ // hint (./jev-hint.ts) and, once per session while it is on, a plain-text banner; with its switch
10
+ // off, that path makes no request and writes nothing.
9
11
  import { isAbsolute } from "node:path";
10
- import { applyPreToolUseCreateGoalGuard, runUserPromptSubmitHook } from "./codex-hook.js";
12
+ import { applyPreToolUseCreateGoalGuard, isLitUserPromptSubmitInput, runUserPromptSubmitHook } from "./codex-hook.js";
13
+ import { claimJevOnBanner, formatJevHookOutput, jevSwitchState, runJevSkillHint, withJevBanner, } from "./jev-hint.js";
11
14
  import { evaluatePlanPersistence, formatStopBlockOutput, recordLitPlanActivation } from "./plan-persistence.js";
12
15
  /** Hard cap on stdin to bound memory / ReDoS exposure inside the 5 s Codex hook budget. 8 MB. */
13
16
  export const MAX_STDIN_BYTES = 8_000_000;
@@ -66,7 +69,7 @@ function readStdin(stdin) {
66
69
  * NEVER throws. Writes the camelCase activation line to stdout (empty on no-op), or a LitHookError
67
70
  * line to stderr on malformed / oversized stdin.
68
71
  */
69
- export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot = process.cwd()) {
72
+ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot = process.cwd(), jev = {}) {
70
73
  const decoded = await readStdin(stdin);
71
74
  if (decoded === null) {
72
75
  stderr.write(errorLine("LIT_HOOK_STDIN_TOO_LARGE", TOO_LARGE_MESSAGE));
@@ -94,10 +97,39 @@ export async function runUserPromptSubmitHookCli(stdin, stdout, stderr, repoRoot
94
97
  if (scope !== null)
95
98
  recordLitPlanActivation(scope.cwd, scope.sessionId);
96
99
  }
97
- if (decision.kind === "inject")
100
+ if (decision.kind === "inject") {
98
101
  stdout.write(decision.stdout);
102
+ return 0;
103
+ }
104
+ const hint = await jevHintOutput(parsed, repoRoot, jev);
105
+ if (hint !== "")
106
+ stdout.write(hint);
99
107
  return 0;
100
108
  }
109
+ /** Optional Jev skill hint for a turn the deterministic router left alone. Never throws. */
110
+ async function jevHintOutput(parsed, repoRoot, options) {
111
+ const env = options.env ?? process.env;
112
+ if (jevSwitchState(env) === "off" || !isLitUserPromptSubmitInput(parsed))
113
+ return "";
114
+ const record = parsed;
115
+ const sessionId = typeof record["session_id"] === "string" ? record["session_id"] : null;
116
+ const cwd = typeof record["cwd"] === "string" && isAbsolute(record["cwd"]) ? record["cwd"] : repoRoot;
117
+ try {
118
+ const banner = claimJevOnBanner(cwd, sessionId, env);
119
+ const result = await runJevSkillHint({
120
+ prompt: parsed.prompt,
121
+ sessionId,
122
+ repoRoot: cwd,
123
+ env,
124
+ ...(options.http === undefined ? {} : { http: options.http }),
125
+ ...(options.skillsRoot === undefined ? {} : { skillsRoot: options.skillsRoot }),
126
+ });
127
+ return formatJevHookOutput(withJevBanner(result, banner));
128
+ }
129
+ catch {
130
+ return "";
131
+ }
132
+ }
101
133
  /** Read `{ session_id, cwd }` from a hook event; `cwd` falls back to `repoRoot` when absent or relative. */
102
134
  function hookSessionScope(parsed, repoRoot) {
103
135
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))