prism-mcp-server 20.21.4 → 20.21.5

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.
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
2
2
  const IMPLEMENTATION_REQUEST_RE = /\b(?:implement|write|create|generate|complete|finish|fix)\b[\s\S]{0,160}\b(?:code|source|function|method|class|interface|struct|enum|implementation|algorithm|component|endpoint)\b/i;
3
3
  const STRICT_SOURCE_REQUEST_RE = /\b(?:return|output|respond with)\s+only\s+(?:the\s+)?(?:implementation\s+)?(?:source\s+)?code\b/i;
4
4
  const CODE_SHAPE_RE = /(?:^|\n)\s*(?:(?:export|public|private|protected|internal|open|pub|static|final|abstract|async)\s+)*(?:class|interface|struct|enum|function|def|func|fun|fn|type)\s+[A-Za-z_$][\w$]*|(?:^|\n)\s*(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=|(?:^|\n)\s*(?:[A-Za-z_$][\w$:<>,.?*[\]&]*\s+)+[A-Za-z_$][\w$]*\s*\([^;\n]*\)\s*(?:const\s*)?(?:noexcept\s*)?(?:\{|=>)|=>\s*[{(]/m;
5
+ import { analyzeTypeScript } from "./typescriptDiagnostics.js";
5
6
  export const INCOMPLETE_IMPLEMENTATION_PATTERNS = [
6
7
  {
7
8
  reason: "code_placeholder",
@@ -46,6 +47,8 @@ const PYTHON_AST_SCRIPT = `import ast,sys; print('${PYTHON_READY_SENTINEL}', flu
46
47
  "tree=ast.parse(sys.stdin.read()); compile(tree, '<prism-coding-gate>', 'exec')";
47
48
  const PYTHON_COMMANDS = ["python3", "python"];
48
49
  const PYTHON_CHILDREN_KEYS_UNPACK_RE = /\bfor\s+[A-Za-z_]\w*\s*,\s*child(?:_node)?\s+in\s+(?:sorted\(\s*)?[A-Za-z_][\w.]*\.children\.keys\(\)\s*\)?\s*:/;
50
+ /** Enough of a type-annotation or declaration signal to call a block TypeScript. */
51
+ const TS_SIGNAL_RE = /:\s*(?:string|number|boolean|void|any|unknown|never|Promise<)\b|\binterface\s+[A-Z]|\bexport\s+(?:class|interface|type|abstract)\b|\b(?:private|public|protected|readonly)\s+\w+\s*[:=]|<[A-Z]\w*(?:\s*,\s*[A-Z]\w*)*>/;
49
52
  function extractUnfencedPythonCode(output) {
50
53
  const lines = output.trim().split(/\r?\n/);
51
54
  const start = lines.findIndex((line) => UNFENCED_PYTHON_START_RE.test(line));
@@ -75,9 +78,11 @@ function extractCode(output) {
75
78
  })).filter((block) => block.code.length > 0);
76
79
  if (blocks.length === 0) {
77
80
  const python = extractUnfencedPythonCode(output);
81
+ const bare = output.trim();
78
82
  return {
79
- all: output.trim(),
83
+ all: bare,
80
84
  ...(python ? { python } : {}),
85
+ ...(!python && TS_SIGNAL_RE.test(bare) ? { typescript: bare } : {}),
81
86
  hasFences: false,
82
87
  };
83
88
  }
@@ -86,11 +91,18 @@ function extractCode(output) {
86
91
  block.language === "py" ||
87
92
  (!block.language && PYTHON_SIGNAL_RE.test(block.code))))
88
93
  .map((block) => block.code);
94
+ const tsBlocks = blocks
95
+ .filter((block) => (block.language === "typescript" ||
96
+ block.language === "ts" ||
97
+ block.language === "tsx" ||
98
+ (!block.language && TS_SIGNAL_RE.test(block.code))))
99
+ .map((block) => block.code);
89
100
  return {
90
101
  all: blocks.map((block) => block.code).join("\n\n"),
91
102
  ...(pythonBlocks.length > 0
92
103
  ? { python: pythonBlocks.join("\n\n") }
93
104
  : {}),
105
+ ...(tsBlocks.length > 0 ? { typescript: tsBlocks.join("\n\n") } : {}),
94
106
  hasFences: true,
95
107
  };
96
108
  }
@@ -460,9 +472,18 @@ export function passesCodingQualityGate(prompt, output) {
460
472
  if (pythonFailure)
461
473
  return { pass: false, reason: pythonFailure };
462
474
  }
475
+ // The regex floor runs first: it is the one finding with a deterministic
476
+ // repair, and it works even if the compiler cannot be loaded.
463
477
  const tsFailure = tsStaticContractFailure(code);
464
478
  if (tsFailure)
465
479
  return { pass: false, reason: tsFailure };
480
+ // Then the compiler, over TypeScript blocks only.
481
+ if (extracted.typescript) {
482
+ const findings = analyzeTypeScript(extracted.typescript, extracted.hasFences);
483
+ if (findings.length > 0) {
484
+ return { pass: false, reason: `ts_static_contract:${findings.join(",")}` };
485
+ }
486
+ }
466
487
  return { pass: true };
467
488
  }
468
489
  const CODING_REPAIR_SYSTEM_INSTRUCTION = "Repair the supplied implementation. Return one complete replacement implementation with no prose, " +
@@ -477,6 +498,11 @@ const CODING_REPAIR_GUIDANCE = {
477
498
  python_method_missing_receiver: "Instance methods must take self first; class methods must take cls first unless decorated staticmethod.",
478
499
  python_undefined_private_helper: "Define every directly called private self helper or replace the call with the correct defined helper.",
479
500
  constructor_attribute_missing_receiver: "In __init__, persist instance state as self.<attribute>; do not assign it to a discarded local variable.",
501
+ syntax_error: "The code does not parse. Balance every brace, bracket and parenthesis, and finish every statement.",
502
+ optional_chain_assignment: "Optional chaining cannot appear on the left of an assignment. Guard with an if, or assert the value is present, before assigning to the property.",
503
+ type_not_assignable: "Make the returned value match the declared return type, or widen the declaration to what the implementation actually produces.",
504
+ implicit_any_param: "Annotate every parameter; under strict mode an inferred any is an error.",
505
+ deferred_mutation_returned_sync: "A value mutated inside a then/catch/setTimeout callback is returned before that callback runs. Await the work, or return a Promise that resolves after it.",
480
506
  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.",
481
507
  dict_keys_unpack: "When unpacking key and value, iterate dictionary .items(); .keys() yields one key per iteration.",
482
508
  };
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Real type checking for generated TypeScript, plus one AST rule a type checker
3
+ * cannot express.
4
+ *
5
+ * The regex gate that shipped in 20.21.4 catches exactly one defect class
6
+ * (TS2314, a generic with no type argument). The very next sample defeated it:
7
+ * a doubly-linked-list splice written as `node.next?.prev = this.head`, which is
8
+ * TS2779 and does not compile. Extending the regex per error code is an arms
9
+ * race the compiler already wins.
10
+ *
11
+ * WHY THIS IS NOT JUST `tsc`. A generated snippet has no tsconfig, no resolved
12
+ * imports, and no way to declare whether it targets the DOM or Node. Checking a
13
+ * fragment therefore produces errors about the HARNESS rather than the code.
14
+ * Measured while building this: checking one LRU cache against the DOM lib made
15
+ * the snippet's own `Node` class collide with the DOM's, producing twelve
16
+ * phantom errors beside the two real ones. A gate that fails correct code gets
17
+ * switched off, so the design is an ALLOWLIST: a diagnostic is reported only if
18
+ * its code appears in ALLOWED_CODES. That, and nothing else, is what prevents a
19
+ * context failure from being reported as a defect.
20
+ *
21
+ * Two things that look load-bearing and are not — established by mutation, and
22
+ * recorded so nobody trusts them for safety:
23
+ *
24
+ * IGNORED_CODES does NOT filter anything. It marks codes already triaged as
25
+ * context failures, so the debug log can flag genuinely unclassified ones.
26
+ * Emptying it changes no reported finding.
27
+ *
28
+ * The narrow default library (`lib.es2022.d.ts`, no DOM) is defence in depth,
29
+ * not protection. It was chosen after the DOM lib made a snippet's own `Node`
30
+ * class collide with the DOM's and produce twelve extra diagnostics — but all
31
+ * twelve were outside the allowlist, so none would have been reported anyway.
32
+ * No constructed case makes the library choice change a reported finding. It
33
+ * is kept because less noise and less work are both worth having.
34
+ */
35
+ import { createRequire } from "node:module";
36
+ import { dirname, join } from "node:path";
37
+ import { readFileSync } from "node:fs";
38
+ import { debugLog } from "./logger.js";
39
+ /** Semantic diagnostics that indict the SNIPPET. Each observed on real output. */
40
+ const ALLOWED_CODES = new Map([
41
+ [2314, "bare_generic"], // Map<string, Array>
42
+ [2779, "optional_chain_assignment"], // node.next?.prev = x
43
+ [2322, "type_not_assignable"], // Promise<PromiseSettledResult[]> as Promise<void>
44
+ [7006, "implicit_any_param"], // (listener) => ... under strict — CONDITIONAL, see below
45
+ ]);
46
+ /**
47
+ * An implicit `any` only indicts the snippet once everything else resolved.
48
+ *
49
+ * `app.get("/", (req, res) => ...)` is correct Express, and `req` is implicitly
50
+ * any ONLY because a fragment cannot resolve `express`. Reporting that blames
51
+ * the harness. So TS7006 is suppressed whenever a module or name failed to
52
+ * resolve — found by attacking the allowlist rather than by review.
53
+ */
54
+ const CONDITIONAL_ON_RESOLUTION = 7006;
55
+ const RESOLUTION_FAILURE_CODES = new Set([2304, 2307, 2792, 2583]);
56
+ /**
57
+ * Codes already triaged as context failures rather than defects.
58
+ *
59
+ * NOT a filter — the allowlist above is what decides what is reported. This
60
+ * exists so the debug log can distinguish "known to be noise" from "never seen
61
+ * before", which is how the allowlist gets extended from evidence.
62
+ *
63
+ * 2304/2583/2584 unresolved name, 2307 unresolved module, 2300 duplicate
64
+ * identifier, 2315/2554 a snippet type shadowed by a lib type (the `Node`
65
+ * collision), 6053 a lib file we did not serve, 2686/2695 UMD and expression
66
+ * complaints that only make sense inside a real project.
67
+ */
68
+ const IGNORED_CODES = new Set([2300, 2304, 2307, 2315, 2554, 2583, 2584, 2686, 2695, 2792, 6053]);
69
+ let tsModule;
70
+ /** Loaded once, synchronously, so the quality gate stays synchronous. */
71
+ function loadTypeScript() {
72
+ if (tsModule !== undefined)
73
+ return tsModule;
74
+ try {
75
+ tsModule = createRequire(import.meta.url)("typescript");
76
+ }
77
+ catch (e) {
78
+ // A declared dependency, so this means a broken install. The regex floor
79
+ // in codingQualityPolicy still runs; this enhancement simply does not.
80
+ debugLog(`[ts-diagnostics] typescript unavailable: ${e instanceof Error ? e.message : e}`);
81
+ tsModule = null;
82
+ }
83
+ return tsModule;
84
+ }
85
+ const libCache = new Map();
86
+ function readLib(libDir, file) {
87
+ if (!libCache.has(file)) {
88
+ try {
89
+ libCache.set(file, readFileSync(join(libDir, file), "utf8"));
90
+ }
91
+ catch {
92
+ libCache.set(file, undefined);
93
+ }
94
+ }
95
+ return libCache.get(file);
96
+ }
97
+ /**
98
+ * Allowed findings only, de-duplicated, stable order. Empty when unavailable.
99
+ *
100
+ * `fenced` says the text was inside a ``` block, i.e. the model MEANT it as
101
+ * code. Only then is a parse failure attributable to the snippet. Unfenced
102
+ * output is ambiguous: "the function takes a value: string and returns a
103
+ * formatted result" is a sentence, and reporting it as a syntax error rejects a
104
+ * correct answer. Ambiguity favours the caller.
105
+ */
106
+ export function typecheckSnippet(code, fenced = true) {
107
+ const ts = loadTypeScript();
108
+ if (!ts)
109
+ return [];
110
+ const libDir = dirname(createRequire(import.meta.url).resolve("typescript"));
111
+ const name = "snippet.ts";
112
+ const sourceOf = (file) => file === name ? code : readLib(libDir, file);
113
+ const host = {
114
+ getSourceFile: (file) => {
115
+ const text = sourceOf(file);
116
+ return text === undefined
117
+ ? undefined
118
+ : ts.createSourceFile(file, text, ts.ScriptTarget.ES2022, true);
119
+ },
120
+ getDefaultLibFileName: () => "lib.es2022.d.ts",
121
+ writeFile: () => { },
122
+ getCurrentDirectory: () => "/",
123
+ getCanonicalFileName: (file) => file,
124
+ useCaseSensitiveFileNames: () => true,
125
+ getNewLine: () => "\n",
126
+ fileExists: (file) => sourceOf(file) !== undefined,
127
+ readFile: sourceOf,
128
+ };
129
+ let syntactic;
130
+ let semantic;
131
+ try {
132
+ const program = ts.createProgram([name], {
133
+ strict: true,
134
+ target: ts.ScriptTarget.ES2022,
135
+ noEmit: true,
136
+ types: [],
137
+ skipLibCheck: true,
138
+ }, host);
139
+ syntactic = program.getSyntacticDiagnostics();
140
+ semantic = program.getSemanticDiagnostics();
141
+ }
142
+ catch (e) {
143
+ debugLog(`[ts-diagnostics] check failed: ${e instanceof Error ? e.message : e}`);
144
+ return [];
145
+ }
146
+ // A parse failure needs no allowlist. Nothing about a missing library or an
147
+ // unresolved import can make a brace go missing, so a syntactic diagnostic
148
+ // always indicts the snippet. And once the file does not parse, the semantic
149
+ // results describe a tree that was never valid, so they are not consulted.
150
+ if (syntactic.length > 0)
151
+ return fenced ? ["syntax_error"] : [];
152
+ const unresolved = semantic.some(d => RESOLUTION_FAILURE_CODES.has(d.code));
153
+ const found = new Set();
154
+ for (const d of semantic) {
155
+ if (d.code === CONDITIONAL_ON_RESOLUTION && unresolved)
156
+ continue;
157
+ const name_ = ALLOWED_CODES.get(d.code);
158
+ if (name_)
159
+ found.add(name_);
160
+ else if (!IGNORED_CODES.has(d.code)) {
161
+ // Neither indicted nor excused. Logged so the lists can be extended
162
+ // from evidence rather than guessed at; never reported as a finding,
163
+ // because an unclassified code is exactly the kind that turns out to
164
+ // be about the harness.
165
+ debugLog(`[ts-diagnostics] unclassified TS${d.code}`);
166
+ }
167
+ }
168
+ return [...found].sort();
169
+ }
170
+ const DEFERRED_METHOD = /^(then|catch|finally)$/;
171
+ const DEFERRED_FN = /^(setTimeout|setInterval|setImmediate|queueMicrotask)$/;
172
+ /**
173
+ * A value mutated inside a promise or timer callback and then returned
174
+ * synchronously by the enclosing function.
175
+ *
176
+ * Valid TypeScript, and wrong: the callback runs in a later microtask, so the
177
+ * returned value never includes it. From the first multi-turn benchmark, where
178
+ * `emit()` incremented its counter inside `result.then(() => count++)` and
179
+ * returned 1 for three listeners. No type checker expresses this, but the AST
180
+ * is already loaded, so the rule is nearly free.
181
+ */
182
+ export function findDeferredMutationReturnedSync(code) {
183
+ const ts = loadTypeScript();
184
+ if (!ts)
185
+ return [];
186
+ const sf = ts.createSourceFile("snippet.ts", code, ts.ScriptTarget.ES2022, true);
187
+ const hits = new Set();
188
+ const insideDeferredCallback = (node) => {
189
+ for (let p = node.parent; p; p = p.parent) {
190
+ if (ts.isCallExpression(p)) {
191
+ const callee = p.expression;
192
+ if (ts.isPropertyAccessExpression(callee) && DEFERRED_METHOD.test(callee.name.text))
193
+ return true;
194
+ if (ts.isIdentifier(callee) && DEFERRED_FN.test(callee.text))
195
+ return true;
196
+ }
197
+ // Stop at the enclosing function: a mutation in a sibling function
198
+ // says nothing about this one's return value.
199
+ if (ts.isFunctionDeclaration(p) || ts.isMethodDeclaration(p))
200
+ return false;
201
+ }
202
+ return false;
203
+ };
204
+ const inspect = (fn) => {
205
+ const mutatedLate = new Set();
206
+ const returned = new Set();
207
+ const visit = (n) => {
208
+ const target = (ts.isPostfixUnaryExpression(n) || ts.isPrefixUnaryExpression(n)) && ts.isIdentifier(n.operand)
209
+ ? n.operand.text
210
+ : ts.isBinaryExpression(n) && ts.isIdentifier(n.left) && [
211
+ ts.SyntaxKind.EqualsToken,
212
+ ts.SyntaxKind.PlusEqualsToken,
213
+ ts.SyntaxKind.MinusEqualsToken,
214
+ ].includes(n.operatorToken.kind)
215
+ ? n.left.text
216
+ : null;
217
+ if (target && insideDeferredCallback(n))
218
+ mutatedLate.add(target);
219
+ if (ts.isReturnStatement(n) && n.expression && ts.isIdentifier(n.expression)) {
220
+ returned.add(n.expression.text);
221
+ }
222
+ // Do not descend into a NESTED named function or method: it has its
223
+ // own scope and its own `count`, and `scan` visits it separately.
224
+ // Without this, `inner`'s deferred mutation was credited to `outer`,
225
+ // flagging correct code. Arrow functions and anonymous function
226
+ // expressions ARE entered, because that is what a callback is.
227
+ if (ts.isFunctionDeclaration(n) || ts.isMethodDeclaration(n))
228
+ return;
229
+ ts.forEachChild(n, visit);
230
+ };
231
+ ts.forEachChild(fn, visit);
232
+ for (const v of mutatedLate)
233
+ if (returned.has(v))
234
+ hits.add(v);
235
+ return;
236
+ };
237
+ const scan = (n) => {
238
+ if (ts.isMethodDeclaration(n) || ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n))
239
+ inspect(n);
240
+ ts.forEachChild(n, scan);
241
+ };
242
+ ts.forEachChild(sf, scan);
243
+ return hits.size ? ["deferred_mutation_returned_sync"] : [];
244
+ }
245
+ /** Every TypeScript finding for a snippet, type errors and the AST rule. */
246
+ export function analyzeTypeScript(code, fenced = true) {
247
+ return [...typecheckSnippet(code, fenced), ...findDeferredMutationReturnedSync(code)].sort();
248
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "prism-mcp-server",
3
- "version": "20.21.4",
3
+ "version": "20.21.5",
4
4
  "mcpName": "io.github.dcostenco/prism-coder",
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.",
5
+ "description": "Persistent session memory for AI coding agents that never leaves your machine \u2014 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",
7
7
  "type": "module",
8
8
  "main": "dist/server.js",
@@ -114,6 +114,7 @@
114
114
  "stream-json": "^3.6.0",
115
115
  "tldts": "^7.0.27",
116
116
  "turndown": "^7.2.2",
117
+ "typescript": "^5.9.3",
117
118
  "zod": "^4.3.6"
118
119
  }
119
120
  }