@plannotator/sem-jiff 0.0.0-stage → 0.2.0
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 +36 -0
- package/LICENSE-APACHE +191 -0
- package/LICENSE-MIT +21 -0
- package/README.md +110 -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 +76 -0
- package/dist/index.js +493 -0
- package/dist/inline.d.ts +21 -0
- package/dist/inline.js +723 -0
- package/dist/languages.d.ts +2 -0
- package/dist/languages.js +28 -0
- package/dist/linediff.d.ts +27 -0
- package/dist/linediff.js +163 -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 +137 -0
- package/dist/parse.d.ts +118 -0
- package/dist/parse.js +1274 -0
- package/dist/pierre-types.d.ts +101 -0
- package/dist/pierre-types.js +5 -0
- package/dist/runtime.d.ts +46 -0
- package/dist/runtime.js +51 -0
- package/dist/structure.d.ts +13 -0
- package/dist/structure.js +894 -0
- package/dist/summary.d.ts +19 -0
- package/dist/summary.js +15 -0
- package/dist/syntax.d.ts +67 -0
- package/dist/syntax.js +412 -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,27 @@
|
|
|
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
|
+
/** Lines as `diffLines` gives them (see there). */
|
|
25
|
+
export declare function alignedLineDiff(oldRoot: Node, newRoot: Node, cfg: LanguageConfig, oldLines: string[], newLines: string[]): ChangeBlock[];
|
|
26
|
+
/** Unified diff text for the blocks (standard unified diff format). */
|
|
27
|
+
export declare function toPatch(name: string, blocks: ChangeBlock[], oldLines: string[], newLines: string[], context?: number): string;
|
package/dist/linediff.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
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 { attachedAbove, codeLines, endLine, keepWeights, longestInOrder, pairSameNamed, startLine, tokens } from "./syntax.js";
|
|
10
|
+
function anchors(oldContainer, newContainer, cfg) {
|
|
11
|
+
const keyed = (container) => {
|
|
12
|
+
const seen = new Map();
|
|
13
|
+
return cfg.declarationsIn(container).map((d) => {
|
|
14
|
+
const accessor = d.node.children.find((c) => c?.type === 'get' || c?.type === 'set')?.type ?? '';
|
|
15
|
+
const base = `${d.kind}:${accessor}${d.name}`;
|
|
16
|
+
const n = seen.get(base) ?? 0;
|
|
17
|
+
seen.set(base, n + 1);
|
|
18
|
+
return { key: n ? `${base}#${n}` : base, d };
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
// Same pairing as the move detector: repeated names pair by similarity.
|
|
22
|
+
const base = (x) => x.key.replace(/#\d+$/, '');
|
|
23
|
+
// Repeated containers of a type spread over several (Swift extensions) pair by the members they hold.
|
|
24
|
+
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)];
|
|
25
|
+
const pairs = pairSameNamed(keyed(oldContainer), keyed(newContainer), base, similarBy)
|
|
26
|
+
.map(([o, n]) => ({ a: o.d, b: n.d }))
|
|
27
|
+
.sort((x, y) => x.a.node.startIndex - y.a.node.startIndex);
|
|
28
|
+
// Keep the longest run whose order is the same on both sides (the same choice the move detector makes).
|
|
29
|
+
const seq = pairs.map((p) => p.b.node.startIndex);
|
|
30
|
+
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);
|
|
31
|
+
return keep.map((i) => {
|
|
32
|
+
const { a, b } = pairs[i];
|
|
33
|
+
return { a: a.node, b: b.node, ...(a.members && b.members ? { members: [a.members, b.members] } : {}) };
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A file's lines for diffing: the real lines only (no empty entry after a final
|
|
38
|
+
* newline), with a missing final newline marked on the last line, so that adding or
|
|
39
|
+
* removing it is a change and the patch can say so.
|
|
40
|
+
*/
|
|
41
|
+
export const NO_FINAL_NEWLINE = '\u0000no-newline';
|
|
42
|
+
export function diffLines(text) {
|
|
43
|
+
if (text === '')
|
|
44
|
+
return [];
|
|
45
|
+
const lines = text.split('\n');
|
|
46
|
+
if (text.endsWith('\n'))
|
|
47
|
+
lines.pop();
|
|
48
|
+
else
|
|
49
|
+
lines[lines.length - 1] += NO_FINAL_NEWLINE;
|
|
50
|
+
return lines;
|
|
51
|
+
}
|
|
52
|
+
/** Lines as `diffLines` gives them (see there). */
|
|
53
|
+
export function alignedLineDiff(oldRoot, newRoot, cfg, oldLines, newLines) {
|
|
54
|
+
const blocks = [];
|
|
55
|
+
/** Free diff of a region (1-based inclusive lines; may be empty). */
|
|
56
|
+
const freeDiff = (r) => {
|
|
57
|
+
if (r.oldStart > r.oldEnd && r.newStart > r.newEnd)
|
|
58
|
+
return;
|
|
59
|
+
const a = oldLines.slice(r.oldStart - 1, Math.max(r.oldStart - 1, r.oldEnd));
|
|
60
|
+
const b = newLines.slice(r.newStart - 1, Math.max(r.newStart - 1, r.newEnd));
|
|
61
|
+
let o = r.oldStart;
|
|
62
|
+
let n = r.newStart;
|
|
63
|
+
let open = null;
|
|
64
|
+
for (const part of diffArrays(a, b)) {
|
|
65
|
+
const count = part.count ?? part.value.length;
|
|
66
|
+
if (!part.added && !part.removed) {
|
|
67
|
+
open = null;
|
|
68
|
+
o += count;
|
|
69
|
+
n += count;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (!open) {
|
|
73
|
+
open = { old: null, new: null, oldAt: o, newAt: n };
|
|
74
|
+
blocks.push(open);
|
|
75
|
+
}
|
|
76
|
+
if (part.removed) {
|
|
77
|
+
open.old = { start: o, end: o + count - 1 };
|
|
78
|
+
o += count;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
open.new = { start: n, end: n + count - 1 };
|
|
82
|
+
n += count;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
/** Diff a region, anchoring on declarations paired inside `containers`. */
|
|
87
|
+
const anchored = (r, containers) => {
|
|
88
|
+
const pairs = containers ? anchors(containers[0], containers[1], cfg) : [];
|
|
89
|
+
let o = r.oldStart;
|
|
90
|
+
let n = r.newStart;
|
|
91
|
+
for (const p of pairs) {
|
|
92
|
+
// Half-written code can end past the last line (the parser supplies a missing `}`).
|
|
93
|
+
const ps = {
|
|
94
|
+
oldStart: startLine(p.a),
|
|
95
|
+
oldEnd: Math.min(endLine(p.a), oldLines.length),
|
|
96
|
+
newStart: startLine(p.b),
|
|
97
|
+
newEnd: Math.min(endLine(p.b), newLines.length),
|
|
98
|
+
};
|
|
99
|
+
if (ps.oldStart > oldLines.length || ps.newStart > newLines.length)
|
|
100
|
+
continue;
|
|
101
|
+
if (ps.oldStart < o || ps.newStart < n)
|
|
102
|
+
continue; // overlaps a previous anchor (e.g. two declarations on one line)
|
|
103
|
+
freeDiff({ oldStart: o, oldEnd: ps.oldStart - 1, newStart: n, newEnd: ps.newStart - 1 });
|
|
104
|
+
if (p.members)
|
|
105
|
+
anchored(ps, p.members);
|
|
106
|
+
else
|
|
107
|
+
freeDiff(ps);
|
|
108
|
+
o = ps.oldEnd + 1;
|
|
109
|
+
n = ps.newEnd + 1;
|
|
110
|
+
}
|
|
111
|
+
freeDiff({ oldStart: o, oldEnd: r.oldEnd, newStart: n, newEnd: r.newEnd });
|
|
112
|
+
};
|
|
113
|
+
anchored({ oldStart: 1, oldEnd: oldLines.length, newStart: 1, newEnd: newLines.length }, [oldRoot, newRoot]);
|
|
114
|
+
return blocks;
|
|
115
|
+
}
|
|
116
|
+
/** Unified diff text for the blocks (standard unified diff format). */
|
|
117
|
+
export function toPatch(name, blocks, oldLines, newLines, context = 3) {
|
|
118
|
+
const oldCount = oldLines.length;
|
|
119
|
+
// git's header form, so readers strip the a/ and b/ prefixes and see one file.
|
|
120
|
+
const out = [`diff --git a/${name} b/${name}`, `--- a/${name}`, `+++ b/${name}`];
|
|
121
|
+
// Merge blocks whose context would touch into hunks.
|
|
122
|
+
let i = 0;
|
|
123
|
+
while (i < blocks.length) {
|
|
124
|
+
let j = i;
|
|
125
|
+
const startO = (b) => b.old?.start ?? b.oldAt;
|
|
126
|
+
const endO = (b) => (b.old ? b.old.end : b.oldAt - 1);
|
|
127
|
+
while (j + 1 < blocks.length && startO(blocks[j + 1]) - endO(blocks[j]) - 1 <= 2 * context)
|
|
128
|
+
j++;
|
|
129
|
+
const first = blocks[i];
|
|
130
|
+
const hunkOldStart = Math.max(1, startO(first) - context);
|
|
131
|
+
const lead = startO(first) - hunkOldStart;
|
|
132
|
+
const hunkNewStart = (first.new?.start ?? first.newAt) - lead;
|
|
133
|
+
const lines = [];
|
|
134
|
+
let o = hunkOldStart;
|
|
135
|
+
let n = hunkNewStart;
|
|
136
|
+
for (let k = i; k <= j; k++) {
|
|
137
|
+
const b = blocks[k];
|
|
138
|
+
while (o < startO(b)) {
|
|
139
|
+
lines.push(' ' + (oldLines[o - 1] ?? ''));
|
|
140
|
+
o++;
|
|
141
|
+
n++;
|
|
142
|
+
}
|
|
143
|
+
if (b.old)
|
|
144
|
+
for (let l = b.old.start; l <= b.old.end; l++, o++)
|
|
145
|
+
lines.push('-' + (oldLines[l - 1] ?? ''));
|
|
146
|
+
if (b.new)
|
|
147
|
+
for (let l = b.new.start; l <= b.new.end; l++, n++)
|
|
148
|
+
lines.push('+' + (newLines[l - 1] ?? ''));
|
|
149
|
+
}
|
|
150
|
+
const trailEnd = Math.min(oldCount, o - 1 + context);
|
|
151
|
+
while (o <= trailEnd) {
|
|
152
|
+
lines.push(' ' + (oldLines[o - 1] ?? ''));
|
|
153
|
+
o++;
|
|
154
|
+
n++;
|
|
155
|
+
}
|
|
156
|
+
const oldLen = lines.filter((l) => l[0] !== '+').length;
|
|
157
|
+
const newLen = lines.filter((l) => l[0] !== '-').length;
|
|
158
|
+
out.push(`@@ -${oldLen ? hunkOldStart : hunkOldStart - 1},${oldLen} +${newLen ? hunkNewStart : hunkNewStart - 1},${newLen} @@`, ...lines);
|
|
159
|
+
i = j + 1;
|
|
160
|
+
}
|
|
161
|
+
// git's marker for a last line without a newline, right after that line.
|
|
162
|
+
return out.flatMap((l) => (l.endsWith(NO_FINAL_NEWLINE) ? [l.slice(0, -NO_FINAL_NEWLINE.length), '\'] : [l])).join('\n') + '\n';
|
|
163
|
+
}
|
|
@@ -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;
|
package/dist/pairing.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Which function on one side is the same function on the other: the pairing the extract/inline
|
|
2
|
+
// check builds on. A function with a counterpart still exists (it was not inlined or extracted);
|
|
3
|
+
// one with a twin moved or was renamed. Each rule below is one way the same function shows up.
|
|
4
|
+
import { rule } from "./runtime.js";
|
|
5
|
+
import { callsTo, dice, pairSameNamed, tokens } from "./syntax.js";
|
|
6
|
+
export function pairFunctions(oldFns, newFns, oldRoot, newRoot, cfg) {
|
|
7
|
+
// Same function in both versions: same class (or receiver) and name, or, when the
|
|
8
|
+
// class itself was renamed, the only function of that name on each side.
|
|
9
|
+
// Overloads share a name: pair them by body similarity, not by order.
|
|
10
|
+
// The overload that kept the old parameter list is the old function: when code moves
|
|
11
|
+
// into a new, longer overload (`readFrom(in, funnel)` -> `readFrom(in, funnel, max)`),
|
|
12
|
+
// body similarity alone would pair the old one with the overload now holding its code.
|
|
13
|
+
const signature = (f) => {
|
|
14
|
+
const p = tokens(f.node.childForFieldName('parameters') ?? f.node.childForFieldName('value')?.childForFieldName('parameters') ?? f.body).slice(0, 60);
|
|
15
|
+
return [...p, ...p, ...p, ...tokens(f.body)];
|
|
16
|
+
};
|
|
17
|
+
// An overload that kept the old parameter list exactly is the old function, however
|
|
18
|
+
// much its body changed: `consumeMessages(brokerUrl, topics)` became a wrapper around a
|
|
19
|
+
// new `consumeMessages(consumer, topics)` that now holds the old body.
|
|
20
|
+
const base = (f) => f.key.replace(/#\d+$/, '');
|
|
21
|
+
const params = (f) => {
|
|
22
|
+
const p = f.node.childForFieldName('parameters') ?? f.node.childForFieldName('value')?.childForFieldName('parameters');
|
|
23
|
+
return p ? tokens(p).join(' ') : null;
|
|
24
|
+
};
|
|
25
|
+
const samePlace = (fs, f) => fs.filter((g) => base(g) === base(f));
|
|
26
|
+
const pinned = [];
|
|
27
|
+
// Either way round: one function became several overloads, or several became one.
|
|
28
|
+
for (const f of oldFns) {
|
|
29
|
+
const p = params(f);
|
|
30
|
+
const olds = samePlace(oldFns, f);
|
|
31
|
+
const news = samePlace(newFns, f);
|
|
32
|
+
if (p === null || olds.length > 1 || news.length < 2)
|
|
33
|
+
continue;
|
|
34
|
+
const same = news.filter((g) => params(g) === p);
|
|
35
|
+
if (same.length === 1)
|
|
36
|
+
pinned.push([f, same[0]]);
|
|
37
|
+
}
|
|
38
|
+
for (const g of newFns) {
|
|
39
|
+
const p = params(g);
|
|
40
|
+
const olds = samePlace(oldFns, g);
|
|
41
|
+
const news = samePlace(newFns, g);
|
|
42
|
+
if (p === null || news.length > 1 || olds.length < 2)
|
|
43
|
+
continue;
|
|
44
|
+
const same = olds.filter((f) => params(f) === p);
|
|
45
|
+
if (same.length === 1)
|
|
46
|
+
pinned.push([same[0], g]);
|
|
47
|
+
}
|
|
48
|
+
// A body that reappears token for token under another name was renamed, even when a new
|
|
49
|
+
// function took the old name (`run` -> `fly` and a new `run`; `comments` -> `reviewComments`
|
|
50
|
+
// while `conversation` -> `comments`): pairing by name would set up a false extract and inline.
|
|
51
|
+
// Only one-to-one identical bodies of some size, and only when the same-name partner differs.
|
|
52
|
+
if (rule('SWAPPED_RENAMES')) {
|
|
53
|
+
const text = (f) => tokens(f.body).join(' ');
|
|
54
|
+
const sized = (f) => tokens(f.body).length >= 12;
|
|
55
|
+
const group = (fs) => fs.filter(sized).reduce((m, f) => m.set(text(f), [...(m.get(text(f)) ?? []), f]), new Map());
|
|
56
|
+
const og = group(oldFns);
|
|
57
|
+
const ng = group(newFns);
|
|
58
|
+
const taken = new Set(pinned.flat());
|
|
59
|
+
for (const [t, os] of og) {
|
|
60
|
+
const ns = ng.get(t);
|
|
61
|
+
if (os.length !== 1 || ns?.length !== 1)
|
|
62
|
+
continue;
|
|
63
|
+
const [f, g] = [os[0], ns[0]];
|
|
64
|
+
if (f.name === g.name || taken.has(f) || taken.has(g))
|
|
65
|
+
continue;
|
|
66
|
+
const sameNameNew = newFns.filter((x) => base(x) === base(f));
|
|
67
|
+
const sameNameOld = oldFns.filter((x) => base(x) === base(g));
|
|
68
|
+
// Unless one side's same-name partner is just as identical (then it is a copy, not a rename).
|
|
69
|
+
if ([...sameNameNew, ...sameNameOld].some((x) => text(x) === t))
|
|
70
|
+
continue;
|
|
71
|
+
if (!sameNameNew.length && !sameNameOld.length)
|
|
72
|
+
continue; // a plain rename: hasTwin handles it
|
|
73
|
+
// A namesake that called the other one took its whole body: an inline (`entrySet()` that
|
|
74
|
+
// called `createEntrySet()` now holds its body) or, the other way round, an extract.
|
|
75
|
+
if (sameNameOld.some((x) => callsTo(x.node, f.name, cfg).length) || sameNameNew.some((x) => callsTo(x.node, g.name, cfg).length))
|
|
76
|
+
continue;
|
|
77
|
+
pinned.push([f, g]);
|
|
78
|
+
taken.add(f).add(g);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const pinnedOld = new Set(pinned.map(([a]) => a));
|
|
82
|
+
const pinnedNew = new Set(pinned.map(([, b]) => b));
|
|
83
|
+
const byKey = new Map([
|
|
84
|
+
...pinned,
|
|
85
|
+
...pairSameNamed(oldFns.filter((f) => !pinnedOld.has(f)), newFns.filter((f) => !pinnedNew.has(f)), base, signature),
|
|
86
|
+
]);
|
|
87
|
+
const count = (fs) => fs.reduce((m, f) => m.set(f.name, (m.get(f.name) ?? 0) + 1), new Map());
|
|
88
|
+
const oldCount = count(oldFns);
|
|
89
|
+
const newCount = count(newFns);
|
|
90
|
+
const newOnlyByName = new Map(newFns.filter((f) => newCount.get(f.name) === 1).map((f) => [f.name, f]));
|
|
91
|
+
const counterpart = (f) => byKey.get(f) ?? (oldCount.get(f.name) === 1 ? newOnlyByName.get(f.name) : undefined);
|
|
92
|
+
// A function whose twin (same name, same body) is on the other side was moved or
|
|
93
|
+
// had its class renamed; it was not inlined or extracted.
|
|
94
|
+
// Likewise one whose body reappears in a new function under another name was renamed
|
|
95
|
+
// (`entryIterator` -> `internalEntryIterator`, callers updated).
|
|
96
|
+
const matched = new Set(oldFns.map((f) => counterpart(f)).filter((g) => !!g));
|
|
97
|
+
// A rename takes the old name away. When that name is still declared on this side (the
|
|
98
|
+
// function was kept, say as a one-line arrow the pairing above does not see), its body
|
|
99
|
+
// moving to a new function is an extract or inline, not a rename. (Mere references do
|
|
100
|
+
// not count: callers elsewhere may keep calling the old name.)
|
|
101
|
+
// Declarations are counted: overrides in several classes share a name, and renaming
|
|
102
|
+
// some of them still takes declarations away.
|
|
103
|
+
let declared = null;
|
|
104
|
+
const stillNamed = (name) => {
|
|
105
|
+
declared ??= [namesIn(oldRoot), namesIn(newRoot)];
|
|
106
|
+
return (declared[0].get(name) ?? 0) >= (declared[1].get(name) ?? 0);
|
|
107
|
+
};
|
|
108
|
+
const hasTwin = (f) => {
|
|
109
|
+
const t = tokens(f.body);
|
|
110
|
+
return newFns.some((g) => {
|
|
111
|
+
// Same name, same body: moved. Unless that function is still paired with another one
|
|
112
|
+
// here (it kept its signature as a wrapper): then the body went into a new overload.
|
|
113
|
+
if (g.name === f.name)
|
|
114
|
+
return !matched.has(g) && dice(tokens(g.body), t) >= 0.9;
|
|
115
|
+
// Renamed and lightly edited on the way (`IsSafe` -> `Validate`, 0.82 alike).
|
|
116
|
+
return !matched.has(g) && t.length >= 8 && dice(tokens(g.body), t) >= 0.8 && !stillNamed(g.name);
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
return { counterpart, hasTwin };
|
|
120
|
+
}
|
|
121
|
+
/** How often the tree declares each name (a leaf that is its parent's `name` field). */
|
|
122
|
+
function namesIn(root) {
|
|
123
|
+
const out = new Map();
|
|
124
|
+
const stack = [root];
|
|
125
|
+
while (stack.length) {
|
|
126
|
+
const n = stack.pop();
|
|
127
|
+
if (n.childCount === 0) {
|
|
128
|
+
if (n.parent?.childForFieldName('name')?.id === n.id)
|
|
129
|
+
out.set(n.text, (out.get(n.text) ?? 0) + 1);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
for (const c of n.children)
|
|
133
|
+
if (c)
|
|
134
|
+
stack.push(c);
|
|
135
|
+
}
|
|
136
|
+
return out;
|
|
137
|
+
}
|