prism-mcp-server 20.21.3 → 20.21.4

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.
@@ -30,7 +30,7 @@ import { getEntitlements, clampCeiling, multiTurnPolicy, ABSOLUTE_MULTI_TURN } f
30
30
  import { ddLog } from "../utils/ddLogger.js";
31
31
  import { stripThink } from "../utils/thinkStrip.js";
32
32
  import { passesQualityGate } from "../utils/qualityGate.js";
33
- import { passesClinicalQualityGate, formatClinicalSections, } from "../utils/clinicalQualityPolicy.js";
33
+ import { passesClinicalQualityGate, clinicalPlanScaffold, formatClinicalSections, } from "../utils/clinicalQualityPolicy.js";
34
34
  import { applyDeterministicCodingRepairs, buildCodingRepairPrompt, passesCodingQualityGate, } from "../utils/codingQualityPolicy.js";
35
35
  import { checkInputSafety, checkOutputSafety } from "../utils/safetyGate.js";
36
36
  import { callLayer1 as defaultCallLayer1, classifyDeterministicLayer1, keywordBackstop, reservedCategory, MAX_CLASSIFIER_PROMPT_LENGTH } from "../utils/layer1.js";
@@ -2018,9 +2018,13 @@ export async function runInfer(args, deps) {
2018
2018
  // their own — never override an explicit instruction.
2019
2019
  // `=== undefined`, not falsy: `system: ""` is a caller explicitly asking
2020
2020
  // for no system prompt, and overriding that is still an override.
2021
- const effectiveSystem = (resolvedImages?.length ?? 0) > 0 && args.system === undefined
2022
- ? VISION_SYSTEM_PROMPT
2023
- : args.system;
2021
+ // A caller's own `system` always wins, including `system: ""`, which is an
2022
+ // explicit request for none. Defaults apply only when it is undefined.
2023
+ const defaultSystem = [
2024
+ (resolvedImages?.length ?? 0) > 0 ? VISION_SYSTEM_PROMPT : undefined,
2025
+ clinicalPlanScaffold(args.prompt),
2026
+ ].filter(Boolean).join("\n\n") || undefined;
2027
+ const effectiveSystem = args.system === undefined ? defaultSystem : args.system;
2024
2028
  // Walk order for images.
2025
2029
  //
2026
2030
  // Smallest-first was tried and REVERTED on 2026-08-15. It is correct
@@ -2299,7 +2303,8 @@ export async function runInfer(args, deps) {
2299
2303
  const codingGateFailure = !gate.pass &&
2300
2304
  mode === "code" &&
2301
2305
  (gate.reason?.startsWith("code_") === true ||
2302
- gate.reason?.startsWith("python_") === true);
2306
+ gate.reason?.startsWith("python_") === true ||
2307
+ gate.reason?.startsWith("ts_") === true);
2303
2308
  if (!codingGateFailure)
2304
2309
  break;
2305
2310
  const failedReason = gate.reason ?? "code_quality";
@@ -36,16 +36,16 @@ const OPERATIONAL_DEFINITION_REQUEST_RE = /\boperational(?:ly)?[ -]?(?:defin\w*)
36
36
  const CLINICAL_CONTEXT_RE = /\b(aba\b|bcba\b|behaviou?r analyst|functional behaviou?r assessment|\bfba\b|\bbip\b|replacement behaviou?r|target behaviou?r|reinforcement schedule|\bfct\b|\bdro\b|\bdra\b|\bncr\b)/i;
37
37
  /** Ordered so the report reads the way a plan is written. */
38
38
  const PLAN_SECTIONS = [
39
- { name: "operational_definition", pattern: /operational(?:ly)?[ -]?defin|\bdefinition\b[\s\S]{0,80}\b(observable|measurable)\b/i },
40
- { name: "function_hypothesis", pattern: /\b(hypothesi[sz]ed function|function of the behaviou?r|maintained by|\ba-?b-?c\b|antecedent[\s\S]{0,40}consequence)\b/i },
41
- { name: "antecedent_strategies", pattern: /\b(antecedent (?:strateg|modificat|intervention)|prevention strateg|setting event|environmental modificat)/i },
42
- { name: "replacement_behaviour", pattern: /\b(replacement behaviou?r|functional communication training|\bfct\b|alternative behaviou?r|\bdra\b)/i },
43
- { name: "consequence_strategies", pattern: /\b(consequence (?:strateg|procedure)|reinforcement (?:schedule|procedure|strateg)|\bdro\b|\bncr\b|extinction)/i },
44
- { name: "data_collection", pattern: /\b(data collection|data sheet|measurement (?:system|procedure)|frequency count|partial interval|momentary time sampling|\bioa\b|interobserver)/i },
45
- { name: "decision_rules", pattern: /\b(decision rule|mastery criteri|criteri\w+ for (?:change|modificat|advancement)|review (?:schedule|trigger)|plan review)/i },
46
- { name: "generalisation_maintenance", pattern: /\b(generali[sz]|maintenance)\b/i },
47
- { name: "caregiver_training", pattern: /\b((?:caregiver|staff|parent|family)[ -]?training|train(?:ing)? (?:the )?(?:caregivers?|staff|parents?))/i },
48
- { name: "bcba_review_disclaimer", pattern: /\b(reviewed and individuali[sz]ed|credentialed bcba|licensed behaviou?r analyst|must be reviewed)\b/i },
39
+ { name: "operational_definition", requirement: "an operational definition that is observable and measurable, with examples AND non-examples", pattern: /operational(?:ly)?[ -]?defin|\bdefinition\b[\s\S]{0,80}\b(observable|measurable)\b/i },
40
+ { name: "function_hypothesis", requirement: "a hypothesised function supported by A-B-C data", pattern: /\b(hypothesi[sz]ed function|function of the behaviou?r|maintained by|\ba-?b-?c\b|antecedent[\s\S]{0,40}consequence)\b/i },
41
+ { name: "antecedent_strategies", requirement: "antecedent and prevention strategies", pattern: /\b(antecedent (?:strateg|modificat|intervention|procedure|support)|prevention strateg|proactive strateg|pre-?work strateg|pre-?correct|setting event|environmental modificat|visual (?:schedule|timer|cue)|priming)/i },
42
+ { name: "replacement_behaviour", requirement: "a functionally equivalent replacement behaviour", pattern: /\b(replacement behaviou?r|functional communication training|\bfct\b|alternative behaviou?r|\bdra\b)/i },
43
+ { name: "consequence_strategies", requirement: "consequence strategies, including what reinforces the replacement", pattern: /\b(consequence|reinforcement (?:schedule|procedure|strateg|plan|system|for\b)|reinforc\w+ the (?:replacement|desired|appropriate|target)|planned ignoring|response to (?:the )?behaviou?r|redirect\w*|\bpraise\b|\bdro\b|\bncr\b|extinction)/i },
44
+ { name: "data_collection", requirement: "a data collection method", pattern: /\b(data collection|data sheet|measurement (?:system|procedure)|frequency count|partial interval|momentary time sampling|\bioa\b|interobserver)/i },
45
+ { name: "decision_rules", requirement: "decision rules and a review schedule", pattern: /\b(decision rule|mastery criteri|criteri\w+ for (?:change|modificat|advancement)|evaluation criteri|review (?:schedule|trigger|date)|plan review|progress monitor\w*|plan will be (?:adjusted|modified|revised|changed))/i },
46
+ { name: "generalisation_maintenance", requirement: "generalisation and maintenance", pattern: /\b(generali[sz]|maintenance)\b/i },
47
+ { name: "caregiver_training", requirement: "caregiver and staff training", pattern: /\b((?:caregiver|staff|parent|family|teacher|team)[ -]?training|train(?:ing|ed)? (?:the )?(?:caregivers?|staff|parents?|team)|(?:staff|caregivers?|parents?|team|teachers?)\b[^.\n]{0,30}\btrain\w+|train\w+ on the plan)/i },
48
+ { name: "bcba_review_disclaimer", requirement: "a statement that a credentialed BCBA must review and individualise the plan before implementation", pattern: /\b(reviewed and individuali[sz]ed|credentialed bcba|licensed behaviou?r analyst|must be reviewed)\b/i },
49
49
  ];
50
50
  /**
51
51
  * AAC access may never be removed, withheld or delayed as a consequence.
@@ -102,6 +102,58 @@ function aacRestrictedAsConsequence(output) {
102
102
  }
103
103
  return false;
104
104
  }
105
+ /** Characters of real prose required near a section marker for it to count. */
106
+ const SECTION_CONTENT_CHARS = 30;
107
+ const SECTION_WINDOW = 400;
108
+ /** Drop whole heading lines. Stripping only the `#` turns the NEXT heading into
109
+ * prose, which is why ten empty headings first scored 8 of 10. */
110
+ function proseOnly(text) {
111
+ return text
112
+ .split("\n")
113
+ .filter(line => !/^\s*#{1,6}\s/.test(line)) // markdown headings
114
+ .filter(line => !/^\s*\*\*[^*]+\*\*\s*:?\s*$/.test(line)) // bold-only lines
115
+ .join(" ")
116
+ .replace(/[>#*_|]+/g, "")
117
+ .replace(/\[[^\]]*\]/g, "") // [placeholders]
118
+ .replace(/[-\s]+/g, " ")
119
+ .trim();
120
+ }
121
+ /**
122
+ * A section counts only when there is real prose NEAR its marker.
123
+ *
124
+ * Without this, ten empty headings scored 8 of 10: an output with no clinical
125
+ * content looked nearly complete, because the census matched vocabulary rather
126
+ * than substance. The scaffold already demands "substantive content rather than
127
+ * a heading alone"; this is the census checking the same thing.
128
+ *
129
+ * The window spans both directions. A first version looked only forward and
130
+ * dropped a legitimate credit — "we will write down how often it happens on a
131
+ * data sheet" puts the content BEFORE the keyword.
132
+ *
133
+ * Two limits, both measured rather than assumed.
134
+ *
135
+ * The window is wide, so in a dense document a marker finds prose belonging to
136
+ * a NEIGHBOURING section and is credited for it. This is therefore closer to a
137
+ * document-level check than a per-section one; what it reliably catches is the
138
+ * empty or near-empty output, which is what it was added for.
139
+ *
140
+ * And a model that echoes the section list back as prose still scores full
141
+ * marks, because a description of what a plan must contain is, at this level of
142
+ * analysis, indistinguishable from a plan. That is a limit of the approach, not
143
+ * something to regex away, and one more reason nothing here is an endorsement.
144
+ *
145
+ * The floor is deliberately low. At 50 characters a legitimately terse section
146
+ * — "Frequency count / Daily tally / Weekly IOA" — was refused, and a false
147
+ * negative on real content is the more expensive error for a gap report.
148
+ */
149
+ function sectionHasContent(output, pattern) {
150
+ const m = new RegExp(pattern.source, pattern.flags.replace("g", "")).exec(output);
151
+ if (!m)
152
+ return false;
153
+ const at = m.index ?? 0;
154
+ const window = output.slice(Math.max(0, at - SECTION_WINDOW), at + m[0].length + SECTION_WINDOW);
155
+ return proseOnly(window).length >= SECTION_CONTENT_CHARS;
156
+ }
105
157
  /**
106
158
  * Raise-only structural check. `pass: true` means nothing was detected as
107
159
  * missing — it is not a clinical endorsement.
@@ -127,7 +179,9 @@ export function passesClinicalQualityGate(prompt, output) {
127
179
  }
128
180
  if (!CLINICAL_PLAN_REQUEST_RE.test(prompt))
129
181
  return { pass: true };
130
- const missing = PLAN_SECTIONS.filter(s => !s.pattern.test(output)).map(s => s.name);
182
+ const missing = PLAN_SECTIONS
183
+ .filter(s => !sectionHasContent(output, s.pattern))
184
+ .map(s => s.name);
131
185
  const sections = {
132
186
  required: PLAN_SECTIONS.length,
133
187
  present: PLAN_SECTIONS.length - missing.length,
@@ -150,3 +204,42 @@ export function formatClinicalSections(s) {
150
204
  const base = `clinical_sections=${s.present}/${s.required}`;
151
205
  return s.missing.length ? `${base} missing:${s.missing.join(",")}` : base;
152
206
  }
207
+ /**
208
+ * A system instruction naming every section a plan must contain, generated from
209
+ * PLAN_SECTIONS so the list that INSTRUCTS is the list that VERIFIES.
210
+ *
211
+ * Measured on prism-coder:9b: the same plan request scored 7/10 unscaffolded and
212
+ * 10/10 scaffolded, in FEWER characters — it restructured rather than padded,
213
+ * and the previously absent sections came back with substantive content
214
+ * (a real observable definition with non-examples, real generalisation content,
215
+ * a correctly worded review statement).
216
+ *
217
+ * KNOWN EPISTEMIC COST, recorded rather than hidden: once the model is told the
218
+ * list, the census stops being independent confirmation and becomes a check
219
+ * that the instruction was followed. A scaffolded 10/10 is weaker evidence than
220
+ * an unscaffolded one. Sharing one list is still the right trade — two lists
221
+ * drift, and a census that disagrees with the instruction is worse than a
222
+ * census that merely confirms it — but nothing here should be read as evidence
223
+ * that the model knows what a plan needs.
224
+ *
225
+ * LOCAL ONLY. `callCloud` takes the prompt and no system argument, so nothing
226
+ * here reaches an escalated request — true of VISION_SYSTEM_PROMPT as well, and
227
+ * pre-existing rather than introduced with this scaffold. The consequence is
228
+ * that a cloud-served plan is measured by the census WITHOUT having been given
229
+ * the list, so it can score lower than a local one for reasons that have
230
+ * nothing to do with the model. Threading `system` through the portal API is
231
+ * the real fix and is deliberately out of scope here.
232
+ *
233
+ * Returns undefined unless a full plan was requested, so it never touches the
234
+ * prompt for ordinary work.
235
+ */
236
+ export function clinicalPlanScaffold(prompt) {
237
+ if (!CLINICAL_PLAN_REQUEST_RE.test(prompt))
238
+ return undefined;
239
+ const items = PLAN_SECTIONS.map(s => `- ${s.requirement}`).join("\n");
240
+ return ("A behaviour plan must contain all of the following, each with substantive "
241
+ + "content rather than a heading alone:\n" + items
242
+ + "\n\nUse least restrictive, dignity-preserving, function-based procedures. "
243
+ + "Never restrict, remove or delay access to an AAC or communication device "
244
+ + "as a consequence.");
245
+ }
@@ -304,7 +304,98 @@ function pythonStaticContractFailure(code) {
304
304
  ? `python_static_contract:${[...issues].sort().join(",")}`
305
305
  : undefined;
306
306
  }
307
+ /**
308
+ * A generic used with no type argument, e.g. `Map<string, Array>`.
309
+ *
310
+ * prism-coder:9b emits this repeatedly — observed in four separate generations
311
+ * of the same EventEmitter task — and it is a hard compile error (TS2314), so
312
+ * the file never builds. Detecting it needs no TypeScript dependency: the shape
313
+ * is unambiguous when the bare name sits inside a type-argument list or
314
+ * directly after a type annotation.
315
+ *
316
+ * Deliberately narrow. Prose mentioning "the Array, then the Map" must not
317
+ * match, so a bare name is only a finding when it is syntactically in a type
318
+ * position; a bare `Promise` as a lone return type with no delimiter after it
319
+ * is missed, which is the conservative direction.
320
+ */
321
+ const TS_GENERIC = "(?:Array|Map|Set|Promise|Record|Partial|Readonly|WeakMap|WeakSet)";
322
+ const TS_BARE_GENERIC_RE = new RegExp(`<[^<>]*\\b${TS_GENERIC}\\b(?!\\s*<)[^<>]*>` +
323
+ `|:\\s*${TS_GENERIC}\\b(?!\\s*<)\\s*[={;,)\\]]`);
324
+ /** Null when the code carries no TypeScript static-contract defect. */
325
+ function tsStaticContractFailure(code) {
326
+ return TS_BARE_GENERIC_RE.test(code) ? "ts_static_contract:bare_generic" : null;
327
+ }
328
+ /** Character ranges a repair must not touch on one line.
329
+ *
330
+ * Strings, because rewriting `"use Map<string, Array> carefully"` changes a
331
+ * RUNTIME VALUE rather than a type. And comments, because `// don't use a bare
332
+ * Map<string, Array>` is a warning against the very thing the repair would
333
+ * write, so editing it inverts the author's meaning. Both found in review. */
334
+ function protectedSpans(line) {
335
+ const spans = [];
336
+ const strings = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`/g;
337
+ for (const m of line.matchAll(strings))
338
+ spans.push([m.index ?? 0, (m.index ?? 0) + m[0].length]);
339
+ // A line comment runs to end of line. An apostrophe in prose ("don't")
340
+ // breaks the string scan, which is how comments slipped through before.
341
+ const comment = /\/\/|\/\*/.exec(line);
342
+ if (comment)
343
+ spans.push([comment.index, line.length]);
344
+ return spans;
345
+ }
346
+ /** Fence languages whose contents are TypeScript. A bare generic inside a
347
+ * python or json block is not a type error to fix — the first version rewrote
348
+ * a comment inside a python block in a multi-language answer. */
349
+ const TS_FENCE_LANG = /^\s*```\s*(ts|typescript|tsx)?\s*$/i;
350
+ /** `Map<string, Array>` -> `Map<string, Array<any>>`, within code only.
351
+ *
352
+ * `any` rather than `unknown` on purpose: `unknown` makes the file compile and
353
+ * then breaks every use of the value, which trades one compile error for
354
+ * several. This makes the code build; it does not make it well typed.
355
+ *
356
+ * Scoped twice, both from adversarial review. Fenced output is repaired only
357
+ * INSIDE its fences, because rewriting the surrounding prose inverts sentences
358
+ * like "do not write Map<string, Array>". And no match inside a string literal
359
+ * is touched, because that is a value, not a type. */
360
+ function repairBareGenerics(code) {
361
+ let changed = false;
362
+ const spanRe = new RegExp(TS_BARE_GENERIC_RE.source, "g");
363
+ const repairLine = (line) => {
364
+ const off_limits = protectedSpans(line);
365
+ return line.replace(spanRe, (span, offset) => {
366
+ if (off_limits.some(([a, b]) => offset >= a && offset < b))
367
+ return span;
368
+ const fixed = span.replace(new RegExp(`\\b(${TS_GENERIC})\\b(?!\\s*<)`, "g"), "$1<any>");
369
+ if (fixed !== span)
370
+ changed = true;
371
+ return fixed;
372
+ });
373
+ };
374
+ const lines = code.split("\n");
375
+ const hasFences = /^\s*```/m.test(code);
376
+ let inFence = false;
377
+ let fenceIsTs = false;
378
+ const out = lines.map((line) => {
379
+ if (/^\s*```/.test(line)) {
380
+ if (!inFence)
381
+ fenceIsTs = TS_FENCE_LANG.test(line);
382
+ inFence = !inFence;
383
+ return line;
384
+ }
385
+ // No fences at all: the whole output is the code block.
386
+ return (!hasFences || (inFence && fenceIsTs)) ? repairLine(line) : line;
387
+ });
388
+ return { code: out.join("\n"), changed };
389
+ }
307
390
  export function applyDeterministicCodingRepairs(output, reason) {
391
+ if (reason.startsWith("ts_static_contract:")) {
392
+ if (!reason.includes("bare_generic"))
393
+ return { output, changes: [] };
394
+ const repaired = repairBareGenerics(output);
395
+ return repaired.changed
396
+ ? { output: repaired.code, changes: ["bare_generic"] }
397
+ : { output, changes: [] };
398
+ }
308
399
  if (!reason.startsWith("python_static_contract:")) {
309
400
  return { output, changes: [] };
310
401
  }
@@ -369,6 +460,9 @@ export function passesCodingQualityGate(prompt, output) {
369
460
  if (pythonFailure)
370
461
  return { pass: false, reason: pythonFailure };
371
462
  }
463
+ const tsFailure = tsStaticContractFailure(code);
464
+ if (tsFailure)
465
+ return { pass: false, reason: tsFailure };
372
466
  return { pass: true };
373
467
  }
374
468
  const CODING_REPAIR_SYSTEM_INSTRUCTION = "Repair the supplied implementation. Return one complete replacement implementation with no prose, " +
@@ -383,6 +477,7 @@ const CODING_REPAIR_GUIDANCE = {
383
477
  python_method_missing_receiver: "Instance methods must take self first; class methods must take cls first unless decorated staticmethod.",
384
478
  python_undefined_private_helper: "Define every directly called private self helper or replace the call with the correct defined helper.",
385
479
  constructor_attribute_missing_receiver: "In __init__, persist instance state as self.<attribute>; do not assign it to a discarded local variable.",
480
+ bare_generic: "Every generic needs its type argument: write Array<T>, Map<K, V>, Set<T>, Promise<T> — never a bare Array, Map, Set or Promise in a type position.",
386
481
  dict_keys_unpack: "When unpacking key and value, iterate dictionary .items(); .keys() yields one key per iteration.",
387
482
  };
388
483
  function repairGuidance(reason) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prism-mcp-server",
3
- "version": "20.21.3",
3
+ "version": "20.21.4",
4
4
  "mcpName": "io.github.dcostenco/prism-coder",
5
5
  "description": "Persistent session memory for AI coding agents that never leaves your machine — including the on-device model that reasons over it. Restores your prior decisions, open TODOs, and changed files across sessions; adds associative recall of related past work, semantic drift detection, and local inference. Local-first by default. Works with Claude Code, Cursor, and Codex.",
6
6
  "module": "index.ts",