Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,4 @@
# tools/copycheck
- A finding is fixed by rewriting the code, never by excusing it. There is no allowlist.
- Test: `./gradlew :tools:copycheck:test`; run for real with `./incari copycheck`.
@@ -0,0 +1,28 @@
# tools/copycheck: the verbatim-copy check
Fails if an Incari Java file has a long run of code identical to the decompiled game. Pasting
from the decompiled tree is easy to do by accident, for people and agents. This is the mechanical
half of "write it fresh"; review is the other half.
```sh
./incari copycheck # after ./incari setup, ~10 seconds; CI runs it too
./incari copycheck --window=40 # stricter, for spot checks
```
`JavaTokens` lexes, `WindowIndex` hashes every 60-token window of the game, `CopyCheck` reports
matching runs.
## Invariants
- **Compares against the pristine decompiled source**, not the patched tree.
- **Checks every Java file outside `work/`** that git tracks or would track, so it works before a commit.
- **Formatting, comments, imports and `package` lines are ignored,** so reformatting doesn't hide a
paste. Identifiers count.
- **A 60-token window** (5–8 lines). Shorter shared runs (signatures, common loops) are normal.
- **No allowlist.** A finding means a rewrite.
## How to test
```sh
./gradlew :tools:copycheck:test
```
@@ -0,0 +1,21 @@
plugins {
application
}
dependencies {
// The workspace layout and version pin: compares against the same decompiled tree
// `incari setup` produced.
implementation(project(":tools:build"))
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testRuntimeOnly(libs.junit.launcher)
}
application {
applicationName = "incari-copycheck"
mainClass = "incari.tools.copycheck.Main"
// The vendor tree has millions of token windows; the index is a sorted long[].
applicationDefaultJvmArgs = listOf("-Xmx2g")
}
@@ -0,0 +1,90 @@
package incari.tools.copycheck;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Finds runs of Incari code that are token-for-token identical to code in the vendor tree.
*
* <p>Agents and people work next to the decompiled game, and code pasted from it into an
* Incari module is both a quality problem and a legal one: Incari modules are published, Mojang
* code must never be. Formatting, comments and imports are ignored, so reformatting a pasted
* block doesn't hide it; renaming every identifier would, which is what a review is for.
*/
final class CopyCheck {
/** Enough tokens for about five to eight lines of code: past what signatures and idioms share. */
static final int DEFAULT_WINDOW = 60;
/** One copied run: {@code tokens} tokens long, on lines {@code firstLine..lastLine} of {@code file}. */
record Finding(String file, int firstLine, int lastLine, int tokens) {
@Override
public String toString() {
return file + ":" + firstLine + "-" + lastLine + ": " + tokens + " tokens identical to vendor code";
}
}
private final WindowIndex index;
private CopyCheck(WindowIndex index) {
this.index = index;
}
/** Indexes every {@code .java} file under {@code vendorRoot}. */
static CopyCheck indexVendorTree(Path vendorRoot, int window) throws IOException {
WindowIndex index = new WindowIndex(window);
try (Stream<Path> files = Files.walk(vendorRoot)) {
for (Path file : (Iterable<Path>) files.filter(p -> p.toString().endsWith(".java"))::iterator) {
index.addFile(JavaTokens.tokenize(Files.readString(file, StandardCharsets.UTF_8)));
}
}
index.seal();
return new CopyCheck(index);
}
static CopyCheck of(List<String> vendorSources, int window) {
WindowIndex index = new WindowIndex(window);
for (String source : vendorSources) {
index.addFile(JavaTokens.tokenize(source));
}
index.seal();
return new CopyCheck(index);
}
/** Every copied run in one Incari file, merged where windows overlap. */
List<Finding> check(String name, String source) {
List<JavaTokens.Token> tokens = JavaTokens.tokenize(source);
long[] hashes = WindowIndex.windowHashes(tokens, index.window());
List<Finding> findings = new ArrayList<>();
int runStart = -1;
int runEnd = -1;
for (int i = 0; i < hashes.length; i++) {
if (!index.contains(hashes[i])) {
continue;
}
int windowEnd = i + index.window() - 1;
if (runStart >= 0 && i <= runEnd + 1) {
runEnd = windowEnd;
} else {
if (runStart >= 0) {
findings.add(finding(name, tokens, runStart, runEnd));
}
runStart = i;
runEnd = windowEnd;
}
}
if (runStart >= 0) {
findings.add(finding(name, tokens, runStart, runEnd));
}
return findings;
}
private static Finding finding(String name, List<JavaTokens.Token> tokens, int start, int end) {
return new Finding(name, tokens.get(start).line(), tokens.get(end).line(), end - start + 1);
}
}
@@ -0,0 +1,110 @@
package incari.tools.copycheck;
import java.util.ArrayList;
import java.util.List;
/**
* A deliberately small Java lexer: enough to compare code by its tokens while ignoring
* whitespace, comments, formatting, and the {@code package}/{@code import} header.
*
* <p>It doesn't need to be a correct Java lexer, only a consistent one: the same text must
* always give the same tokens, on both sides of the comparison.
*/
final class JavaTokens {
/** One token and the 1-based line it starts on. */
record Token(String text, int line) {}
private JavaTokens() {}
static List<Token> tokenize(String source) {
List<Token> tokens = new ArrayList<>();
int i = 0;
int line = 1;
int n = source.length();
while (i < n) {
char c = source.charAt(i);
if (c == '\n') {
line++;
i++;
} else if (Character.isWhitespace(c)) {
i++;
} else if (c == '/' && i + 1 < n && source.charAt(i + 1) == '/') {
while (i < n && source.charAt(i) != '\n') {
i++;
}
} else if (c == '/' && i + 1 < n && source.charAt(i + 1) == '*') {
int end = source.indexOf("*/", i + 2);
int stop = end < 0 ? n : end + 2;
line += count(source, i, stop, '\n');
i = stop;
} else if (source.startsWith("\"\"\"", i)) {
int end = source.indexOf("\"\"\"", i + 3);
int stop = end < 0 ? n : end + 3;
tokens.add(new Token(source.substring(i, stop), line));
line += count(source, i, stop, '\n');
i = stop;
} else if (c == '"' || c == '\'') {
int stop = i + 1;
while (stop < n && source.charAt(stop) != c && source.charAt(stop) != '\n') {
stop += source.charAt(stop) == '\\' ? 2 : 1;
}
stop = Math.min(stop + 1, n);
tokens.add(new Token(source.substring(i, stop), line));
i = stop;
} else if (Character.isJavaIdentifierStart(c) || Character.isDigit(c)) {
int stop = i + 1;
while (stop < n
&& (Character.isJavaIdentifierPart(source.charAt(stop))
|| isDecimalPoint(source, stop, Character.isDigit(c)))) {
stop++;
}
tokens.add(new Token(source.substring(i, stop), line));
i = stop;
} else {
tokens.add(new Token(String.valueOf(c), line));
i++;
}
}
return dropHeader(tokens);
}
/** Drops {@code package} and {@code import} statements: every file shares their shape. */
private static List<Token> dropHeader(List<Token> tokens) {
List<Token> body = new ArrayList<>(tokens.size());
boolean skipping = false;
for (int i = 0; i < tokens.size(); i++) {
Token token = tokens.get(i);
boolean statementStart = i == 0 || tokens.get(i - 1).text().equals(";");
if (!skipping
&& statementStart
&& (token.text().equals("package") || token.text().equals("import"))) {
skipping = true;
}
if (!skipping) {
body.add(token);
} else if (token.text().equals(";")) {
skipping = false;
}
}
return body;
}
/** A {@code .} inside a number literal ({@code 1.5}), as opposed to a member access. */
private static boolean isDecimalPoint(String source, int at, boolean inNumber) {
return inNumber
&& source.charAt(at) == '.'
&& at + 1 < source.length()
&& Character.isDigit(source.charAt(at + 1));
}
private static int count(String text, int from, int to, char c) {
int count = 0;
for (int i = from; i < to; i++) {
if (text.charAt(i) == c) {
count++;
}
}
return count;
}
}
@@ -0,0 +1,90 @@
package incari.tools.copycheck;
import incari.tools.build.BuildConfig;
import incari.tools.build.CliException;
import incari.tools.build.Git;
import incari.tools.build.Log;
import incari.tools.build.Workspace;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
/**
* {@code ./incari copycheck}: fails if any Incari Java file contains a long run copied from
* the decompiled game.
*
* <p>Compares against the pristine decompiled sources in {@code work/decompiled}, not the
* patched tree: the patched tree holds Incari's own replacement classes, which would match
* themselves. Checks every Java file git tracks or would track outside {@code work/}.
*/
public final class Main {
private Main() {}
public static void main(String[] args) {
try {
System.exit(run(List.of(args)));
} catch (CliException e) {
System.err.println("error: " + e.getMessage());
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
static int run(List<String> args) throws Exception {
int window = CopyCheck.DEFAULT_WINDOW;
for (String arg : args) {
if (arg.startsWith("--window=")) {
window = Integer.parseInt(arg.substring("--window=".length()));
} else {
throw new CliException("Unknown option '" + arg + "'. Usage: ./incari copycheck [--window=<tokens>]");
}
}
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
BuildConfig config = BuildConfig.load(ws.repoRoot());
Path vendor = ws.decompiledDir(config.minecraftVersion());
if (!Files.isDirectory(vendor)) {
throw new CliException("No decompiled sources to compare against. Run: ./incari setup");
}
Log.step("Indexing the decompiled " + config.minecraftVersion() + " sources");
CopyCheck check = CopyCheck.indexVendorTree(vendor, window);
List<String> files = incariJavaFiles(ws);
Log.step("Checking " + files.size() + " Incari Java files (" + window + "-token windows)");
List<CopyCheck.Finding> findings = new ArrayList<>();
for (String file : files) {
String source = Files.readString(ws.repoRoot().resolve(file), StandardCharsets.UTF_8);
findings.addAll(check.check(file, source));
}
if (!findings.isEmpty()) {
System.err.println("Code identical to the decompiled game (write Incari code fresh, never copy it):");
findings.forEach(f -> System.err.println(" " + f));
return 1;
}
Log.step("Copy check passed: no Incari file repeats vendor code");
return 0;
}
/** Tracked and untracked-but-not-ignored Java files outside {@code work/}. */
private static List<String> incariJavaFiles(Workspace ws) throws Exception {
String out = new Git(ws.repoRoot())
.run("ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", "*.java");
List<String> files = new ArrayList<>();
for (String file : out.split("\0", -1)) {
if (!file.isEmpty()
&& !file.startsWith("work/")
&& Files.isRegularFile(ws.repoRoot().resolve(file))) {
files.add(file);
}
}
files.sort(null);
return files;
}
}
@@ -0,0 +1,85 @@
package incari.tools.copycheck;
import java.util.Arrays;
import java.util.List;
/**
* Hashes of every run of {@code window} consecutive tokens in the vendor tree, sorted for
* binary search.
*
* <p>A primitive sorted array rather than a hash set: the vendor tree has millions of windows,
* and boxed longs would need several times the memory.
*/
final class WindowIndex {
private final int window;
private long[] hashes = new long[1 << 20];
private int size;
private boolean sealed;
WindowIndex(int window) {
this.window = window;
}
int window() {
return window;
}
void addFile(List<JavaTokens.Token> tokens) {
if (sealed) {
throw new IllegalStateException("index is sealed");
}
for (long hash : windowHashes(tokens, window)) {
if (size == hashes.length) {
hashes = Arrays.copyOf(hashes, size * 2);
}
hashes[size++] = hash;
}
}
/** Sorts the hashes. Call once, after the last {@link #addFile}. */
void seal() {
hashes = Arrays.copyOf(hashes, size);
Arrays.sort(hashes);
sealed = true;
}
boolean contains(long hash) {
if (!sealed) {
throw new IllegalStateException("seal() the index first");
}
return Arrays.binarySearch(hashes, hash) >= 0;
}
/**
* One hash per window: {@code result[i]} covers tokens {@code i .. i + window - 1}. Each
* window is hashed independently, so equal windows get equal hashes wherever they occur.
*/
static long[] windowHashes(List<JavaTokens.Token> tokens, int window) {
int count = tokens.size() - window + 1;
if (count <= 0) {
return new long[0];
}
long[] tokenHashes = new long[tokens.size()];
for (int i = 0; i < tokens.size(); i++) {
tokenHashes[i] = mix(tokens.get(i).text().hashCode());
}
long[] result = new long[count];
for (int start = 0; start < count; start++) {
long hash = 0x9E3779B97F4A7C15L;
for (int j = start; j < start + window; j++) {
hash = (hash ^ tokenHashes[j]) * 0x100000001B3L;
hash = Long.rotateLeft(hash, 27);
}
result[start] = hash;
}
return result;
}
private static long mix(long value) {
long z = value + 0x9E3779B97F4A7C15L;
z = (z ^ (z >>> 30)) * 0xBF58476D1CE4E5B9L;
z = (z ^ (z >>> 27)) * 0x94D049BB133111EBL;
return z ^ (z >>> 31);
}
}
@@ -0,0 +1,114 @@
package incari.tools.copycheck;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.jupiter.api.Test;
class CopyCheckTest {
private static final String VENDOR = """
package com.example.vendor;
import java.util.List;
public class Engine {
private int speed;
public int accelerate(int delta, List<Integer> history) {
int next = this.speed + delta;
if (next > 100) {
next = 100;
} else if (next < 0) {
next = 0;
}
history.add(next);
this.speed = next;
return next;
}
}
""";
@Test
void flagsACopiedMethodEvenWhenReformattedAndCommented() {
String incari = """
package incari.platform;
import java.util.List;
import java.util.ArrayList;
final class Pasted {
// Looks innocent after a reformat.
public int accelerate(int delta, List<Integer> history) { int next = this.speed + delta;
if (next > 100) { next = 100; }
else if (next < 0) { next = 0; }
history.add(next); this.speed = next; return next; }
}
""";
List<CopyCheck.Finding> findings = CopyCheck.of(List.of(VENDOR), 20).check("Pasted.java", incari);
assertThat(findings).singleElement().satisfies(f -> {
assertThat(f.file()).isEqualTo("Pasted.java");
assertThat(f.firstLine()).isEqualTo(8);
assertThat(f.lastLine()).isEqualTo(12);
assertThat(f.tokens()).isGreaterThanOrEqualTo(40);
});
}
@Test
void ignoresSharedImportsAndShortCommonRuns() {
String incari = """
package incari.platform;
import java.util.List;
final class Fresh {
int clamp(int value) {
return Math.max(0, Math.min(100, value));
}
public int accelerate(int delta, List<Integer> history) {
return clamp(delta);
}
}
""";
assertThat(CopyCheck.of(List.of(VENDOR), 20).check("Fresh.java", incari))
.isEmpty();
}
@Test
void reportsSeparateRunsSeparately() {
String block = IntStream.range(0, 30).mapToObj(i -> "call" + i + "();").collect(Collectors.joining("\n"));
String vendor = "class V { void a() {\n" + block + "\n} }";
String incari =
"class I { void a() {\n" + block + "\nfresh(); other(); stuff(); here(); and(); more(); code();\n"
+ "fillers(); to(); break(); the(); run(); apart(); now();\n" + block + "\n} }";
List<CopyCheck.Finding> findings = CopyCheck.of(List.of(vendor), 20).check("I.java", incari);
assertThat(findings).hasSize(2);
}
@Test
void tokenizerSkipsCommentsAndKeepsLiteralsWhole() {
List<String> tokens =
JavaTokens.tokenize("""
package a.b; import c.D;
/* block
comment */ String s = "a // not a comment"; // tail
char c = '\\''; double d = 1.5e3; var t = \"""
text block
\""";
""").stream().map(JavaTokens.Token::text).toList();
assertThat(tokens)
.containsSubsequence("String", "s", "=", "\"a // not a comment\"", ";")
.contains("'\\''", "1.5e3")
.doesNotContain("package", "import", "block", "tail");
assertThat(tokens.stream().filter(t -> t.startsWith("\"\"\""))).hasSize(1);
}
}