@plannotator/sem-jiff 0.0.0-stage → 0.2.2
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/CHANGELOG.md +77 -0
- package/LICENSE-APACHE +191 -0
- package/LICENSE-MIT +21 -0
- package/README.md +122 -2
- package/THIRD-PARTY-NOTICES +367 -0
- package/dist/candidate.d.ts +14 -0
- package/dist/candidate.js +1 -0
- package/dist/classifier.d.ts +25 -0
- package/dist/classifier.js +32 -0
- package/dist/copy-wasm-bin.d.ts +2 -0
- package/dist/copy-wasm-bin.js +11 -0
- package/dist/copy-wasm.d.ts +3 -0
- package/dist/copy-wasm.js +43 -0
- package/dist/coverage.d.ts +7 -0
- package/dist/coverage.js +43 -0
- package/dist/edits.d.ts +10 -0
- package/dist/edits.js +230 -0
- package/dist/extract.d.ts +5 -0
- package/dist/extract.js +24 -0
- package/dist/grammars.d.ts +22 -0
- package/dist/grammars.js +37 -0
- package/dist/index.d.ts +79 -0
- package/dist/index.js +581 -0
- package/dist/inline.d.ts +21 -0
- package/dist/inline.js +959 -0
- package/dist/languages.d.ts +2 -0
- package/dist/languages.js +28 -0
- package/dist/linediff.d.ts +28 -0
- package/dist/linediff.js +205 -0
- package/dist/opinions.d.ts +84 -0
- package/dist/opinions.js +201 -0
- package/dist/pairing.d.ts +10 -0
- package/dist/pairing.js +269 -0
- package/dist/parse.d.ts +119 -0
- package/dist/parse.js +1293 -0
- package/dist/pierre-types.d.ts +101 -0
- package/dist/pierre-types.js +5 -0
- package/dist/runtime.d.ts +48 -0
- package/dist/runtime.js +60 -0
- package/dist/structure.d.ts +23 -0
- package/dist/structure.js +1111 -0
- package/dist/summary.d.ts +19 -0
- package/dist/summary.js +15 -0
- package/dist/symbol-types.d.ts +18 -0
- package/dist/symbol-types.js +1 -0
- package/dist/symbols.d.ts +6 -0
- package/dist/symbols.js +458 -0
- package/dist/syntax.d.ts +69 -0
- package/dist/syntax.js +450 -0
- package/dist/textdiff.d.ts +15 -0
- package/dist/textdiff.js +64 -0
- package/dist/textmoves.d.ts +8 -0
- package/dist/textmoves.js +143 -0
- package/package.json +108 -4
- package/src/candidate.ts +10 -0
- package/src/grammars.ts +44 -0
- package/src/opinions.ts +271 -0
- package/wasm/SHA256SUMS +12 -0
- package/wasm/tree-sitter-c_sharp.wasm +0 -0
- package/wasm/tree-sitter-go.wasm +0 -0
- package/wasm/tree-sitter-java.wasm +0 -0
- package/wasm/tree-sitter-kotlin.wasm +0 -0
- package/wasm/tree-sitter-php.wasm +0 -0
- package/wasm/tree-sitter-python.wasm +0 -0
- package/wasm/tree-sitter-ruby.wasm +0 -0
- package/wasm/tree-sitter-rust.wasm +0 -0
- package/wasm/tree-sitter-swift.wasm +0 -0
- package/wasm/tree-sitter-tsx.wasm +0 -0
- package/wasm/tree-sitter-typescript.wasm +0 -0
- package/wasm/web-tree-sitter.wasm +0 -0
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { range } from "./syntax.js";
|
|
2
|
+
import { positions } from "./textdiff.js";
|
|
3
|
+
/** A moved block may differ by at most this share of its characters; beyond that it reads as rewritten. */
|
|
4
|
+
export const MAX_MOVED_EDIT_RATIO = 0.2;
|
|
5
|
+
export function detectTextMoves(result, oldText, newText) {
|
|
6
|
+
const operations = [];
|
|
7
|
+
const folds = [];
|
|
8
|
+
if (result.hitTimeout)
|
|
9
|
+
return { operations, folds };
|
|
10
|
+
const at = { old: positions(oldText), new: positions(newText) };
|
|
11
|
+
const text = { old: oldText.split('\n'), new: newText.split('\n') };
|
|
12
|
+
for (const move of result.moves) {
|
|
13
|
+
const o = move.range.original;
|
|
14
|
+
const m = move.range.modified;
|
|
15
|
+
const changed = move.innerEdit.replacements.reduce((n, r) => n + Math.max(r.range.length, r.newText.length), 0);
|
|
16
|
+
if (changed > MAX_MOVED_EDIT_RATIO * Math.max(o.length, m.length))
|
|
17
|
+
continue;
|
|
18
|
+
// Ranges cover whole lines and end at the start of the next line.
|
|
19
|
+
const oldStart = at.old(o.start);
|
|
20
|
+
const oldEnd = at.old(o.endExclusive);
|
|
21
|
+
const newStart = at.new(m.start);
|
|
22
|
+
const newEnd = at.new(m.endExclusive);
|
|
23
|
+
const oldLines = { start: oldStart.line, end: oldEnd.character === 0 ? oldEnd.line - 1 : oldEnd.line };
|
|
24
|
+
const newLines = { start: newStart.line, end: newEnd.character === 0 ? newEnd.line - 1 : newEnd.line };
|
|
25
|
+
trimEdges(oldLines, newLines, text.old, text.new);
|
|
26
|
+
// Too little left, or text that repeats in the file (`if err != nil { return err }`):
|
|
27
|
+
// there is no telling which copy moved where.
|
|
28
|
+
const block = nonBlank(text.old, oldLines);
|
|
29
|
+
if (block.length < 2 || occurrences(text.old, block) > 1 || occurrences(text.new, nonBlank(text.new, newLines)) > 1)
|
|
30
|
+
continue;
|
|
31
|
+
const inside = (side, r) => {
|
|
32
|
+
const l = side === 'old' ? oldLines : newLines;
|
|
33
|
+
return r.start.line >= l.start && r.end.line <= l.end + 1;
|
|
34
|
+
};
|
|
35
|
+
const spans = [
|
|
36
|
+
{
|
|
37
|
+
role: 'root',
|
|
38
|
+
relation: 'moved',
|
|
39
|
+
old: [range({ line: oldLines.start, character: 0 }, { line: oldLines.end + 1, character: 0 })],
|
|
40
|
+
new: [range({ line: newLines.start, character: 0 }, { line: newLines.end + 1, character: 0 })],
|
|
41
|
+
linePairs: [{ old: oldLines, new: newLines }],
|
|
42
|
+
},
|
|
43
|
+
];
|
|
44
|
+
// Edits inside the moved text, mapped to both files.
|
|
45
|
+
let delta = 0;
|
|
46
|
+
for (const r of move.innerEdit.replacements) {
|
|
47
|
+
const os = o.start + r.range.start;
|
|
48
|
+
const oe = o.start + r.range.endExclusive;
|
|
49
|
+
const ns = m.start + r.range.start + delta;
|
|
50
|
+
const ne = ns + r.newText.length;
|
|
51
|
+
delta += r.newText.length - r.range.length;
|
|
52
|
+
if (os === oe)
|
|
53
|
+
spans.push({ role: 'focus', relation: 'introduced', new: [range(at.new(ns), at.new(ne))] });
|
|
54
|
+
else if (ns === ne)
|
|
55
|
+
spans.push({ role: 'focus', relation: 'removed', old: [range(at.old(os), at.old(oe))] });
|
|
56
|
+
else
|
|
57
|
+
spans.push({ role: 'focus', relation: 'replaced', old: [range(at.old(os), at.old(oe))], new: [range(at.new(ns), at.new(ne))], linePairs: [] });
|
|
58
|
+
}
|
|
59
|
+
// Keep only the edits inside the (trimmed) block.
|
|
60
|
+
for (let i = spans.length - 1; i > 0; i--) {
|
|
61
|
+
const sp = spans[i];
|
|
62
|
+
const olds = 'old' in sp ? (sp.old ?? []) : [];
|
|
63
|
+
const news = 'new' in sp ? (sp.new ?? []) : [];
|
|
64
|
+
if (!olds.every((r) => inside('old', r)) || !news.every((r) => inside('new', r)))
|
|
65
|
+
spans.splice(i, 1);
|
|
66
|
+
}
|
|
67
|
+
const edited = spans.length > 1 || nonBlank(text.old, oldLines).join('\n') !== nonBlank(text.new, newLines).join('\n');
|
|
68
|
+
const index = operations.push({
|
|
69
|
+
type: edited ? 'movedWithEdit' : 'moved',
|
|
70
|
+
spans,
|
|
71
|
+
lines: { old: [{ ...oldLines, spanIndex: 0 }], new: [{ ...newLines, spanIndex: 0 }] },
|
|
72
|
+
}) - 1;
|
|
73
|
+
if (!edited)
|
|
74
|
+
folds.push({ old: oldLines, operations: [index], counts: { moved: oldLines.end - oldLines.start + 1, edited: 0, removed: 0 } });
|
|
75
|
+
}
|
|
76
|
+
return { operations, folds };
|
|
77
|
+
}
|
|
78
|
+
const norm = (l) => (l ?? '').trim();
|
|
79
|
+
/** Trimmed non-blank lines of a block. */
|
|
80
|
+
function nonBlank(lines, r) {
|
|
81
|
+
return lines.slice(r.start - 1, r.end).map(norm).filter(Boolean);
|
|
82
|
+
}
|
|
83
|
+
/** How often a block (as trimmed non-blank lines) appears in a file. */
|
|
84
|
+
function occurrences(lines, block) {
|
|
85
|
+
if (!block.length)
|
|
86
|
+
return 0;
|
|
87
|
+
const flat = lines.map(norm).filter(Boolean);
|
|
88
|
+
let n = 0;
|
|
89
|
+
for (let i = 0; i + block.length <= flat.length; i++) {
|
|
90
|
+
if (flat[i] !== block[0])
|
|
91
|
+
continue;
|
|
92
|
+
let k = 1;
|
|
93
|
+
while (k < block.length && flat[i + k] === block[k])
|
|
94
|
+
k++;
|
|
95
|
+
if (k === block.length)
|
|
96
|
+
n++;
|
|
97
|
+
}
|
|
98
|
+
return n;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* VS Code's moves can take in a neighbouring line that did not move (the next
|
|
102
|
+
* import in a sorted list, an `if (x) {` wrapped around the block). Drop edge
|
|
103
|
+
* lines that have no counterpart in the other side's block.
|
|
104
|
+
*/
|
|
105
|
+
function trimEdges(o, n, oldText, newText) {
|
|
106
|
+
const has = (lines, r, line) => lines.slice(r.start - 1, r.end).some((l) => norm(l) === line);
|
|
107
|
+
for (const end of ['start', 'end']) {
|
|
108
|
+
const step = end === 'start' ? 1 : -1;
|
|
109
|
+
while (o.start <= o.end && n.start <= n.end) {
|
|
110
|
+
const a = norm(oldText[o[end] - 1]);
|
|
111
|
+
const b = norm(newText[n[end] - 1]);
|
|
112
|
+
if (a === b || similar(a, b))
|
|
113
|
+
break; // an edited edge line still moved
|
|
114
|
+
const dropOld = !has(newText, n, a);
|
|
115
|
+
const dropNew = !has(oldText, o, b);
|
|
116
|
+
if (!dropOld && !dropNew)
|
|
117
|
+
break;
|
|
118
|
+
if (dropOld)
|
|
119
|
+
o[end] += step;
|
|
120
|
+
if (dropNew)
|
|
121
|
+
n[end] += step;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
const KEYWORDS = new Set(['import', 'export', 'from', 'type', 'const', 'let', 'var', 'return', 'func', 'function', 'if', 'else', 'for']);
|
|
126
|
+
const words = (l) => (l.match(/\w{2,}/g) ?? []).filter((w) => !KEYWORDS.has(w));
|
|
127
|
+
/** Two lines share most of their words: one is an edit of the other. */
|
|
128
|
+
function similar(a, b) {
|
|
129
|
+
const x = words(a);
|
|
130
|
+
const y = words(b);
|
|
131
|
+
if (!x.length || !y.length)
|
|
132
|
+
return false;
|
|
133
|
+
const pool = [...y];
|
|
134
|
+
let common = 0;
|
|
135
|
+
for (const w of x) {
|
|
136
|
+
const i = pool.indexOf(w);
|
|
137
|
+
if (i >= 0) {
|
|
138
|
+
common++;
|
|
139
|
+
pool.splice(i, 1);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return (2 * common) / (x.length + y.length) >= 0.5;
|
|
143
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,110 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@plannotator/sem-jiff",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "Semantic diffs for code review: finds moved, renamed, reformatted, extracted and inlined code with tree-sitter, for any diff viewer.",
|
|
5
|
+
"license": "MIT OR Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"default": "./dist/index.js"
|
|
11
|
+
},
|
|
12
|
+
"./summary": {
|
|
13
|
+
"types": "./dist/summary.d.ts",
|
|
14
|
+
"default": "./dist/summary.js"
|
|
15
|
+
},
|
|
16
|
+
"./opinions": {
|
|
17
|
+
"types": "./dist/opinions.d.ts",
|
|
18
|
+
"default": "./dist/opinions.js"
|
|
19
|
+
},
|
|
20
|
+
"./candidate": {
|
|
21
|
+
"types": "./dist/candidate.d.ts",
|
|
22
|
+
"default": "./dist/candidate.js"
|
|
23
|
+
},
|
|
24
|
+
"./languages": {
|
|
25
|
+
"types": "./dist/languages.d.ts",
|
|
26
|
+
"default": "./dist/languages.js"
|
|
27
|
+
},
|
|
28
|
+
"./grammars": {
|
|
29
|
+
"types": "./dist/grammars.d.ts",
|
|
30
|
+
"default": "./dist/grammars.js"
|
|
31
|
+
},
|
|
32
|
+
"./copy-wasm": {
|
|
33
|
+
"types": "./dist/copy-wasm.d.ts",
|
|
34
|
+
"default": "./dist/copy-wasm.js"
|
|
35
|
+
},
|
|
36
|
+
"./wasm/*": "./wasm/*",
|
|
37
|
+
"./package.json": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"bin": {
|
|
41
|
+
"sem-jiff-copy-wasm": "./dist/copy-wasm-bin.js"
|
|
42
|
+
},
|
|
43
|
+
"files": [
|
|
44
|
+
"dist",
|
|
45
|
+
"wasm",
|
|
46
|
+
"src/candidate.ts",
|
|
47
|
+
"src/opinions.ts",
|
|
48
|
+
"src/grammars.ts",
|
|
49
|
+
"README.md",
|
|
50
|
+
"CHANGELOG.md",
|
|
51
|
+
"LICENSE-MIT",
|
|
52
|
+
"LICENSE-APACHE",
|
|
53
|
+
"THIRD-PARTY-NOTICES"
|
|
54
|
+
],
|
|
55
|
+
"keywords": [
|
|
56
|
+
"diff",
|
|
57
|
+
"semantic-diff",
|
|
58
|
+
"code-review",
|
|
59
|
+
"tree-sitter",
|
|
60
|
+
"refactoring",
|
|
61
|
+
"plannotator"
|
|
62
|
+
],
|
|
63
|
+
"repository": {
|
|
64
|
+
"type": "git",
|
|
65
|
+
"url": "https://github.com/plannotator/sem-jiff"
|
|
66
|
+
},
|
|
67
|
+
"homepage": "https://github.com/plannotator/sem-jiff#readme",
|
|
68
|
+
"bugs": {
|
|
69
|
+
"url": "https://github.com/plannotator/sem-jiff/issues"
|
|
70
|
+
},
|
|
71
|
+
"scripts": {
|
|
72
|
+
"test": "node --test --test-concurrency=${SEM_DIFF_TEST_WORKERS:-2} test/*.test.ts",
|
|
73
|
+
"typecheck": "tsc -p .",
|
|
74
|
+
"check": "npm run typecheck && npm test",
|
|
75
|
+
"demo:data": "node demo/data.ts",
|
|
76
|
+
"demo:build": "node demo/build.ts",
|
|
77
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && node scripts/fix-dts.ts && node scripts/build-wasm.ts",
|
|
78
|
+
"prepack": "npm run build",
|
|
79
|
+
"smoke": "node scripts/smoke.mjs",
|
|
80
|
+
"smoke:browser": "node scripts/browser-smoke.mjs"
|
|
81
|
+
},
|
|
82
|
+
"engines": {
|
|
83
|
+
"node": ">=24"
|
|
84
|
+
},
|
|
85
|
+
"dependencies": {
|
|
86
|
+
"@vscode/diff": "^0.0.2-133",
|
|
87
|
+
"diff": "^8.0.4",
|
|
88
|
+
"web-tree-sitter": "^0.27.1"
|
|
89
|
+
},
|
|
90
|
+
"devDependencies": {
|
|
91
|
+
"@tree-sitter-grammars/tree-sitter-kotlin": "file:vendor/tree-sitter-kotlin",
|
|
92
|
+
"@types/node": "^24.19.2",
|
|
93
|
+
"esbuild": "^0.25.12",
|
|
94
|
+
"playwright": "^1.65.0",
|
|
95
|
+
"tree-sitter-c-sharp": "^0.23.5",
|
|
96
|
+
"tree-sitter-go": "^0.25.0",
|
|
97
|
+
"tree-sitter-java": "^0.23.5",
|
|
98
|
+
"tree-sitter-php": "^0.24.2",
|
|
99
|
+
"tree-sitter-python": "^0.25.0",
|
|
100
|
+
"tree-sitter-ruby": "^0.23.1",
|
|
101
|
+
"tree-sitter-rust": "^0.24.0",
|
|
102
|
+
"tree-sitter-swift": "file:vendor/tree-sitter-swift",
|
|
103
|
+
"tree-sitter-typescript": "^0.23.2",
|
|
104
|
+
"typescript": "5.9",
|
|
105
|
+
"vite": "^7.3.8"
|
|
106
|
+
},
|
|
107
|
+
"publishConfig": {
|
|
108
|
+
"access": "public"
|
|
109
|
+
}
|
|
110
|
+
}
|
package/src/candidate.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** One extract/inline candidate, as a second opinion sees it. */
|
|
2
|
+
export interface Candidate {
|
|
3
|
+
kind: 'extract' | 'inline';
|
|
4
|
+
/** The file's name, as given to `semanticDiffFile` (filled in for per-diff second opinions). */
|
|
5
|
+
file?: string;
|
|
6
|
+
helper: string;
|
|
7
|
+
caller: string;
|
|
8
|
+
/** Source text. For an extract, `caller` is the new caller and `callerNew` the old one (extract is inline run backwards). */
|
|
9
|
+
code: { helper: string; caller: string; callerNew: string };
|
|
10
|
+
}
|
package/src/grammars.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The wasm files the engine loads, by the names a host serves them under. The package ships them in
|
|
2
|
+
// its `wasm/` folder (`@plannotator/sem-jiff/wasm/<file>`); a host that runs the engine in a page or a
|
|
3
|
+
// compiled binary copies them from there (`copyWasm` in `@plannotator/sem-jiff/copy-wasm`, or the
|
|
4
|
+
// `sem-jiff-copy-wasm` bin) and points `configure({ locateGrammar, locateRuntime })` at them.
|
|
5
|
+
// This file imports nothing, so a host can vendor it as source (it ships as `src/grammars.ts`).
|
|
6
|
+
|
|
7
|
+
/** web-tree-sitter's own runtime. */
|
|
8
|
+
export const SEM_DIFF_RUNTIME_FILE = 'web-tree-sitter.wasm';
|
|
9
|
+
|
|
10
|
+
/** The grammar file each language loads (keys are the engine's language ids). */
|
|
11
|
+
export const SEM_DIFF_GRAMMARS = {
|
|
12
|
+
typescript: 'tree-sitter-typescript.wasm',
|
|
13
|
+
tsx: 'tree-sitter-tsx.wasm',
|
|
14
|
+
python: 'tree-sitter-python.wasm',
|
|
15
|
+
go: 'tree-sitter-go.wasm',
|
|
16
|
+
rust: 'tree-sitter-rust.wasm',
|
|
17
|
+
java: 'tree-sitter-java.wasm',
|
|
18
|
+
csharp: 'tree-sitter-c_sharp.wasm',
|
|
19
|
+
php: 'tree-sitter-php.wasm',
|
|
20
|
+
ruby: 'tree-sitter-ruby.wasm',
|
|
21
|
+
kotlin: 'tree-sitter-kotlin.wasm',
|
|
22
|
+
swift: 'tree-sitter-swift.wasm',
|
|
23
|
+
} as const;
|
|
24
|
+
|
|
25
|
+
/** Every grammar file, once each, in the order of SEM_DIFF_GRAMMARS. */
|
|
26
|
+
export const SEM_DIFF_GRAMMAR_FILES = [
|
|
27
|
+
'tree-sitter-typescript.wasm',
|
|
28
|
+
'tree-sitter-tsx.wasm',
|
|
29
|
+
'tree-sitter-python.wasm',
|
|
30
|
+
'tree-sitter-go.wasm',
|
|
31
|
+
'tree-sitter-rust.wasm',
|
|
32
|
+
'tree-sitter-java.wasm',
|
|
33
|
+
'tree-sitter-c_sharp.wasm',
|
|
34
|
+
'tree-sitter-php.wasm',
|
|
35
|
+
'tree-sitter-ruby.wasm',
|
|
36
|
+
'tree-sitter-kotlin.wasm',
|
|
37
|
+
'tree-sitter-swift.wasm',
|
|
38
|
+
] as const;
|
|
39
|
+
|
|
40
|
+
/** Everything in the package's `wasm/` folder: the runtime first, then the grammars. */
|
|
41
|
+
export const SEM_DIFF_WASM_FILES = [SEM_DIFF_RUNTIME_FILE, ...SEM_DIFF_GRAMMAR_FILES] as const;
|
|
42
|
+
|
|
43
|
+
/** One of the wasm files the package ships. */
|
|
44
|
+
export type SemDiffWasmFile = (typeof SEM_DIFF_WASM_FILES)[number];
|
package/src/opinions.ts
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
// Bring-your-own-model second opinions for `semanticDiffFile(..., { secondOpinion })`.
|
|
2
|
+
// Each asks a decision model, once per candidate, whether a helper the rules rejected really was
|
|
3
|
+
// extracted (or inlined), with the question and cut-off measured in harness/compare/ (see
|
|
4
|
+
// harness/compare/README.md). Keys are the user's own; call these from a server or the
|
|
5
|
+
// user's machine, never from a page that other people load.
|
|
6
|
+
import type { Candidate } from './candidate.ts';
|
|
7
|
+
|
|
8
|
+
type Fetch = typeof fetch;
|
|
9
|
+
|
|
10
|
+
/** The text a model sees: the caller before and after, then the helper (layouts tested: this one is best). */
|
|
11
|
+
export function candidateState(c: Candidate): string {
|
|
12
|
+
const file = c.file ?? 'the file';
|
|
13
|
+
const cut = (s: string) => (s.length <= 12000 ? s : s.slice(0, 12000) + '\n... (cut)');
|
|
14
|
+
// Extract is detected as inline run backwards: for an extract, `caller` is the new caller.
|
|
15
|
+
const [before, after] = c.kind === 'extract' ? [c.code.callerNew, c.code.caller] : [c.code.caller, c.code.callerNew];
|
|
16
|
+
const where = c.kind === 'extract' ? 'added in this change' : 'removed in this change';
|
|
17
|
+
return `A code change in ${file}.\n\n=== CALLER BEFORE ===\n${cut(before)}\n\n=== CALLER AFTER ===\n${cut(after)}\n\n=== HELPER \`${c.helper}\` (${where}) ===\n${cut(c.code.helper)}\n`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const YES_NO = {
|
|
21
|
+
extract:
|
|
22
|
+
"Was code that used to be written out inside the caller moved into the helper function, so the caller now calls the helper instead (an extracted function)? Answer no if the helper's code is new, or the caller's old code was deleted or rewritten rather than moved.",
|
|
23
|
+
inline:
|
|
24
|
+
"Was the helper function's code folded back into the caller, so the caller now does the work itself instead of calling the helper (an inlined function)? Answer no if the caller's new code is a different implementation, or the helper's code was simply deleted.",
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const CHOICE = {
|
|
28
|
+
extract: {
|
|
29
|
+
instructions: "What best describes the helper and the caller's old code?",
|
|
30
|
+
criteria: {
|
|
31
|
+
moved: "The helper's statements were written out in the caller before, and now live in the helper (renamed variables, new parameters or small edits allowed).",
|
|
32
|
+
new: "The helper is new code: the caller's old code did not contain these statements.",
|
|
33
|
+
rewritten: "The caller's old code did something similar, but the helper is a different implementation, not the same statements.",
|
|
34
|
+
elsewhere: "The helper's statements came from some other place, not from this caller.",
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
inline: {
|
|
38
|
+
instructions: "What best describes the helper and the caller's new code?",
|
|
39
|
+
criteria: {
|
|
40
|
+
moved: "The helper's statements now appear written out in the caller, in place of the call (renamed variables or small edits allowed).",
|
|
41
|
+
deleted: "The helper's code was dropped: the caller's new code does not contain these statements.",
|
|
42
|
+
rewritten: "The caller now does something similar, but with a different implementation, not the same statements.",
|
|
43
|
+
elsewhere: "The helper's statements went to some other place, not into this caller.",
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** The key was refused or the account has no credit: no other question would succeed either. */
|
|
49
|
+
export class OpinionKeyError extends Error {
|
|
50
|
+
readonly provider: 'jev' | 'clef';
|
|
51
|
+
readonly status: number;
|
|
52
|
+
constructor(provider: 'jev' | 'clef', status: number, detail: string) {
|
|
53
|
+
super(
|
|
54
|
+
`${provider === 'jev' ? 'TypeSafe' : 'Cloudflare'} ${
|
|
55
|
+
status === 402 ? 'account has no credit left' : 'refused the key'
|
|
56
|
+
} (${status})${detail ? `: ${detail.slice(0, 200)}` : ''}`
|
|
57
|
+
);
|
|
58
|
+
this.name = 'OpinionKeyError';
|
|
59
|
+
this.provider = provider;
|
|
60
|
+
this.status = status;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const FATAL = new Set([401, 402, 403]);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Ask at most `limit` at a time. A question that fails for a passing reason (network, a 5xx)
|
|
68
|
+
* counts as "no"; a refused key or an empty account stops the batch and throws, so the diff
|
|
69
|
+
* reports it (`diagnostics`, pass "second-opinion") instead of quietly answering "no" to all.
|
|
70
|
+
*/
|
|
71
|
+
async function each<T, R>(items: T[], limit: number, f: (x: T) => Promise<R>, fallback: (x: T) => R): Promise<R[]> {
|
|
72
|
+
const out = items.map(fallback);
|
|
73
|
+
let next = 0;
|
|
74
|
+
let fatal: unknown = null;
|
|
75
|
+
await Promise.all(
|
|
76
|
+
Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
77
|
+
while (next < items.length && !fatal) {
|
|
78
|
+
const i = next++;
|
|
79
|
+
try {
|
|
80
|
+
out[i] = await f(items[i]!);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
if (e instanceof OpinionKeyError) fatal = e;
|
|
83
|
+
else out[i] = fallback(items[i]!);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
})
|
|
87
|
+
);
|
|
88
|
+
if (fatal) throw fatal;
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function post(doFetch: Fetch, provider: 'jev' | 'clef', url: string, token: string, body: unknown): Promise<any> {
|
|
93
|
+
const r = await doFetch(url, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
94
|
+
if (FATAL.has(r.status)) throw new OpinionKeyError(provider, r.status, await r.text().catch(() => ''));
|
|
95
|
+
if (!r.ok) throw new Error(`${r.status} ${await r.text()}`);
|
|
96
|
+
const out = await r.json();
|
|
97
|
+
return out.result ?? out;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* The same candidate asked twice (the diff opened again, or a file shown in two views) is
|
|
102
|
+
* answered from memory: one entry per candidate's code, the oldest dropped past `size`.
|
|
103
|
+
*/
|
|
104
|
+
function remembered<R>(size: number, ask: (c: Candidate) => Promise<R>): (c: Candidate) => Promise<R> {
|
|
105
|
+
const memo = new Map<string, Promise<R>>();
|
|
106
|
+
return (c) => {
|
|
107
|
+
const key = [c.kind, c.file ?? '', c.helper, c.caller, c.code.helper, c.code.caller, c.code.callerNew].join('\0');
|
|
108
|
+
const hit = memo.get(key);
|
|
109
|
+
if (hit) return hit;
|
|
110
|
+
const p = ask(c);
|
|
111
|
+
memo.set(key, p);
|
|
112
|
+
// A failed question is not remembered: the next diff may ask it again.
|
|
113
|
+
p.catch(() => memo.delete(key));
|
|
114
|
+
if (memo.size > size) memo.delete(memo.keys().next().value!);
|
|
115
|
+
return p;
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export type OpinionBand = 'very-likely' | 'likely';
|
|
120
|
+
|
|
121
|
+
/** One model answer about one candidate, kept so a reader can be told what was asked and why. */
|
|
122
|
+
export interface OpinionAnswer {
|
|
123
|
+
accept: boolean;
|
|
124
|
+
score: number;
|
|
125
|
+
band?: OpinionBand;
|
|
126
|
+
model: string;
|
|
127
|
+
question: string;
|
|
128
|
+
options: string[];
|
|
129
|
+
answer: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** "Very likely" from 0.90, "Likely" from the accept threshold, nothing below it. */
|
|
133
|
+
export function bandFor(score: number, threshold: number): OpinionBand | undefined {
|
|
134
|
+
if (score >= 0.9) return 'very-likely';
|
|
135
|
+
return score >= threshold ? 'likely' : undefined;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const unanswered = (model: string, question: string, options: string[]) => (): OpinionAnswer => ({ accept: false, score: 0, model, question, options, answer: 'unanswered' });
|
|
139
|
+
|
|
140
|
+
export interface JevOptions {
|
|
141
|
+
/** A TypeSafe API key. */
|
|
142
|
+
apiKey: string;
|
|
143
|
+
model?: string;
|
|
144
|
+
/** Accept when P(moved) is at least this (multiple-choice question; 0.74 measured). */
|
|
145
|
+
threshold?: number;
|
|
146
|
+
concurrency?: number;
|
|
147
|
+
/** Answers kept in memory, per candidate (default 2,000; 0 turns it off). */
|
|
148
|
+
remember?: number;
|
|
149
|
+
/**
|
|
150
|
+
* A second model for the cases Jev is unsure of: when P(moved) is at least `from` (0.6) but under
|
|
151
|
+
* `threshold`, accept if `ask` says at least `threshold` (0.8). Measured with Clef yes/no as the
|
|
152
|
+
* tie-breaker: on practice +25 real, +1 wrong, +10 borderline over Jev alone, and only a few
|
|
153
|
+
* percent of candidates are asked twice. `clefScore({ accountId, apiToken })` makes one.
|
|
154
|
+
*/
|
|
155
|
+
tieBreaker?: { ask: (c: Candidate) => Promise<number>; from?: number; threshold?: number };
|
|
156
|
+
fetch?: Fetch;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** TypeSafe's Jev, asked a multiple-choice question (moved / new / rewritten / elsewhere), with its answer kept. */
|
|
160
|
+
export function jevAnswers(o: JevOptions): (candidates: Candidate[]) => Promise<OpinionAnswer[]> {
|
|
161
|
+
const doFetch = o.fetch ?? fetch;
|
|
162
|
+
const t = o.threshold ?? 0.74;
|
|
163
|
+
const model = o.model ?? 'jev-1.14.0';
|
|
164
|
+
const ask = async (c: Candidate): Promise<OpinionAnswer> => {
|
|
165
|
+
const q = CHOICE[c.kind];
|
|
166
|
+
const options = Object.keys(q.criteria);
|
|
167
|
+
const out = await post(doFetch, 'jev', JEV_URL, o.apiKey, {
|
|
168
|
+
model,
|
|
169
|
+
state: candidateState(c),
|
|
170
|
+
questions: { q: { type: 'choice', instructions: q.instructions, criteria: q.criteria } },
|
|
171
|
+
});
|
|
172
|
+
const probabilities: Record<string, number> = out.answers.q.probabilities ?? {};
|
|
173
|
+
const answer = Object.entries(probabilities).sort((x, y) => y[1] - x[1])[0]?.[0] ?? 'unanswered';
|
|
174
|
+
const p = probabilities.moved ?? 0;
|
|
175
|
+
const base = { model, question: q.instructions, options, answer };
|
|
176
|
+
if (p >= t) return { ...base, accept: true, score: p, band: bandFor(p, t) };
|
|
177
|
+
const tb = o.tieBreaker;
|
|
178
|
+
if (!tb || p < (tb.from ?? 0.6)) return { ...base, accept: false, score: p };
|
|
179
|
+
try {
|
|
180
|
+
const second = await tb.ask(c);
|
|
181
|
+
const threshold = tb.threshold ?? 0.8;
|
|
182
|
+
const accept = second >= threshold;
|
|
183
|
+
return { ...base, model: `${model} + clef`, accept, score: accept ? second : p, band: accept ? bandFor(second, threshold) : undefined };
|
|
184
|
+
} catch (e) {
|
|
185
|
+
if (e instanceof OpinionKeyError) throw e;
|
|
186
|
+
return { ...base, accept: false, score: p };
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
const answer = o.remember === 0 ? ask : remembered(o.remember ?? 2000, ask);
|
|
190
|
+
return (cs) => each(cs, o.concurrency ?? 8, answer, (c) => unanswered(model, CHOICE[c.kind].instructions, Object.keys(CHOICE[c.kind].criteria))());
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** TypeSafe's Jev as a yes/no second opinion (see `jevAnswers` for the answers themselves). */
|
|
194
|
+
export function jevOpinion(o: JevOptions): (candidates: Candidate[]) => Promise<boolean[]> {
|
|
195
|
+
const answers = jevAnswers(o);
|
|
196
|
+
return async (cs) => (await answers(cs)).map((a) => a.accept);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const JEV_URL = 'https://api.typesafe.ai/v1/systemone';
|
|
200
|
+
|
|
201
|
+
export interface ClefOptions {
|
|
202
|
+
/** Cloudflare account ID and an API token with Workers AI permission. */
|
|
203
|
+
accountId: string;
|
|
204
|
+
apiToken: string;
|
|
205
|
+
model?: 'clef' | 'clef-flash';
|
|
206
|
+
/** Accept when the yes/no probability is at least this (0.9 measured for clef). */
|
|
207
|
+
threshold?: number;
|
|
208
|
+
concurrency?: number;
|
|
209
|
+
/** Answers kept in memory, per candidate (default 2,000; 0 turns it off). */
|
|
210
|
+
remember?: number;
|
|
211
|
+
fetch?: Fetch;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Cloudflare's Clef on Workers AI: the yes/no probability for one candidate (for `tieBreaker`). */
|
|
215
|
+
export function clefScore(o: Omit<ClefOptions, 'threshold' | 'concurrency' | 'remember'>): (c: Candidate) => Promise<number> {
|
|
216
|
+
const doFetch = o.fetch ?? fetch;
|
|
217
|
+
return async (c) => {
|
|
218
|
+
const out = await post(doFetch, 'clef', clefUrl(o.accountId), o.apiToken, {
|
|
219
|
+
model: o.model ?? 'clef',
|
|
220
|
+
state: candidateState(c),
|
|
221
|
+
questions: { q: { type: 'noul', instructions: YES_NO[c.kind] } },
|
|
222
|
+
});
|
|
223
|
+
return out.answers.q.noul ?? 0;
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question, with its answer kept. */
|
|
228
|
+
export function clefAnswers(o: ClefOptions): (candidates: Candidate[]) => Promise<OpinionAnswer[]> {
|
|
229
|
+
const t = o.threshold ?? 0.9;
|
|
230
|
+
const model = o.model ?? 'clef';
|
|
231
|
+
const score = clefScore(o);
|
|
232
|
+
const ask = async (c: Candidate): Promise<OpinionAnswer> => {
|
|
233
|
+
const p = await score(c);
|
|
234
|
+
const accept = p >= t;
|
|
235
|
+
return { accept, score: p, band: accept ? bandFor(p, t) : undefined, model, question: YES_NO[c.kind], options: ['yes', 'no'], answer: p >= 0.5 ? 'yes' : 'no' };
|
|
236
|
+
};
|
|
237
|
+
const answer = o.remember === 0 ? ask : remembered(o.remember ?? 2000, ask);
|
|
238
|
+
return (cs) => each(cs, o.concurrency ?? 8, answer, (c) => unanswered(model, YES_NO[c.kind], ['yes', 'no'])());
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question. */
|
|
242
|
+
export function clefOpinion(o: ClefOptions): (candidates: Candidate[]) => Promise<boolean[]> {
|
|
243
|
+
const answers = clefAnswers(o);
|
|
244
|
+
return async (cs) => (await answers(cs)).map((a) => a.accept);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const clefUrl = (accountId: string) => `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/@cf/cloudflare/clef`;
|
|
248
|
+
|
|
249
|
+
export type KeyCheck = { ok: true; ms: number } | { ok: false; reason: string };
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* For a "power up with your key" setting: asks one tiny question (a fraction of a cent) and says
|
|
253
|
+
* whether the key works, or why not, in words a settings screen can show.
|
|
254
|
+
*/
|
|
255
|
+
export async function checkKey(
|
|
256
|
+
o: ({ provider: 'jev' } & Pick<JevOptions, 'apiKey' | 'model'>) | ({ provider: 'clef' } & Pick<ClefOptions, 'accountId' | 'apiToken' | 'model'>),
|
|
257
|
+
doFetch: Fetch = fetch
|
|
258
|
+
): Promise<KeyCheck> {
|
|
259
|
+
const start = Date.now();
|
|
260
|
+
const question = { q: { type: 'noul', instructions: 'Does this text contain a number?' } };
|
|
261
|
+
try {
|
|
262
|
+
const out =
|
|
263
|
+
o.provider === 'jev'
|
|
264
|
+
? await post(doFetch, 'jev', JEV_URL, o.apiKey, { model: o.model ?? 'jev-1.14.0', state: 'There are 3 apples.', questions: question })
|
|
265
|
+
: await post(doFetch, 'clef', clefUrl(o.accountId), o.apiToken, { model: o.model ?? 'clef', state: 'There are 3 apples.', questions: question });
|
|
266
|
+
if (typeof out?.answers?.q?.noul !== 'number') return { ok: false, reason: 'the service answered in an unexpected shape' };
|
|
267
|
+
return { ok: true, ms: Date.now() - start };
|
|
268
|
+
} catch (e) {
|
|
269
|
+
return { ok: false, reason: e instanceof OpinionKeyError ? e.message : `could not reach the service (${(e as Error).message.slice(0, 120)})` };
|
|
270
|
+
}
|
|
271
|
+
}
|
package/wasm/SHA256SUMS
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
beca80e44cccbf2299ed4d1e3fa6462a9a6fe818aeebf847547a392227ce4acc web-tree-sitter.wasm
|
|
2
|
+
778025db5a8be0e70f8ccc3671e486dfeddd048c25d9e8a70c26de2e1bf6f97d tree-sitter-typescript.wasm
|
|
3
|
+
79e5da75ea62855a0cd67177685f0164eac87d5f630b3cbe1e0a099751ad30f8 tree-sitter-tsx.wasm
|
|
4
|
+
16108b50df4ee9a30168794252ab55e7c93bfc5765d7fa0aa3e335752c515f47 tree-sitter-python.wasm
|
|
5
|
+
9504573f352b20be7f2f1911754d710622aedc15afff16d5ed8fb5645681aee7 tree-sitter-go.wasm
|
|
6
|
+
f65f354215611fd94ad34134b3427eb3d58cbb745df7b6509ba722184db73d57 tree-sitter-rust.wasm
|
|
7
|
+
4fdeac4ca6ca089f06c6f7e562abcac1733cd465728cc7031ebb73c2019122c4 tree-sitter-java.wasm
|
|
8
|
+
6f69e1cae44e1c32c1eccc170dc5a9778fb94ff716f71113fe1f8c4299aa2f40 tree-sitter-c_sharp.wasm
|
|
9
|
+
d4df6a6ff08c87c3ec4f9cbb785fe09998a0cb570e03f57d7b19b3acfb146aa7 tree-sitter-php.wasm
|
|
10
|
+
09a96427d7c72f0613ed470cd9812223fc4a91d6a9c025c0235cc6bd59ff96f4 tree-sitter-ruby.wasm
|
|
11
|
+
7009d69453bc8735e438b2818a633efb21c88f99782769abba60dffedfab73f7 tree-sitter-kotlin.wasm
|
|
12
|
+
0258a7ef17303a8079ffe0748b3583d59656b5c3e8653fca7b6451b3e6689eb2 tree-sitter-swift.wasm
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|