@quikit/quikpilot-runner 9.2.0-rc.2 → 9.2.0-rc.3
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/README.md +17 -0
- package/dist/index.js +2251 -1514
- package/dist/index.js.map +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -73,7 +73,7 @@ async function describeQuikTrackFailure(res) {
|
|
|
73
73
|
|
|
74
74
|
// src/callback.ts
|
|
75
75
|
async function reportBack(params) {
|
|
76
|
-
const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unresolved } = params;
|
|
76
|
+
const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, codegenLoop, unresolved } = params;
|
|
77
77
|
const body = { status };
|
|
78
78
|
if (branch) body.branch = branch;
|
|
79
79
|
if (warnings && warnings.length > 0) body.warnings = warnings;
|
|
@@ -81,6 +81,7 @@ async function reportBack(params) {
|
|
|
81
81
|
if (targeting) body.targeting = targeting;
|
|
82
82
|
if (baselineFindings) body.baselineFindings = baselineFindings;
|
|
83
83
|
if (vanishedTests) body.vanishedTests = vanishedTests;
|
|
84
|
+
if (codegenLoop) body.codegenLoop = codegenLoop;
|
|
84
85
|
const res = await fetch(callbackUrl, {
|
|
85
86
|
method: "POST",
|
|
86
87
|
headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
|
|
@@ -624,8 +625,8 @@ var TS_SIBLINGS = { ".js": [".ts", ".tsx"], ".jsx": [".tsx"], ".mjs": [".mts"],
|
|
|
624
625
|
function resolveImport(fromPath, specifier, listing) {
|
|
625
626
|
if (/^(?:@\/|~\/|#|\$|\/)/.test(specifier)) return { kind: "unresolved", reason: "alias" };
|
|
626
627
|
const clean = specifier.replace(/[?#].*$/, "");
|
|
627
|
-
const
|
|
628
|
-
if (!
|
|
628
|
+
const relative6 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
|
|
629
|
+
if (!relative6) return { kind: "external" };
|
|
629
630
|
const base = import_node_path.posix.normalize(import_node_path.posix.join(import_node_path.posix.dirname(fromPath), clean));
|
|
630
631
|
if (base === ".." || base.startsWith("../") || import_node_path.posix.isAbsolute(base)) return { kind: "unresolved", reason: "not found" };
|
|
631
632
|
const ext = import_node_path.posix.extname(base);
|
|
@@ -1071,11 +1072,11 @@ async function runCodegen(gateway, targets, workspaceListing, requiredTests, den
|
|
|
1071
1072
|
envelope = await res.json();
|
|
1072
1073
|
checkHardFailure(envelope, "pilot.codegen", target.path);
|
|
1073
1074
|
throwOnTerminalRefusal(envelope, target.path);
|
|
1074
|
-
const
|
|
1075
|
-
if (
|
|
1076
|
-
throw codegenRefusedError(target.path,
|
|
1075
|
+
const whole2 = unwrapExecute(envelope, "pilot.codegen");
|
|
1076
|
+
if (whole2.outcome !== "GENERATED" || typeof whole2.newContent !== "string") {
|
|
1077
|
+
throw codegenRefusedError(target.path, whole2);
|
|
1077
1078
|
}
|
|
1078
|
-
newContent =
|
|
1079
|
+
newContent = whole2.newContent;
|
|
1079
1080
|
} catch (error) {
|
|
1080
1081
|
if (error instanceof RuntimeReplyError) {
|
|
1081
1082
|
throw new RuntimeReplyError(
|
|
@@ -1131,1669 +1132,2399 @@ function flushCodegenResults(results) {
|
|
|
1131
1132
|
}
|
|
1132
1133
|
}
|
|
1133
1134
|
|
|
1134
|
-
// src/
|
|
1135
|
-
var
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
"
|
|
1141
|
-
|
|
1142
|
-
"child_process",
|
|
1143
|
-
"cluster",
|
|
1144
|
-
"crypto",
|
|
1145
|
-
"dgram",
|
|
1146
|
-
"dns",
|
|
1147
|
-
"domain",
|
|
1148
|
-
"events",
|
|
1149
|
-
"fs",
|
|
1150
|
-
"http",
|
|
1151
|
-
"http2",
|
|
1152
|
-
"https",
|
|
1153
|
-
"net",
|
|
1154
|
-
"os",
|
|
1155
|
-
"path",
|
|
1156
|
-
"perf_hooks",
|
|
1157
|
-
"process",
|
|
1158
|
-
"punycode",
|
|
1159
|
-
"querystring",
|
|
1160
|
-
"readline",
|
|
1161
|
-
"repl",
|
|
1162
|
-
"stream",
|
|
1163
|
-
"string_decoder",
|
|
1164
|
-
"sys",
|
|
1165
|
-
"timers",
|
|
1166
|
-
"tls",
|
|
1167
|
-
"tty",
|
|
1168
|
-
"url",
|
|
1169
|
-
"util",
|
|
1170
|
-
"v8",
|
|
1171
|
-
"vm",
|
|
1172
|
-
"worker_threads",
|
|
1173
|
-
"zlib",
|
|
1174
|
-
"inspector",
|
|
1175
|
-
"async_hooks"
|
|
1176
|
-
]);
|
|
1177
|
-
var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
|
|
1178
|
-
function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
|
|
1179
|
-
if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
|
|
1180
|
-
if (specifier.startsWith("node:")) return null;
|
|
1181
|
-
if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
|
|
1182
|
-
const segments = specifier.split("/");
|
|
1183
|
-
const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
1184
|
-
if (NODE_BUILTINS.has(name)) return null;
|
|
1185
|
-
return name;
|
|
1186
|
-
}
|
|
1187
|
-
function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
|
|
1188
|
-
const found = /* @__PURE__ */ new Set();
|
|
1189
|
-
let match;
|
|
1190
|
-
IMPORT_RE.lastIndex = 0;
|
|
1191
|
-
while (match = IMPORT_RE.exec(source)) {
|
|
1192
|
-
const name = packageNameFromSpecifier(match[2], aliasPrefixes);
|
|
1193
|
-
if (name) found.add(name);
|
|
1194
|
-
}
|
|
1195
|
-
return [...found];
|
|
1135
|
+
// src/codegenMode.ts
|
|
1136
|
+
var CODEGEN_MODE_ENV = "QUIKPILOT_CODEGEN_MODE";
|
|
1137
|
+
function parse(value) {
|
|
1138
|
+
if (typeof value !== "string") return null;
|
|
1139
|
+
const v = value.trim().toLowerCase();
|
|
1140
|
+
if (v === "loop") return "loop";
|
|
1141
|
+
if (v === "single") return "single";
|
|
1142
|
+
return null;
|
|
1196
1143
|
}
|
|
1197
|
-
function
|
|
1198
|
-
|
|
1199
|
-
const violations = [];
|
|
1200
|
-
for (const { targetPath, newContent } of results) {
|
|
1201
|
-
if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
|
|
1202
|
-
const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
|
|
1203
|
-
if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
|
|
1204
|
-
}
|
|
1205
|
-
return { blocked: violations.length > 0, violations };
|
|
1144
|
+
function resolveCodegenMode(env2 = process.env, packetSetting) {
|
|
1145
|
+
return parse(packetSetting) ?? parse(env2[CODEGEN_MODE_ENV]) ?? "single";
|
|
1206
1146
|
}
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1147
|
+
|
|
1148
|
+
// src/codegenLoopRecord.ts
|
|
1149
|
+
var MAX_RECORD_PATHS = 50;
|
|
1150
|
+
var MAX_RECORD_PATH_CHARS = 300;
|
|
1151
|
+
var MAX_RECORD_REASONING_TURNS = 30;
|
|
1152
|
+
var MAX_RECORD_REASONING_CHARS = 500;
|
|
1153
|
+
var MAX_RECORD_FALLBACK_REASON_CHARS = 40;
|
|
1154
|
+
var MAX_STATUS_KEYS = 20;
|
|
1155
|
+
var MAX_STATUS_KEY_CHARS = 40;
|
|
1156
|
+
function whole(n) {
|
|
1157
|
+
return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
|
|
1213
1158
|
}
|
|
1214
|
-
function
|
|
1215
|
-
|
|
1216
|
-
const generated = results.find((r) => (0, import_node_path3.resolve)(r.targetPath) === packageJsonPath);
|
|
1217
|
-
let raw;
|
|
1218
|
-
if (generated) {
|
|
1219
|
-
raw = generated.newContent;
|
|
1220
|
-
} else {
|
|
1221
|
-
try {
|
|
1222
|
-
raw = (0, import_node_fs2.readFileSync)(packageJsonPath, "utf8");
|
|
1223
|
-
} catch {
|
|
1224
|
-
raw = null;
|
|
1225
|
-
}
|
|
1226
|
-
}
|
|
1227
|
-
if (raw === null) return null;
|
|
1228
|
-
try {
|
|
1229
|
-
return dependencyNames(JSON.parse(raw));
|
|
1230
|
-
} catch {
|
|
1231
|
-
return null;
|
|
1232
|
-
}
|
|
1159
|
+
function pathOk(p) {
|
|
1160
|
+
return typeof p === "string" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;
|
|
1233
1161
|
}
|
|
1234
|
-
function
|
|
1235
|
-
let
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
if (inLineComment) {
|
|
1243
|
-
if (c === "\n") {
|
|
1244
|
-
inLineComment = false;
|
|
1245
|
-
out += c;
|
|
1246
|
-
}
|
|
1247
|
-
continue;
|
|
1248
|
-
}
|
|
1249
|
-
if (inBlockComment) {
|
|
1250
|
-
if (c === "*" && next === "/") {
|
|
1251
|
-
inBlockComment = false;
|
|
1252
|
-
i++;
|
|
1162
|
+
function buildCodegenLoopRecord(loop) {
|
|
1163
|
+
let cut = false;
|
|
1164
|
+
const room = (rows) => {
|
|
1165
|
+
const kept = [];
|
|
1166
|
+
for (const r of rows) {
|
|
1167
|
+
if (kept.length >= MAX_RECORD_PATHS) {
|
|
1168
|
+
cut = true;
|
|
1169
|
+
break;
|
|
1253
1170
|
}
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
if (inString) {
|
|
1257
|
-
out += c;
|
|
1258
|
-
if (c === "\\") {
|
|
1259
|
-
out += next;
|
|
1260
|
-
i++;
|
|
1171
|
+
if (!pathOk(r.path)) {
|
|
1172
|
+
cut = true;
|
|
1261
1173
|
continue;
|
|
1262
1174
|
}
|
|
1263
|
-
|
|
1264
|
-
continue;
|
|
1265
|
-
}
|
|
1266
|
-
if (c === '"') {
|
|
1267
|
-
inString = true;
|
|
1268
|
-
out += c;
|
|
1269
|
-
continue;
|
|
1270
|
-
}
|
|
1271
|
-
if (c === "/" && next === "/") {
|
|
1272
|
-
inLineComment = true;
|
|
1273
|
-
i++;
|
|
1274
|
-
continue;
|
|
1275
|
-
}
|
|
1276
|
-
if (c === "/" && next === "*") {
|
|
1277
|
-
inBlockComment = true;
|
|
1278
|
-
i++;
|
|
1279
|
-
continue;
|
|
1280
|
-
}
|
|
1281
|
-
out += c;
|
|
1282
|
-
}
|
|
1283
|
-
return out.replace(/,(\s*[}\]])/g, "$1");
|
|
1284
|
-
}
|
|
1285
|
-
function resolveAliasPrefixes(results, workspaceRoot) {
|
|
1286
|
-
const root = (0, import_node_path3.resolve)(workspaceRoot ?? ".");
|
|
1287
|
-
for (const filename of ["tsconfig.json", "jsconfig.json"]) {
|
|
1288
|
-
const configPath = (0, import_node_path3.join)(root, filename);
|
|
1289
|
-
const generated = results.find((r) => (0, import_node_path3.resolve)(r.targetPath) === configPath);
|
|
1290
|
-
let raw;
|
|
1291
|
-
if (generated) {
|
|
1292
|
-
raw = generated.newContent;
|
|
1293
|
-
} else {
|
|
1294
|
-
try {
|
|
1295
|
-
raw = (0, import_node_fs2.readFileSync)(configPath, "utf8");
|
|
1296
|
-
} catch {
|
|
1297
|
-
raw = null;
|
|
1298
|
-
}
|
|
1175
|
+
kept.push(r);
|
|
1299
1176
|
}
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1177
|
+
return kept;
|
|
1178
|
+
};
|
|
1179
|
+
const reads = room(loop.reads).map((r) => ({
|
|
1180
|
+
path: r.path.trim(),
|
|
1181
|
+
...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
|
|
1182
|
+
...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
|
|
1183
|
+
chars: whole(r.chars),
|
|
1184
|
+
...r.refused ? { refused: true } : {}
|
|
1185
|
+
}));
|
|
1186
|
+
const edits = room(loop.edits).map((e) => ({ path: e.path, count: whole(e.count) }));
|
|
1187
|
+
const created = room(loop.created).map((c) => ({ path: c.path, chars: whole(c.chars) }));
|
|
1188
|
+
const statusCounts = {};
|
|
1189
|
+
for (const [k, v] of Object.entries(loop.statusCounts).slice(0, MAX_STATUS_KEYS)) {
|
|
1190
|
+
if (k.length > 0 && k.length <= MAX_STATUS_KEY_CHARS) statusCounts[k] = whole(v);
|
|
1191
|
+
else cut = true;
|
|
1192
|
+
}
|
|
1193
|
+
if (Object.keys(loop.statusCounts).length > MAX_STATUS_KEYS) cut = true;
|
|
1194
|
+
const reasoning = [];
|
|
1195
|
+
for (const r of loop.reasoning) {
|
|
1196
|
+
if (reasoning.length >= MAX_RECORD_REASONING_TURNS) {
|
|
1197
|
+
cut = true;
|
|
1198
|
+
break;
|
|
1308
1199
|
}
|
|
1200
|
+
const text = typeof r.text === "string" ? r.text.trim() : "";
|
|
1201
|
+
if (text.length === 0) continue;
|
|
1202
|
+
const over = text.length > MAX_RECORD_REASONING_CHARS;
|
|
1203
|
+
reasoning.push({ turn: whole(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...over ? { truncated: true } : {} });
|
|
1309
1204
|
}
|
|
1310
|
-
return
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1205
|
+
return {
|
|
1206
|
+
turns: whole(loop.turns),
|
|
1207
|
+
toolCalls: whole(loop.toolCalls),
|
|
1208
|
+
refused: whole(loop.refused),
|
|
1209
|
+
stopReason: loop.stopReason,
|
|
1210
|
+
...loop.fellBack ? { fellBack: true } : {},
|
|
1211
|
+
...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_RECORD_FALLBACK_REASON_CHARS) } : {},
|
|
1212
|
+
reads,
|
|
1213
|
+
edits,
|
|
1214
|
+
created,
|
|
1215
|
+
statusCounts,
|
|
1216
|
+
reasoning,
|
|
1217
|
+
...cut ? { truncated: true } : {}
|
|
1218
|
+
};
|
|
1314
1219
|
}
|
|
1315
1220
|
|
|
1316
|
-
// src/
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1221
|
+
// src/targetingPaths.ts
|
|
1222
|
+
var import_node_path3 = require("node:path");
|
|
1223
|
+
var MAX_PATH_CHARS = 300;
|
|
1224
|
+
function hasControlChar(s) {
|
|
1225
|
+
for (let i = 0; i < s.length; i++) {
|
|
1226
|
+
const c = s.charCodeAt(i);
|
|
1227
|
+
if (c < 32 || c === 127) return true;
|
|
1323
1228
|
}
|
|
1229
|
+
return false;
|
|
1324
1230
|
}
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
headers: { Authorization: `Bearer ${runToken}` }
|
|
1331
|
-
});
|
|
1332
|
-
if (!res.ok) {
|
|
1333
|
-
throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
|
|
1231
|
+
function normaliseToolPath(raw, options = {}) {
|
|
1232
|
+
const allowRoot = options.allowRoot === true;
|
|
1233
|
+
if ((raw === void 0 || raw === null || raw === "") && allowRoot) return { ok: true, path: "" };
|
|
1234
|
+
if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_PATH_CHARS) {
|
|
1235
|
+
return { ok: false, reason: "path_invalid" };
|
|
1334
1236
|
}
|
|
1335
|
-
|
|
1336
|
-
if (
|
|
1337
|
-
|
|
1237
|
+
if (hasControlChar(raw)) return { ok: false, reason: "path_invalid" };
|
|
1238
|
+
if (raw.includes("\\")) return { ok: false, reason: "path_invalid" };
|
|
1239
|
+
if (raw.startsWith("/") || /^[A-Za-z]:/.test(raw)) return { ok: false, reason: "path_invalid" };
|
|
1240
|
+
if (raw.split("/").includes("..")) return { ok: false, reason: "outside_workspace" };
|
|
1241
|
+
const normalised = import_node_path3.posix.normalize(raw).replace(/\/+$/, "");
|
|
1242
|
+
if (normalised === "" || normalised === ".") {
|
|
1243
|
+
return allowRoot ? { ok: true, path: "" } : { ok: false, reason: "path_invalid" };
|
|
1338
1244
|
}
|
|
1339
|
-
return
|
|
1245
|
+
return { ok: true, path: normalised };
|
|
1340
1246
|
}
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
env2.ACTIONS_ID_TOKEN_REQUEST_URL
|
|
1348
|
-
);
|
|
1349
|
-
const requestToken = required(
|
|
1350
|
-
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
|
|
1351
|
-
env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
|
|
1352
|
-
);
|
|
1353
|
-
const separator = requestUrl.includes("?") ? "&" : "?";
|
|
1354
|
-
const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
|
|
1355
|
-
const res = await fetch(url, {
|
|
1356
|
-
headers: { Authorization: `Bearer ${requestToken}` }
|
|
1357
|
-
});
|
|
1358
|
-
if (!res.ok) {
|
|
1359
|
-
throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
|
|
1360
|
-
}
|
|
1361
|
-
const body = await res.json();
|
|
1362
|
-
if (!body.value) {
|
|
1363
|
-
throw new Error("GitHub OIDC token response carried no value");
|
|
1364
|
-
}
|
|
1365
|
-
return body.value;
|
|
1247
|
+
function matchesPrefix(path, prefix) {
|
|
1248
|
+
if (prefix === "") return true;
|
|
1249
|
+
return path === prefix || path.startsWith(`${prefix}/`);
|
|
1250
|
+
}
|
|
1251
|
+
function buildVisibleListing(listing, deniedPaths) {
|
|
1252
|
+
return listing.filter((p) => !matchesDeniedPath(p, deniedPaths)).sort();
|
|
1366
1253
|
}
|
|
1367
1254
|
|
|
1368
|
-
// src/
|
|
1369
|
-
var
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
"will",
|
|
1411
|
-
"shall",
|
|
1412
|
-
"when",
|
|
1413
|
-
"if",
|
|
1414
|
-
"than",
|
|
1415
|
-
"then",
|
|
1416
|
-
"so",
|
|
1417
|
-
"do",
|
|
1418
|
-
"does",
|
|
1419
|
-
"did"
|
|
1420
|
-
]);
|
|
1421
|
-
var MIN_WORD_LENGTH = 3;
|
|
1422
|
-
function significantWords(step) {
|
|
1423
|
-
return new Set(
|
|
1424
|
-
step.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length >= MIN_WORD_LENGTH && !STOPWORDS.has(w))
|
|
1425
|
-
);
|
|
1426
|
-
}
|
|
1427
|
-
function jaccard(a, b) {
|
|
1428
|
-
if (a.size === 0 || b.size === 0) return 0;
|
|
1429
|
-
let intersection = 0;
|
|
1430
|
-
for (const w of a) if (b.has(w)) intersection++;
|
|
1431
|
-
const union = a.size + b.size - intersection;
|
|
1432
|
-
return intersection / union;
|
|
1255
|
+
// src/targetingTools.ts
|
|
1256
|
+
var import_node_fs2 = require("node:fs");
|
|
1257
|
+
var import_node_path4 = require("node:path");
|
|
1258
|
+
var DEFAULT_LIMITS = {
|
|
1259
|
+
maxTurns: 12,
|
|
1260
|
+
maxToolCalls: 25,
|
|
1261
|
+
maxCallsPerTurn: 8,
|
|
1262
|
+
readCharsPerRead: 2e4,
|
|
1263
|
+
// The per-run read cap stops the COST; the per-turn ceiling below stops the FAILURE. Different jobs.
|
|
1264
|
+
readCharsTotal: 6e4,
|
|
1265
|
+
resultCharsTotal: 8e4,
|
|
1266
|
+
// 131,072 (the smallest 128k-class window) - 8,192 reserved output - a 3,741-token real request leaves
|
|
1267
|
+
// ~116,000; 90,000 keeps ~26,000 for a repository whose listing is thousands of paths, and stays well
|
|
1268
|
+
// clear of the per-minute quota, which binds before the window does. Set by the AI Runtime owner.
|
|
1269
|
+
maxRequestTokens: 9e4,
|
|
1270
|
+
grepMaxMatches: 40,
|
|
1271
|
+
grepLineChars: 200,
|
|
1272
|
+
grepFileBytes: 262144,
|
|
1273
|
+
grepMaxFiles: 3e3,
|
|
1274
|
+
grepMaxBytes: 2e7,
|
|
1275
|
+
fileBytesMax: 1e6,
|
|
1276
|
+
listMaxEntries: 500,
|
|
1277
|
+
maxReasoningChars: 500,
|
|
1278
|
+
maxPatternChars: 200
|
|
1279
|
+
};
|
|
1280
|
+
function createNodeToolFs(rootDir = process.cwd()) {
|
|
1281
|
+
const rootReal = (0, import_node_fs2.realpathSync)(rootDir);
|
|
1282
|
+
return {
|
|
1283
|
+
rootReal,
|
|
1284
|
+
lstat(rel) {
|
|
1285
|
+
const s = (0, import_node_fs2.lstatSync)((0, import_node_path4.join)(rootDir, rel));
|
|
1286
|
+
return { isSymlink: s.isSymbolicLink(), isFile: s.isFile(), size: s.size };
|
|
1287
|
+
},
|
|
1288
|
+
realpathInside(rel) {
|
|
1289
|
+
const real = (0, import_node_fs2.realpathSync)((0, import_node_path4.join)(rootDir, rel));
|
|
1290
|
+
const r = (0, import_node_path4.relative)(rootReal, real);
|
|
1291
|
+
return r !== "" && !r.startsWith("..") && !(0, import_node_path4.isAbsolute)(r);
|
|
1292
|
+
},
|
|
1293
|
+
readBytes(rel) {
|
|
1294
|
+
return (0, import_node_fs2.readFileSync)((0, import_node_path4.join)(rootDir, rel));
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1433
1297
|
}
|
|
1434
|
-
function
|
|
1435
|
-
return
|
|
1298
|
+
function newLedger() {
|
|
1299
|
+
return { toolCalls: 0, readChars: 0, resultChars: 0, refused: 0, seen: /* @__PURE__ */ new Map() };
|
|
1436
1300
|
}
|
|
1437
|
-
var
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
target: target.path,
|
|
1442
|
-
step,
|
|
1443
|
-
words: significantWords(step)
|
|
1444
|
-
}))
|
|
1445
|
-
);
|
|
1446
|
-
const warnings = [];
|
|
1447
|
-
for (let i = 0; i < items.length; i++) {
|
|
1448
|
-
for (let j = i + 1; j < items.length; j++) {
|
|
1449
|
-
if (items[i].target === items[j].target) continue;
|
|
1450
|
-
if (isTestTarget(items[i].target) || isTestTarget(items[j].target)) continue;
|
|
1451
|
-
if (jaccard(items[i].words, items[j].words) >= OVERLAP_THRESHOLD) {
|
|
1452
|
-
warnings.push({
|
|
1453
|
-
targetA: items[i].target,
|
|
1454
|
-
stepA: items[i].step,
|
|
1455
|
-
targetB: items[j].target,
|
|
1456
|
-
stepB: items[j].step,
|
|
1457
|
-
severity: normalizedStep(items[i].step) === normalizedStep(items[j].step) ? "identical" : "similar"
|
|
1458
|
-
});
|
|
1459
|
-
}
|
|
1460
|
-
}
|
|
1461
|
-
}
|
|
1462
|
-
return warnings;
|
|
1301
|
+
var INVALID_PATH = "(invalid path)";
|
|
1302
|
+
var CUT = "\u2026[line cut]";
|
|
1303
|
+
function isPlainObject(x) {
|
|
1304
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
1463
1305
|
}
|
|
1464
|
-
function
|
|
1465
|
-
return
|
|
1466
|
-
(w) => `${w.targetA} and ${w.targetB} both implement what looks like the same rule \u2014 "${w.stepA}" / "${w.stepB}". Check these aren't two independent implementations of the same behavior.`
|
|
1467
|
-
);
|
|
1306
|
+
function bad(message) {
|
|
1307
|
+
return { fail: { status: "bad_args", message } };
|
|
1468
1308
|
}
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
|
|
1473
|
-
const res = await fetch(url, {
|
|
1474
|
-
headers: { Authorization: `Bearer ${runToken}` }
|
|
1475
|
-
});
|
|
1476
|
-
if (!res.ok) {
|
|
1477
|
-
throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
|
|
1478
|
-
}
|
|
1479
|
-
const body = await res.json();
|
|
1480
|
-
if (body.success !== true) {
|
|
1481
|
-
throw new Error("Fetch work packet failed: response did not carry success:true");
|
|
1482
|
-
}
|
|
1483
|
-
return body.data;
|
|
1309
|
+
function optionalInt(v) {
|
|
1310
|
+
if (v === void 0 || v === null) return void 0;
|
|
1311
|
+
return typeof v === "number" && Number.isInteger(v) ? v : "bad";
|
|
1484
1312
|
}
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
(0, import_node_fs3.mkdirSync)(".quikpilot", { recursive: true });
|
|
1490
|
-
(0, import_node_fs3.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
|
|
1491
|
-
`);
|
|
1313
|
+
function hasNul(bytes) {
|
|
1314
|
+
const n = Math.min(bytes.length, 8e3);
|
|
1315
|
+
for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;
|
|
1316
|
+
return false;
|
|
1492
1317
|
}
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
1498
|
-
function walkForJUnitByName(dir) {
|
|
1499
|
-
let entries;
|
|
1500
|
-
try {
|
|
1501
|
-
entries = (0, import_node_fs4.readdirSync)(dir);
|
|
1502
|
-
} catch {
|
|
1503
|
-
return null;
|
|
1504
|
-
}
|
|
1505
|
-
for (const entry of entries) {
|
|
1506
|
-
if (SKIP_DIRS.has(entry)) continue;
|
|
1507
|
-
const full = (0, import_node_path4.join)(dir, entry);
|
|
1508
|
-
let stat;
|
|
1509
|
-
try {
|
|
1510
|
-
stat = (0, import_node_fs4.statSync)(full);
|
|
1511
|
-
} catch {
|
|
1512
|
-
continue;
|
|
1513
|
-
}
|
|
1514
|
-
if (stat.isDirectory()) {
|
|
1515
|
-
const found = walkForJUnitByName(full);
|
|
1516
|
-
if (found) return found;
|
|
1517
|
-
} else if (/^junit.*\.xml$/.test(entry)) {
|
|
1518
|
-
return full;
|
|
1519
|
-
}
|
|
1318
|
+
function gatePath(raw, env2) {
|
|
1319
|
+
const n = normaliseToolPath(raw);
|
|
1320
|
+
if (!n.ok) {
|
|
1321
|
+
return { ok: false, path: INVALID_PATH, fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
|
|
1520
1322
|
}
|
|
1521
|
-
|
|
1522
|
-
}
|
|
1523
|
-
function firstXmlIn(dir, namePattern) {
|
|
1524
|
-
let entries;
|
|
1525
|
-
try {
|
|
1526
|
-
entries = (0, import_node_fs4.readdirSync)(dir);
|
|
1527
|
-
} catch {
|
|
1528
|
-
return null;
|
|
1323
|
+
if (matchesDeniedPath(n.path, env2.deniedPaths)) {
|
|
1324
|
+
return { ok: false, path: n.path, fail: { status: "refused", reason: "denied", message: "That path is protected and cannot be read." } };
|
|
1529
1325
|
}
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
}
|
|
1533
|
-
function readTestReportBytes(cwd = process.cwd()) {
|
|
1534
|
-
try {
|
|
1535
|
-
const report = findJUnitReport(cwd);
|
|
1536
|
-
return report ? (0, import_node_fs4.readFileSync)(report) : null;
|
|
1537
|
-
} catch {
|
|
1538
|
-
return null;
|
|
1326
|
+
if (!env2.listing.has(n.path)) {
|
|
1327
|
+
return { ok: false, path: n.path, fail: { status: "not_found", message: "Not a tracked file. Use list_files to see the available paths." } };
|
|
1539
1328
|
}
|
|
1329
|
+
return { ok: true, path: n.path };
|
|
1540
1330
|
}
|
|
1541
|
-
function
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
return
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
if (
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
}
|
|
1552
|
-
async function reportToQuikTest(params) {
|
|
1553
|
-
const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;
|
|
1554
|
-
if (!resultsUrl) {
|
|
1555
|
-
console.log("packet.quikTest is null \u2014 this run has no QuikTest run to report into.");
|
|
1556
|
-
return null;
|
|
1557
|
-
}
|
|
1558
|
-
const report = findJUnitReport(cwd);
|
|
1559
|
-
if (!report) {
|
|
1560
|
-
console.warn("::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.");
|
|
1561
|
-
return null;
|
|
1331
|
+
function prepareReadFile(args, env2, ledger) {
|
|
1332
|
+
const start = optionalInt(args.startLine);
|
|
1333
|
+
const end = optionalInt(args.endLine);
|
|
1334
|
+
if (start === "bad" || end === "bad") return bad("startLine and endLine must be whole numbers.");
|
|
1335
|
+
if (start !== void 0 && end !== void 0 && end < start) return bad("endLine must not be before startLine.");
|
|
1336
|
+
if (typeof args.path !== "string") return bad("path must be a string.");
|
|
1337
|
+
const gate = gatePath(args.path, env2);
|
|
1338
|
+
if (!gate.ok) {
|
|
1339
|
+
const read = gate.fail.status === "refused" ? { path: gate.path, chars: 0, refused: true } : void 0;
|
|
1340
|
+
return { fail: gate.fail, ...read ? { read } : {} };
|
|
1562
1341
|
}
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1342
|
+
const path = gate.path;
|
|
1343
|
+
const key = JSON.stringify({ path, startLine: start ?? null, endLine: end ?? null });
|
|
1344
|
+
return {
|
|
1345
|
+
key,
|
|
1346
|
+
exec: () => {
|
|
1347
|
+
let size;
|
|
1348
|
+
try {
|
|
1349
|
+
const st = env2.fs.lstat(path);
|
|
1350
|
+
if (st.isSymlink) {
|
|
1351
|
+
return { result: { status: "refused", reason: "symlink", message: "Links are not followed." }, read: { path, chars: 0, refused: true } };
|
|
1352
|
+
}
|
|
1353
|
+
if (!st.isFile) return { result: { status: "unreadable", reason: "not_a_file", message: "That entry is not a regular file." } };
|
|
1354
|
+
size = st.size;
|
|
1355
|
+
if (size > env2.limits.fileBytesMax) {
|
|
1356
|
+
return { result: { status: "unreadable", reason: "too_large", message: "That file is too large to read." } };
|
|
1357
|
+
}
|
|
1358
|
+
if (!env2.fs.realpathInside(path)) {
|
|
1359
|
+
return { result: { status: "refused", reason: "outside_workspace", message: "That path is not allowed." }, read: { path, chars: 0, refused: true } };
|
|
1360
|
+
}
|
|
1361
|
+
} catch {
|
|
1362
|
+
return { result: { status: "unreadable", reason: "io", message: "That file could not be read." } };
|
|
1363
|
+
}
|
|
1364
|
+
let bytes;
|
|
1365
|
+
try {
|
|
1366
|
+
bytes = env2.fs.readBytes(path);
|
|
1367
|
+
} catch {
|
|
1368
|
+
return { result: { status: "unreadable", reason: "io", message: "That file could not be read." } };
|
|
1369
|
+
}
|
|
1370
|
+
if (hasNul(bytes)) return { result: { status: "unreadable", reason: "binary", message: "That file is binary." } };
|
|
1371
|
+
let text;
|
|
1372
|
+
try {
|
|
1373
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1374
|
+
} catch {
|
|
1375
|
+
return { result: { status: "unreadable", reason: "not_utf8", message: "That file is not valid UTF-8 text." } };
|
|
1376
|
+
}
|
|
1377
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
1378
|
+
text = text.replace(/\r\n/g, "\n");
|
|
1379
|
+
const lines = text === "" ? [] : text.split("\n");
|
|
1380
|
+
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
1381
|
+
const totalLines = lines.length;
|
|
1382
|
+
const startLine = Math.max(1, start ?? 1);
|
|
1383
|
+
const endWanted = Math.min(totalLines, end ?? totalLines);
|
|
1384
|
+
if (startLine > totalLines) {
|
|
1385
|
+
return {
|
|
1386
|
+
result: { status: "ok", output: { path, startLine, endLine: totalLines, totalLines, truncated: false, content: "" } },
|
|
1387
|
+
read: { path, startLine, endLine: totalLines, chars: 0 }
|
|
1388
|
+
};
|
|
1389
|
+
}
|
|
1390
|
+
const budget = Math.max(0, Math.min(env2.limits.readCharsPerRead, env2.limits.readCharsTotal - ledger.readChars));
|
|
1391
|
+
const out = [];
|
|
1392
|
+
let used = 0;
|
|
1393
|
+
let endLine = startLine - 1;
|
|
1394
|
+
let truncated = false;
|
|
1395
|
+
for (let n = startLine; n <= endWanted; n++) {
|
|
1396
|
+
const line = `${n} ${lines[n - 1]}`;
|
|
1397
|
+
const cost = line.length + (out.length > 0 ? 1 : 0);
|
|
1398
|
+
if (used + cost <= budget) {
|
|
1399
|
+
out.push(line);
|
|
1400
|
+
used += cost;
|
|
1401
|
+
endLine = n;
|
|
1402
|
+
continue;
|
|
1403
|
+
}
|
|
1404
|
+
truncated = true;
|
|
1405
|
+
if (out.length === 0) {
|
|
1406
|
+
const keep = Math.max(0, budget - CUT.length);
|
|
1407
|
+
out.push(line.slice(0, keep) + CUT);
|
|
1408
|
+
used = out[0].length;
|
|
1409
|
+
endLine = n;
|
|
1410
|
+
}
|
|
1411
|
+
break;
|
|
1412
|
+
}
|
|
1413
|
+
let content = out.join("\n");
|
|
1414
|
+
ledger.readChars += used;
|
|
1415
|
+
const output = { path, startLine, endLine, totalLines, truncated };
|
|
1416
|
+
if (truncated) {
|
|
1417
|
+
if (endLine < totalLines) {
|
|
1418
|
+
output.nextStartLine = endLine + 1;
|
|
1419
|
+
content += `
|
|
1420
|
+
[truncated: showing lines ${startLine}-${endLine} of ${totalLines}; call read_file with startLine=${endLine + 1}]`;
|
|
1421
|
+
} else {
|
|
1422
|
+
content += `
|
|
1423
|
+
[truncated: line ${endLine} was cut]`;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
output.content = content;
|
|
1427
|
+
return { result: { status: "ok", output }, read: { path, startLine, endLine, chars: used } };
|
|
1579
1428
|
}
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
function prepareListFiles(args, env2) {
|
|
1432
|
+
const max = optionalInt(args.maxEntries);
|
|
1433
|
+
if (max === "bad" || max !== void 0 && max < 1) return bad("maxEntries must be a whole number of at least 1.");
|
|
1434
|
+
if (args.prefix !== void 0 && args.prefix !== null && typeof args.prefix !== "string") return bad("prefix must be a string.");
|
|
1435
|
+
const n = normaliseToolPath(args.prefix, { allowRoot: true });
|
|
1436
|
+
if (!n.ok) return { fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
|
|
1437
|
+
const prefix = n.path;
|
|
1438
|
+
const cap = Math.min(max ?? env2.limits.listMaxEntries, env2.limits.listMaxEntries);
|
|
1439
|
+
return {
|
|
1440
|
+
key: JSON.stringify({ prefix, maxEntries: cap }),
|
|
1441
|
+
exec: () => {
|
|
1442
|
+
const matching = env2.visible.filter((p) => matchesPrefix(p, prefix));
|
|
1443
|
+
const entries = matching.slice(0, cap);
|
|
1444
|
+
const truncated = matching.length > cap;
|
|
1445
|
+
const output = { entries, total: matching.length, truncated };
|
|
1446
|
+
if (truncated) {
|
|
1447
|
+
const counts = /* @__PURE__ */ new Map();
|
|
1448
|
+
for (const p of matching) {
|
|
1449
|
+
const rest = prefix === "" ? p : p.slice(prefix.length + 1);
|
|
1450
|
+
const slash = rest.indexOf("/");
|
|
1451
|
+
if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);
|
|
1452
|
+
}
|
|
1453
|
+
output.subdirs = [...counts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1)).slice(0, 50);
|
|
1454
|
+
}
|
|
1455
|
+
return { result: { status: "ok", output } };
|
|
1586
1456
|
}
|
|
1587
|
-
|
|
1588
|
-
} catch (err) {
|
|
1589
|
-
console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);
|
|
1590
|
-
return null;
|
|
1591
|
-
}
|
|
1457
|
+
};
|
|
1592
1458
|
}
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
var TESTSUITE_OPEN_RE = /<testsuite\b([^>]*?)>/g;
|
|
1607
|
-
var FILE_ATTR_RE = /\bfile="([^"]*)"/;
|
|
1608
|
-
var QP_TOKEN_BRACKET_RE = /\[(QP-[A-Z][A-Z0-9]*-\d+-\d+)\]/;
|
|
1609
|
-
function normalizeSlashes(path) {
|
|
1610
|
-
return path.replace(/\\/g, "/");
|
|
1459
|
+
var WORD_CHAR = /[A-Za-z0-9_$]/;
|
|
1460
|
+
function lineMatches(line, needle, ignoreCase, wholeWord) {
|
|
1461
|
+
const hay = ignoreCase ? line.toLowerCase() : line;
|
|
1462
|
+
let from = 0;
|
|
1463
|
+
for (; ; ) {
|
|
1464
|
+
const i = hay.indexOf(needle, from);
|
|
1465
|
+
if (i === -1) return -1;
|
|
1466
|
+
if (!wholeWord) return i;
|
|
1467
|
+
const before = i > 0 ? hay[i - 1] : "";
|
|
1468
|
+
const after = i + needle.length < hay.length ? hay[i + needle.length] : "";
|
|
1469
|
+
if (!(before && WORD_CHAR.test(before)) && !(after && WORD_CHAR.test(after))) return i;
|
|
1470
|
+
from = i + 1;
|
|
1471
|
+
}
|
|
1611
1472
|
}
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1473
|
+
function excerpt(line, at, max) {
|
|
1474
|
+
const t = line.trim();
|
|
1475
|
+
if (t.length <= max) return t;
|
|
1476
|
+
const lead = line.length - line.trimStart().length;
|
|
1477
|
+
const pos = Math.max(0, at - lead);
|
|
1478
|
+
const from = Math.max(0, Math.min(pos - 40, t.length - max));
|
|
1479
|
+
const piece = t.slice(from, from + max);
|
|
1480
|
+
return `${from > 0 ? "\u2026" : ""}${piece}${from + max < t.length ? "\u2026" : ""}`;
|
|
1617
1481
|
}
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
const
|
|
1625
|
-
|
|
1626
|
-
|
|
1482
|
+
function prepareGrep(args, env2) {
|
|
1483
|
+
const pattern = args.pattern;
|
|
1484
|
+
if (typeof pattern !== "string" || pattern.length === 0 || pattern.length > env2.limits.maxPatternChars) {
|
|
1485
|
+
return bad("pattern must be a non-empty string within the length limit.");
|
|
1486
|
+
}
|
|
1487
|
+
if (/[\u0000\r\n]/.test(pattern)) return bad("pattern must be a single line of plain text.");
|
|
1488
|
+
for (const flag of ["ignoreCase", "wholeWord"]) {
|
|
1489
|
+
if (args[flag] !== void 0 && typeof args[flag] !== "boolean") return bad(`${flag} must be true or false.`);
|
|
1490
|
+
}
|
|
1491
|
+
const maxIn = optionalInt(args.maxResults);
|
|
1492
|
+
if (maxIn === "bad" || maxIn !== void 0 && maxIn < 1) return bad("maxResults must be a whole number of at least 1.");
|
|
1493
|
+
if (args.pathPrefix !== void 0 && args.pathPrefix !== null && typeof args.pathPrefix !== "string") return bad("pathPrefix must be a string.");
|
|
1494
|
+
const n = normaliseToolPath(args.pathPrefix, { allowRoot: true });
|
|
1495
|
+
if (!n.ok) return { fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
|
|
1496
|
+
const prefix = n.path;
|
|
1497
|
+
const ignoreCase = args.ignoreCase === true;
|
|
1498
|
+
const wholeWord = args.wholeWord === true;
|
|
1499
|
+
const maxMatches = Math.min(maxIn ?? env2.limits.grepMaxMatches, env2.limits.grepMaxMatches);
|
|
1500
|
+
const needle = ignoreCase ? pattern.toLowerCase() : pattern;
|
|
1501
|
+
return {
|
|
1502
|
+
key: JSON.stringify({ pattern, pathPrefix: prefix, maxResults: maxMatches, ignoreCase, wholeWord }),
|
|
1503
|
+
exec: () => {
|
|
1504
|
+
const matches = [];
|
|
1505
|
+
const skipped = { large: 0, binary: 0 };
|
|
1506
|
+
let filesScanned = 0;
|
|
1507
|
+
let bytesScanned = 0;
|
|
1508
|
+
let scanCapped = false;
|
|
1509
|
+
let truncated = false;
|
|
1510
|
+
scan: for (const path of env2.visible) {
|
|
1511
|
+
if (!matchesPrefix(path, prefix)) continue;
|
|
1512
|
+
if (filesScanned >= env2.limits.grepMaxFiles || bytesScanned >= env2.limits.grepMaxBytes) {
|
|
1513
|
+
scanCapped = true;
|
|
1514
|
+
break;
|
|
1515
|
+
}
|
|
1516
|
+
filesScanned += 1;
|
|
1517
|
+
let bytes;
|
|
1518
|
+
try {
|
|
1519
|
+
const st = env2.fs.lstat(path);
|
|
1520
|
+
if (st.isSymlink || !st.isFile) continue;
|
|
1521
|
+
if (st.size > env2.limits.grepFileBytes) {
|
|
1522
|
+
skipped.large += 1;
|
|
1523
|
+
continue;
|
|
1524
|
+
}
|
|
1525
|
+
if (!env2.fs.realpathInside(path)) continue;
|
|
1526
|
+
bytes = env2.fs.readBytes(path);
|
|
1527
|
+
} catch {
|
|
1528
|
+
continue;
|
|
1529
|
+
}
|
|
1530
|
+
bytesScanned += bytes.length;
|
|
1531
|
+
if (hasNul(bytes)) {
|
|
1532
|
+
skipped.binary += 1;
|
|
1533
|
+
continue;
|
|
1534
|
+
}
|
|
1535
|
+
const lines = new TextDecoder("utf-8").decode(bytes).replace(/\r\n/g, "\n").split("\n");
|
|
1536
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1537
|
+
const at = lineMatches(lines[i], needle, ignoreCase, wholeWord);
|
|
1538
|
+
if (at === -1) continue;
|
|
1539
|
+
if (matches.length >= maxMatches) {
|
|
1540
|
+
truncated = true;
|
|
1541
|
+
break scan;
|
|
1542
|
+
}
|
|
1543
|
+
matches.push({ path, line: i + 1, text: excerpt(lines[i], at, env2.limits.grepLineChars) });
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
const output = { matches, truncated, filesScanned, skipped };
|
|
1547
|
+
if (scanCapped) output.scanCapped = true;
|
|
1548
|
+
return { result: { status: "ok", output } };
|
|
1549
|
+
}
|
|
1550
|
+
};
|
|
1627
1551
|
}
|
|
1628
|
-
function
|
|
1629
|
-
|
|
1630
|
-
if (!tag) return null;
|
|
1631
|
-
const [, attrs = "", inner = ""] = tag;
|
|
1632
|
-
const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];
|
|
1633
|
-
const raw = (messageAttr ?? inner).trim();
|
|
1634
|
-
if (!raw) return null;
|
|
1635
|
-
const text = unescapeXmlEntities(raw);
|
|
1636
|
-
const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;
|
|
1637
|
-
const location = messageAttr === void 0 ? null : parseFailureLocation(inner);
|
|
1638
|
-
return location ? `${shortened} [at ${location}]` : shortened;
|
|
1552
|
+
function budgetResult(reason) {
|
|
1553
|
+
return { status: "budget_exhausted", reason, message: "That limit has been reached; give your answer from what you have." };
|
|
1639
1554
|
}
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
const
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
const rawName = NAME_ATTR_RE.exec(attrs)?.[1];
|
|
1658
|
-
if (!rawName) continue;
|
|
1659
|
-
const name = unescapeXmlEntities(rawName);
|
|
1660
|
-
const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];
|
|
1661
|
-
const classname = rawClassname === void 0 ? void 0 : unescapeXmlEntities(rawClassname);
|
|
1662
|
-
const id = classname ? `${classname}::${name}` : name;
|
|
1663
|
-
const failed = FAILURE_CHILD_RE.test(body);
|
|
1664
|
-
outcomes.set(id, !failed);
|
|
1665
|
-
if (failed) {
|
|
1666
|
-
const text = extractFailureText(body);
|
|
1667
|
-
if (text) failureText.set(id, text);
|
|
1555
|
+
function executeToolCall(call, env2, ledger) {
|
|
1556
|
+
const wrap = (r) => ({ id: call.id, name: call.name, ...r });
|
|
1557
|
+
const finish = (r, read) => {
|
|
1558
|
+
const result = wrap(r);
|
|
1559
|
+
ledger.resultChars += JSON.stringify(result).length;
|
|
1560
|
+
if (result.status === "refused") ledger.refused += 1;
|
|
1561
|
+
return read ? { result, read } : { result };
|
|
1562
|
+
};
|
|
1563
|
+
if (ledger.toolCalls >= env2.limits.maxToolCalls) return finish(budgetResult("tool_calls"));
|
|
1564
|
+
if (ledger.resultChars >= env2.limits.resultCharsTotal) return finish(budgetResult("result_chars"));
|
|
1565
|
+
if (call.name === "read_file" && ledger.readChars >= env2.limits.readCharsTotal) return finish(budgetResult("read_chars"));
|
|
1566
|
+
ledger.toolCalls += 1;
|
|
1567
|
+
let prepared;
|
|
1568
|
+
try {
|
|
1569
|
+
const extra = env2.extraTools && Object.prototype.hasOwnProperty.call(env2.extraTools, call.name) ? env2.extraTools[call.name] : void 0;
|
|
1570
|
+
if (call.name !== "read_file" && call.name !== "list_files" && call.name !== "grep" && !extra) {
|
|
1571
|
+
return finish({ status: "unknown_tool", message: "Unknown tool. Use list_files, read_file or grep." });
|
|
1668
1572
|
}
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1573
|
+
if (!isPlainObject(call.args)) return finish({ status: "bad_args", message: "Arguments must be an object." });
|
|
1574
|
+
prepared = extra ? extra(call.args, env2, ledger) : call.name === "read_file" ? prepareReadFile(call.args, env2, ledger) : call.name === "list_files" ? prepareListFiles(call.args, env2) : prepareGrep(call.args, env2);
|
|
1575
|
+
} catch {
|
|
1576
|
+
return finish({ status: "bad_args", message: "Those arguments could not be used." });
|
|
1577
|
+
}
|
|
1578
|
+
if ("fail" in prepared) return finish(prepared.fail, prepared.read);
|
|
1579
|
+
const dupKey = `${call.name}:${prepared.key}`;
|
|
1580
|
+
const earlier = ledger.seen.get(dupKey);
|
|
1581
|
+
if (earlier !== void 0) {
|
|
1582
|
+
return finish({ status: "duplicate", reason: earlier, message: "Identical call already made; see its result." });
|
|
1583
|
+
}
|
|
1584
|
+
ledger.seen.set(dupKey, call.id);
|
|
1585
|
+
let executed;
|
|
1586
|
+
try {
|
|
1587
|
+
executed = prepared.exec();
|
|
1588
|
+
} catch {
|
|
1589
|
+
executed = { result: { status: "unreadable", reason: "io", message: "That could not be read." } };
|
|
1590
|
+
}
|
|
1591
|
+
return finish(executed.result, executed.read);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// src/workspaceOverlay.ts
|
|
1595
|
+
var import_node_fs3 = require("node:fs");
|
|
1596
|
+
var import_node_path5 = require("node:path");
|
|
1597
|
+
function createNodeWriteFs(rootDir = process.cwd()) {
|
|
1598
|
+
const base = createNodeToolFs(rootDir);
|
|
1599
|
+
const inside = (real) => {
|
|
1600
|
+
const r = (0, import_node_path5.relative)(base.rootReal, real);
|
|
1601
|
+
return !r.startsWith("..") && !(0, import_node_path5.isAbsolute)(r);
|
|
1602
|
+
};
|
|
1603
|
+
return {
|
|
1604
|
+
...base,
|
|
1605
|
+
parentInside(rel) {
|
|
1606
|
+
let dir = (0, import_node_path5.dirname)((0, import_node_path5.join)(rootDir, rel));
|
|
1607
|
+
for (; ; ) {
|
|
1608
|
+
try {
|
|
1609
|
+
return inside((0, import_node_fs3.realpathSync)(dir));
|
|
1610
|
+
} catch {
|
|
1611
|
+
const up = (0, import_node_path5.dirname)(dir);
|
|
1612
|
+
if (up === dir) return false;
|
|
1613
|
+
dir = up;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
},
|
|
1617
|
+
exists(rel) {
|
|
1618
|
+
try {
|
|
1619
|
+
(0, import_node_fs3.lstatSync)((0, import_node_path5.join)(rootDir, rel));
|
|
1620
|
+
return true;
|
|
1621
|
+
} catch {
|
|
1622
|
+
return false;
|
|
1623
|
+
}
|
|
1678
1624
|
}
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
var WorkspaceOverlay = class {
|
|
1628
|
+
entries = /* @__PURE__ */ new Map();
|
|
1629
|
+
get(path) {
|
|
1630
|
+
return this.entries.get(path);
|
|
1679
1631
|
}
|
|
1680
|
-
|
|
1632
|
+
has(path) {
|
|
1633
|
+
return this.entries.has(path);
|
|
1634
|
+
}
|
|
1635
|
+
isCreated(path) {
|
|
1636
|
+
return this.entries.get(path)?.created === true;
|
|
1637
|
+
}
|
|
1638
|
+
/** Record new text for an existing file. The first call remembers the original; later calls only replace the text. */
|
|
1639
|
+
setEdited(path, lf, base) {
|
|
1640
|
+
const current = this.entries.get(path);
|
|
1641
|
+
if (current) {
|
|
1642
|
+
current.lf = lf;
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
this.entries.set(path, { lf, ending: base.ending, bom: base.bom, created: false, originalLf: base.originalLf });
|
|
1646
|
+
}
|
|
1647
|
+
/** Create a file, or replace one the loop itself created earlier. */
|
|
1648
|
+
setCreated(path, lf) {
|
|
1649
|
+
this.entries.set(path, { lf, ending: "LF", bom: false, created: true, originalLf: null });
|
|
1650
|
+
}
|
|
1651
|
+
/** Paths whose final text differs from what is on disk, in the order they were first touched. */
|
|
1652
|
+
changedPaths() {
|
|
1653
|
+
return [...this.entries.entries()].filter(([, e]) => e.created || e.lf !== e.originalLf).map(([p]) => p);
|
|
1654
|
+
}
|
|
1655
|
+
/** The full text of an entry as it would be written to disk. */
|
|
1656
|
+
fullText(path) {
|
|
1657
|
+
const e = this.entries.get(path);
|
|
1658
|
+
return e ? `${e.bom ? "\uFEFF" : ""}${fromLf(e.lf, e.ending)}` : void 0;
|
|
1659
|
+
}
|
|
1660
|
+
results() {
|
|
1661
|
+
return this.changedPaths().map((path) => ({ targetPath: path, newContent: this.fullText(path) }));
|
|
1662
|
+
}
|
|
1663
|
+
};
|
|
1664
|
+
function createOverlayFs(base, overlay) {
|
|
1665
|
+
const encode = (path) => new TextEncoder().encode(overlay.fullText(path));
|
|
1666
|
+
return {
|
|
1667
|
+
rootReal: base.rootReal,
|
|
1668
|
+
lstat(rel) {
|
|
1669
|
+
if (overlay.has(rel)) return { isSymlink: false, isFile: true, size: encode(rel).length };
|
|
1670
|
+
return base.lstat(rel);
|
|
1671
|
+
},
|
|
1672
|
+
realpathInside(rel) {
|
|
1673
|
+
if (overlay.isCreated(rel)) return base.parentInside(rel);
|
|
1674
|
+
return base.realpathInside(rel);
|
|
1675
|
+
},
|
|
1676
|
+
readBytes(rel) {
|
|
1677
|
+
return overlay.has(rel) ? encode(rel) : base.readBytes(rel);
|
|
1678
|
+
},
|
|
1679
|
+
parentInside: (rel) => base.parentInside(rel),
|
|
1680
|
+
exists: (rel) => overlay.has(rel) || base.exists(rel)
|
|
1681
|
+
};
|
|
1681
1682
|
}
|
|
1682
|
-
function
|
|
1683
|
-
const
|
|
1684
|
-
if (
|
|
1683
|
+
function hasNul2(bytes) {
|
|
1684
|
+
const n = Math.min(bytes.length, 8e3);
|
|
1685
|
+
for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;
|
|
1686
|
+
return false;
|
|
1687
|
+
}
|
|
1688
|
+
function loadTextForEdit(fs, path, maxBytes) {
|
|
1689
|
+
let bytes;
|
|
1685
1690
|
try {
|
|
1686
|
-
|
|
1691
|
+
const st = fs.lstat(path);
|
|
1692
|
+
if (st.isSymlink) return { ok: false, result: { status: "refused", reason: "symlink", message: "Links are not followed." } };
|
|
1693
|
+
if (!st.isFile) return { ok: false, result: { status: "unreadable", reason: "not_a_file", message: "That entry is not a regular file." } };
|
|
1694
|
+
if (st.size > maxBytes) return { ok: false, result: { status: "too_large", reason: "too_large", message: "That file is too large to edit." } };
|
|
1695
|
+
if (!fs.realpathInside(path)) {
|
|
1696
|
+
return { ok: false, result: { status: "refused", reason: "outside_workspace", message: "That path is not allowed." } };
|
|
1697
|
+
}
|
|
1698
|
+
bytes = fs.readBytes(path);
|
|
1687
1699
|
} catch {
|
|
1688
|
-
return
|
|
1700
|
+
return { ok: false, result: { status: "unreadable", reason: "io", message: "That file could not be read." } };
|
|
1701
|
+
}
|
|
1702
|
+
if (hasNul2(bytes)) return { ok: false, result: { status: "unreadable", reason: "binary", message: "That file is binary." } };
|
|
1703
|
+
let text;
|
|
1704
|
+
try {
|
|
1705
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1706
|
+
} catch {
|
|
1707
|
+
return { ok: false, result: { status: "unreadable", reason: "not_utf8", message: "That file is not valid UTF-8 text." } };
|
|
1708
|
+
}
|
|
1709
|
+
const bom = bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191;
|
|
1710
|
+
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
1711
|
+
const ending = detectLineEnding(text);
|
|
1712
|
+
if (ending === "mixed") {
|
|
1713
|
+
return {
|
|
1714
|
+
ok: false,
|
|
1715
|
+
result: { status: "refused", reason: "mixed_line_endings", message: "That file mixes line endings and cannot be edited faithfully." }
|
|
1716
|
+
};
|
|
1689
1717
|
}
|
|
1718
|
+
return { ok: true, lf: toLf(text), ending, bom };
|
|
1690
1719
|
}
|
|
1691
|
-
|
|
1692
|
-
|
|
1720
|
+
|
|
1721
|
+
// src/codegenTools.ts
|
|
1722
|
+
var CODEGEN_LIMITS = {
|
|
1723
|
+
...DEFAULT_LIMITS,
|
|
1724
|
+
maxTurns: 20,
|
|
1725
|
+
maxToolCalls: 40,
|
|
1726
|
+
writeCharsTotal: 12e4,
|
|
1727
|
+
findChars: 8e3,
|
|
1728
|
+
replaceChars: 2e4,
|
|
1729
|
+
contentChars: 2e5
|
|
1730
|
+
};
|
|
1731
|
+
function newCodegenLedger() {
|
|
1732
|
+
return { ...newLedger(), writeChars: 0 };
|
|
1693
1733
|
}
|
|
1694
|
-
function
|
|
1695
|
-
|
|
1696
|
-
const parsed = readJUnitOutcomes(cwd);
|
|
1697
|
-
return {
|
|
1698
|
-
outcome,
|
|
1699
|
-
results: parsed?.outcomes ?? null,
|
|
1700
|
-
failureText: parsed?.failureText,
|
|
1701
|
-
discoveredFiles: parsed?.discoveredFiles ?? null,
|
|
1702
|
-
discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
|
|
1703
|
-
};
|
|
1734
|
+
function bad2(message) {
|
|
1735
|
+
return { fail: { status: "bad_args", message } };
|
|
1704
1736
|
}
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1737
|
+
function refused(reason, message) {
|
|
1738
|
+
return { fail: { status: "refused", reason, message } };
|
|
1739
|
+
}
|
|
1740
|
+
function countLines(text) {
|
|
1741
|
+
if (text === "") return 0;
|
|
1742
|
+
const n = text.split("\n").length;
|
|
1743
|
+
return text.endsWith("\n") ? n - 1 : n;
|
|
1744
|
+
}
|
|
1745
|
+
function createCodegenWorkspace(args) {
|
|
1746
|
+
const limits = { ...CODEGEN_LIMITS, ...args.limits };
|
|
1747
|
+
const baseFs = args.fs ?? createNodeWriteFs();
|
|
1748
|
+
const overlay = new WorkspaceOverlay();
|
|
1749
|
+
const listing = new Set(args.listing);
|
|
1750
|
+
const visible = buildVisibleListing(args.listing, args.deniedPaths);
|
|
1751
|
+
const protectedTests = new Set(args.protectedTestPaths);
|
|
1752
|
+
const edits = /* @__PURE__ */ new Map();
|
|
1753
|
+
const created = /* @__PURE__ */ new Map();
|
|
1754
|
+
const noteCreated = (path) => {
|
|
1755
|
+
listing.add(path);
|
|
1756
|
+
if (!visible.includes(path)) {
|
|
1757
|
+
visible.push(path);
|
|
1758
|
+
visible.sort();
|
|
1759
|
+
}
|
|
1714
1760
|
};
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: /* @__PURE__ */ new Map() };
|
|
1719
|
-
}
|
|
1720
|
-
const regressions = [];
|
|
1721
|
-
const newFailures = [];
|
|
1722
|
-
const preExisting = [];
|
|
1723
|
-
const failureText = /* @__PURE__ */ new Map();
|
|
1724
|
-
const afterFailureText = after.failureText;
|
|
1725
|
-
for (const [testId, passed] of after.results) {
|
|
1726
|
-
if (passed) continue;
|
|
1727
|
-
const before = baseline.results.get(testId);
|
|
1728
|
-
if (before === true) {
|
|
1729
|
-
regressions.push(testId);
|
|
1730
|
-
const text = afterFailureText?.get(testId);
|
|
1731
|
-
if (text) failureText.set(testId, text);
|
|
1732
|
-
} else if (before === false) {
|
|
1733
|
-
preExisting.push(testId);
|
|
1734
|
-
} else {
|
|
1735
|
-
newFailures.push(testId);
|
|
1736
|
-
const text = afterFailureText?.get(testId);
|
|
1737
|
-
if (text) failureText.set(testId, text);
|
|
1761
|
+
const forgetReads = (ledger) => {
|
|
1762
|
+
for (const key of [...ledger.seen.keys()]) {
|
|
1763
|
+
if (key.startsWith("read_file:") || key.startsWith("grep:") || key.startsWith("list_files:")) ledger.seen.delete(key);
|
|
1738
1764
|
}
|
|
1739
|
-
}
|
|
1740
|
-
return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };
|
|
1741
|
-
}
|
|
1742
|
-
function describeRegressions(check) {
|
|
1743
|
-
const withText = (id) => {
|
|
1744
|
-
const text = check.failureText.get(id);
|
|
1745
|
-
return text ? `${id} (${text})` : id;
|
|
1746
1765
|
};
|
|
1747
|
-
const
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1766
|
+
const gate = (raw, deniedPaths) => {
|
|
1767
|
+
const n = normaliseToolPath(raw);
|
|
1768
|
+
if (!n.ok) return { ok: false, fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
|
|
1769
|
+
if (matchesDeniedPath(n.path, deniedPaths)) {
|
|
1770
|
+
return { ok: false, fail: { status: "refused", reason: "denied", message: "That path is protected and cannot be changed." } };
|
|
1771
|
+
}
|
|
1772
|
+
return { ok: true, path: n.path };
|
|
1773
|
+
};
|
|
1774
|
+
const prepareEdit = (a, env3, ledger) => {
|
|
1775
|
+
if (typeof a.path !== "string") return bad2("path must be a string.");
|
|
1776
|
+
if (typeof a.find !== "string" || a.find.length === 0 || a.find.length > limits.findChars) {
|
|
1777
|
+
return bad2("find must be a non-empty string within the length limit.");
|
|
1778
|
+
}
|
|
1779
|
+
if (typeof a.replace !== "string" || a.replace.length > limits.replaceChars) return bad2("replace must be a string within the length limit.");
|
|
1780
|
+
const g = gate(a.path, env3.deniedPaths);
|
|
1781
|
+
if (!g.ok) return { fail: g.fail };
|
|
1782
|
+
const path = g.path;
|
|
1783
|
+
if (!env3.listing.has(path)) {
|
|
1784
|
+
return { fail: { status: "not_found", message: "Not a tracked file. Use edit_file on an existing file, or write_file for a new one." } };
|
|
1785
|
+
}
|
|
1786
|
+
const find = a.find;
|
|
1787
|
+
const replace = a.replace;
|
|
1788
|
+
return {
|
|
1789
|
+
key: JSON.stringify({ path, find, replace }),
|
|
1790
|
+
exec: () => {
|
|
1791
|
+
const cl = ledger;
|
|
1792
|
+
if (cl.writeChars + replace.length > limits.writeCharsTotal) {
|
|
1793
|
+
return { result: { status: "budget_exhausted", reason: "write_chars", message: "The limit on text written has been reached; finish with what you have." } };
|
|
1794
|
+
}
|
|
1795
|
+
const entry = overlay.get(path);
|
|
1796
|
+
let lf;
|
|
1797
|
+
let base;
|
|
1798
|
+
if (entry) {
|
|
1799
|
+
lf = entry.lf;
|
|
1800
|
+
base = { ending: entry.ending, bom: entry.bom, originalLf: entry.originalLf ?? entry.lf };
|
|
1801
|
+
} else {
|
|
1802
|
+
const loaded = loadTextForEdit(baseFs, path, limits.fileBytesMax);
|
|
1803
|
+
if (!loaded.ok) return { result: loaded.result };
|
|
1804
|
+
lf = loaded.lf;
|
|
1805
|
+
base = { ending: loaded.ending, bom: loaded.bom, originalLf: loaded.lf };
|
|
1806
|
+
}
|
|
1807
|
+
if (protectedTests.has(path) && !(replace.startsWith(find) || replace.endsWith(find))) {
|
|
1808
|
+
return { result: { status: "protected", reason: "existing_test", message: "An existing test can only be added to: keep the anchor text and add new text before or after it." } };
|
|
1809
|
+
}
|
|
1810
|
+
const applied = applyEdits(lf, [{ find, replace }]);
|
|
1811
|
+
if (!applied.ok) {
|
|
1812
|
+
const refusal = applied.refusals[0];
|
|
1813
|
+
if (refusal?.kind === "no_match") {
|
|
1814
|
+
return { result: { status: "no_match", message: "That text was not found in the file. Read it again and copy it exactly." } };
|
|
1815
|
+
}
|
|
1816
|
+
if (refusal?.kind === "ambiguous") {
|
|
1817
|
+
const n = refusal.matchCount ?? 0;
|
|
1818
|
+
return { result: { status: "ambiguous", message: `That text matches ${n} places. Include more surrounding text so it matches exactly once.` } };
|
|
1819
|
+
}
|
|
1820
|
+
return { result: { status: "bad_args", message: "That edit could not be applied." } };
|
|
1821
|
+
}
|
|
1822
|
+
overlay.setEdited(path, applied.content, base);
|
|
1823
|
+
cl.writeChars += replace.length;
|
|
1824
|
+
edits.set(path, (edits.get(path) ?? 0) + 1);
|
|
1825
|
+
forgetReads(ledger);
|
|
1826
|
+
return { result: { status: "ok", output: { path, replaced: 1, totalLines: countLines(applied.content) } } };
|
|
1827
|
+
}
|
|
1828
|
+
};
|
|
1829
|
+
};
|
|
1830
|
+
const prepareWrite = (a, env3, ledger) => {
|
|
1831
|
+
if (typeof a.path !== "string") return bad2("path must be a string.");
|
|
1832
|
+
if (typeof a.content !== "string") return bad2("content must be a string.");
|
|
1833
|
+
const g = gate(a.path, env3.deniedPaths);
|
|
1834
|
+
if (!g.ok) return { fail: g.fail };
|
|
1835
|
+
const path = g.path;
|
|
1836
|
+
if (a.content.length > limits.contentChars) return { fail: { status: "too_large", message: "That file is too large to write." } };
|
|
1837
|
+
const own = overlay.isCreated(path);
|
|
1838
|
+
if (!own && (env3.listing.has(path) || baseFs.exists(path))) {
|
|
1839
|
+
return { fail: { status: "exists", message: "That file already exists. Use edit_file to change it." } };
|
|
1840
|
+
}
|
|
1841
|
+
const parts = path.split("/");
|
|
1842
|
+
for (let i = 1; i < parts.length; i++) {
|
|
1843
|
+
if (env3.listing.has(parts.slice(0, i).join("/"))) return refused("parent_is_file", "That path is not allowed.");
|
|
1844
|
+
}
|
|
1845
|
+
if (env3.visible.some((p) => p.startsWith(`${path}/`))) return refused("is_directory", "That path is not allowed.");
|
|
1846
|
+
if (!baseFs.parentInside(path)) return refused("outside_workspace", "That path is not allowed.");
|
|
1847
|
+
const content = a.content;
|
|
1848
|
+
return {
|
|
1849
|
+
key: JSON.stringify({ path, content }),
|
|
1850
|
+
exec: () => {
|
|
1851
|
+
const cl = ledger;
|
|
1852
|
+
if (cl.writeChars + content.length > limits.writeCharsTotal) {
|
|
1853
|
+
return { result: { status: "budget_exhausted", reason: "write_chars", message: "The limit on text written has been reached; finish with what you have." } };
|
|
1854
|
+
}
|
|
1855
|
+
const lf = toLf(content);
|
|
1856
|
+
overlay.setCreated(path, lf);
|
|
1857
|
+
noteCreated(path);
|
|
1858
|
+
cl.writeChars += content.length;
|
|
1859
|
+
created.set(path, content.length);
|
|
1860
|
+
forgetReads(ledger);
|
|
1861
|
+
return { result: { status: "ok", output: { path, totalLines: countLines(lf), chars: content.length } } };
|
|
1862
|
+
}
|
|
1863
|
+
};
|
|
1864
|
+
};
|
|
1865
|
+
const env2 = {
|
|
1866
|
+
listing,
|
|
1867
|
+
visible,
|
|
1868
|
+
deniedPaths: args.deniedPaths,
|
|
1869
|
+
fs: createOverlayFs(baseFs, overlay),
|
|
1870
|
+
limits,
|
|
1871
|
+
extraTools: { edit_file: prepareEdit, write_file: prepareWrite }
|
|
1872
|
+
};
|
|
1873
|
+
return { env: env2, ledger: newCodegenLedger(), overlay, limits, edits, created };
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
// src/targetingErrors.ts
|
|
1877
|
+
var DeniedPathError = class extends Error {
|
|
1878
|
+
constructor(message) {
|
|
1879
|
+
super(message);
|
|
1880
|
+
this.name = "DeniedPathError";
|
|
1752
1881
|
}
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1882
|
+
};
|
|
1883
|
+
var TargetingHttpError = class extends Error {
|
|
1884
|
+
status;
|
|
1885
|
+
constructor(status, statusText) {
|
|
1886
|
+
super(`Targeting call failed: ${status} ${statusText}`);
|
|
1887
|
+
this.name = "TargetingHttpError";
|
|
1888
|
+
this.status = status;
|
|
1757
1889
|
}
|
|
1758
|
-
|
|
1759
|
-
|
|
1890
|
+
};
|
|
1891
|
+
|
|
1892
|
+
// src/tokenEstimate.ts
|
|
1893
|
+
var TOKENS_PER_ALPHA_CHAR = 0.3;
|
|
1894
|
+
var TOKENS_PER_DIGIT_CHAR = 0.18;
|
|
1895
|
+
var TOKENS_PER_SPACE_CHAR = 0.05;
|
|
1896
|
+
var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
|
|
1897
|
+
var TOKENS_PER_NON_ASCII_CHAR = 1;
|
|
1898
|
+
var PROMPT_OVERHEAD_TOKENS = 5e3;
|
|
1899
|
+
function estimateTokens(text) {
|
|
1900
|
+
let alpha = 0;
|
|
1901
|
+
let digit = 0;
|
|
1902
|
+
let space = 0;
|
|
1903
|
+
let punct = 0;
|
|
1904
|
+
let nonAscii = 0;
|
|
1905
|
+
for (const ch of text) {
|
|
1906
|
+
const code = ch.codePointAt(0);
|
|
1907
|
+
if (code >= 128) nonAscii++;
|
|
1908
|
+
else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
|
|
1909
|
+
else if (code >= 48 && code <= 57) digit++;
|
|
1910
|
+
else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
|
|
1911
|
+
else punct++;
|
|
1760
1912
|
}
|
|
1761
|
-
return
|
|
1913
|
+
return Math.ceil(
|
|
1914
|
+
alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
|
|
1915
|
+
);
|
|
1762
1916
|
}
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
var BASELINE_CHECK_TIMEOUT_MS = 12e4;
|
|
1766
|
-
function shellQuote(value) {
|
|
1767
|
-
return `'${value.split("'").join("'\\''")}'`;
|
|
1917
|
+
function estimateRequestTokens(contextData) {
|
|
1918
|
+
return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
|
|
1768
1919
|
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1920
|
+
|
|
1921
|
+
// src/targetingLoop.ts
|
|
1922
|
+
var LOOP_CONTRACT_VERSION = "targeting-loop-1";
|
|
1923
|
+
var LoopFailure = class extends Error {
|
|
1924
|
+
reason;
|
|
1925
|
+
runtimeCode;
|
|
1926
|
+
/** What the loop had done when it failed, so reads made before the failure are not lost. */
|
|
1927
|
+
summary;
|
|
1928
|
+
constructor(reason, runtimeCode, cause) {
|
|
1929
|
+
super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
|
|
1930
|
+
this.name = "LoopFailure";
|
|
1931
|
+
this.reason = reason;
|
|
1932
|
+
this.runtimeCode = runtimeCode;
|
|
1933
|
+
if (cause !== void 0) this.cause = cause;
|
|
1934
|
+
}
|
|
1935
|
+
};
|
|
1936
|
+
var SafetyRefusalError = class extends RuntimeReplyError {
|
|
1937
|
+
constructor(message, summary) {
|
|
1938
|
+
super(message, summary);
|
|
1939
|
+
this.name = "SafetyRefusalError";
|
|
1940
|
+
}
|
|
1941
|
+
};
|
|
1942
|
+
var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
|
|
1943
|
+
var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
|
|
1944
|
+
var MAX_ID_CHARS = 64;
|
|
1945
|
+
var MAX_CALLS_IN_A_REPLY = 50;
|
|
1946
|
+
var MAX_ARGS_JSON_CHARS = 1e3;
|
|
1947
|
+
function isPlainObject2(x) {
|
|
1948
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
1772
1949
|
}
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
return typeof type === "string" && type.trim() !== "" && type.trim().toUpperCase() !== "REGRESSION";
|
|
1780
|
-
});
|
|
1950
|
+
function safeArgs(args) {
|
|
1951
|
+
try {
|
|
1952
|
+
return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS ? args : { _omitted: "too large" };
|
|
1953
|
+
} catch {
|
|
1954
|
+
return { _omitted: "unreadable" };
|
|
1955
|
+
}
|
|
1781
1956
|
}
|
|
1782
|
-
function
|
|
1783
|
-
|
|
1784
|
-
const
|
|
1785
|
-
|
|
1957
|
+
function classifyTransport(err) {
|
|
1958
|
+
if (err instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err);
|
|
1959
|
+
const name = err?.name;
|
|
1960
|
+
if (name === "TimeoutError" || name === "AbortError") return new LoopFailure("turn_timeout", void 0, err);
|
|
1961
|
+
return new LoopFailure("transport", void 0, err);
|
|
1786
1962
|
}
|
|
1787
|
-
function
|
|
1788
|
-
const
|
|
1789
|
-
const
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1963
|
+
async function runTargetingLoop(args, deps) {
|
|
1964
|
+
const limits = { ...DEFAULT_LIMITS, ...deps.limits };
|
|
1965
|
+
const now = deps.now ?? Date.now;
|
|
1966
|
+
const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
|
|
1967
|
+
const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
|
|
1968
|
+
const deadlineMs = deps.deadlineMs ?? 6e5;
|
|
1969
|
+
const env2 = {
|
|
1970
|
+
listing: new Set(args.listing),
|
|
1971
|
+
visible: buildVisibleListing(args.listing, args.deniedPaths),
|
|
1972
|
+
deniedPaths: args.deniedPaths,
|
|
1973
|
+
fs: deps.fs ?? createNodeToolFs(),
|
|
1974
|
+
limits
|
|
1975
|
+
};
|
|
1976
|
+
const ledger = newLedger();
|
|
1977
|
+
const reads = [];
|
|
1978
|
+
const transcript = [];
|
|
1979
|
+
const toolResults = [];
|
|
1980
|
+
const usedIds = /* @__PURE__ */ new Set();
|
|
1981
|
+
let turns = 0;
|
|
1982
|
+
let noProgressStreak = 0;
|
|
1983
|
+
let forced = null;
|
|
1984
|
+
const started = now();
|
|
1985
|
+
const buildContext = (turn, isFinal, finalReason) => ({
|
|
1986
|
+
...args.baseContext,
|
|
1987
|
+
contractVersion: LOOP_CONTRACT_VERSION,
|
|
1988
|
+
loop: {
|
|
1989
|
+
turn,
|
|
1990
|
+
maxTurns: limits.maxTurns,
|
|
1991
|
+
final: isFinal,
|
|
1992
|
+
...isFinal ? { finalReason } : {},
|
|
1993
|
+
remaining: {
|
|
1994
|
+
toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
|
|
1995
|
+
readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
|
|
1996
|
+
},
|
|
1997
|
+
transcript,
|
|
1998
|
+
toolResults
|
|
1796
1999
|
}
|
|
1797
|
-
}
|
|
1798
|
-
(
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
2000
|
+
});
|
|
2001
|
+
const snapshot = (stopReason) => ({
|
|
2002
|
+
turns,
|
|
2003
|
+
toolCalls: ledger.toolCalls,
|
|
2004
|
+
readChars: ledger.readChars,
|
|
2005
|
+
refused: ledger.refused,
|
|
2006
|
+
stopReason,
|
|
2007
|
+
reads: [...reads]
|
|
2008
|
+
});
|
|
2009
|
+
log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
|
|
2010
|
+
try {
|
|
2011
|
+
for (let turn = 1; turn <= limits.maxTurns; turn++) {
|
|
2012
|
+
turns = turn;
|
|
2013
|
+
if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
|
|
2014
|
+
const isFinal = forced !== null || turn === limits.maxTurns;
|
|
2015
|
+
const finalReason = forced ?? "max_turns";
|
|
2016
|
+
const contextData = buildContext(turn, isFinal, finalReason);
|
|
2017
|
+
const requestChars = JSON.stringify(contextData).length;
|
|
2018
|
+
const requestTokens = estimateRequestTokens(contextData);
|
|
2019
|
+
if (requestTokens > limits.maxRequestTokens) {
|
|
2020
|
+
log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
|
|
2021
|
+
throw new LoopFailure("token_ceiling");
|
|
2022
|
+
}
|
|
2023
|
+
const turnStarted = now();
|
|
2024
|
+
let envelope;
|
|
2025
|
+
try {
|
|
2026
|
+
envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
|
|
2027
|
+
} catch (err) {
|
|
2028
|
+
throw classifyTransport(err);
|
|
2029
|
+
}
|
|
2030
|
+
const code = envelope?.errorCode;
|
|
2031
|
+
try {
|
|
2032
|
+
checkHardFailure(envelope, "pilot.targeting");
|
|
2033
|
+
} catch (err) {
|
|
2034
|
+
throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
|
|
2035
|
+
}
|
|
2036
|
+
if (envelope?.success === false) {
|
|
2037
|
+
const runtimeCode = typeof code === "string" ? code : void 0;
|
|
2038
|
+
if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
|
|
2039
|
+
let inner;
|
|
2040
|
+
try {
|
|
2041
|
+
unwrapExecute(envelope, "pilot.targeting");
|
|
2042
|
+
} catch (e) {
|
|
2043
|
+
inner = e instanceof RuntimeReplyError ? e : void 0;
|
|
2044
|
+
}
|
|
2045
|
+
const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
|
|
2046
|
+
throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
|
|
1810
2047
|
}
|
|
2048
|
+
throw new LoopFailure("runtime_failed", runtimeCode);
|
|
1811
2049
|
}
|
|
1812
|
-
|
|
1813
|
-
|
|
2050
|
+
let body;
|
|
2051
|
+
try {
|
|
2052
|
+
body = unwrapExecute(envelope, "pilot.targeting");
|
|
2053
|
+
} catch (err) {
|
|
2054
|
+
throw new LoopFailure("bad_reply", void 0, err);
|
|
2055
|
+
}
|
|
2056
|
+
if (body.outcome === "TARGETED" || body.outcome === "NO_TARGET") {
|
|
2057
|
+
log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
|
|
2058
|
+
const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
|
|
2059
|
+
log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
|
|
2060
|
+
return { body, summary: snapshot(stopReason) };
|
|
2061
|
+
}
|
|
2062
|
+
if (body.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
|
|
2063
|
+
if (isFinal) throw new LoopFailure("final_not_produced");
|
|
2064
|
+
const rawCalls = body.toolCalls;
|
|
2065
|
+
if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
|
|
2066
|
+
throw new LoopFailure("bad_reply");
|
|
2067
|
+
}
|
|
2068
|
+
const calls = [];
|
|
2069
|
+
for (const c of rawCalls) {
|
|
2070
|
+
if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
|
|
2071
|
+
throw new LoopFailure("bad_reply");
|
|
2072
|
+
}
|
|
2073
|
+
if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
|
|
2074
|
+
calls.push({ id: c.id, name: c.name, args: c.args });
|
|
2075
|
+
}
|
|
2076
|
+
for (const c of calls) usedIds.add(c.id);
|
|
2077
|
+
const results = [];
|
|
2078
|
+
const logged = [];
|
|
2079
|
+
const turnReads = [];
|
|
2080
|
+
calls.forEach((call, index) => {
|
|
2081
|
+
let result;
|
|
2082
|
+
let read;
|
|
2083
|
+
if (index >= limits.maxCallsPerTurn) {
|
|
2084
|
+
result = {
|
|
2085
|
+
id: call.id,
|
|
2086
|
+
name: call.name,
|
|
2087
|
+
status: "budget_exhausted",
|
|
2088
|
+
reason: "too_many_calls",
|
|
2089
|
+
message: "Too many calls in one turn; this one was not run."
|
|
2090
|
+
};
|
|
2091
|
+
} else {
|
|
2092
|
+
try {
|
|
2093
|
+
({ result, read } = executeToolCall(call, env2, ledger));
|
|
2094
|
+
} catch (err) {
|
|
2095
|
+
throw new LoopFailure("executor_error", void 0, err);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
results.push(result);
|
|
2099
|
+
turnReads[index] = read;
|
|
2100
|
+
if (read) reads.push(read);
|
|
2101
|
+
const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
|
|
2102
|
+
const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
|
|
2103
|
+
logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
|
|
2104
|
+
if (result.status === "refused") {
|
|
2105
|
+
log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
|
|
2106
|
+
}
|
|
2107
|
+
});
|
|
2108
|
+
const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
|
|
2109
|
+
transcript.push({
|
|
2110
|
+
turn,
|
|
2111
|
+
...reasoning ? { reasoning } : {},
|
|
2112
|
+
toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
|
|
2113
|
+
});
|
|
2114
|
+
toolResults.push(...results);
|
|
2115
|
+
noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
|
|
2116
|
+
if (noProgressStreak >= 2) forced = "no_progress";
|
|
2117
|
+
else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
|
|
2118
|
+
else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
|
|
2119
|
+
const nextTurn = turn + 1;
|
|
2120
|
+
if (nextTurn <= limits.maxTurns) {
|
|
2121
|
+
const nextFinal = forced !== null || nextTurn === limits.maxTurns;
|
|
2122
|
+
const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
|
|
2123
|
+
if (projected > limits.maxRequestTokens) {
|
|
2124
|
+
results.forEach((r, idx) => {
|
|
2125
|
+
if (r.status !== "ok") return;
|
|
2126
|
+
toolResults[toolResults.indexOf(r)] = {
|
|
2127
|
+
id: r.id,
|
|
2128
|
+
name: r.name,
|
|
2129
|
+
status: "budget_exhausted",
|
|
2130
|
+
reason: "token_ceiling",
|
|
2131
|
+
message: "Too large to include; answer from what you have."
|
|
2132
|
+
};
|
|
2133
|
+
const dropped = turnReads[idx];
|
|
2134
|
+
if (dropped) {
|
|
2135
|
+
const at = reads.indexOf(dropped);
|
|
2136
|
+
if (at >= 0) reads.splice(at, 1);
|
|
2137
|
+
}
|
|
2138
|
+
logged[idx].status = "budget_exhausted";
|
|
2139
|
+
logged[idx].reason = "token_ceiling";
|
|
2140
|
+
});
|
|
2141
|
+
forced = "read_budget";
|
|
2142
|
+
const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
|
|
2143
|
+
const fits = trimmed <= limits.maxRequestTokens;
|
|
2144
|
+
log({
|
|
2145
|
+
event: "targeting.loop_ceiling",
|
|
2146
|
+
turn,
|
|
2147
|
+
action: fits ? "dropped_results" : "fallback",
|
|
2148
|
+
projectedTokens: projected,
|
|
2149
|
+
ceiling: limits.maxRequestTokens
|
|
2150
|
+
});
|
|
2151
|
+
if (!fits) throw new LoopFailure("token_ceiling");
|
|
2152
|
+
}
|
|
2153
|
+
}
|
|
2154
|
+
log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
|
|
1814
2155
|
}
|
|
2156
|
+
throw new LoopFailure("final_not_produced");
|
|
2157
|
+
} catch (err) {
|
|
2158
|
+
if (err instanceof SafetyRefusalError) throw err;
|
|
2159
|
+
const failure = err instanceof LoopFailure ? err : new LoopFailure("internal_error", void 0, err);
|
|
2160
|
+
failure.summary ??= snapshot("fallback");
|
|
2161
|
+
throw failure;
|
|
1815
2162
|
}
|
|
1816
2163
|
}
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
} catch {
|
|
1834
|
-
return null;
|
|
2164
|
+
|
|
2165
|
+
// src/codegenLoop.ts
|
|
2166
|
+
var CODEGEN_LOOP_CONTRACT_VERSION = "codegen-loop-1";
|
|
2167
|
+
var CodegenLoopFailure = class extends Error {
|
|
2168
|
+
reason;
|
|
2169
|
+
runtimeCode;
|
|
2170
|
+
/** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */
|
|
2171
|
+
detail;
|
|
2172
|
+
summary;
|
|
2173
|
+
constructor(reason, runtimeCode, cause, detail) {
|
|
2174
|
+
super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
|
|
2175
|
+
this.name = "CodegenLoopFailure";
|
|
2176
|
+
this.reason = reason;
|
|
2177
|
+
this.runtimeCode = runtimeCode;
|
|
2178
|
+
this.detail = detail;
|
|
2179
|
+
if (cause !== void 0) this.cause = cause;
|
|
1835
2180
|
}
|
|
1836
2181
|
};
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
2182
|
+
var MAX_ID_CHARS2 = 64;
|
|
2183
|
+
var MAX_CALLS_IN_A_REPLY2 = 50;
|
|
2184
|
+
var MAX_SUMMARY_CHARS = 300;
|
|
2185
|
+
var READ_TOOLS = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
|
|
2186
|
+
var WRITE_TOOLS = /* @__PURE__ */ new Set(["edit_file", "write_file"]);
|
|
2187
|
+
var TOOL_NAMES2 = /* @__PURE__ */ new Set([...READ_TOOLS, ...WRITE_TOOLS]);
|
|
2188
|
+
function isPlainObject3(x) {
|
|
2189
|
+
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
2190
|
+
}
|
|
2191
|
+
function classifyTransport2(err) {
|
|
2192
|
+
if (err instanceof TargetingHttpError) return new CodegenLoopFailure("http_error", void 0, err);
|
|
2193
|
+
const name = err?.name;
|
|
2194
|
+
if (name === "TimeoutError" || name === "AbortError") return new CodegenLoopFailure("turn_timeout", void 0, err);
|
|
2195
|
+
return new CodegenLoopFailure("transport", void 0, err);
|
|
2196
|
+
}
|
|
2197
|
+
var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
|
|
2198
|
+
async function runCodegenLoop(args, deps) {
|
|
2199
|
+
const ws = createCodegenWorkspace({
|
|
2200
|
+
listing: args.listing,
|
|
2201
|
+
deniedPaths: args.deniedPaths,
|
|
2202
|
+
protectedTestPaths: args.protectedTestPaths,
|
|
2203
|
+
fs: deps.fs,
|
|
2204
|
+
limits: deps.limits
|
|
2205
|
+
});
|
|
2206
|
+
const { env: env2, ledger, overlay, limits } = ws;
|
|
2207
|
+
const now = deps.now ?? Date.now;
|
|
2208
|
+
const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
|
|
2209
|
+
const turnTimeoutMs = deps.turnTimeoutMs ?? 3e5;
|
|
2210
|
+
const deadlineMs = deps.deadlineMs ?? 15e5;
|
|
2211
|
+
const reads = [];
|
|
2212
|
+
const reasoning = [];
|
|
2213
|
+
const statusCounts = {};
|
|
2214
|
+
const transcript = [];
|
|
2215
|
+
const toolResults = [];
|
|
2216
|
+
const usedIds = /* @__PURE__ */ new Set();
|
|
2217
|
+
let turns = 0;
|
|
2218
|
+
let noProgressStreak = 0;
|
|
2219
|
+
let forced = null;
|
|
2220
|
+
const started = now();
|
|
2221
|
+
const buildContext = (turn, isFinal, finalReason) => ({
|
|
2222
|
+
...args.baseContext,
|
|
2223
|
+
contractVersion: CODEGEN_LOOP_CONTRACT_VERSION,
|
|
2224
|
+
loop: {
|
|
2225
|
+
turn,
|
|
2226
|
+
maxTurns: limits.maxTurns,
|
|
2227
|
+
final: isFinal,
|
|
2228
|
+
...isFinal ? { finalReason } : {},
|
|
2229
|
+
remaining: {
|
|
2230
|
+
toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
|
|
2231
|
+
readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),
|
|
2232
|
+
writeChars: Math.max(0, limits.writeCharsTotal - ledger.writeChars)
|
|
2233
|
+
},
|
|
2234
|
+
transcript,
|
|
2235
|
+
toolResults
|
|
2236
|
+
}
|
|
2237
|
+
});
|
|
2238
|
+
const snapshot = (stopReason) => ({
|
|
2239
|
+
turns,
|
|
2240
|
+
toolCalls: ledger.toolCalls,
|
|
2241
|
+
refused: ledger.refused,
|
|
2242
|
+
stopReason,
|
|
2243
|
+
reads: [...reads],
|
|
2244
|
+
edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),
|
|
2245
|
+
created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),
|
|
2246
|
+
statusCounts: { ...statusCounts },
|
|
2247
|
+
reasoning: [...reasoning]
|
|
2248
|
+
});
|
|
2249
|
+
const makeRoom = (nextTurn, nextFinal, finalReason) => {
|
|
2250
|
+
const fits = () => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limits.maxRequestTokens;
|
|
2251
|
+
if (fits()) return true;
|
|
2252
|
+
for (let i = 0; i < toolResults.length && !fits(); i++) {
|
|
2253
|
+
const r = toolResults[i];
|
|
2254
|
+
if (READ_TOOLS.has(r.name) && r.status === "ok" && r.output !== DROPPED_OUTPUT) toolResults[i] = { ...r, output: DROPPED_OUTPUT };
|
|
1849
2255
|
}
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
}
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
console.log("Baseline check: no case with a known, non-Regression label \u2014 nothing to check.");
|
|
1863
|
-
return nothing;
|
|
1864
|
-
}
|
|
1865
|
-
const warnings = [];
|
|
1866
|
-
const flagged = [];
|
|
1867
|
-
const written = [];
|
|
1868
|
-
const unsafe = /* @__PURE__ */ new Set();
|
|
1869
|
-
const skip = (path, why) => {
|
|
1870
|
-
const message = `Baseline check skipped for ${path}: ${why}`;
|
|
1871
|
-
console.warn(`::warning::${message}`);
|
|
1872
|
-
warnings.push(message);
|
|
2256
|
+
for (const key of [...ledger.seen.keys()]) {
|
|
2257
|
+
if (key.startsWith("read_file:") || key.startsWith("grep:") || key.startsWith("list_files:")) ledger.seen.delete(key);
|
|
2258
|
+
}
|
|
2259
|
+
for (const entry of transcript) {
|
|
2260
|
+
if (fits()) break;
|
|
2261
|
+
entry.toolCalls = entry.toolCalls.map((c) => {
|
|
2262
|
+
if (!WRITE_TOOLS.has(c.name) || !isPlainObject3(c.args) || "_omitted" in c.args) return c;
|
|
2263
|
+
const path = typeof c.args.path === "string" ? { path: c.args.path } : {};
|
|
2264
|
+
return { ...c, args: { ...path, _omitted: "written earlier; read the file to see it" } };
|
|
2265
|
+
});
|
|
2266
|
+
}
|
|
2267
|
+
return fits();
|
|
1873
2268
|
};
|
|
2269
|
+
log({ event: "codegen.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
|
|
1874
2270
|
try {
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
const
|
|
1879
|
-
|
|
1880
|
-
const
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
2271
|
+
for (let turn = 1; turn <= limits.maxTurns; turn++) {
|
|
2272
|
+
turns = turn;
|
|
2273
|
+
if (now() - started > deadlineMs) throw new CodegenLoopFailure("loop_deadline");
|
|
2274
|
+
const isFinal = forced !== null || turn === limits.maxTurns;
|
|
2275
|
+
const finalReason = forced ?? "max_turns";
|
|
2276
|
+
const contextData = buildContext(turn, isFinal, finalReason);
|
|
2277
|
+
const requestTokens = estimateRequestTokens(contextData);
|
|
2278
|
+
if (requestTokens > limits.maxRequestTokens) {
|
|
2279
|
+
log({ event: "codegen.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
|
|
2280
|
+
throw new CodegenLoopFailure("token_ceiling");
|
|
1884
2281
|
}
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
2282
|
+
const turnStarted = now();
|
|
2283
|
+
let envelope;
|
|
2284
|
+
try {
|
|
2285
|
+
envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
|
|
2286
|
+
} catch (err) {
|
|
2287
|
+
throw classifyTransport2(err);
|
|
1891
2288
|
}
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
target.path,
|
|
1910
|
-
"the single-file command wrote no new JUnit report (it must write the same JUnit report as the test command), so nothing could be checked."
|
|
1911
|
-
);
|
|
1912
|
-
} else {
|
|
1913
|
-
const byId = readAutomationIdResults(cwd);
|
|
1914
|
-
for (const id of ids) if (byId?.get(id) === "pass") flagged.push(id);
|
|
2289
|
+
const code = envelope?.errorCode;
|
|
2290
|
+
try {
|
|
2291
|
+
checkHardFailure(envelope, "pilot.codegen");
|
|
2292
|
+
} catch (err) {
|
|
2293
|
+
throw new CodegenLoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
|
|
2294
|
+
}
|
|
2295
|
+
if (envelope?.success === false) {
|
|
2296
|
+
const runtimeCode = typeof code === "string" ? code : void 0;
|
|
2297
|
+
if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
|
|
2298
|
+
let inner;
|
|
2299
|
+
try {
|
|
2300
|
+
unwrapExecute(envelope, "pilot.codegen");
|
|
2301
|
+
} catch (e) {
|
|
2302
|
+
inner = e instanceof RuntimeReplyError ? e : void 0;
|
|
2303
|
+
}
|
|
2304
|
+
const fallbackText = `pilot.codegen failed: ${runtimeCode}`;
|
|
2305
|
+
throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
|
|
1915
2306
|
}
|
|
2307
|
+
throw new CodegenLoopFailure("runtime_failed", runtimeCode);
|
|
1916
2308
|
}
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
2309
|
+
let body;
|
|
2310
|
+
try {
|
|
2311
|
+
body = unwrapExecute(envelope, "pilot.codegen");
|
|
2312
|
+
} catch (err) {
|
|
2313
|
+
throw new CodegenLoopFailure("bad_reply", void 0, err);
|
|
2314
|
+
}
|
|
2315
|
+
const reasonText = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
|
|
2316
|
+
if (body.outcome === "CANNOT_COMPLETE") {
|
|
2317
|
+
log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
|
|
2318
|
+
const said = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
|
|
2319
|
+
throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said);
|
|
2320
|
+
}
|
|
2321
|
+
if (body.outcome === "DONE") {
|
|
2322
|
+
log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
|
|
2323
|
+
const changed = overlay.changedPaths();
|
|
2324
|
+
if (changed.length === 0) throw new CodegenLoopFailure("no_writes");
|
|
2325
|
+
const texts = changed.map((p) => overlay.get(p)?.lf ?? "");
|
|
2326
|
+
const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
|
|
2327
|
+
if (missing.length > 0) {
|
|
2328
|
+
log({ event: "codegen.loop_refused", turn, reason: "coverage_missing", missing: missing.length });
|
|
2329
|
+
throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`);
|
|
2330
|
+
}
|
|
2331
|
+
const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);
|
|
2332
|
+
for (const path of changed) {
|
|
2333
|
+
const entry = overlay.get(path);
|
|
2334
|
+
if (!entry || entry.created || entry.originalLf === null) continue;
|
|
2335
|
+
const pseudo = { path, kind: "EXISTING", planStepsImplemented: planSteps };
|
|
2336
|
+
const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);
|
|
2337
|
+
if (suspect) {
|
|
2338
|
+
log({ event: "codegen.loop_refused", turn, reason: "truncation_guard", path });
|
|
2339
|
+
throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`);
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
|
|
2343
|
+
const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
|
|
2344
|
+
log({ event: "codegen.loop_done", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });
|
|
2345
|
+
return { results: overlay.results(), summary: snapshot(stopReason), doneSummary };
|
|
2346
|
+
}
|
|
2347
|
+
if (body.outcome !== "TOOL_CALLS") throw new CodegenLoopFailure("bad_reply");
|
|
2348
|
+
if (isFinal) throw new CodegenLoopFailure("final_not_produced");
|
|
2349
|
+
const rawCalls = body.toolCalls;
|
|
2350
|
+
if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY2) throw new CodegenLoopFailure("bad_reply");
|
|
2351
|
+
const calls = [];
|
|
2352
|
+
for (const c of rawCalls) {
|
|
2353
|
+
if (!isPlainObject3(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS2 || typeof c.name !== "string") {
|
|
2354
|
+
throw new CodegenLoopFailure("bad_reply");
|
|
2355
|
+
}
|
|
2356
|
+
if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new CodegenLoopFailure("duplicate_call_ids");
|
|
2357
|
+
calls.push({ id: c.id, name: c.name, args: c.args });
|
|
2358
|
+
}
|
|
2359
|
+
for (const c of calls) usedIds.add(c.id);
|
|
2360
|
+
const results = [];
|
|
2361
|
+
const logged = [];
|
|
2362
|
+
calls.forEach((call, index) => {
|
|
2363
|
+
let result;
|
|
2364
|
+
let read;
|
|
2365
|
+
if (index >= limits.maxCallsPerTurn) {
|
|
2366
|
+
result = { id: call.id, name: call.name, status: "budget_exhausted", reason: "too_many_calls", message: "Too many calls in one turn; this one was not run." };
|
|
2367
|
+
} else {
|
|
2368
|
+
try {
|
|
2369
|
+
({ result, read } = executeToolCall(call, env2, ledger));
|
|
2370
|
+
} catch (err) {
|
|
2371
|
+
throw new CodegenLoopFailure("executor_error", void 0, err);
|
|
2372
|
+
}
|
|
2373
|
+
}
|
|
2374
|
+
results.push(result);
|
|
2375
|
+
if (read) reads.push(read);
|
|
2376
|
+
statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;
|
|
2377
|
+
const tool = TOOL_NAMES2.has(call.name) ? call.name : "unknown";
|
|
2378
|
+
const pathArg = isPlainObject3(call.args) && typeof call.args.path === "string" && result.status !== "refused" ? { path: call.args.path } : {};
|
|
2379
|
+
logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...pathArg });
|
|
2380
|
+
if (result.status === "refused" || result.status === "protected") {
|
|
2381
|
+
log({ event: "codegen.loop_refused", turn, tool, status: result.status, reason: result.reason });
|
|
2382
|
+
}
|
|
2383
|
+
});
|
|
2384
|
+
if (reasonText) reasoning.push({ turn, text: reasonText });
|
|
2385
|
+
transcript.push({ turn, ...reasonText ? { reasoning: reasonText } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });
|
|
2386
|
+
toolResults.push(...results);
|
|
2387
|
+
noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
|
|
2388
|
+
if (noProgressStreak >= 2) forced = "no_progress";
|
|
2389
|
+
else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
|
|
2390
|
+
else if (ledger.writeChars >= limits.writeCharsTotal) forced = "write_budget";
|
|
2391
|
+
else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
|
|
2392
|
+
const nextTurn = turn + 1;
|
|
2393
|
+
if (nextTurn <= limits.maxTurns) {
|
|
2394
|
+
const nextFinal = forced !== null || nextTurn === limits.maxTurns;
|
|
2395
|
+
if (!makeRoom(nextTurn, nextFinal, forced ?? "max_turns")) {
|
|
2396
|
+
forced = forced ?? "read_budget";
|
|
2397
|
+
const fits = makeRoom(nextTurn, true, forced);
|
|
2398
|
+
log({ event: "codegen.loop_ceiling", turn, action: fits ? "forced_final" : "fallback", ceiling: limits.maxRequestTokens });
|
|
2399
|
+
if (!fits) throw new CodegenLoopFailure("token_ceiling");
|
|
1923
2400
|
}
|
|
1924
2401
|
}
|
|
2402
|
+
log({ event: "codegen.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
|
|
1925
2403
|
}
|
|
1926
|
-
|
|
1927
|
-
const automationIds = [...new Set(flagged)].slice(0, 200);
|
|
1928
|
-
const list = automationIds.join(", ");
|
|
1929
|
-
warnings.push(
|
|
1930
|
-
cause === "NO_OP" ? `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, and every file the generated change edited came out unchanged, so the change itself may have been a no-op: ${list}.` : `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, so they may assert something already true: ${list}. This check cannot tell that from a change that did nothing.`
|
|
1931
|
-
);
|
|
1932
|
-
return { findings: { cause, automationIds }, warnings };
|
|
2404
|
+
throw new CodegenLoopFailure("final_not_produced");
|
|
1933
2405
|
} catch (err) {
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
restore(written);
|
|
2406
|
+
if (err instanceof SafetyRefusalError) throw err;
|
|
2407
|
+
const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
|
|
2408
|
+
failure.summary ??= snapshot("fallback");
|
|
2409
|
+
throw failure;
|
|
1939
2410
|
}
|
|
1940
2411
|
}
|
|
1941
2412
|
|
|
1942
|
-
// src/
|
|
1943
|
-
var
|
|
1944
|
-
|
|
2413
|
+
// src/overlapCheck.ts
|
|
2414
|
+
var TEST_PATH_RE = /(\.(test|spec)\.[jt]sx?$)|(^|\/)(__tests__|tests?)\//i;
|
|
2415
|
+
function isTestTarget(path) {
|
|
2416
|
+
return TEST_PATH_RE.test(path);
|
|
2417
|
+
}
|
|
2418
|
+
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
2419
|
+
"a",
|
|
2420
|
+
"an",
|
|
2421
|
+
"the",
|
|
2422
|
+
"is",
|
|
2423
|
+
"are",
|
|
2424
|
+
"was",
|
|
2425
|
+
"were",
|
|
2426
|
+
"be",
|
|
2427
|
+
"been",
|
|
2428
|
+
"being",
|
|
2429
|
+
"of",
|
|
2430
|
+
"to",
|
|
2431
|
+
"in",
|
|
2432
|
+
"on",
|
|
2433
|
+
"for",
|
|
2434
|
+
"with",
|
|
2435
|
+
"at",
|
|
2436
|
+
"by",
|
|
2437
|
+
"from",
|
|
2438
|
+
"as",
|
|
2439
|
+
"and",
|
|
2440
|
+
"or",
|
|
2441
|
+
"not",
|
|
2442
|
+
"no",
|
|
2443
|
+
"nor",
|
|
2444
|
+
"this",
|
|
2445
|
+
"that",
|
|
2446
|
+
"these",
|
|
2447
|
+
"those",
|
|
2448
|
+
"it",
|
|
2449
|
+
"its",
|
|
2450
|
+
"cannot",
|
|
2451
|
+
"can't",
|
|
2452
|
+
"should",
|
|
2453
|
+
"must",
|
|
2454
|
+
"may",
|
|
2455
|
+
"will",
|
|
2456
|
+
"shall",
|
|
2457
|
+
"when",
|
|
2458
|
+
"if",
|
|
2459
|
+
"than",
|
|
2460
|
+
"then",
|
|
2461
|
+
"so",
|
|
2462
|
+
"do",
|
|
2463
|
+
"does",
|
|
2464
|
+
"did"
|
|
2465
|
+
]);
|
|
2466
|
+
var MIN_WORD_LENGTH = 3;
|
|
2467
|
+
function significantWords(step) {
|
|
2468
|
+
return new Set(
|
|
2469
|
+
step.toLowerCase().replace(/[^a-z0-9\s]/g, " ").split(/\s+/).filter((w) => w.length >= MIN_WORD_LENGTH && !STOPWORDS.has(w))
|
|
2470
|
+
);
|
|
2471
|
+
}
|
|
2472
|
+
function jaccard(a, b) {
|
|
2473
|
+
if (a.size === 0 || b.size === 0) return 0;
|
|
2474
|
+
let intersection = 0;
|
|
2475
|
+
for (const w of a) if (b.has(w)) intersection++;
|
|
2476
|
+
const union = a.size + b.size - intersection;
|
|
2477
|
+
return intersection / union;
|
|
2478
|
+
}
|
|
2479
|
+
function normalizedStep(step) {
|
|
2480
|
+
return step.trim().toLowerCase().replace(/\s+/g, " ");
|
|
2481
|
+
}
|
|
2482
|
+
var OVERLAP_THRESHOLD = 0.5;
|
|
2483
|
+
function findOverlappingSteps(targets) {
|
|
2484
|
+
const items = targets.flatMap(
|
|
2485
|
+
(target) => target.planStepsImplemented.map((step) => ({
|
|
2486
|
+
target: target.path,
|
|
2487
|
+
step,
|
|
2488
|
+
words: significantWords(step)
|
|
2489
|
+
}))
|
|
2490
|
+
);
|
|
2491
|
+
const warnings = [];
|
|
2492
|
+
for (let i = 0; i < items.length; i++) {
|
|
2493
|
+
for (let j = i + 1; j < items.length; j++) {
|
|
2494
|
+
if (items[i].target === items[j].target) continue;
|
|
2495
|
+
if (isTestTarget(items[i].target) || isTestTarget(items[j].target)) continue;
|
|
2496
|
+
if (jaccard(items[i].words, items[j].words) >= OVERLAP_THRESHOLD) {
|
|
2497
|
+
warnings.push({
|
|
2498
|
+
targetA: items[i].target,
|
|
2499
|
+
stepA: items[i].step,
|
|
2500
|
+
targetB: items[j].target,
|
|
2501
|
+
stepB: items[j].step,
|
|
2502
|
+
severity: normalizedStep(items[i].step) === normalizedStep(items[j].step) ? "identical" : "similar"
|
|
2503
|
+
});
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
return warnings;
|
|
2508
|
+
}
|
|
2509
|
+
function describeOverlapWarnings(warnings) {
|
|
2510
|
+
return warnings.map(
|
|
2511
|
+
(w) => `${w.targetA} and ${w.targetB} both implement what looks like the same rule \u2014 "${w.stepA}" / "${w.stepB}". Check these aren't two independent implementations of the same behavior.`
|
|
2512
|
+
);
|
|
2513
|
+
}
|
|
1945
2514
|
|
|
1946
|
-
// src/
|
|
1947
|
-
var
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
if (err instanceof RuntimeReplyError) return err.summary;
|
|
1964
|
-
return err instanceof Error ? err.message : String(err);
|
|
2515
|
+
// src/codegenStep.ts
|
|
2516
|
+
var MAX_PROTECTED_PATHS_ON_WIRE = 300;
|
|
2517
|
+
async function postCodegenTurn(gateway, contextData, signal) {
|
|
2518
|
+
const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
|
|
2519
|
+
method: "POST",
|
|
2520
|
+
headers: { "content-type": "application/json", "x-run-token": gateway.token },
|
|
2521
|
+
body: JSON.stringify({
|
|
2522
|
+
appId: "quiktrack",
|
|
2523
|
+
useCase: "pilot.codegen",
|
|
2524
|
+
expectedOutputType: "json",
|
|
2525
|
+
userPrompt: "",
|
|
2526
|
+
contextData
|
|
2527
|
+
}),
|
|
2528
|
+
...signal ? { signal } : {}
|
|
2529
|
+
});
|
|
2530
|
+
if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
|
|
2531
|
+
return res.json();
|
|
1965
2532
|
}
|
|
1966
|
-
function
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
2533
|
+
function protectedTestFiles(listing, testDiscovery) {
|
|
2534
|
+
const inListing = new Set(listing);
|
|
2535
|
+
const found = new Set(listing.filter((p) => isTestTarget(p)));
|
|
2536
|
+
if (testDiscovery.report === "PRESENT") {
|
|
2537
|
+
for (const p of testDiscovery.discoveredTestFiles) if (inListing.has(p)) found.add(p);
|
|
1970
2538
|
}
|
|
1971
|
-
|
|
1972
|
-
return text;
|
|
2539
|
+
return [...found].sort();
|
|
1973
2540
|
}
|
|
1974
|
-
function
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2541
|
+
function buildCodegenLoopArgs(p) {
|
|
2542
|
+
const skipped = new Set(p.skippedCases.map((s) => s.automationId));
|
|
2543
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
2544
|
+
for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);
|
|
2545
|
+
const requiredTests = p.requiredTests.filter((tc) => claimed.has(tc.automationId));
|
|
2546
|
+
const protectedTestPaths = protectedTestFiles(p.workspaceListing, p.testDiscovery);
|
|
2547
|
+
const baseContext = {
|
|
2548
|
+
targets: p.targets.map((t) => ({
|
|
2549
|
+
path: t.path,
|
|
2550
|
+
kind: t.kind,
|
|
2551
|
+
role: (t.automationIds?.length ?? 0) > 0 || isTestTarget(t.path) ? "test" : "code",
|
|
2552
|
+
planSteps: t.planStepsImplemented,
|
|
2553
|
+
automationIds: t.automationIds ?? []
|
|
2554
|
+
})),
|
|
2555
|
+
requiredTests,
|
|
2556
|
+
workspaceListing: p.workspaceListing
|
|
2557
|
+
};
|
|
2558
|
+
if (p.deniedPaths.length > 0) baseContext.deniedPaths = p.deniedPaths;
|
|
2559
|
+
if (protectedTestPaths.length > 0) baseContext.protectedTestPaths = protectedTestPaths.slice(0, MAX_PROTECTED_PATHS_ON_WIRE);
|
|
2560
|
+
if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;
|
|
2561
|
+
return {
|
|
2562
|
+
baseContext,
|
|
2563
|
+
targets: p.targets,
|
|
2564
|
+
requiredAutomationIds: requiredTests.map((tc) => tc.automationId),
|
|
2565
|
+
listing: p.workspaceListing,
|
|
2566
|
+
deniedPaths: p.deniedPaths,
|
|
2567
|
+
protectedTestPaths
|
|
2568
|
+
};
|
|
1978
2569
|
}
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
return
|
|
2570
|
+
var NO_SUMMARY = {
|
|
2571
|
+
turns: 0,
|
|
2572
|
+
toolCalls: 0,
|
|
2573
|
+
refused: 0,
|
|
2574
|
+
stopReason: "fallback",
|
|
2575
|
+
reads: [],
|
|
2576
|
+
edits: [],
|
|
2577
|
+
created: [],
|
|
2578
|
+
statusCounts: {},
|
|
2579
|
+
reasoning: []
|
|
2580
|
+
};
|
|
2581
|
+
function perFile(p) {
|
|
2582
|
+
return runCodegen(
|
|
2583
|
+
p.gateway,
|
|
2584
|
+
p.targets,
|
|
2585
|
+
p.workspaceListing,
|
|
2586
|
+
p.requiredTests,
|
|
2587
|
+
p.deniedPaths,
|
|
2588
|
+
p.judgedByPool,
|
|
2589
|
+
p.warnings,
|
|
2590
|
+
p.contextLog,
|
|
2591
|
+
p.outOfScope
|
|
2592
|
+
);
|
|
1992
2593
|
}
|
|
1993
|
-
function
|
|
1994
|
-
if (
|
|
2594
|
+
async function runCodegenStep(p) {
|
|
2595
|
+
if (p.mode !== "loop") return perFile(p);
|
|
1995
2596
|
try {
|
|
1996
|
-
const
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
if (!
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
(0, import_node_fs7.mkdirSync)((0, import_node_path6.dirname)(destination), { recursive: true });
|
|
2008
|
-
(0, import_node_fs7.writeFileSync)(destination, result.newContent);
|
|
2009
|
-
files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
|
|
2010
|
-
}
|
|
2011
|
-
let testReport = "none";
|
|
2012
|
-
if (input.testReport) {
|
|
2013
|
-
if (input.testReport.byteLength > MAX_REPORT_BYTES) {
|
|
2014
|
-
testReport = "too-large";
|
|
2015
|
-
} else {
|
|
2016
|
-
(0, import_node_fs7.writeFileSync)((0, import_node_path6.join)(base, REPORT_COPY), input.testReport);
|
|
2017
|
-
testReport = "included";
|
|
2597
|
+
const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p), {
|
|
2598
|
+
post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
|
|
2599
|
+
...p.deps
|
|
2600
|
+
});
|
|
2601
|
+
p.out.loop = buildCodegenLoopRecord(summary);
|
|
2602
|
+
const planned = new Set(p.targets.map((t) => t.path));
|
|
2603
|
+
for (const r of results) {
|
|
2604
|
+
if (!planned.has(r.targetPath)) {
|
|
2605
|
+
const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;
|
|
2606
|
+
p.warnings.push(w);
|
|
2607
|
+
console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
|
|
2018
2608
|
}
|
|
2019
2609
|
}
|
|
2020
|
-
|
|
2021
|
-
runId: input.runId,
|
|
2022
|
-
issueKey: input.issueKey,
|
|
2023
|
-
runnerVersion: RUNNER_VERSION,
|
|
2024
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2025
|
-
targets: input.targets.map((t) => ({
|
|
2026
|
-
path: t.path,
|
|
2027
|
-
kind: t.kind,
|
|
2028
|
-
...t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}
|
|
2029
|
-
})),
|
|
2030
|
-
files,
|
|
2031
|
-
skipped,
|
|
2032
|
-
testReport,
|
|
2033
|
-
failureReasons: input.failureReasons
|
|
2034
|
-
};
|
|
2035
|
-
const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
|
|
2036
|
-
(0, import_node_fs7.writeFileSync)((0, import_node_path6.join)(base, "manifest.json"), text);
|
|
2037
|
-
return { written: (0, import_node_fs7.existsSync)((0, import_node_path6.join)(base, "manifest.json")) };
|
|
2610
|
+
return results;
|
|
2038
2611
|
} catch (err) {
|
|
2039
|
-
|
|
2040
|
-
|
|
2612
|
+
if (err instanceof SafetyRefusalError) throw err;
|
|
2613
|
+
const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
|
|
2614
|
+
p.out.loop = buildCodegenLoopRecord({
|
|
2615
|
+
...failure.summary ?? NO_SUMMARY,
|
|
2616
|
+
stopReason: "fallback",
|
|
2617
|
+
fellBack: true,
|
|
2618
|
+
fallbackReason: failure.reason
|
|
2619
|
+
});
|
|
2620
|
+
const said = failure.detail ? `: ${failure.detail}` : "";
|
|
2621
|
+
const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;
|
|
2622
|
+
p.warnings.push(w);
|
|
2623
|
+
console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
|
|
2624
|
+
return perFile(p);
|
|
2041
2625
|
}
|
|
2042
2626
|
}
|
|
2043
2627
|
|
|
2044
|
-
// src/
|
|
2045
|
-
var
|
|
2046
|
-
var
|
|
2047
|
-
var
|
|
2048
|
-
var
|
|
2049
|
-
var
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2628
|
+
// src/dependencyCheck.ts
|
|
2629
|
+
var import_node_fs4 = require("node:fs");
|
|
2630
|
+
var import_node_path6 = require("node:path");
|
|
2631
|
+
var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
|
|
2632
|
+
var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
|
|
2633
|
+
var NODE_BUILTINS = /* @__PURE__ */ new Set([
|
|
2634
|
+
"assert",
|
|
2635
|
+
"buffer",
|
|
2636
|
+
"child_process",
|
|
2637
|
+
"cluster",
|
|
2638
|
+
"crypto",
|
|
2639
|
+
"dgram",
|
|
2640
|
+
"dns",
|
|
2641
|
+
"domain",
|
|
2642
|
+
"events",
|
|
2643
|
+
"fs",
|
|
2644
|
+
"http",
|
|
2645
|
+
"http2",
|
|
2646
|
+
"https",
|
|
2647
|
+
"net",
|
|
2648
|
+
"os",
|
|
2649
|
+
"path",
|
|
2650
|
+
"perf_hooks",
|
|
2651
|
+
"process",
|
|
2652
|
+
"punycode",
|
|
2653
|
+
"querystring",
|
|
2654
|
+
"readline",
|
|
2655
|
+
"repl",
|
|
2656
|
+
"stream",
|
|
2657
|
+
"string_decoder",
|
|
2658
|
+
"sys",
|
|
2659
|
+
"timers",
|
|
2660
|
+
"tls",
|
|
2661
|
+
"tty",
|
|
2662
|
+
"url",
|
|
2663
|
+
"util",
|
|
2664
|
+
"v8",
|
|
2665
|
+
"vm",
|
|
2666
|
+
"worker_threads",
|
|
2667
|
+
"zlib",
|
|
2668
|
+
"inspector",
|
|
2669
|
+
"async_hooks"
|
|
2670
|
+
]);
|
|
2671
|
+
var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
|
|
2672
|
+
function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
|
|
2673
|
+
if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
|
|
2674
|
+
if (specifier.startsWith("node:")) return null;
|
|
2675
|
+
if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
|
|
2676
|
+
const segments = specifier.split("/");
|
|
2677
|
+
const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
|
|
2678
|
+
if (NODE_BUILTINS.has(name)) return null;
|
|
2679
|
+
return name;
|
|
2680
|
+
}
|
|
2681
|
+
function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
|
|
2682
|
+
const found = /* @__PURE__ */ new Set();
|
|
2683
|
+
let match;
|
|
2684
|
+
IMPORT_RE.lastIndex = 0;
|
|
2685
|
+
while (match = IMPORT_RE.exec(source)) {
|
|
2686
|
+
const name = packageNameFromSpecifier(match[2], aliasPrefixes);
|
|
2687
|
+
if (name) found.add(name);
|
|
2062
2688
|
}
|
|
2063
|
-
return found;
|
|
2689
|
+
return [...found];
|
|
2064
2690
|
}
|
|
2065
|
-
function
|
|
2066
|
-
return
|
|
2691
|
+
function checkImportDependencies(results, declaredDependencies, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
|
|
2692
|
+
if (!declaredDependencies) return { blocked: false, violations: [] };
|
|
2693
|
+
const violations = [];
|
|
2694
|
+
for (const { targetPath, newContent } of results) {
|
|
2695
|
+
if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
|
|
2696
|
+
const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
|
|
2697
|
+
if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
|
|
2698
|
+
}
|
|
2699
|
+
return { blocked: violations.length > 0, violations };
|
|
2067
2700
|
}
|
|
2068
|
-
function
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2701
|
+
function dependencyNames(pkg) {
|
|
2702
|
+
return /* @__PURE__ */ new Set([
|
|
2703
|
+
...Object.keys(pkg.dependencies ?? {}),
|
|
2704
|
+
...Object.keys(pkg.devDependencies ?? {}),
|
|
2705
|
+
...Object.keys(pkg.peerDependencies ?? {})
|
|
2706
|
+
]);
|
|
2074
2707
|
}
|
|
2075
|
-
function
|
|
2076
|
-
const
|
|
2077
|
-
|
|
2708
|
+
function readDeclaredDependencies(results, workspaceRoot) {
|
|
2709
|
+
const packageJsonPath = (0, import_node_path6.join)((0, import_node_path6.resolve)(workspaceRoot ?? "."), "package.json");
|
|
2710
|
+
const generated = results.find((r) => (0, import_node_path6.resolve)(r.targetPath) === packageJsonPath);
|
|
2711
|
+
let raw;
|
|
2712
|
+
if (generated) {
|
|
2713
|
+
raw = generated.newContent;
|
|
2714
|
+
} else {
|
|
2715
|
+
try {
|
|
2716
|
+
raw = (0, import_node_fs4.readFileSync)(packageJsonPath, "utf8");
|
|
2717
|
+
} catch {
|
|
2718
|
+
raw = null;
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
if (raw === null) return null;
|
|
2722
|
+
try {
|
|
2723
|
+
return dependencyNames(JSON.parse(raw));
|
|
2724
|
+
} catch {
|
|
2725
|
+
return null;
|
|
2726
|
+
}
|
|
2078
2727
|
}
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
];
|
|
2086
|
-
|
|
2087
|
-
|
|
2728
|
+
function stripJsonComments(text) {
|
|
2729
|
+
let out = "";
|
|
2730
|
+
let inString = false;
|
|
2731
|
+
let inLineComment = false;
|
|
2732
|
+
let inBlockComment = false;
|
|
2733
|
+
for (let i = 0; i < text.length; i++) {
|
|
2734
|
+
const c = text[i];
|
|
2735
|
+
const next = text[i + 1];
|
|
2736
|
+
if (inLineComment) {
|
|
2737
|
+
if (c === "\n") {
|
|
2738
|
+
inLineComment = false;
|
|
2739
|
+
out += c;
|
|
2740
|
+
}
|
|
2741
|
+
continue;
|
|
2742
|
+
}
|
|
2743
|
+
if (inBlockComment) {
|
|
2744
|
+
if (c === "*" && next === "/") {
|
|
2745
|
+
inBlockComment = false;
|
|
2746
|
+
i++;
|
|
2747
|
+
}
|
|
2748
|
+
continue;
|
|
2749
|
+
}
|
|
2750
|
+
if (inString) {
|
|
2751
|
+
out += c;
|
|
2752
|
+
if (c === "\\") {
|
|
2753
|
+
out += next;
|
|
2754
|
+
i++;
|
|
2755
|
+
continue;
|
|
2756
|
+
}
|
|
2757
|
+
if (c === '"') inString = false;
|
|
2758
|
+
continue;
|
|
2759
|
+
}
|
|
2760
|
+
if (c === '"') {
|
|
2761
|
+
inString = true;
|
|
2762
|
+
out += c;
|
|
2763
|
+
continue;
|
|
2764
|
+
}
|
|
2765
|
+
if (c === "/" && next === "/") {
|
|
2766
|
+
inLineComment = true;
|
|
2767
|
+
i++;
|
|
2768
|
+
continue;
|
|
2769
|
+
}
|
|
2770
|
+
if (c === "/" && next === "*") {
|
|
2771
|
+
inBlockComment = true;
|
|
2772
|
+
i++;
|
|
2773
|
+
continue;
|
|
2774
|
+
}
|
|
2775
|
+
out += c;
|
|
2776
|
+
}
|
|
2777
|
+
return out.replace(/,(\s*[}\]])/g, "$1");
|
|
2088
2778
|
}
|
|
2089
|
-
function
|
|
2090
|
-
const
|
|
2091
|
-
const
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
if (isNewFile) {
|
|
2098
|
-
scanned = newContent;
|
|
2779
|
+
function resolveAliasPrefixes(results, workspaceRoot) {
|
|
2780
|
+
const root = (0, import_node_path6.resolve)(workspaceRoot ?? ".");
|
|
2781
|
+
for (const filename of ["tsconfig.json", "jsconfig.json"]) {
|
|
2782
|
+
const configPath = (0, import_node_path6.join)(root, filename);
|
|
2783
|
+
const generated = results.find((r) => (0, import_node_path6.resolve)(r.targetPath) === configPath);
|
|
2784
|
+
let raw;
|
|
2785
|
+
if (generated) {
|
|
2786
|
+
raw = generated.newContent;
|
|
2099
2787
|
} else {
|
|
2100
|
-
let currentContent;
|
|
2101
2788
|
try {
|
|
2102
|
-
|
|
2789
|
+
raw = (0, import_node_fs4.readFileSync)(configPath, "utf8");
|
|
2103
2790
|
} catch {
|
|
2104
|
-
|
|
2791
|
+
raw = null;
|
|
2105
2792
|
}
|
|
2106
|
-
scanned = addedLines(currentContent, newContent);
|
|
2107
2793
|
}
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
|
|
2111
|
-
|
|
2794
|
+
if (raw === null) continue;
|
|
2795
|
+
try {
|
|
2796
|
+
const parsed = JSON.parse(stripJsonComments(raw));
|
|
2797
|
+
const paths = parsed.compilerOptions?.paths;
|
|
2798
|
+
const fromConfig = paths && typeof paths === "object" ? Object.keys(paths).map((k) => k.endsWith("*") ? k.slice(0, -1) : k) : [];
|
|
2799
|
+
return [.../* @__PURE__ */ new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];
|
|
2800
|
+
} catch {
|
|
2801
|
+
continue;
|
|
2112
2802
|
}
|
|
2113
2803
|
}
|
|
2114
|
-
return
|
|
2804
|
+
return DEFAULT_ALIAS_PREFIXES;
|
|
2115
2805
|
}
|
|
2116
|
-
function
|
|
2117
|
-
return check.violations.map((v) => `${v.file}
|
|
2806
|
+
function describeDependencyViolations(check) {
|
|
2807
|
+
return check.violations.map((v) => `${v.file} imports ${v.packages.join(", ")}, not a dependency of this repository`).join("; ");
|
|
2118
2808
|
}
|
|
2119
2809
|
|
|
2120
|
-
// src/
|
|
2121
|
-
|
|
2810
|
+
// src/guardrail.ts
|
|
2811
|
+
function checkGuardrail(deniedPaths) {
|
|
2812
|
+
addAll();
|
|
2813
|
+
const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
|
|
2814
|
+
if (violations.length > 0) {
|
|
2815
|
+
throw new Error(`QuikPilot touched denied paths:
|
|
2816
|
+
${violations.join("\n")}`);
|
|
2817
|
+
}
|
|
2818
|
+
}
|
|
2122
2819
|
|
|
2123
|
-
// src/
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2820
|
+
// src/installationToken.ts
|
|
2821
|
+
async function exchangeForInstallationToken(installationTokenUrl, runToken) {
|
|
2822
|
+
const res = await fetch(installationTokenUrl, {
|
|
2823
|
+
method: "POST",
|
|
2824
|
+
headers: { Authorization: `Bearer ${runToken}` }
|
|
2825
|
+
});
|
|
2826
|
+
if (!res.ok) {
|
|
2827
|
+
throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
|
|
2128
2828
|
}
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
constructor(status, statusText) {
|
|
2133
|
-
super(`Targeting call failed: ${status} ${statusText}`);
|
|
2134
|
-
this.name = "TargetingHttpError";
|
|
2135
|
-
this.status = status;
|
|
2829
|
+
const body = await res.json();
|
|
2830
|
+
if (body.success !== true) {
|
|
2831
|
+
throw new Error("Exchange installation token failed: response did not carry success:true");
|
|
2136
2832
|
}
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
// src/targetingMode.ts
|
|
2140
|
-
var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
|
|
2141
|
-
function parse(value) {
|
|
2142
|
-
if (typeof value !== "string") return null;
|
|
2143
|
-
const v = value.trim().toLowerCase();
|
|
2144
|
-
if (v === "loop") return "loop";
|
|
2145
|
-
if (v === "single") return "single";
|
|
2146
|
-
return null;
|
|
2147
|
-
}
|
|
2148
|
-
function resolveTargetingMode(env2 = process.env, packetSetting) {
|
|
2149
|
-
const fromSetting = parse(packetSetting);
|
|
2150
|
-
if (fromSetting) return fromSetting;
|
|
2151
|
-
return parse(env2[TARGETING_MODE_ENV]) ?? "single";
|
|
2833
|
+
return body.data.token;
|
|
2152
2834
|
}
|
|
2153
2835
|
|
|
2154
|
-
// src/
|
|
2155
|
-
var
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2836
|
+
// src/oidc.ts
|
|
2837
|
+
var QUIKPILOT_OIDC_AUDIENCE = "quiktrack-quikpilot";
|
|
2838
|
+
async function fetchGithubOidcToken(env2 = process.env) {
|
|
2839
|
+
const requestUrl = required(
|
|
2840
|
+
"ACTIONS_ID_TOKEN_REQUEST_URL",
|
|
2841
|
+
env2.ACTIONS_ID_TOKEN_REQUEST_URL
|
|
2842
|
+
);
|
|
2843
|
+
const requestToken = required(
|
|
2844
|
+
"ACTIONS_ID_TOKEN_REQUEST_TOKEN",
|
|
2845
|
+
env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
|
|
2846
|
+
);
|
|
2847
|
+
const separator = requestUrl.includes("?") ? "&" : "?";
|
|
2848
|
+
const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
|
|
2849
|
+
const res = await fetch(url, {
|
|
2850
|
+
headers: { Authorization: `Bearer ${requestToken}` }
|
|
2851
|
+
});
|
|
2852
|
+
if (!res.ok) {
|
|
2853
|
+
throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
|
|
2161
2854
|
}
|
|
2162
|
-
|
|
2855
|
+
const body = await res.json();
|
|
2856
|
+
if (!body.value) {
|
|
2857
|
+
throw new Error("GitHub OIDC token response carried no value");
|
|
2858
|
+
}
|
|
2859
|
+
return body.value;
|
|
2163
2860
|
}
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2861
|
+
|
|
2862
|
+
// src/packet.ts
|
|
2863
|
+
async function fetchPacket(packetUrl, runToken, githubRunId) {
|
|
2864
|
+
const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
|
|
2865
|
+
const res = await fetch(url, {
|
|
2866
|
+
headers: { Authorization: `Bearer ${runToken}` }
|
|
2867
|
+
});
|
|
2868
|
+
if (!res.ok) {
|
|
2869
|
+
throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
|
|
2169
2870
|
}
|
|
2170
|
-
|
|
2171
|
-
if (
|
|
2172
|
-
|
|
2173
|
-
if (raw.split("/").includes("..")) return { ok: false, reason: "outside_workspace" };
|
|
2174
|
-
const normalised = import_node_path7.posix.normalize(raw).replace(/\/+$/, "");
|
|
2175
|
-
if (normalised === "" || normalised === ".") {
|
|
2176
|
-
return allowRoot ? { ok: true, path: "" } : { ok: false, reason: "path_invalid" };
|
|
2871
|
+
const body = await res.json();
|
|
2872
|
+
if (body.success !== true) {
|
|
2873
|
+
throw new Error("Fetch work packet failed: response did not carry success:true");
|
|
2177
2874
|
}
|
|
2178
|
-
return
|
|
2179
|
-
}
|
|
2180
|
-
function matchesPrefix(path, prefix) {
|
|
2181
|
-
if (prefix === "") return true;
|
|
2182
|
-
return path === prefix || path.startsWith(`${prefix}/`);
|
|
2875
|
+
return body.data;
|
|
2183
2876
|
}
|
|
2184
|
-
|
|
2185
|
-
|
|
2877
|
+
|
|
2878
|
+
// src/phase0.ts
|
|
2879
|
+
var import_node_fs5 = require("node:fs");
|
|
2880
|
+
function writePhase0Marker(runId) {
|
|
2881
|
+
(0, import_node_fs5.mkdirSync)(".quikpilot", { recursive: true });
|
|
2882
|
+
(0, import_node_fs5.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
|
|
2883
|
+
`);
|
|
2186
2884
|
}
|
|
2187
2885
|
|
|
2188
|
-
// src/
|
|
2189
|
-
var
|
|
2190
|
-
var
|
|
2191
|
-
var
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
2201
|
-
|
|
2202
|
-
|
|
2203
|
-
|
|
2204
|
-
|
|
2205
|
-
|
|
2206
|
-
|
|
2207
|
-
grepMaxBytes: 2e7,
|
|
2208
|
-
fileBytesMax: 1e6,
|
|
2209
|
-
listMaxEntries: 500,
|
|
2210
|
-
maxReasoningChars: 500,
|
|
2211
|
-
maxPatternChars: 200
|
|
2212
|
-
};
|
|
2213
|
-
function createNodeToolFs(rootDir = process.cwd()) {
|
|
2214
|
-
const rootReal = (0, import_node_fs9.realpathSync)(rootDir);
|
|
2215
|
-
return {
|
|
2216
|
-
rootReal,
|
|
2217
|
-
lstat(rel) {
|
|
2218
|
-
const s = (0, import_node_fs9.lstatSync)((0, import_node_path8.join)(rootDir, rel));
|
|
2219
|
-
return { isSymlink: s.isSymbolicLink(), isFile: s.isFile(), size: s.size };
|
|
2220
|
-
},
|
|
2221
|
-
realpathInside(rel) {
|
|
2222
|
-
const real = (0, import_node_fs9.realpathSync)((0, import_node_path8.join)(rootDir, rel));
|
|
2223
|
-
const r = (0, import_node_path8.relative)(rootReal, real);
|
|
2224
|
-
return r !== "" && !r.startsWith("..") && !(0, import_node_path8.isAbsolute)(r);
|
|
2225
|
-
},
|
|
2226
|
-
readBytes(rel) {
|
|
2227
|
-
return (0, import_node_fs9.readFileSync)((0, import_node_path8.join)(rootDir, rel));
|
|
2886
|
+
// src/quiktest.ts
|
|
2887
|
+
var import_node_fs6 = require("node:fs");
|
|
2888
|
+
var import_node_path7 = require("node:path");
|
|
2889
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
2890
|
+
function walkForJUnitByName(dir) {
|
|
2891
|
+
let entries;
|
|
2892
|
+
try {
|
|
2893
|
+
entries = (0, import_node_fs6.readdirSync)(dir);
|
|
2894
|
+
} catch {
|
|
2895
|
+
return null;
|
|
2896
|
+
}
|
|
2897
|
+
for (const entry of entries) {
|
|
2898
|
+
if (SKIP_DIRS.has(entry)) continue;
|
|
2899
|
+
const full = (0, import_node_path7.join)(dir, entry);
|
|
2900
|
+
let stat;
|
|
2901
|
+
try {
|
|
2902
|
+
stat = (0, import_node_fs6.statSync)(full);
|
|
2903
|
+
} catch {
|
|
2904
|
+
continue;
|
|
2228
2905
|
}
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2906
|
+
if (stat.isDirectory()) {
|
|
2907
|
+
const found = walkForJUnitByName(full);
|
|
2908
|
+
if (found) return found;
|
|
2909
|
+
} else if (/^junit.*\.xml$/.test(entry)) {
|
|
2910
|
+
return full;
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
return null;
|
|
2233
2914
|
}
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2915
|
+
function firstXmlIn(dir, namePattern) {
|
|
2916
|
+
let entries;
|
|
2917
|
+
try {
|
|
2918
|
+
entries = (0, import_node_fs6.readdirSync)(dir);
|
|
2919
|
+
} catch {
|
|
2920
|
+
return null;
|
|
2921
|
+
}
|
|
2922
|
+
const match = entries.find((e) => namePattern.test(e));
|
|
2923
|
+
return match ? (0, import_node_path7.join)(dir, match) : null;
|
|
2238
2924
|
}
|
|
2239
|
-
function
|
|
2240
|
-
|
|
2925
|
+
function readTestReportBytes(cwd = process.cwd()) {
|
|
2926
|
+
try {
|
|
2927
|
+
const report = findJUnitReport(cwd);
|
|
2928
|
+
return report ? (0, import_node_fs6.readFileSync)(report) : null;
|
|
2929
|
+
} catch {
|
|
2930
|
+
return null;
|
|
2931
|
+
}
|
|
2241
2932
|
}
|
|
2242
|
-
function
|
|
2243
|
-
|
|
2244
|
-
return typeof v === "number" && Number.isInteger(v) ? v : "bad";
|
|
2933
|
+
function findJUnitReport(cwd = process.cwd()) {
|
|
2934
|
+
return walkForJUnitByName(cwd) ?? firstXmlIn((0, import_node_path7.join)(cwd, "test-results"), /\.xml$/) ?? firstXmlIn((0, import_node_path7.join)(cwd, "reports"), /^junit.*\.xml$/) ?? firstXmlIn((0, import_node_path7.join)(cwd, "target", "surefire-reports"), /\.xml$/);
|
|
2245
2935
|
}
|
|
2246
|
-
function
|
|
2247
|
-
|
|
2248
|
-
for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;
|
|
2249
|
-
return false;
|
|
2936
|
+
function buildCiUrl(serverUrl, repository, githubRunId) {
|
|
2937
|
+
return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;
|
|
2250
2938
|
}
|
|
2251
|
-
function
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2939
|
+
function describeUnmatchedAutomationIds(unmatched) {
|
|
2940
|
+
if (unmatched.length === 0) return null;
|
|
2941
|
+
const named = unmatched.map((u) => `${u.automationId} (\xD7${u.count})`).join(", ");
|
|
2942
|
+
return `${unmatched.length} generated test result(s) did not match any test case: ${named} \u2014 check the automationId format.`;
|
|
2943
|
+
}
|
|
2944
|
+
async function reportToQuikTest(params) {
|
|
2945
|
+
const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;
|
|
2946
|
+
if (!resultsUrl) {
|
|
2947
|
+
console.log("packet.quikTest is null \u2014 this run has no QuikTest run to report into.");
|
|
2948
|
+
return null;
|
|
2255
2949
|
}
|
|
2256
|
-
|
|
2257
|
-
|
|
2950
|
+
const report = findJUnitReport(cwd);
|
|
2951
|
+
if (!report) {
|
|
2952
|
+
console.warn("::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.");
|
|
2953
|
+
return null;
|
|
2258
2954
|
}
|
|
2259
|
-
|
|
2260
|
-
|
|
2955
|
+
try {
|
|
2956
|
+
console.log(`reporting ${report}`);
|
|
2957
|
+
const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
|
|
2958
|
+
const { readFileSync: readFileSync8 } = await import("node:fs");
|
|
2959
|
+
const body = readFileSync8(report);
|
|
2960
|
+
let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
|
|
2961
|
+
if (generatedFiles) {
|
|
2962
|
+
url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
|
|
2963
|
+
}
|
|
2964
|
+
const res = await fetch(url, {
|
|
2965
|
+
method: "POST",
|
|
2966
|
+
headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "text/xml" },
|
|
2967
|
+
body
|
|
2968
|
+
});
|
|
2969
|
+
if (!res.ok) {
|
|
2970
|
+
throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);
|
|
2971
|
+
}
|
|
2972
|
+
(0, import_node_fs6.rmSync)(report, { force: true });
|
|
2973
|
+
let unmatched = [];
|
|
2974
|
+
try {
|
|
2975
|
+
const json = await res.json();
|
|
2976
|
+
unmatched = json.data?.unmatched ?? [];
|
|
2977
|
+
} catch {
|
|
2978
|
+
}
|
|
2979
|
+
return { unmatched };
|
|
2980
|
+
} catch (err) {
|
|
2981
|
+
console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);
|
|
2982
|
+
return null;
|
|
2261
2983
|
}
|
|
2262
|
-
return { ok: true, path: n.path };
|
|
2263
2984
|
}
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2985
|
+
|
|
2986
|
+
// src/baselineCheck.ts
|
|
2987
|
+
var import_node_child_process3 = require("node:child_process");
|
|
2988
|
+
var import_node_fs8 = require("node:fs");
|
|
2989
|
+
var import_node_path8 = require("node:path");
|
|
2990
|
+
|
|
2991
|
+
// src/regressionCheck.ts
|
|
2992
|
+
var import_node_fs7 = require("node:fs");
|
|
2993
|
+
var TESTCASE_RE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
|
|
2994
|
+
var NAME_ATTR_RE = /\bname="([^"]*)"/;
|
|
2995
|
+
var CLASSNAME_ATTR_RE = /\bclassname="([^"]*)"/;
|
|
2996
|
+
var FAILURE_CHILD_RE = /<failure\b|<error\b/;
|
|
2997
|
+
var SKIPPED_CHILD_RE = /<skipped\b/;
|
|
2998
|
+
var TESTSUITE_OPEN_RE = /<testsuite\b([^>]*?)>/g;
|
|
2999
|
+
var FILE_ATTR_RE = /\bfile="([^"]*)"/;
|
|
3000
|
+
var QP_TOKEN_BRACKET_RE = /\[(QP-[A-Z][A-Z0-9]*-\d+-\d+)\]/;
|
|
3001
|
+
function normalizeSlashes(path) {
|
|
3002
|
+
return path.replace(/\\/g, "/");
|
|
3003
|
+
}
|
|
3004
|
+
var FAILURE_TAG_RE = /<(?:failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:failure|error)>)/;
|
|
3005
|
+
var FAILURE_MESSAGE_ATTR_RE = /\bmessage="([^"]*)"/;
|
|
3006
|
+
var MAX_FAILURE_TEXT = 500;
|
|
3007
|
+
function unescapeXmlEntities(s) {
|
|
3008
|
+
return s.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&");
|
|
3009
|
+
}
|
|
3010
|
+
var FAILURE_FILE_LINE_RE = /^[ \t]*File:[ \t]*(\S[^\r\n]*?:\d+(?::\d+)?)[ \t]*$/m;
|
|
3011
|
+
var MAX_FAILURE_LOCATION = 300;
|
|
3012
|
+
function parseFailureLocation(body) {
|
|
3013
|
+
const found = FAILURE_FILE_LINE_RE.exec(unescapeXmlEntities(body));
|
|
3014
|
+
if (!found) return null;
|
|
3015
|
+
const path = normalizeSlashes(found[1]);
|
|
3016
|
+
const root = `${normalizeSlashes(process.cwd()).replace(/\/+$/, "")}/`;
|
|
3017
|
+
const shown = path.startsWith(root) ? path.slice(root.length) : path;
|
|
3018
|
+
return shown.length > MAX_FAILURE_LOCATION ? `${shown.slice(0, MAX_FAILURE_LOCATION)}\u2026` : shown;
|
|
3019
|
+
}
|
|
3020
|
+
function extractFailureText(testcaseBody) {
|
|
3021
|
+
const tag = FAILURE_TAG_RE.exec(testcaseBody);
|
|
3022
|
+
if (!tag) return null;
|
|
3023
|
+
const [, attrs = "", inner = ""] = tag;
|
|
3024
|
+
const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];
|
|
3025
|
+
const raw = (messageAttr ?? inner).trim();
|
|
3026
|
+
if (!raw) return null;
|
|
3027
|
+
const text = unescapeXmlEntities(raw);
|
|
3028
|
+
const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;
|
|
3029
|
+
const location = messageAttr === void 0 ? null : parseFailureLocation(inner);
|
|
3030
|
+
return location ? `${shortened} [at ${location}]` : shortened;
|
|
3031
|
+
}
|
|
3032
|
+
var RESULT_RANK = { pass: 0, skipped: 1, fail: 2 };
|
|
3033
|
+
function parseJUnitOutcomes(xml) {
|
|
3034
|
+
const outcomes = /* @__PURE__ */ new Map();
|
|
3035
|
+
const automationIdResults = /* @__PURE__ */ new Map();
|
|
3036
|
+
const failureText = /* @__PURE__ */ new Map();
|
|
3037
|
+
const discoveredFiles = /* @__PURE__ */ new Set();
|
|
3038
|
+
const discoveredAutomationIds = /* @__PURE__ */ new Set();
|
|
3039
|
+
TESTSUITE_OPEN_RE.lastIndex = 0;
|
|
3040
|
+
let suiteMatch;
|
|
3041
|
+
while (suiteMatch = TESTSUITE_OPEN_RE.exec(xml)) {
|
|
3042
|
+
const file = FILE_ATTR_RE.exec(suiteMatch[1])?.[1];
|
|
3043
|
+
if (file) discoveredFiles.add(normalizeSlashes(file));
|
|
2274
3044
|
}
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
exec
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
|
|
2283
|
-
|
|
2284
|
-
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2288
|
-
|
|
2289
|
-
|
|
2290
|
-
}
|
|
2291
|
-
if (!env2.fs.realpathInside(path)) {
|
|
2292
|
-
return { result: { status: "refused", reason: "outside_workspace", message: "That path is not allowed." }, read: { path, chars: 0, refused: true } };
|
|
2293
|
-
}
|
|
2294
|
-
} catch {
|
|
2295
|
-
return { result: { status: "unreadable", reason: "io", message: "That file could not be read." } };
|
|
2296
|
-
}
|
|
2297
|
-
let bytes;
|
|
2298
|
-
try {
|
|
2299
|
-
bytes = env2.fs.readBytes(path);
|
|
2300
|
-
} catch {
|
|
2301
|
-
return { result: { status: "unreadable", reason: "io", message: "That file could not be read." } };
|
|
2302
|
-
}
|
|
2303
|
-
if (hasNul(bytes)) return { result: { status: "unreadable", reason: "binary", message: "That file is binary." } };
|
|
2304
|
-
let text;
|
|
2305
|
-
try {
|
|
2306
|
-
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
2307
|
-
} catch {
|
|
2308
|
-
return { result: { status: "unreadable", reason: "not_utf8", message: "That file is not valid UTF-8 text." } };
|
|
2309
|
-
}
|
|
2310
|
-
if (text.charCodeAt(0) === 65279) text = text.slice(1);
|
|
2311
|
-
text = text.replace(/\r\n/g, "\n");
|
|
2312
|
-
const lines = text === "" ? [] : text.split("\n");
|
|
2313
|
-
if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
|
|
2314
|
-
const totalLines = lines.length;
|
|
2315
|
-
const startLine = Math.max(1, start ?? 1);
|
|
2316
|
-
const endWanted = Math.min(totalLines, end ?? totalLines);
|
|
2317
|
-
if (startLine > totalLines) {
|
|
2318
|
-
return {
|
|
2319
|
-
result: { status: "ok", output: { path, startLine, endLine: totalLines, totalLines, truncated: false, content: "" } },
|
|
2320
|
-
read: { path, startLine, endLine: totalLines, chars: 0 }
|
|
2321
|
-
};
|
|
2322
|
-
}
|
|
2323
|
-
const budget = Math.max(0, Math.min(env2.limits.readCharsPerRead, env2.limits.readCharsTotal - ledger.readChars));
|
|
2324
|
-
const out = [];
|
|
2325
|
-
let used = 0;
|
|
2326
|
-
let endLine = startLine - 1;
|
|
2327
|
-
let truncated = false;
|
|
2328
|
-
for (let n = startLine; n <= endWanted; n++) {
|
|
2329
|
-
const line = `${n} ${lines[n - 1]}`;
|
|
2330
|
-
const cost = line.length + (out.length > 0 ? 1 : 0);
|
|
2331
|
-
if (used + cost <= budget) {
|
|
2332
|
-
out.push(line);
|
|
2333
|
-
used += cost;
|
|
2334
|
-
endLine = n;
|
|
2335
|
-
continue;
|
|
2336
|
-
}
|
|
2337
|
-
truncated = true;
|
|
2338
|
-
if (out.length === 0) {
|
|
2339
|
-
const keep = Math.max(0, budget - CUT.length);
|
|
2340
|
-
out.push(line.slice(0, keep) + CUT);
|
|
2341
|
-
used = out[0].length;
|
|
2342
|
-
endLine = n;
|
|
2343
|
-
}
|
|
2344
|
-
break;
|
|
2345
|
-
}
|
|
2346
|
-
let content = out.join("\n");
|
|
2347
|
-
ledger.readChars += used;
|
|
2348
|
-
const output = { path, startLine, endLine, totalLines, truncated };
|
|
2349
|
-
if (truncated) {
|
|
2350
|
-
if (endLine < totalLines) {
|
|
2351
|
-
output.nextStartLine = endLine + 1;
|
|
2352
|
-
content += `
|
|
2353
|
-
[truncated: showing lines ${startLine}-${endLine} of ${totalLines}; call read_file with startLine=${endLine + 1}]`;
|
|
2354
|
-
} else {
|
|
2355
|
-
content += `
|
|
2356
|
-
[truncated: line ${endLine} was cut]`;
|
|
2357
|
-
}
|
|
2358
|
-
}
|
|
2359
|
-
output.content = content;
|
|
2360
|
-
return { result: { status: "ok", output }, read: { path, startLine, endLine, chars: used } };
|
|
3045
|
+
let match;
|
|
3046
|
+
TESTCASE_RE.lastIndex = 0;
|
|
3047
|
+
while (match = TESTCASE_RE.exec(xml)) {
|
|
3048
|
+
const [, attrs, body = ""] = match;
|
|
3049
|
+
const rawName = NAME_ATTR_RE.exec(attrs)?.[1];
|
|
3050
|
+
if (!rawName) continue;
|
|
3051
|
+
const name = unescapeXmlEntities(rawName);
|
|
3052
|
+
const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];
|
|
3053
|
+
const classname = rawClassname === void 0 ? void 0 : unescapeXmlEntities(rawClassname);
|
|
3054
|
+
const id = classname ? `${classname}::${name}` : name;
|
|
3055
|
+
const failed = FAILURE_CHILD_RE.test(body);
|
|
3056
|
+
outcomes.set(id, !failed);
|
|
3057
|
+
if (failed) {
|
|
3058
|
+
const text = extractFailureText(body);
|
|
3059
|
+
if (text) failureText.set(id, text);
|
|
2361
3060
|
}
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
const cap = Math.min(max ?? env2.limits.listMaxEntries, env2.limits.listMaxEntries);
|
|
2372
|
-
return {
|
|
2373
|
-
key: JSON.stringify({ prefix, maxEntries: cap }),
|
|
2374
|
-
exec: () => {
|
|
2375
|
-
const matching = env2.visible.filter((p) => matchesPrefix(p, prefix));
|
|
2376
|
-
const entries = matching.slice(0, cap);
|
|
2377
|
-
const truncated = matching.length > cap;
|
|
2378
|
-
const output = { entries, total: matching.length, truncated };
|
|
2379
|
-
if (truncated) {
|
|
2380
|
-
const counts = /* @__PURE__ */ new Map();
|
|
2381
|
-
for (const p of matching) {
|
|
2382
|
-
const rest = prefix === "" ? p : p.slice(prefix.length + 1);
|
|
2383
|
-
const slash = rest.indexOf("/");
|
|
2384
|
-
if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);
|
|
2385
|
-
}
|
|
2386
|
-
output.subdirs = [...counts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1)).slice(0, 50);
|
|
2387
|
-
}
|
|
2388
|
-
return { result: { status: "ok", output } };
|
|
3061
|
+
const file = FILE_ATTR_RE.exec(attrs)?.[1];
|
|
3062
|
+
if (file) discoveredFiles.add(normalizeSlashes(file));
|
|
3063
|
+
if (classname) discoveredFiles.add(normalizeSlashes(classname));
|
|
3064
|
+
const bracket = QP_TOKEN_BRACKET_RE.exec(name)?.[1];
|
|
3065
|
+
if (bracket) {
|
|
3066
|
+
discoveredAutomationIds.add(bracket);
|
|
3067
|
+
const result = failed ? "fail" : SKIPPED_CHILD_RE.test(body) ? "skipped" : "pass";
|
|
3068
|
+
const seen = automationIdResults.get(bracket);
|
|
3069
|
+
if (!seen || RESULT_RANK[result] > RESULT_RANK[seen]) automationIdResults.set(bracket, result);
|
|
2389
3070
|
}
|
|
2390
|
-
}
|
|
3071
|
+
}
|
|
3072
|
+
return { outcomes, automationIdResults, failureText, discoveredFiles, discoveredAutomationIds };
|
|
2391
3073
|
}
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
if (!wholeWord) return i;
|
|
2400
|
-
const before = i > 0 ? hay[i - 1] : "";
|
|
2401
|
-
const after = i + needle.length < hay.length ? hay[i + needle.length] : "";
|
|
2402
|
-
if (!(before && WORD_CHAR.test(before)) && !(after && WORD_CHAR.test(after))) return i;
|
|
2403
|
-
from = i + 1;
|
|
3074
|
+
function readJUnitOutcomes(cwd) {
|
|
3075
|
+
const report = findJUnitReport(cwd);
|
|
3076
|
+
if (!report) return null;
|
|
3077
|
+
try {
|
|
3078
|
+
return parseJUnitOutcomes((0, import_node_fs7.readFileSync)(report, "utf8"));
|
|
3079
|
+
} catch {
|
|
3080
|
+
return null;
|
|
2404
3081
|
}
|
|
2405
3082
|
}
|
|
2406
|
-
function
|
|
2407
|
-
|
|
2408
|
-
if (t.length <= max) return t;
|
|
2409
|
-
const lead = line.length - line.trimStart().length;
|
|
2410
|
-
const pos = Math.max(0, at - lead);
|
|
2411
|
-
const from = Math.max(0, Math.min(pos - 40, t.length - max));
|
|
2412
|
-
const piece = t.slice(from, from + max);
|
|
2413
|
-
return `${from > 0 ? "\u2026" : ""}${piece}${from + max < t.length ? "\u2026" : ""}`;
|
|
3083
|
+
function readAutomationIdResults(cwd = process.cwd()) {
|
|
3084
|
+
return readJUnitOutcomes(cwd)?.automationIdResults ?? null;
|
|
2414
3085
|
}
|
|
2415
|
-
function
|
|
2416
|
-
const
|
|
2417
|
-
|
|
2418
|
-
return bad("pattern must be a non-empty string within the length limit.");
|
|
2419
|
-
}
|
|
2420
|
-
if (/[\u0000\r\n]/.test(pattern)) return bad("pattern must be a single line of plain text.");
|
|
2421
|
-
for (const flag of ["ignoreCase", "wholeWord"]) {
|
|
2422
|
-
if (args[flag] !== void 0 && typeof args[flag] !== "boolean") return bad(`${flag} must be true or false.`);
|
|
2423
|
-
}
|
|
2424
|
-
const maxIn = optionalInt(args.maxResults);
|
|
2425
|
-
if (maxIn === "bad" || maxIn !== void 0 && maxIn < 1) return bad("maxResults must be a whole number of at least 1.");
|
|
2426
|
-
if (args.pathPrefix !== void 0 && args.pathPrefix !== null && typeof args.pathPrefix !== "string") return bad("pathPrefix must be a string.");
|
|
2427
|
-
const n = normaliseToolPath(args.pathPrefix, { allowRoot: true });
|
|
2428
|
-
if (!n.ok) return { fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
|
|
2429
|
-
const prefix = n.path;
|
|
2430
|
-
const ignoreCase = args.ignoreCase === true;
|
|
2431
|
-
const wholeWord = args.wholeWord === true;
|
|
2432
|
-
const maxMatches = Math.min(maxIn ?? env2.limits.grepMaxMatches, env2.limits.grepMaxMatches);
|
|
2433
|
-
const needle = ignoreCase ? pattern.toLowerCase() : pattern;
|
|
3086
|
+
function captureTestSnapshot(command, cwd = process.cwd()) {
|
|
3087
|
+
const outcome = runTestCommand(command);
|
|
3088
|
+
const parsed = readJUnitOutcomes(cwd);
|
|
2434
3089
|
return {
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
let bytesScanned = 0;
|
|
2441
|
-
let scanCapped = false;
|
|
2442
|
-
let truncated = false;
|
|
2443
|
-
scan: for (const path of env2.visible) {
|
|
2444
|
-
if (!matchesPrefix(path, prefix)) continue;
|
|
2445
|
-
if (filesScanned >= env2.limits.grepMaxFiles || bytesScanned >= env2.limits.grepMaxBytes) {
|
|
2446
|
-
scanCapped = true;
|
|
2447
|
-
break;
|
|
2448
|
-
}
|
|
2449
|
-
filesScanned += 1;
|
|
2450
|
-
let bytes;
|
|
2451
|
-
try {
|
|
2452
|
-
const st = env2.fs.lstat(path);
|
|
2453
|
-
if (st.isSymlink || !st.isFile) continue;
|
|
2454
|
-
if (st.size > env2.limits.grepFileBytes) {
|
|
2455
|
-
skipped.large += 1;
|
|
2456
|
-
continue;
|
|
2457
|
-
}
|
|
2458
|
-
if (!env2.fs.realpathInside(path)) continue;
|
|
2459
|
-
bytes = env2.fs.readBytes(path);
|
|
2460
|
-
} catch {
|
|
2461
|
-
continue;
|
|
2462
|
-
}
|
|
2463
|
-
bytesScanned += bytes.length;
|
|
2464
|
-
if (hasNul(bytes)) {
|
|
2465
|
-
skipped.binary += 1;
|
|
2466
|
-
continue;
|
|
2467
|
-
}
|
|
2468
|
-
const lines = new TextDecoder("utf-8").decode(bytes).replace(/\r\n/g, "\n").split("\n");
|
|
2469
|
-
for (let i = 0; i < lines.length; i++) {
|
|
2470
|
-
const at = lineMatches(lines[i], needle, ignoreCase, wholeWord);
|
|
2471
|
-
if (at === -1) continue;
|
|
2472
|
-
if (matches.length >= maxMatches) {
|
|
2473
|
-
truncated = true;
|
|
2474
|
-
break scan;
|
|
2475
|
-
}
|
|
2476
|
-
matches.push({ path, line: i + 1, text: excerpt(lines[i], at, env2.limits.grepLineChars) });
|
|
2477
|
-
}
|
|
2478
|
-
}
|
|
2479
|
-
const output = { matches, truncated, filesScanned, skipped };
|
|
2480
|
-
if (scanCapped) output.scanCapped = true;
|
|
2481
|
-
return { result: { status: "ok", output } };
|
|
2482
|
-
}
|
|
3090
|
+
outcome,
|
|
3091
|
+
results: parsed?.outcomes ?? null,
|
|
3092
|
+
failureText: parsed?.failureText,
|
|
3093
|
+
discoveredFiles: parsed?.discoveredFiles ?? null,
|
|
3094
|
+
discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
|
|
2483
3095
|
};
|
|
2484
3096
|
}
|
|
2485
|
-
function
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
return read ? { result, read } : { result };
|
|
3097
|
+
async function captureBaselineSnapshot(command, cwd = process.cwd()) {
|
|
3098
|
+
const outcome = await runTestCommandAsync(command);
|
|
3099
|
+
const parsed = readJUnitOutcomes(cwd);
|
|
3100
|
+
return {
|
|
3101
|
+
outcome,
|
|
3102
|
+
results: parsed?.outcomes ?? null,
|
|
3103
|
+
failureText: parsed?.failureText,
|
|
3104
|
+
discoveredFiles: parsed?.discoveredFiles ?? null,
|
|
3105
|
+
discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
|
|
2495
3106
|
};
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
if (
|
|
2499
|
-
|
|
2500
|
-
|
|
2501
|
-
|
|
2502
|
-
|
|
2503
|
-
|
|
3107
|
+
}
|
|
3108
|
+
function checkForRegressions(baseline, after) {
|
|
3109
|
+
if (!baseline.results || !after.results) {
|
|
3110
|
+
return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: /* @__PURE__ */ new Map() };
|
|
3111
|
+
}
|
|
3112
|
+
const regressions = [];
|
|
3113
|
+
const newFailures = [];
|
|
3114
|
+
const preExisting = [];
|
|
3115
|
+
const failureText = /* @__PURE__ */ new Map();
|
|
3116
|
+
const afterFailureText = after.failureText;
|
|
3117
|
+
for (const [testId, passed] of after.results) {
|
|
3118
|
+
if (passed) continue;
|
|
3119
|
+
const before = baseline.results.get(testId);
|
|
3120
|
+
if (before === true) {
|
|
3121
|
+
regressions.push(testId);
|
|
3122
|
+
const text = afterFailureText?.get(testId);
|
|
3123
|
+
if (text) failureText.set(testId, text);
|
|
3124
|
+
} else if (before === false) {
|
|
3125
|
+
preExisting.push(testId);
|
|
3126
|
+
} else {
|
|
3127
|
+
newFailures.push(testId);
|
|
3128
|
+
const text = afterFailureText?.get(testId);
|
|
3129
|
+
if (text) failureText.set(testId, text);
|
|
2504
3130
|
}
|
|
2505
|
-
if (!isPlainObject(call.args)) return finish({ status: "bad_args", message: "Arguments must be an object." });
|
|
2506
|
-
prepared = call.name === "read_file" ? prepareReadFile(call.args, env2, ledger) : call.name === "list_files" ? prepareListFiles(call.args, env2) : prepareGrep(call.args, env2);
|
|
2507
|
-
} catch {
|
|
2508
|
-
return finish({ status: "bad_args", message: "Those arguments could not be used." });
|
|
2509
3131
|
}
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
|
|
2513
|
-
|
|
2514
|
-
|
|
3132
|
+
return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };
|
|
3133
|
+
}
|
|
3134
|
+
function describeRegressions(check) {
|
|
3135
|
+
const withText = (id) => {
|
|
3136
|
+
const text = check.failureText.get(id);
|
|
3137
|
+
return text ? `${id} (${text})` : id;
|
|
3138
|
+
};
|
|
3139
|
+
const parts = [];
|
|
3140
|
+
if (check.regressions.length > 0) {
|
|
3141
|
+
parts.push(
|
|
3142
|
+
`${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(", ")}`
|
|
3143
|
+
);
|
|
2515
3144
|
}
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
|
|
2519
|
-
|
|
2520
|
-
} catch {
|
|
2521
|
-
executed = { result: { status: "unreadable", reason: "io", message: "That could not be read." } };
|
|
3145
|
+
if (check.newFailures.length > 0) {
|
|
3146
|
+
parts.push(
|
|
3147
|
+
`${check.newFailures.length} new failure(s) (did not exist before): ${check.newFailures.map(withText).join(", ")}`
|
|
3148
|
+
);
|
|
2522
3149
|
}
|
|
2523
|
-
|
|
3150
|
+
if (check.preExisting.length > 0) {
|
|
3151
|
+
parts.push(`${check.preExisting.length} pre-existing failure(s), unrelated to this change, not blocking`);
|
|
3152
|
+
}
|
|
3153
|
+
return parts.join("; ");
|
|
2524
3154
|
}
|
|
2525
3155
|
|
|
2526
|
-
// src/
|
|
2527
|
-
var
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
|
|
2531
|
-
var TOKENS_PER_NON_ASCII_CHAR = 1;
|
|
2532
|
-
var PROMPT_OVERHEAD_TOKENS = 5e3;
|
|
2533
|
-
function estimateTokens(text) {
|
|
2534
|
-
let alpha = 0;
|
|
2535
|
-
let digit = 0;
|
|
2536
|
-
let space = 0;
|
|
2537
|
-
let punct = 0;
|
|
2538
|
-
let nonAscii = 0;
|
|
2539
|
-
for (const ch of text) {
|
|
2540
|
-
const code = ch.codePointAt(0);
|
|
2541
|
-
if (code >= 128) nonAscii++;
|
|
2542
|
-
else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
|
|
2543
|
-
else if (code >= 48 && code <= 57) digit++;
|
|
2544
|
-
else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
|
|
2545
|
-
else punct++;
|
|
2546
|
-
}
|
|
2547
|
-
return Math.ceil(
|
|
2548
|
-
alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
|
|
2549
|
-
);
|
|
3156
|
+
// src/baselineCheck.ts
|
|
3157
|
+
var BASELINE_CHECK_TIMEOUT_MS = 12e4;
|
|
3158
|
+
function shellQuote(value) {
|
|
3159
|
+
return `'${value.split("'").join("'\\''")}'`;
|
|
2550
3160
|
}
|
|
2551
|
-
function
|
|
2552
|
-
|
|
3161
|
+
function buildSingleFileCommand(command, path) {
|
|
3162
|
+
const quoted = shellQuote(path);
|
|
3163
|
+
return command.includes("{file}") ? command.split("{file}").join(quoted) : `${command} ${quoted}`;
|
|
2553
3164
|
}
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
3165
|
+
var isTestTarget2 = (t) => (t.automationIds?.length ?? 0) > 0;
|
|
3166
|
+
function checkableIds(ids, types) {
|
|
3167
|
+
if (!types) return [];
|
|
3168
|
+
return ids.filter((id) => {
|
|
3169
|
+
if (!Object.prototype.hasOwnProperty.call(types, id)) return false;
|
|
3170
|
+
const type = types[id];
|
|
3171
|
+
return typeof type === "string" && type.trim() !== "" && type.trim().toUpperCase() !== "REGRESSION";
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
function insideCheckout(cwd, path) {
|
|
3175
|
+
const abs = (0, import_node_path8.resolve)(cwd, path);
|
|
3176
|
+
const rel = (0, import_node_path8.relative)(cwd, abs);
|
|
3177
|
+
return rel === "" || rel.startsWith("..") || (0, import_node_path8.isAbsolute)(rel) ? null : abs;
|
|
3178
|
+
}
|
|
3179
|
+
function writeForCheck(abs, content) {
|
|
3180
|
+
const original = (0, import_node_fs8.existsSync)(abs) ? (0, import_node_fs8.readFileSync)(abs) : null;
|
|
3181
|
+
const createdDirs = [];
|
|
3182
|
+
if (original === null) {
|
|
3183
|
+
const missing = [];
|
|
3184
|
+
for (let d = (0, import_node_path8.dirname)(abs); !(0, import_node_fs8.existsSync)(d); d = (0, import_node_path8.dirname)(d)) missing.push(d);
|
|
3185
|
+
for (const d of missing.reverse()) {
|
|
3186
|
+
(0, import_node_fs8.mkdirSync)(d);
|
|
3187
|
+
createdDirs.push(d);
|
|
3188
|
+
}
|
|
2568
3189
|
}
|
|
2569
|
-
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
|
|
2573
|
-
|
|
3190
|
+
(0, import_node_fs8.writeFileSync)(abs, content);
|
|
3191
|
+
return { abs, original, createdDirs };
|
|
3192
|
+
}
|
|
3193
|
+
function restore(written) {
|
|
3194
|
+
for (const file of [...written].reverse()) {
|
|
3195
|
+
try {
|
|
3196
|
+
if (file.original !== null) (0, import_node_fs8.writeFileSync)(file.abs, file.original);
|
|
3197
|
+
else (0, import_node_fs8.rmSync)(file.abs, { force: true });
|
|
3198
|
+
for (const d of [...file.createdDirs].reverse()) {
|
|
3199
|
+
try {
|
|
3200
|
+
(0, import_node_fs8.rmdirSync)(d);
|
|
3201
|
+
} catch {
|
|
3202
|
+
}
|
|
3203
|
+
}
|
|
3204
|
+
} catch (err) {
|
|
3205
|
+
console.error(`Baseline check could not restore ${file.abs}: ${err instanceof Error ? err.message : String(err)}`);
|
|
3206
|
+
}
|
|
2574
3207
|
}
|
|
2575
|
-
};
|
|
2576
|
-
var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
|
|
2577
|
-
var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
|
|
2578
|
-
var MAX_ID_CHARS = 64;
|
|
2579
|
-
var MAX_CALLS_IN_A_REPLY = 50;
|
|
2580
|
-
var MAX_ARGS_JSON_CHARS = 1e3;
|
|
2581
|
-
function isPlainObject2(x) {
|
|
2582
|
-
return typeof x === "object" && x !== null && !Array.isArray(x);
|
|
2583
3208
|
}
|
|
2584
|
-
function
|
|
3209
|
+
function untrackedFiles(cwd) {
|
|
2585
3210
|
try {
|
|
2586
|
-
|
|
3211
|
+
const out = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
|
|
3212
|
+
cwd,
|
|
3213
|
+
encoding: "utf8",
|
|
3214
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
3215
|
+
maxBuffer: 64 * 1024 * 1024
|
|
3216
|
+
});
|
|
3217
|
+
return new Set(out.split("\0").filter(Boolean));
|
|
2587
3218
|
} catch {
|
|
2588
|
-
return
|
|
3219
|
+
return null;
|
|
2589
3220
|
}
|
|
2590
3221
|
}
|
|
2591
|
-
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2595
|
-
|
|
3222
|
+
var mtimeOf = (path) => {
|
|
3223
|
+
try {
|
|
3224
|
+
return (0, import_node_fs8.statSync)(path).mtimeMs;
|
|
3225
|
+
} catch {
|
|
3226
|
+
return null;
|
|
3227
|
+
}
|
|
3228
|
+
};
|
|
3229
|
+
function decideCause(targets, results, cwd) {
|
|
3230
|
+
const codeTargets = targets.filter((t) => !isTestTarget2(t));
|
|
3231
|
+
if (codeTargets.length === 0) return "ALREADY_TRUE";
|
|
3232
|
+
for (const t of codeTargets) {
|
|
3233
|
+
if (t.kind === "NEW_FILE") return "ALREADY_TRUE";
|
|
3234
|
+
const next = results.get(t.path);
|
|
3235
|
+
const abs = insideCheckout(cwd, t.path);
|
|
3236
|
+
if (next === void 0 || abs === null) return "ALREADY_TRUE";
|
|
3237
|
+
try {
|
|
3238
|
+
if ((0, import_node_fs8.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
|
|
3239
|
+
} catch {
|
|
3240
|
+
return "ALREADY_TRUE";
|
|
3241
|
+
}
|
|
3242
|
+
}
|
|
3243
|
+
return "NO_OP";
|
|
2596
3244
|
}
|
|
2597
|
-
async function
|
|
2598
|
-
const
|
|
2599
|
-
const
|
|
2600
|
-
const
|
|
2601
|
-
const
|
|
2602
|
-
|
|
2603
|
-
const
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
3245
|
+
async function runBaselineCheck(params) {
|
|
3246
|
+
const { targets, results, testFileCmd, requiredTestTypes } = params;
|
|
3247
|
+
const cwd = params.cwd ?? process.cwd();
|
|
3248
|
+
const runFile = params.runFile ?? runCommandWithTimeout;
|
|
3249
|
+
const nothing = { findings: null, warnings: [] };
|
|
3250
|
+
if (!testFileCmd || testFileCmd.trim() === "") return nothing;
|
|
3251
|
+
const testTargets = targets.filter(isTestTarget2);
|
|
3252
|
+
const toCheck = testTargets.map((target) => ({ target, ids: checkableIds(target.automationIds ?? [], requiredTestTypes) })).filter((entry) => entry.ids.length > 0);
|
|
3253
|
+
if (toCheck.length === 0) {
|
|
3254
|
+
console.log("Baseline check: no case with a known, non-Regression label \u2014 nothing to check.");
|
|
3255
|
+
return nothing;
|
|
3256
|
+
}
|
|
3257
|
+
const warnings = [];
|
|
3258
|
+
const flagged = [];
|
|
3259
|
+
const written = [];
|
|
3260
|
+
const unsafe = /* @__PURE__ */ new Set();
|
|
3261
|
+
const skip = (path, why) => {
|
|
3262
|
+
const message = `Baseline check skipped for ${path}: ${why}`;
|
|
3263
|
+
console.warn(`::warning::${message}`);
|
|
3264
|
+
warnings.push(message);
|
|
2609
3265
|
};
|
|
2610
|
-
const ledger = newLedger();
|
|
2611
|
-
const reads = [];
|
|
2612
|
-
const transcript = [];
|
|
2613
|
-
const toolResults = [];
|
|
2614
|
-
const usedIds = /* @__PURE__ */ new Set();
|
|
2615
|
-
let turns = 0;
|
|
2616
|
-
let noProgressStreak = 0;
|
|
2617
|
-
let forced = null;
|
|
2618
|
-
const started = now();
|
|
2619
|
-
const buildContext = (turn, isFinal, finalReason) => ({
|
|
2620
|
-
...args.baseContext,
|
|
2621
|
-
contractVersion: LOOP_CONTRACT_VERSION,
|
|
2622
|
-
loop: {
|
|
2623
|
-
turn,
|
|
2624
|
-
maxTurns: limits.maxTurns,
|
|
2625
|
-
final: isFinal,
|
|
2626
|
-
...isFinal ? { finalReason } : {},
|
|
2627
|
-
remaining: {
|
|
2628
|
-
toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
|
|
2629
|
-
readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
|
|
2630
|
-
},
|
|
2631
|
-
transcript,
|
|
2632
|
-
toolResults
|
|
2633
|
-
}
|
|
2634
|
-
});
|
|
2635
|
-
const snapshot = (stopReason) => ({
|
|
2636
|
-
turns,
|
|
2637
|
-
toolCalls: ledger.toolCalls,
|
|
2638
|
-
readChars: ledger.readChars,
|
|
2639
|
-
refused: ledger.refused,
|
|
2640
|
-
stopReason,
|
|
2641
|
-
reads: [...reads]
|
|
2642
|
-
});
|
|
2643
|
-
log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
|
|
2644
3266
|
try {
|
|
2645
|
-
|
|
2646
|
-
|
|
2647
|
-
|
|
2648
|
-
const
|
|
2649
|
-
|
|
2650
|
-
const
|
|
2651
|
-
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
|
|
2655
|
-
throw new LoopFailure("token_ceiling");
|
|
3267
|
+
const contentByPath = new Map(results.map((r) => [r.targetPath, r.newContent]));
|
|
3268
|
+
const cause = decideCause(targets, contentByPath, cwd);
|
|
3269
|
+
for (const target of testTargets) {
|
|
3270
|
+
const content = contentByPath.get(target.path);
|
|
3271
|
+
if (content === void 0) continue;
|
|
3272
|
+
const abs = insideCheckout(cwd, target.path);
|
|
3273
|
+
if (abs === null) {
|
|
3274
|
+
unsafe.add(target.path);
|
|
3275
|
+
continue;
|
|
2656
3276
|
}
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
3277
|
+
written.push(writeForCheck(abs, content));
|
|
3278
|
+
}
|
|
3279
|
+
for (const { target, ids } of toCheck) {
|
|
3280
|
+
if (unsafe.has(target.path)) {
|
|
3281
|
+
skip(target.path, "the path is outside the checkout, so the file was not written or run.");
|
|
3282
|
+
continue;
|
|
2663
3283
|
}
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
3284
|
+
if (!contentByPath.has(target.path)) continue;
|
|
3285
|
+
const reportBefore = findJUnitReport(cwd);
|
|
3286
|
+
const mtimeBefore = reportBefore ? mtimeOf(reportBefore) : null;
|
|
3287
|
+
const untrackedBefore = untrackedFiles(cwd);
|
|
3288
|
+
const outcome = await runFile(buildSingleFileCommand(testFileCmd, target.path), BASELINE_CHECK_TIMEOUT_MS);
|
|
3289
|
+
if (outcome === "timeout") {
|
|
3290
|
+
skip(
|
|
3291
|
+
target.path,
|
|
3292
|
+
`the single-file command did not finish within ${BASELINE_CHECK_TIMEOUT_MS / 1e3} seconds and was stopped. No test case from this file was flagged.`
|
|
3293
|
+
);
|
|
3294
|
+
} else if (outcome === "error") {
|
|
3295
|
+
skip(target.path, "the single-file command could not be started. No test case from this file was flagged.");
|
|
3296
|
+
} else {
|
|
3297
|
+
const reportAfter = findJUnitReport(cwd);
|
|
3298
|
+
const fresh = reportAfter !== null && (reportAfter !== reportBefore || mtimeOf(reportAfter) !== mtimeBefore);
|
|
3299
|
+
if (!fresh) {
|
|
3300
|
+
skip(
|
|
3301
|
+
target.path,
|
|
3302
|
+
"the single-file command wrote no new JUnit report (it must write the same JUnit report as the test command), so nothing could be checked."
|
|
3303
|
+
);
|
|
3304
|
+
} else {
|
|
3305
|
+
const byId = readAutomationIdResults(cwd);
|
|
3306
|
+
for (const id of ids) if (byId?.get(id) === "pass") flagged.push(id);
|
|
3307
|
+
}
|
|
3308
|
+
}
|
|
3309
|
+
const untrackedAfter = untrackedFiles(cwd);
|
|
3310
|
+
if (untrackedBefore && untrackedAfter) {
|
|
3311
|
+
for (const file of untrackedAfter) {
|
|
3312
|
+
if (untrackedBefore.has(file)) continue;
|
|
3313
|
+
const abs = insideCheckout(cwd, file);
|
|
3314
|
+
if (abs) (0, import_node_fs8.rmSync)(abs, { force: true });
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
if (flagged.length === 0) return { findings: null, warnings };
|
|
3319
|
+
const automationIds = [...new Set(flagged)].slice(0, 200);
|
|
3320
|
+
const list = automationIds.join(", ");
|
|
3321
|
+
warnings.push(
|
|
3322
|
+
cause === "NO_OP" ? `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, and every file the generated change edited came out unchanged, so the change itself may have been a no-op: ${list}.` : `Baseline check: ${automationIds.length} test case(s) passed against the unmodified code, so they may assert something already true: ${list}. This check cannot tell that from a change that did nothing.`
|
|
3323
|
+
);
|
|
3324
|
+
return { findings: { cause, automationIds }, warnings };
|
|
3325
|
+
} catch (err) {
|
|
3326
|
+
const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;
|
|
3327
|
+
console.warn(`::warning::${message}`);
|
|
3328
|
+
return { findings: null, warnings: [...warnings, message] };
|
|
3329
|
+
} finally {
|
|
3330
|
+
restore(written);
|
|
3331
|
+
}
|
|
3332
|
+
}
|
|
3333
|
+
|
|
3334
|
+
// src/failureArtifact.ts
|
|
3335
|
+
var import_node_fs9 = require("node:fs");
|
|
3336
|
+
var import_node_path9 = require("node:path");
|
|
3337
|
+
|
|
3338
|
+
// src/failureReason.ts
|
|
3339
|
+
var MAX_FAILURE_REASON = 1e3;
|
|
3340
|
+
var MIN_SECRET_LENGTH = 8;
|
|
3341
|
+
var CREDENTIAL_PATTERNS = [
|
|
3342
|
+
/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
|
|
3343
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}/g,
|
|
3344
|
+
/x-access-token:[^@\s'"]+/gi,
|
|
3345
|
+
// Only the header form ("Authorization: basic <token>"), or a bearer value that contains a digit: a bare
|
|
3346
|
+
// "basic authentication" or "bearer of the news" is prose, not a credential.
|
|
3347
|
+
/\bauthorization:\s*(?:basic|bearer|token)\s+[^\s'"]{8,}/gi,
|
|
3348
|
+
/\bbearer\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{12,}/gi,
|
|
3349
|
+
// A signed JWT is three dot-separated segments; QuikPilot's own run token is an encrypted JWT (alg dir) of five, the
|
|
3350
|
+
// second one empty. The run token is also matched by exact value, but one that has expired or rotated is not the
|
|
3351
|
+
// current value, so its shape has to catch it.
|
|
3352
|
+
/\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]*){2,4}/g
|
|
3353
|
+
];
|
|
3354
|
+
function failureSummary(err) {
|
|
3355
|
+
if (err instanceof RuntimeReplyError) return err.summary;
|
|
3356
|
+
return err instanceof Error ? err.message : String(err);
|
|
3357
|
+
}
|
|
3358
|
+
function scrubSecrets(message, secrets = []) {
|
|
3359
|
+
let text = message;
|
|
3360
|
+
for (const secret of secrets) {
|
|
3361
|
+
if (secret.length >= MIN_SECRET_LENGTH) text = text.split(secret).join("***");
|
|
3362
|
+
}
|
|
3363
|
+
for (const pattern of CREDENTIAL_PATTERNS) text = text.replace(pattern, "***");
|
|
3364
|
+
return text;
|
|
3365
|
+
}
|
|
3366
|
+
function describeFailureReason(message, secrets = []) {
|
|
3367
|
+
let text = scrubSecrets(message, secrets);
|
|
3368
|
+
text = text.replace(/\s*\n\s*/g, " | ").trim();
|
|
3369
|
+
return text.length > MAX_FAILURE_REASON ? `${text.slice(0, MAX_FAILURE_REASON)}\u2026` : text;
|
|
3370
|
+
}
|
|
3371
|
+
|
|
3372
|
+
// src/failureArtifact.ts
|
|
3373
|
+
var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
|
|
3374
|
+
var REPORT_COPY = "final-test-report.xml";
|
|
3375
|
+
var MAX_REPORT_BYTES = 5 * 1024 * 1024;
|
|
3376
|
+
var MAX_FILES = 200;
|
|
3377
|
+
var RUNNER_VERSION = true ? "9.2.0-rc.3" : "dev";
|
|
3378
|
+
function safeDestination(base, repoPath) {
|
|
3379
|
+
if (!repoPath || (0, import_node_path9.isAbsolute)(repoPath)) return null;
|
|
3380
|
+
const destination = (0, import_node_path9.resolve)(base, repoPath);
|
|
3381
|
+
const rel = (0, import_node_path9.relative)(base, destination);
|
|
3382
|
+
if (!rel || rel.startsWith("..") || (0, import_node_path9.isAbsolute)(rel)) return null;
|
|
3383
|
+
return destination;
|
|
3384
|
+
}
|
|
3385
|
+
function writeFailureArtifact(input) {
|
|
3386
|
+
if (input.results.length === 0) return { written: false };
|
|
3387
|
+
try {
|
|
3388
|
+
const base = (0, import_node_path9.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
|
|
3389
|
+
(0, import_node_fs9.rmSync)(base, { recursive: true, force: true });
|
|
3390
|
+
(0, import_node_fs9.mkdirSync)(base, { recursive: true });
|
|
3391
|
+
const files = [];
|
|
3392
|
+
const skipped = [];
|
|
3393
|
+
for (const result of input.results) {
|
|
3394
|
+
const destination = files.length < MAX_FILES ? safeDestination(base, result.targetPath) : null;
|
|
3395
|
+
if (!destination) {
|
|
3396
|
+
skipped.push(result.targetPath);
|
|
3397
|
+
continue;
|
|
2669
3398
|
}
|
|
2670
|
-
|
|
2671
|
-
|
|
2672
|
-
|
|
2673
|
-
|
|
2674
|
-
|
|
2675
|
-
|
|
2676
|
-
|
|
2677
|
-
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
}
|
|
2682
|
-
throw new LoopFailure("runtime_failed", runtimeCode);
|
|
3399
|
+
(0, import_node_fs9.mkdirSync)((0, import_node_path9.dirname)(destination), { recursive: true });
|
|
3400
|
+
(0, import_node_fs9.writeFileSync)(destination, result.newContent);
|
|
3401
|
+
files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
|
|
3402
|
+
}
|
|
3403
|
+
let testReport = "none";
|
|
3404
|
+
if (input.testReport) {
|
|
3405
|
+
if (input.testReport.byteLength > MAX_REPORT_BYTES) {
|
|
3406
|
+
testReport = "too-large";
|
|
3407
|
+
} else {
|
|
3408
|
+
(0, import_node_fs9.writeFileSync)((0, import_node_path9.join)(base, REPORT_COPY), input.testReport);
|
|
3409
|
+
testReport = "included";
|
|
2683
3410
|
}
|
|
2684
|
-
|
|
3411
|
+
}
|
|
3412
|
+
const manifest = {
|
|
3413
|
+
runId: input.runId,
|
|
3414
|
+
issueKey: input.issueKey,
|
|
3415
|
+
runnerVersion: RUNNER_VERSION,
|
|
3416
|
+
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3417
|
+
targets: input.targets.map((t) => ({
|
|
3418
|
+
path: t.path,
|
|
3419
|
+
kind: t.kind,
|
|
3420
|
+
...t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}
|
|
3421
|
+
})),
|
|
3422
|
+
files,
|
|
3423
|
+
skipped,
|
|
3424
|
+
testReport,
|
|
3425
|
+
failureReasons: input.failureReasons
|
|
3426
|
+
};
|
|
3427
|
+
const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
|
|
3428
|
+
(0, import_node_fs9.writeFileSync)((0, import_node_path9.join)(base, "manifest.json"), text);
|
|
3429
|
+
return { written: (0, import_node_fs9.existsSync)((0, import_node_path9.join)(base, "manifest.json")) };
|
|
3430
|
+
} catch (err) {
|
|
3431
|
+
console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
|
|
3432
|
+
return { written: false };
|
|
3433
|
+
}
|
|
3434
|
+
}
|
|
3435
|
+
|
|
3436
|
+
// src/scopeCheck.ts
|
|
3437
|
+
var import_node_fs10 = require("node:fs");
|
|
3438
|
+
var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
|
|
3439
|
+
var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
|
|
3440
|
+
var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
|
|
3441
|
+
var NO_PATH = "(this file's route)";
|
|
3442
|
+
function detectMentions(text) {
|
|
3443
|
+
const found = [];
|
|
3444
|
+
for (const line of text.split("\n")) {
|
|
3445
|
+
const methodMatch = ROUTE_METHOD_RE.exec(line);
|
|
3446
|
+
const pathMatch = ROUTE_PATH_RE.exec(line);
|
|
3447
|
+
if (methodMatch && pathMatch) {
|
|
3448
|
+
found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0] });
|
|
3449
|
+
}
|
|
3450
|
+
const exportMatch = ROUTE_EXPORT_RE.exec(line);
|
|
3451
|
+
if (exportMatch) {
|
|
3452
|
+
found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
return found;
|
|
3456
|
+
}
|
|
3457
|
+
function normalizePath(path) {
|
|
3458
|
+
return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
|
|
3459
|
+
}
|
|
3460
|
+
function surfaceCovers(surface, mention) {
|
|
3461
|
+
if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
|
|
3462
|
+
if (mention.path === NO_PATH) return true;
|
|
3463
|
+
const declaredPath = normalizePath(surface);
|
|
3464
|
+
const mentionPath = normalizePath(mention.path);
|
|
3465
|
+
return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
|
|
3466
|
+
}
|
|
3467
|
+
function addedLines(before, after) {
|
|
3468
|
+
const beforeLines = new Set(before.split("\n"));
|
|
3469
|
+
return after.split("\n").filter((line) => !beforeLines.has(line)).join("\n");
|
|
3470
|
+
}
|
|
3471
|
+
var TEST_FILE_RES = [
|
|
3472
|
+
/(^|\/)(__tests__|__mocks__|tests?|specs?)\//i,
|
|
3473
|
+
/\.(test|spec)\.[^/.]+$/i,
|
|
3474
|
+
/(^|\/)test_[^/]+\.py$/i,
|
|
3475
|
+
/_test\.(py|go)$/i,
|
|
3476
|
+
/Tests?\.(java|kt|cs)$/
|
|
3477
|
+
];
|
|
3478
|
+
function isTestFile(path) {
|
|
3479
|
+
return TEST_FILE_RES.some((re) => re.test(path));
|
|
3480
|
+
}
|
|
3481
|
+
function checkApiScope(results, targets, apiChanges) {
|
|
3482
|
+
const targetsByPath = new Map(targets.map((t) => [t.path, t]));
|
|
3483
|
+
const violations = [];
|
|
3484
|
+
for (const { targetPath, newContent } of results) {
|
|
3485
|
+
if (isTestFile(targetPath)) continue;
|
|
3486
|
+
const target = targetsByPath.get(targetPath);
|
|
3487
|
+
const isNewFile = target?.kind === "NEW_FILE";
|
|
3488
|
+
let scanned;
|
|
3489
|
+
if (isNewFile) {
|
|
3490
|
+
scanned = newContent;
|
|
3491
|
+
} else {
|
|
3492
|
+
let currentContent;
|
|
2685
3493
|
try {
|
|
2686
|
-
|
|
2687
|
-
} catch
|
|
2688
|
-
|
|
2689
|
-
}
|
|
2690
|
-
if (body.outcome === "TARGETED" || body.outcome === "NO_TARGET") {
|
|
2691
|
-
log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
|
|
2692
|
-
const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
|
|
2693
|
-
log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
|
|
2694
|
-
return { body, summary: snapshot(stopReason) };
|
|
2695
|
-
}
|
|
2696
|
-
if (body.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
|
|
2697
|
-
if (isFinal) throw new LoopFailure("final_not_produced");
|
|
2698
|
-
const rawCalls = body.toolCalls;
|
|
2699
|
-
if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
|
|
2700
|
-
throw new LoopFailure("bad_reply");
|
|
2701
|
-
}
|
|
2702
|
-
const calls = [];
|
|
2703
|
-
for (const c of rawCalls) {
|
|
2704
|
-
if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
|
|
2705
|
-
throw new LoopFailure("bad_reply");
|
|
2706
|
-
}
|
|
2707
|
-
if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
|
|
2708
|
-
calls.push({ id: c.id, name: c.name, args: c.args });
|
|
3494
|
+
currentContent = (0, import_node_fs10.readFileSync)(targetPath, "utf8");
|
|
3495
|
+
} catch {
|
|
3496
|
+
currentContent = "";
|
|
2709
3497
|
}
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
|
|
2715
|
-
let result;
|
|
2716
|
-
let read;
|
|
2717
|
-
if (index >= limits.maxCallsPerTurn) {
|
|
2718
|
-
result = {
|
|
2719
|
-
id: call.id,
|
|
2720
|
-
name: call.name,
|
|
2721
|
-
status: "budget_exhausted",
|
|
2722
|
-
reason: "too_many_calls",
|
|
2723
|
-
message: "Too many calls in one turn; this one was not run."
|
|
2724
|
-
};
|
|
2725
|
-
} else {
|
|
2726
|
-
try {
|
|
2727
|
-
({ result, read } = executeToolCall(call, env2, ledger));
|
|
2728
|
-
} catch (err) {
|
|
2729
|
-
throw new LoopFailure("executor_error", void 0, err);
|
|
2730
|
-
}
|
|
2731
|
-
}
|
|
2732
|
-
results.push(result);
|
|
2733
|
-
turnReads[index] = read;
|
|
2734
|
-
if (read) reads.push(read);
|
|
2735
|
-
const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
|
|
2736
|
-
const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
|
|
2737
|
-
logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
|
|
2738
|
-
if (result.status === "refused") {
|
|
2739
|
-
log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
|
|
2740
|
-
}
|
|
2741
|
-
});
|
|
2742
|
-
const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
|
|
2743
|
-
transcript.push({
|
|
2744
|
-
turn,
|
|
2745
|
-
...reasoning ? { reasoning } : {},
|
|
2746
|
-
toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
|
|
2747
|
-
});
|
|
2748
|
-
toolResults.push(...results);
|
|
2749
|
-
noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
|
|
2750
|
-
if (noProgressStreak >= 2) forced = "no_progress";
|
|
2751
|
-
else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
|
|
2752
|
-
else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
|
|
2753
|
-
const nextTurn = turn + 1;
|
|
2754
|
-
if (nextTurn <= limits.maxTurns) {
|
|
2755
|
-
const nextFinal = forced !== null || nextTurn === limits.maxTurns;
|
|
2756
|
-
const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
|
|
2757
|
-
if (projected > limits.maxRequestTokens) {
|
|
2758
|
-
results.forEach((r, idx) => {
|
|
2759
|
-
if (r.status !== "ok") return;
|
|
2760
|
-
toolResults[toolResults.indexOf(r)] = {
|
|
2761
|
-
id: r.id,
|
|
2762
|
-
name: r.name,
|
|
2763
|
-
status: "budget_exhausted",
|
|
2764
|
-
reason: "token_ceiling",
|
|
2765
|
-
message: "Too large to include; answer from what you have."
|
|
2766
|
-
};
|
|
2767
|
-
const dropped = turnReads[idx];
|
|
2768
|
-
if (dropped) {
|
|
2769
|
-
const at = reads.indexOf(dropped);
|
|
2770
|
-
if (at >= 0) reads.splice(at, 1);
|
|
2771
|
-
}
|
|
2772
|
-
logged[idx].status = "budget_exhausted";
|
|
2773
|
-
logged[idx].reason = "token_ceiling";
|
|
2774
|
-
});
|
|
2775
|
-
forced = "read_budget";
|
|
2776
|
-
const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
|
|
2777
|
-
const fits = trimmed <= limits.maxRequestTokens;
|
|
2778
|
-
log({
|
|
2779
|
-
event: "targeting.loop_ceiling",
|
|
2780
|
-
turn,
|
|
2781
|
-
action: fits ? "dropped_results" : "fallback",
|
|
2782
|
-
projectedTokens: projected,
|
|
2783
|
-
ceiling: limits.maxRequestTokens
|
|
2784
|
-
});
|
|
2785
|
-
if (!fits) throw new LoopFailure("token_ceiling");
|
|
2786
|
-
}
|
|
3498
|
+
scanned = addedLines(currentContent, newContent);
|
|
3499
|
+
}
|
|
3500
|
+
for (const mention of detectMentions(scanned)) {
|
|
3501
|
+
if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
|
|
3502
|
+
violations.push({ file: targetPath, method: mention.method, path: mention.path });
|
|
2787
3503
|
}
|
|
2788
|
-
log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
|
|
2789
3504
|
}
|
|
2790
|
-
throw new LoopFailure("final_not_produced");
|
|
2791
|
-
} catch (err) {
|
|
2792
|
-
if (err instanceof SafetyRefusalError) throw err;
|
|
2793
|
-
const failure = err instanceof LoopFailure ? err : new LoopFailure("internal_error", void 0, err);
|
|
2794
|
-
failure.summary ??= snapshot("fallback");
|
|
2795
|
-
throw failure;
|
|
2796
3505
|
}
|
|
3506
|
+
return { blocked: violations.length > 0, violations };
|
|
3507
|
+
}
|
|
3508
|
+
function describeScopeViolations(check) {
|
|
3509
|
+
return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
|
|
3510
|
+
}
|
|
3511
|
+
|
|
3512
|
+
// src/targeting.ts
|
|
3513
|
+
var import_node_path10 = require("node:path");
|
|
3514
|
+
|
|
3515
|
+
// src/targetingMode.ts
|
|
3516
|
+
var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
|
|
3517
|
+
function parse2(value) {
|
|
3518
|
+
if (typeof value !== "string") return null;
|
|
3519
|
+
const v = value.trim().toLowerCase();
|
|
3520
|
+
if (v === "loop") return "loop";
|
|
3521
|
+
if (v === "single") return "single";
|
|
3522
|
+
return null;
|
|
3523
|
+
}
|
|
3524
|
+
function resolveTargetingMode(env2 = process.env, packetSetting) {
|
|
3525
|
+
const fromSetting = parse2(packetSetting);
|
|
3526
|
+
if (fromSetting) return fromSetting;
|
|
3527
|
+
return parse2(env2[TARGETING_MODE_ENV]) ?? "single";
|
|
2797
3528
|
}
|
|
2798
3529
|
|
|
2799
3530
|
// src/targeting.ts
|
|
@@ -2825,9 +3556,9 @@ function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
|
|
|
2825
3556
|
}
|
|
2826
3557
|
return;
|
|
2827
3558
|
}
|
|
2828
|
-
const root = (0,
|
|
2829
|
-
const rel = (0,
|
|
2830
|
-
if (rel.startsWith("..") || (0,
|
|
3559
|
+
const root = (0, import_node_path10.resolve)(workspaceRoot ?? ".");
|
|
3560
|
+
const rel = (0, import_node_path10.relative)(root, (0, import_node_path10.resolve)(target.path));
|
|
3561
|
+
if (rel.startsWith("..") || (0, import_node_path10.isAbsolute)(rel)) {
|
|
2831
3562
|
throw new Error(
|
|
2832
3563
|
`pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
|
|
2833
3564
|
);
|
|
@@ -2971,7 +3702,7 @@ var MAX_SKIPPED_CONTEXT = 20;
|
|
|
2971
3702
|
var MAX_SKIPPED_CASES = 200;
|
|
2972
3703
|
var MAX_CONTEXT_RECORDS = 25;
|
|
2973
3704
|
var MAX_PATH_CHARS2 = 300;
|
|
2974
|
-
var
|
|
3705
|
+
var MAX_ID_CHARS3 = 100;
|
|
2975
3706
|
var MAX_REASON_CHARS = 300;
|
|
2976
3707
|
var MAX_LOOP_READS = 50;
|
|
2977
3708
|
var MAX_FALLBACK_REASON_CHARS = 40;
|
|
@@ -3051,7 +3782,7 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
3051
3782
|
continue;
|
|
3052
3783
|
}
|
|
3053
3784
|
const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
|
|
3054
|
-
const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET,
|
|
3785
|
+
const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
|
|
3055
3786
|
note(contextPaths.cut);
|
|
3056
3787
|
note(automationIds.cut);
|
|
3057
3788
|
targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });
|
|
@@ -3059,7 +3790,7 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
3059
3790
|
const skipped = clampList(
|
|
3060
3791
|
(targeting.skippedCases ?? []).map((c) => c.automationId),
|
|
3061
3792
|
MAX_SKIPPED_CASES,
|
|
3062
|
-
|
|
3793
|
+
MAX_ID_CHARS3
|
|
3063
3794
|
);
|
|
3064
3795
|
note(skipped.cut);
|
|
3065
3796
|
const codegenContext = [];
|
|
@@ -3195,6 +3926,7 @@ async function run(env2) {
|
|
|
3195
3926
|
let baselineFindings;
|
|
3196
3927
|
let vanishedTests;
|
|
3197
3928
|
const contextLog = [];
|
|
3929
|
+
const codegenOut = {};
|
|
3198
3930
|
try {
|
|
3199
3931
|
runToken = await exchangeForRunToken(env2.tokenUrl, await fetchGithubOidcToken());
|
|
3200
3932
|
packet = await fetchPacket(env2.packetUrl, runToken, env2.githubRunId);
|
|
@@ -3261,17 +3993,21 @@ async function run(env2) {
|
|
|
3261
3993
|
);
|
|
3262
3994
|
const [baseline, results] = await Promise.all([
|
|
3263
3995
|
captureBaselineSnapshot(packet.commands.test),
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3996
|
+
runCodegenStep({
|
|
3997
|
+
mode: resolveCodegenMode(),
|
|
3998
|
+
gateway: packet.gateway,
|
|
3999
|
+
targets: targeting.targets,
|
|
3267
4000
|
workspaceListing,
|
|
3268
|
-
packet.requiredTests,
|
|
3269
|
-
packet.guardrails.deniedPaths,
|
|
4001
|
+
requiredTests: packet.requiredTests,
|
|
4002
|
+
deniedPaths: packet.guardrails.deniedPaths,
|
|
3270
4003
|
judgedByPool,
|
|
3271
4004
|
warnings,
|
|
3272
4005
|
contextLog,
|
|
3273
|
-
outOfScope
|
|
3274
|
-
|
|
4006
|
+
outOfScope,
|
|
4007
|
+
testDiscovery: packet.testDiscovery,
|
|
4008
|
+
skippedCases: targeting.skippedCases ?? [],
|
|
4009
|
+
out: codegenOut
|
|
4010
|
+
})
|
|
3275
4011
|
]);
|
|
3276
4012
|
generatedResults = results;
|
|
3277
4013
|
const depCheck = checkImportDependencies(
|
|
@@ -3407,6 +4143,7 @@ async function run(env2) {
|
|
|
3407
4143
|
targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0,
|
|
3408
4144
|
baselineFindings,
|
|
3409
4145
|
vanishedTests,
|
|
4146
|
+
codegenLoop: codegenOut.loop,
|
|
3410
4147
|
unresolved: failureReasons.length > 0 ? failureReasons : void 0
|
|
3411
4148
|
});
|
|
3412
4149
|
return { hardFailure };
|