@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,28 @@
|
|
|
1
|
+
export function languageForPath(path) {
|
|
2
|
+
if (path.endsWith('.go'))
|
|
3
|
+
return 'go';
|
|
4
|
+
if (path.endsWith('.rs'))
|
|
5
|
+
return 'rust';
|
|
6
|
+
if (/\.pyi?$/.test(path))
|
|
7
|
+
return 'python';
|
|
8
|
+
if (path.endsWith('.java'))
|
|
9
|
+
return 'java';
|
|
10
|
+
if (path.endsWith('.cs'))
|
|
11
|
+
return 'csharp';
|
|
12
|
+
// Blade templates (`.blade.php`) are not PHP code: plain diff.
|
|
13
|
+
if (/\.(php|phtml)$/.test(path) && !path.endsWith('.blade.php'))
|
|
14
|
+
return 'php';
|
|
15
|
+
// ERB templates (`.erb`) are not Ruby code: plain diff.
|
|
16
|
+
if (/\.(rb|rake|gemspec)$/.test(path) || /(^|\/)(Rakefile|Gemfile)$/.test(path))
|
|
17
|
+
return 'ruby';
|
|
18
|
+
if (/\.kts?$/.test(path))
|
|
19
|
+
return 'kotlin';
|
|
20
|
+
if (path.endsWith('.swift'))
|
|
21
|
+
return 'swift';
|
|
22
|
+
// Plain JavaScript may hold JSX (React `.js` files); the TSX grammar reads both.
|
|
23
|
+
if (path.endsWith('.tsx') || /\.(m|c)?jsx?$/.test(path))
|
|
24
|
+
return 'tsx';
|
|
25
|
+
if (/\.(m|c)?(ts|js)$/.test(path))
|
|
26
|
+
return 'typescript';
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import type { LanguageConfig } from './parse.js';
|
|
3
|
+
/** A run of changed lines; one side is null for a pure insertion or deletion. */
|
|
4
|
+
export interface ChangeBlock {
|
|
5
|
+
old: {
|
|
6
|
+
start: number;
|
|
7
|
+
end: number;
|
|
8
|
+
} | null;
|
|
9
|
+
new: {
|
|
10
|
+
start: number;
|
|
11
|
+
end: number;
|
|
12
|
+
} | null;
|
|
13
|
+
/** Line before which the block sits on each side (for placement when one side is empty). */
|
|
14
|
+
oldAt: number;
|
|
15
|
+
newAt: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A file's lines for diffing: the real lines only (no empty entry after a final
|
|
19
|
+
* newline), with a missing final newline marked on the last line, so that adding or
|
|
20
|
+
* removing it is a change and the patch can say so.
|
|
21
|
+
*/
|
|
22
|
+
export declare const NO_FINAL_NEWLINE = "\0no-newline";
|
|
23
|
+
export declare function diffLines(text: string): string[];
|
|
24
|
+
export declare function alignedLineDiff(oldRoot: Node, newRoot: Node, cfg: LanguageConfig, oldLines: string[], newLines: string[]): ChangeBlock[];
|
|
25
|
+
/** Unified diff text for the blocks (standard unified diff format). */
|
|
26
|
+
export declare function toPatch(name: string, blocks: ChangeBlock[], oldLines: string[], newLines: string[], context?: number): string;
|
|
27
|
+
/** The lines `blocks` leave unchanged, old line to new line (1-based). */
|
|
28
|
+
export declare function unchangedLinePairs(blocks: ChangeBlock[], oldCount: number): Map<number, number>;
|
package/dist/linediff.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// A line diff that knows about declarations. Plain line diffs (Myers, as in
|
|
2
|
+
// git or jsdiff) maximise matched lines anywhere, so when a loop is extracted
|
|
3
|
+
// into a new function they keep the loop "in place" and report the caller's
|
|
4
|
+
// untouched tail as new. Here, declarations paired across versions (same kind
|
|
5
|
+
// and name, kept in order) anchor the diff: each pair is diffed on its own,
|
|
6
|
+
// recursively through class members, and only the gaps between anchors are
|
|
7
|
+
// diffed freely.
|
|
8
|
+
import { diffArrays } from 'diff';
|
|
9
|
+
import { trial } from "./runtime.js";
|
|
10
|
+
import { attachedAbove, codeLines, endLine, keepWeights, longestInOrder, pairSameNamed, startLine, tokens } from "./syntax.js";
|
|
11
|
+
function anchors(oldContainer, newContainer, cfg) {
|
|
12
|
+
const keyed = (container) => {
|
|
13
|
+
const seen = new Map();
|
|
14
|
+
return cfg.declarationsIn(container).map((d) => {
|
|
15
|
+
const accessor = d.node.children.find((c) => c?.type === 'get' || c?.type === 'set')?.type ?? '';
|
|
16
|
+
const base = `${d.kind}:${accessor}${d.name}`;
|
|
17
|
+
const n = seen.get(base) ?? 0;
|
|
18
|
+
seen.set(base, n + 1);
|
|
19
|
+
return { key: n ? `${base}#${n}` : base, d };
|
|
20
|
+
});
|
|
21
|
+
};
|
|
22
|
+
// Same pairing as the move detector: repeated names pair by similarity.
|
|
23
|
+
const base = (x) => x.key.replace(/#\d+$/, '');
|
|
24
|
+
// Repeated containers of a type spread over several (Swift extensions) pair by the members they hold.
|
|
25
|
+
const similarBy = (x) => cfg.typeOf && x.d.members ? cfg.declarationsIn(x.d.members).map((m) => `${m.kind}:${m.name}`) : [...(attachedAbove(x.d.node, cfg.attachedTypes).match(/\S+/g) ?? []), ...tokens(x.d.node)];
|
|
26
|
+
const pairs = pairSameNamed(keyed(oldContainer), keyed(newContainer), base, similarBy)
|
|
27
|
+
.map(([o, n]) => ({ a: o.d, b: n.d }))
|
|
28
|
+
.sort((x, y) => x.a.node.startIndex - y.a.node.startIndex);
|
|
29
|
+
// Keep the longest run whose order is the same on both sides (the same choice the move detector makes).
|
|
30
|
+
const seq = pairs.map((p) => p.b.node.startIndex);
|
|
31
|
+
const keep = [...longestInOrder(seq, keepWeights(seq, pairs.map((p) => codeLines(p.a, cfg)), cfg.moveEditedFirst ? pairs.map((p) => p.a.node.text === p.b.node.text) : undefined))].sort((x, y) => x - y);
|
|
32
|
+
return keep.map((i) => {
|
|
33
|
+
const { a, b } = pairs[i];
|
|
34
|
+
return { a: a.node, b: b.node, ...(a.members && b.members ? { members: [a.members, b.members] } : {}) };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* A file's lines for diffing: the real lines only (no empty entry after a final
|
|
39
|
+
* newline), with a missing final newline marked on the last line, so that adding or
|
|
40
|
+
* removing it is a change and the patch can say so.
|
|
41
|
+
*/
|
|
42
|
+
export const NO_FINAL_NEWLINE = '\u0000no-newline';
|
|
43
|
+
export function diffLines(text) {
|
|
44
|
+
if (text === '')
|
|
45
|
+
return [];
|
|
46
|
+
const lines = text.split('\n');
|
|
47
|
+
if (text.endsWith('\n'))
|
|
48
|
+
lines.pop();
|
|
49
|
+
else
|
|
50
|
+
lines[lines.length - 1] += NO_FINAL_NEWLINE;
|
|
51
|
+
return lines;
|
|
52
|
+
}
|
|
53
|
+
/** Lines as `diffLines` gives them (see there). */
|
|
54
|
+
/** First line of the comments and attributes directly above a declaration (no blank line between), else its own first line. */
|
|
55
|
+
function commentStart(n, cfg) {
|
|
56
|
+
let line = startLine(n);
|
|
57
|
+
for (let c = n.previousSibling; c && cfg.attachedTypes.has(c.type); c = c.previousSibling) {
|
|
58
|
+
// A comment node can end at the start of the next line (Rust line comments): compare where it really ends.
|
|
59
|
+
const end = c.endPosition.column === 0 && c.endPosition.row > c.startPosition.row ? c.endPosition.row : c.endPosition.row + 1;
|
|
60
|
+
if (end !== line - 1)
|
|
61
|
+
break;
|
|
62
|
+
line = startLine(c);
|
|
63
|
+
}
|
|
64
|
+
return line;
|
|
65
|
+
}
|
|
66
|
+
export function alignedLineDiff(oldRoot, newRoot, cfg, oldLines, newLines) {
|
|
67
|
+
const blocks = [];
|
|
68
|
+
/** Free diff of a region (1-based inclusive lines; may be empty). */
|
|
69
|
+
const freeDiff = (r) => {
|
|
70
|
+
if (r.oldStart > r.oldEnd && r.newStart > r.newEnd)
|
|
71
|
+
return;
|
|
72
|
+
const a = oldLines.slice(r.oldStart - 1, Math.max(r.oldStart - 1, r.oldEnd));
|
|
73
|
+
const b = newLines.slice(r.newStart - 1, Math.max(r.newStart - 1, r.newEnd));
|
|
74
|
+
let o = r.oldStart;
|
|
75
|
+
let n = r.newStart;
|
|
76
|
+
let open = null;
|
|
77
|
+
for (const part of diffArrays(a, b)) {
|
|
78
|
+
const count = part.count ?? part.value.length;
|
|
79
|
+
if (!part.added && !part.removed) {
|
|
80
|
+
open = null;
|
|
81
|
+
o += count;
|
|
82
|
+
n += count;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (!open) {
|
|
86
|
+
open = { old: null, new: null, oldAt: o, newAt: n };
|
|
87
|
+
blocks.push(open);
|
|
88
|
+
}
|
|
89
|
+
if (part.removed) {
|
|
90
|
+
open.old = { start: o, end: o + count - 1 };
|
|
91
|
+
o += count;
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
open.new = { start: n, end: n + count - 1 };
|
|
95
|
+
n += count;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
/** Diff a region, anchoring on declarations paired inside `containers`. */
|
|
100
|
+
const anchored = (r, containers) => {
|
|
101
|
+
const pairs = containers ? anchors(containers[0], containers[1], cfg) : [];
|
|
102
|
+
let o = r.oldStart;
|
|
103
|
+
let n = r.newStart;
|
|
104
|
+
for (const p of pairs) {
|
|
105
|
+
// Half-written code can end past the last line (the parser supplies a missing `}`).
|
|
106
|
+
// Trial ATTACH_DOC: a declaration's anchor starts at the comments directly above it, so its doc comment lines
|
|
107
|
+
// up with its own counterpart, not with a lookalike `/**` of a neighbour. Only when those comments are the same
|
|
108
|
+
// lines on both sides: a comment that changed (reindented with its code) stays a change block of its own, as before.
|
|
109
|
+
let docOld = startLine(p.a);
|
|
110
|
+
let docNew = startLine(p.b);
|
|
111
|
+
if (trial('ATTACH_DOC')) {
|
|
112
|
+
const ca = commentStart(p.a, cfg);
|
|
113
|
+
const cb = commentStart(p.b, cfg);
|
|
114
|
+
const same = startLine(p.a) - ca === startLine(p.b) - cb && oldLines.slice(ca - 1, startLine(p.a) - 1).every((l, i) => l === newLines[cb - 1 + i]);
|
|
115
|
+
if (same) {
|
|
116
|
+
docOld = ca;
|
|
117
|
+
docNew = cb;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
const ps = {
|
|
121
|
+
oldStart: docOld,
|
|
122
|
+
oldEnd: Math.min(endLine(p.a), oldLines.length),
|
|
123
|
+
newStart: docNew,
|
|
124
|
+
newEnd: Math.min(endLine(p.b), newLines.length),
|
|
125
|
+
};
|
|
126
|
+
if (ps.oldStart > oldLines.length || ps.newStart > newLines.length)
|
|
127
|
+
continue;
|
|
128
|
+
if (ps.oldStart < o || ps.newStart < n)
|
|
129
|
+
continue; // overlaps a previous anchor (e.g. two declarations on one line)
|
|
130
|
+
freeDiff({ oldStart: o, oldEnd: ps.oldStart - 1, newStart: n, newEnd: ps.newStart - 1 });
|
|
131
|
+
if (p.members)
|
|
132
|
+
anchored(ps, p.members);
|
|
133
|
+
else
|
|
134
|
+
freeDiff(ps);
|
|
135
|
+
o = ps.oldEnd + 1;
|
|
136
|
+
n = ps.newEnd + 1;
|
|
137
|
+
}
|
|
138
|
+
freeDiff({ oldStart: o, oldEnd: r.oldEnd, newStart: n, newEnd: r.newEnd });
|
|
139
|
+
};
|
|
140
|
+
anchored({ oldStart: 1, oldEnd: oldLines.length, newStart: 1, newEnd: newLines.length }, [oldRoot, newRoot]);
|
|
141
|
+
return blocks;
|
|
142
|
+
}
|
|
143
|
+
/** Unified diff text for the blocks (standard unified diff format). */
|
|
144
|
+
export function toPatch(name, blocks, oldLines, newLines, context = 3) {
|
|
145
|
+
const oldCount = oldLines.length;
|
|
146
|
+
// git's header form, so readers strip the a/ and b/ prefixes and see one file.
|
|
147
|
+
const out = [`diff --git a/${name} b/${name}`, `--- a/${name}`, `+++ b/${name}`];
|
|
148
|
+
// Merge blocks whose context would touch into hunks.
|
|
149
|
+
let i = 0;
|
|
150
|
+
while (i < blocks.length) {
|
|
151
|
+
let j = i;
|
|
152
|
+
const startO = (b) => b.old?.start ?? b.oldAt;
|
|
153
|
+
const endO = (b) => (b.old ? b.old.end : b.oldAt - 1);
|
|
154
|
+
while (j + 1 < blocks.length && startO(blocks[j + 1]) - endO(blocks[j]) - 1 <= 2 * context)
|
|
155
|
+
j++;
|
|
156
|
+
const first = blocks[i];
|
|
157
|
+
const hunkOldStart = Math.max(1, startO(first) - context);
|
|
158
|
+
const lead = startO(first) - hunkOldStart;
|
|
159
|
+
const hunkNewStart = (first.new?.start ?? first.newAt) - lead;
|
|
160
|
+
const lines = [];
|
|
161
|
+
let o = hunkOldStart;
|
|
162
|
+
let n = hunkNewStart;
|
|
163
|
+
for (let k = i; k <= j; k++) {
|
|
164
|
+
const b = blocks[k];
|
|
165
|
+
while (o < startO(b)) {
|
|
166
|
+
lines.push(' ' + (oldLines[o - 1] ?? ''));
|
|
167
|
+
o++;
|
|
168
|
+
n++;
|
|
169
|
+
}
|
|
170
|
+
if (b.old)
|
|
171
|
+
for (let l = b.old.start; l <= b.old.end; l++, o++)
|
|
172
|
+
lines.push('-' + (oldLines[l - 1] ?? ''));
|
|
173
|
+
if (b.new)
|
|
174
|
+
for (let l = b.new.start; l <= b.new.end; l++, n++)
|
|
175
|
+
lines.push('+' + (newLines[l - 1] ?? ''));
|
|
176
|
+
}
|
|
177
|
+
const trailEnd = Math.min(oldCount, o - 1 + context);
|
|
178
|
+
while (o <= trailEnd) {
|
|
179
|
+
lines.push(' ' + (oldLines[o - 1] ?? ''));
|
|
180
|
+
o++;
|
|
181
|
+
n++;
|
|
182
|
+
}
|
|
183
|
+
const oldLen = lines.filter((l) => l[0] !== '+').length;
|
|
184
|
+
const newLen = lines.filter((l) => l[0] !== '-').length;
|
|
185
|
+
out.push(`@@ -${oldLen ? hunkOldStart : hunkOldStart - 1},${oldLen} +${newLen ? hunkNewStart : hunkNewStart - 1},${newLen} @@`, ...lines);
|
|
186
|
+
i = j + 1;
|
|
187
|
+
}
|
|
188
|
+
// git's marker for a last line without a newline, right after that line.
|
|
189
|
+
return out.flatMap((l) => (l.endsWith(NO_FINAL_NEWLINE) ? [l.slice(0, -NO_FINAL_NEWLINE.length), '\'] : [l])).join('\n') + '\n';
|
|
190
|
+
}
|
|
191
|
+
/** The lines `blocks` leave unchanged, old line to new line (1-based). */
|
|
192
|
+
export function unchangedLinePairs(blocks, oldCount) {
|
|
193
|
+
const out = new Map();
|
|
194
|
+
let o = 1;
|
|
195
|
+
let n = 1;
|
|
196
|
+
for (const b of [...blocks].sort((x, y) => x.oldAt - y.oldAt || x.newAt - y.newAt)) {
|
|
197
|
+
while (o < b.oldAt && n < b.newAt)
|
|
198
|
+
out.set(o++, n++);
|
|
199
|
+
o = b.old ? b.old.end + 1 : b.oldAt;
|
|
200
|
+
n = b.new ? b.new.end + 1 : b.newAt;
|
|
201
|
+
}
|
|
202
|
+
while (o <= oldCount)
|
|
203
|
+
out.set(o++, n++);
|
|
204
|
+
return out;
|
|
205
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { Candidate } from './candidate.js';
|
|
2
|
+
type Fetch = typeof fetch;
|
|
3
|
+
/** The text a model sees: the caller before and after, then the helper (layouts tested: this one is best). */
|
|
4
|
+
export declare function candidateState(c: Candidate): string;
|
|
5
|
+
/** The key was refused or the account has no credit: no other question would succeed either. */
|
|
6
|
+
export declare class OpinionKeyError extends Error {
|
|
7
|
+
readonly provider: 'jev' | 'clef';
|
|
8
|
+
readonly status: number;
|
|
9
|
+
constructor(provider: 'jev' | 'clef', status: number, detail: string);
|
|
10
|
+
}
|
|
11
|
+
export type OpinionBand = 'very-likely' | 'likely';
|
|
12
|
+
/** One model answer about one candidate, kept so a reader can be told what was asked and why. */
|
|
13
|
+
export interface OpinionAnswer {
|
|
14
|
+
accept: boolean;
|
|
15
|
+
score: number;
|
|
16
|
+
band?: OpinionBand;
|
|
17
|
+
model: string;
|
|
18
|
+
question: string;
|
|
19
|
+
options: string[];
|
|
20
|
+
answer: string;
|
|
21
|
+
}
|
|
22
|
+
/** "Very likely" from 0.90, "Likely" from the accept threshold, nothing below it. */
|
|
23
|
+
export declare function bandFor(score: number, threshold: number): OpinionBand | undefined;
|
|
24
|
+
export interface JevOptions {
|
|
25
|
+
/** A TypeSafe API key. */
|
|
26
|
+
apiKey: string;
|
|
27
|
+
model?: string;
|
|
28
|
+
/** Accept when P(moved) is at least this (multiple-choice question; 0.74 measured). */
|
|
29
|
+
threshold?: number;
|
|
30
|
+
concurrency?: number;
|
|
31
|
+
/** Answers kept in memory, per candidate (default 2,000; 0 turns it off). */
|
|
32
|
+
remember?: number;
|
|
33
|
+
/**
|
|
34
|
+
* A second model for the cases Jev is unsure of: when P(moved) is at least `from` (0.6) but under
|
|
35
|
+
* `threshold`, accept if `ask` says at least `threshold` (0.8). Measured with Clef yes/no as the
|
|
36
|
+
* tie-breaker: on practice +25 real, +1 wrong, +10 borderline over Jev alone, and only a few
|
|
37
|
+
* percent of candidates are asked twice. `clefScore({ accountId, apiToken })` makes one.
|
|
38
|
+
*/
|
|
39
|
+
tieBreaker?: {
|
|
40
|
+
ask: (c: Candidate) => Promise<number>;
|
|
41
|
+
from?: number;
|
|
42
|
+
threshold?: number;
|
|
43
|
+
};
|
|
44
|
+
fetch?: Fetch;
|
|
45
|
+
}
|
|
46
|
+
/** TypeSafe's Jev, asked a multiple-choice question (moved / new / rewritten / elsewhere), with its answer kept. */
|
|
47
|
+
export declare function jevAnswers(o: JevOptions): (candidates: Candidate[]) => Promise<OpinionAnswer[]>;
|
|
48
|
+
/** TypeSafe's Jev as a yes/no second opinion (see `jevAnswers` for the answers themselves). */
|
|
49
|
+
export declare function jevOpinion(o: JevOptions): (candidates: Candidate[]) => Promise<boolean[]>;
|
|
50
|
+
export interface ClefOptions {
|
|
51
|
+
/** Cloudflare account ID and an API token with Workers AI permission. */
|
|
52
|
+
accountId: string;
|
|
53
|
+
apiToken: string;
|
|
54
|
+
model?: 'clef' | 'clef-flash';
|
|
55
|
+
/** Accept when the yes/no probability is at least this (0.9 measured for clef). */
|
|
56
|
+
threshold?: number;
|
|
57
|
+
concurrency?: number;
|
|
58
|
+
/** Answers kept in memory, per candidate (default 2,000; 0 turns it off). */
|
|
59
|
+
remember?: number;
|
|
60
|
+
fetch?: Fetch;
|
|
61
|
+
}
|
|
62
|
+
/** Cloudflare's Clef on Workers AI: the yes/no probability for one candidate (for `tieBreaker`). */
|
|
63
|
+
export declare function clefScore(o: Omit<ClefOptions, 'threshold' | 'concurrency' | 'remember'>): (c: Candidate) => Promise<number>;
|
|
64
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question, with its answer kept. */
|
|
65
|
+
export declare function clefAnswers(o: ClefOptions): (candidates: Candidate[]) => Promise<OpinionAnswer[]>;
|
|
66
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question. */
|
|
67
|
+
export declare function clefOpinion(o: ClefOptions): (candidates: Candidate[]) => Promise<boolean[]>;
|
|
68
|
+
export type KeyCheck = {
|
|
69
|
+
ok: true;
|
|
70
|
+
ms: number;
|
|
71
|
+
} | {
|
|
72
|
+
ok: false;
|
|
73
|
+
reason: string;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* For a "power up with your key" setting: asks one tiny question (a fraction of a cent) and says
|
|
77
|
+
* whether the key works, or why not, in words a settings screen can show.
|
|
78
|
+
*/
|
|
79
|
+
export declare function checkKey(o: ({
|
|
80
|
+
provider: 'jev';
|
|
81
|
+
} & Pick<JevOptions, 'apiKey' | 'model'>) | ({
|
|
82
|
+
provider: 'clef';
|
|
83
|
+
} & Pick<ClefOptions, 'accountId' | 'apiToken' | 'model'>), doFetch?: Fetch): Promise<KeyCheck>;
|
|
84
|
+
export {};
|
package/dist/opinions.js
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/** The text a model sees: the caller before and after, then the helper (layouts tested: this one is best). */
|
|
2
|
+
export function candidateState(c) {
|
|
3
|
+
const file = c.file ?? 'the file';
|
|
4
|
+
const cut = (s) => (s.length <= 12000 ? s : s.slice(0, 12000) + '\n... (cut)');
|
|
5
|
+
// Extract is detected as inline run backwards: for an extract, `caller` is the new caller.
|
|
6
|
+
const [before, after] = c.kind === 'extract' ? [c.code.callerNew, c.code.caller] : [c.code.caller, c.code.callerNew];
|
|
7
|
+
const where = c.kind === 'extract' ? 'added in this change' : 'removed in this change';
|
|
8
|
+
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`;
|
|
9
|
+
}
|
|
10
|
+
const YES_NO = {
|
|
11
|
+
extract: "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.",
|
|
12
|
+
inline: "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.",
|
|
13
|
+
};
|
|
14
|
+
const CHOICE = {
|
|
15
|
+
extract: {
|
|
16
|
+
instructions: "What best describes the helper and the caller's old code?",
|
|
17
|
+
criteria: {
|
|
18
|
+
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).",
|
|
19
|
+
new: "The helper is new code: the caller's old code did not contain these statements.",
|
|
20
|
+
rewritten: "The caller's old code did something similar, but the helper is a different implementation, not the same statements.",
|
|
21
|
+
elsewhere: "The helper's statements came from some other place, not from this caller.",
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
inline: {
|
|
25
|
+
instructions: "What best describes the helper and the caller's new code?",
|
|
26
|
+
criteria: {
|
|
27
|
+
moved: "The helper's statements now appear written out in the caller, in place of the call (renamed variables or small edits allowed).",
|
|
28
|
+
deleted: "The helper's code was dropped: the caller's new code does not contain these statements.",
|
|
29
|
+
rewritten: "The caller now does something similar, but with a different implementation, not the same statements.",
|
|
30
|
+
elsewhere: "The helper's statements went to some other place, not into this caller.",
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
/** The key was refused or the account has no credit: no other question would succeed either. */
|
|
35
|
+
export class OpinionKeyError extends Error {
|
|
36
|
+
provider;
|
|
37
|
+
status;
|
|
38
|
+
constructor(provider, status, detail) {
|
|
39
|
+
super(`${provider === 'jev' ? 'TypeSafe' : 'Cloudflare'} ${status === 402 ? 'account has no credit left' : 'refused the key'} (${status})${detail ? `: ${detail.slice(0, 200)}` : ''}`);
|
|
40
|
+
this.name = 'OpinionKeyError';
|
|
41
|
+
this.provider = provider;
|
|
42
|
+
this.status = status;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const FATAL = new Set([401, 402, 403]);
|
|
46
|
+
/**
|
|
47
|
+
* Ask at most `limit` at a time. A question that fails for a passing reason (network, a 5xx)
|
|
48
|
+
* counts as "no"; a refused key or an empty account stops the batch and throws, so the diff
|
|
49
|
+
* reports it (`diagnostics`, pass "second-opinion") instead of quietly answering "no" to all.
|
|
50
|
+
*/
|
|
51
|
+
async function each(items, limit, f, fallback) {
|
|
52
|
+
const out = items.map(fallback);
|
|
53
|
+
let next = 0;
|
|
54
|
+
let fatal = null;
|
|
55
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
56
|
+
while (next < items.length && !fatal) {
|
|
57
|
+
const i = next++;
|
|
58
|
+
try {
|
|
59
|
+
out[i] = await f(items[i]);
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (e instanceof OpinionKeyError)
|
|
63
|
+
fatal = e;
|
|
64
|
+
else
|
|
65
|
+
out[i] = fallback(items[i]);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}));
|
|
69
|
+
if (fatal)
|
|
70
|
+
throw fatal;
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
async function post(doFetch, provider, url, token, body) {
|
|
74
|
+
const r = await doFetch(url, { method: 'POST', headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
75
|
+
if (FATAL.has(r.status))
|
|
76
|
+
throw new OpinionKeyError(provider, r.status, await r.text().catch(() => ''));
|
|
77
|
+
if (!r.ok)
|
|
78
|
+
throw new Error(`${r.status} ${await r.text()}`);
|
|
79
|
+
const out = await r.json();
|
|
80
|
+
return out.result ?? out;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The same candidate asked twice (the diff opened again, or a file shown in two views) is
|
|
84
|
+
* answered from memory: one entry per candidate's code, the oldest dropped past `size`.
|
|
85
|
+
*/
|
|
86
|
+
function remembered(size, ask) {
|
|
87
|
+
const memo = new Map();
|
|
88
|
+
return (c) => {
|
|
89
|
+
const key = [c.kind, c.file ?? '', c.helper, c.caller, c.code.helper, c.code.caller, c.code.callerNew].join('\0');
|
|
90
|
+
const hit = memo.get(key);
|
|
91
|
+
if (hit)
|
|
92
|
+
return hit;
|
|
93
|
+
const p = ask(c);
|
|
94
|
+
memo.set(key, p);
|
|
95
|
+
// A failed question is not remembered: the next diff may ask it again.
|
|
96
|
+
p.catch(() => memo.delete(key));
|
|
97
|
+
if (memo.size > size)
|
|
98
|
+
memo.delete(memo.keys().next().value);
|
|
99
|
+
return p;
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** "Very likely" from 0.90, "Likely" from the accept threshold, nothing below it. */
|
|
103
|
+
export function bandFor(score, threshold) {
|
|
104
|
+
if (score >= 0.9)
|
|
105
|
+
return 'very-likely';
|
|
106
|
+
return score >= threshold ? 'likely' : undefined;
|
|
107
|
+
}
|
|
108
|
+
const unanswered = (model, question, options) => () => ({ accept: false, score: 0, model, question, options, answer: 'unanswered' });
|
|
109
|
+
/** TypeSafe's Jev, asked a multiple-choice question (moved / new / rewritten / elsewhere), with its answer kept. */
|
|
110
|
+
export function jevAnswers(o) {
|
|
111
|
+
const doFetch = o.fetch ?? fetch;
|
|
112
|
+
const t = o.threshold ?? 0.74;
|
|
113
|
+
const model = o.model ?? 'jev-1.14.0';
|
|
114
|
+
const ask = async (c) => {
|
|
115
|
+
const q = CHOICE[c.kind];
|
|
116
|
+
const options = Object.keys(q.criteria);
|
|
117
|
+
const out = await post(doFetch, 'jev', JEV_URL, o.apiKey, {
|
|
118
|
+
model,
|
|
119
|
+
state: candidateState(c),
|
|
120
|
+
questions: { q: { type: 'choice', instructions: q.instructions, criteria: q.criteria } },
|
|
121
|
+
});
|
|
122
|
+
const probabilities = out.answers.q.probabilities ?? {};
|
|
123
|
+
const answer = Object.entries(probabilities).sort((x, y) => y[1] - x[1])[0]?.[0] ?? 'unanswered';
|
|
124
|
+
const p = probabilities.moved ?? 0;
|
|
125
|
+
const base = { model, question: q.instructions, options, answer };
|
|
126
|
+
if (p >= t)
|
|
127
|
+
return { ...base, accept: true, score: p, band: bandFor(p, t) };
|
|
128
|
+
const tb = o.tieBreaker;
|
|
129
|
+
if (!tb || p < (tb.from ?? 0.6))
|
|
130
|
+
return { ...base, accept: false, score: p };
|
|
131
|
+
try {
|
|
132
|
+
const second = await tb.ask(c);
|
|
133
|
+
const threshold = tb.threshold ?? 0.8;
|
|
134
|
+
const accept = second >= threshold;
|
|
135
|
+
return { ...base, model: `${model} + clef`, accept, score: accept ? second : p, band: accept ? bandFor(second, threshold) : undefined };
|
|
136
|
+
}
|
|
137
|
+
catch (e) {
|
|
138
|
+
if (e instanceof OpinionKeyError)
|
|
139
|
+
throw e;
|
|
140
|
+
return { ...base, accept: false, score: p };
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const answer = o.remember === 0 ? ask : remembered(o.remember ?? 2000, ask);
|
|
144
|
+
return (cs) => each(cs, o.concurrency ?? 8, answer, (c) => unanswered(model, CHOICE[c.kind].instructions, Object.keys(CHOICE[c.kind].criteria))());
|
|
145
|
+
}
|
|
146
|
+
/** TypeSafe's Jev as a yes/no second opinion (see `jevAnswers` for the answers themselves). */
|
|
147
|
+
export function jevOpinion(o) {
|
|
148
|
+
const answers = jevAnswers(o);
|
|
149
|
+
return async (cs) => (await answers(cs)).map((a) => a.accept);
|
|
150
|
+
}
|
|
151
|
+
const JEV_URL = 'https://api.typesafe.ai/v1/systemone';
|
|
152
|
+
/** Cloudflare's Clef on Workers AI: the yes/no probability for one candidate (for `tieBreaker`). */
|
|
153
|
+
export function clefScore(o) {
|
|
154
|
+
const doFetch = o.fetch ?? fetch;
|
|
155
|
+
return async (c) => {
|
|
156
|
+
const out = await post(doFetch, 'clef', clefUrl(o.accountId), o.apiToken, {
|
|
157
|
+
model: o.model ?? 'clef',
|
|
158
|
+
state: candidateState(c),
|
|
159
|
+
questions: { q: { type: 'noul', instructions: YES_NO[c.kind] } },
|
|
160
|
+
});
|
|
161
|
+
return out.answers.q.noul ?? 0;
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question, with its answer kept. */
|
|
165
|
+
export function clefAnswers(o) {
|
|
166
|
+
const t = o.threshold ?? 0.9;
|
|
167
|
+
const model = o.model ?? 'clef';
|
|
168
|
+
const score = clefScore(o);
|
|
169
|
+
const ask = async (c) => {
|
|
170
|
+
const p = await score(c);
|
|
171
|
+
const accept = p >= t;
|
|
172
|
+
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' };
|
|
173
|
+
};
|
|
174
|
+
const answer = o.remember === 0 ? ask : remembered(o.remember ?? 2000, ask);
|
|
175
|
+
return (cs) => each(cs, o.concurrency ?? 8, answer, (c) => unanswered(model, YES_NO[c.kind], ['yes', 'no'])());
|
|
176
|
+
}
|
|
177
|
+
/** Cloudflare's Clef on Workers AI, asked a yes/no question. */
|
|
178
|
+
export function clefOpinion(o) {
|
|
179
|
+
const answers = clefAnswers(o);
|
|
180
|
+
return async (cs) => (await answers(cs)).map((a) => a.accept);
|
|
181
|
+
}
|
|
182
|
+
const clefUrl = (accountId) => `https://api.cloudflare.com/client/v4/accounts/${accountId}/ai/run/@cf/cloudflare/clef`;
|
|
183
|
+
/**
|
|
184
|
+
* For a "power up with your key" setting: asks one tiny question (a fraction of a cent) and says
|
|
185
|
+
* whether the key works, or why not, in words a settings screen can show.
|
|
186
|
+
*/
|
|
187
|
+
export async function checkKey(o, doFetch = fetch) {
|
|
188
|
+
const start = Date.now();
|
|
189
|
+
const question = { q: { type: 'noul', instructions: 'Does this text contain a number?' } };
|
|
190
|
+
try {
|
|
191
|
+
const out = o.provider === 'jev'
|
|
192
|
+
? await post(doFetch, 'jev', JEV_URL, o.apiKey, { model: o.model ?? 'jev-1.14.0', state: 'There are 3 apples.', questions: question })
|
|
193
|
+
: await post(doFetch, 'clef', clefUrl(o.accountId), o.apiToken, { model: o.model ?? 'clef', state: 'There are 3 apples.', questions: question });
|
|
194
|
+
if (typeof out?.answers?.q?.noul !== 'number')
|
|
195
|
+
return { ok: false, reason: 'the service answered in an unexpected shape' };
|
|
196
|
+
return { ok: true, ms: Date.now() - start };
|
|
197
|
+
}
|
|
198
|
+
catch (e) {
|
|
199
|
+
return { ok: false, reason: e instanceof OpinionKeyError ? e.message : `could not reach the service (${e.message.slice(0, 120)})` };
|
|
200
|
+
}
|
|
201
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Node } from 'web-tree-sitter';
|
|
2
|
+
import { type LanguageConfig } from './parse.js';
|
|
3
|
+
import { type FunctionInfo } from './syntax.js';
|
|
4
|
+
export interface Pairing {
|
|
5
|
+
/** The same function on the other side, if it still exists there. */
|
|
6
|
+
counterpart(f: FunctionInfo): FunctionInfo | undefined;
|
|
7
|
+
/** Its body reappears in another function on the other side: moved or renamed, not inlined. */
|
|
8
|
+
hasTwin(f: FunctionInfo): boolean;
|
|
9
|
+
}
|
|
10
|
+
export declare function pairFunctions(oldFns: FunctionInfo[], newFns: FunctionInfo[], oldRoot: Node, newRoot: Node, cfg: LanguageConfig): Pairing;
|