@quikit/quikpilot-runner 9.1.0 → 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 +34 -0
- package/dist/index.js +1718 -196
- 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,9 +1132,1502 @@ function flushCodegenResults(results) {
|
|
|
1131
1132
|
}
|
|
1132
1133
|
}
|
|
1133
1134
|
|
|
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;
|
|
1143
|
+
}
|
|
1144
|
+
function resolveCodegenMode(env2 = process.env, packetSetting) {
|
|
1145
|
+
return parse(packetSetting) ?? parse(env2[CODEGEN_MODE_ENV]) ?? "single";
|
|
1146
|
+
}
|
|
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;
|
|
1158
|
+
}
|
|
1159
|
+
function pathOk(p) {
|
|
1160
|
+
return typeof p === "string" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;
|
|
1161
|
+
}
|
|
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;
|
|
1170
|
+
}
|
|
1171
|
+
if (!pathOk(r.path)) {
|
|
1172
|
+
cut = true;
|
|
1173
|
+
continue;
|
|
1174
|
+
}
|
|
1175
|
+
kept.push(r);
|
|
1176
|
+
}
|
|
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;
|
|
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 } : {} });
|
|
1204
|
+
}
|
|
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
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
|
|
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;
|
|
1228
|
+
}
|
|
1229
|
+
return false;
|
|
1230
|
+
}
|
|
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" };
|
|
1236
|
+
}
|
|
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" };
|
|
1244
|
+
}
|
|
1245
|
+
return { ok: true, path: normalised };
|
|
1246
|
+
}
|
|
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();
|
|
1253
|
+
}
|
|
1254
|
+
|
|
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
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
function newLedger() {
|
|
1299
|
+
return { toolCalls: 0, readChars: 0, resultChars: 0, refused: 0, seen: /* @__PURE__ */ new Map() };
|
|
1300
|
+
}
|
|
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);
|
|
1305
|
+
}
|
|
1306
|
+
function bad(message) {
|
|
1307
|
+
return { fail: { status: "bad_args", message } };
|
|
1308
|
+
}
|
|
1309
|
+
function optionalInt(v) {
|
|
1310
|
+
if (v === void 0 || v === null) return void 0;
|
|
1311
|
+
return typeof v === "number" && Number.isInteger(v) ? v : "bad";
|
|
1312
|
+
}
|
|
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;
|
|
1317
|
+
}
|
|
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." } };
|
|
1322
|
+
}
|
|
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." } };
|
|
1325
|
+
}
|
|
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." } };
|
|
1328
|
+
}
|
|
1329
|
+
return { ok: true, path: n.path };
|
|
1330
|
+
}
|
|
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 } : {} };
|
|
1341
|
+
}
|
|
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 } };
|
|
1428
|
+
}
|
|
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 } };
|
|
1456
|
+
}
|
|
1457
|
+
};
|
|
1458
|
+
}
|
|
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
|
+
}
|
|
1472
|
+
}
|
|
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" : ""}`;
|
|
1481
|
+
}
|
|
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
|
+
};
|
|
1551
|
+
}
|
|
1552
|
+
function budgetResult(reason) {
|
|
1553
|
+
return { status: "budget_exhausted", reason, message: "That limit has been reached; give your answer from what you have." };
|
|
1554
|
+
}
|
|
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." });
|
|
1572
|
+
}
|
|
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
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
var WorkspaceOverlay = class {
|
|
1628
|
+
entries = /* @__PURE__ */ new Map();
|
|
1629
|
+
get(path) {
|
|
1630
|
+
return this.entries.get(path);
|
|
1631
|
+
}
|
|
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
|
+
};
|
|
1682
|
+
}
|
|
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;
|
|
1690
|
+
try {
|
|
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);
|
|
1699
|
+
} catch {
|
|
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
|
+
};
|
|
1717
|
+
}
|
|
1718
|
+
return { ok: true, lf: toLf(text), ending, bom };
|
|
1719
|
+
}
|
|
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 };
|
|
1733
|
+
}
|
|
1734
|
+
function bad2(message) {
|
|
1735
|
+
return { fail: { status: "bad_args", message } };
|
|
1736
|
+
}
|
|
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
|
+
}
|
|
1760
|
+
};
|
|
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);
|
|
1764
|
+
}
|
|
1765
|
+
};
|
|
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";
|
|
1881
|
+
}
|
|
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;
|
|
1889
|
+
}
|
|
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++;
|
|
1912
|
+
}
|
|
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
|
+
);
|
|
1916
|
+
}
|
|
1917
|
+
function estimateRequestTokens(contextData) {
|
|
1918
|
+
return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
|
|
1919
|
+
}
|
|
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);
|
|
1949
|
+
}
|
|
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
|
+
}
|
|
1956
|
+
}
|
|
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);
|
|
1962
|
+
}
|
|
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
|
|
1999
|
+
}
|
|
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);
|
|
2047
|
+
}
|
|
2048
|
+
throw new LoopFailure("runtime_failed", runtimeCode);
|
|
2049
|
+
}
|
|
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 });
|
|
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;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
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;
|
|
2180
|
+
}
|
|
2181
|
+
};
|
|
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 };
|
|
2255
|
+
}
|
|
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();
|
|
2268
|
+
};
|
|
2269
|
+
log({ event: "codegen.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
|
|
2270
|
+
try {
|
|
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");
|
|
2281
|
+
}
|
|
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);
|
|
2288
|
+
}
|
|
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);
|
|
2306
|
+
}
|
|
2307
|
+
throw new CodegenLoopFailure("runtime_failed", runtimeCode);
|
|
2308
|
+
}
|
|
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");
|
|
2400
|
+
}
|
|
2401
|
+
}
|
|
2402
|
+
log({ event: "codegen.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
|
|
2403
|
+
}
|
|
2404
|
+
throw new CodegenLoopFailure("final_not_produced");
|
|
2405
|
+
} catch (err) {
|
|
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;
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
|
|
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
|
+
}
|
|
2514
|
+
|
|
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();
|
|
2532
|
+
}
|
|
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);
|
|
2538
|
+
}
|
|
2539
|
+
return [...found].sort();
|
|
2540
|
+
}
|
|
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
|
+
};
|
|
2569
|
+
}
|
|
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
|
+
);
|
|
2593
|
+
}
|
|
2594
|
+
async function runCodegenStep(p) {
|
|
2595
|
+
if (p.mode !== "loop") return perFile(p);
|
|
2596
|
+
try {
|
|
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}`);
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
return results;
|
|
2611
|
+
} catch (err) {
|
|
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);
|
|
2625
|
+
}
|
|
2626
|
+
}
|
|
2627
|
+
|
|
1134
2628
|
// src/dependencyCheck.ts
|
|
1135
|
-
var
|
|
1136
|
-
var
|
|
2629
|
+
var import_node_fs4 = require("node:fs");
|
|
2630
|
+
var import_node_path6 = require("node:path");
|
|
1137
2631
|
var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
|
|
1138
2632
|
var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
|
|
1139
2633
|
var NODE_BUILTINS = /* @__PURE__ */ new Set([
|
|
@@ -1212,14 +2706,14 @@ function dependencyNames(pkg) {
|
|
|
1212
2706
|
]);
|
|
1213
2707
|
}
|
|
1214
2708
|
function readDeclaredDependencies(results, workspaceRoot) {
|
|
1215
|
-
const packageJsonPath = (0,
|
|
1216
|
-
const generated = results.find((r) => (0,
|
|
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);
|
|
1217
2711
|
let raw;
|
|
1218
2712
|
if (generated) {
|
|
1219
2713
|
raw = generated.newContent;
|
|
1220
2714
|
} else {
|
|
1221
2715
|
try {
|
|
1222
|
-
raw = (0,
|
|
2716
|
+
raw = (0, import_node_fs4.readFileSync)(packageJsonPath, "utf8");
|
|
1223
2717
|
} catch {
|
|
1224
2718
|
raw = null;
|
|
1225
2719
|
}
|
|
@@ -1283,16 +2777,16 @@ function stripJsonComments(text) {
|
|
|
1283
2777
|
return out.replace(/,(\s*[}\]])/g, "$1");
|
|
1284
2778
|
}
|
|
1285
2779
|
function resolveAliasPrefixes(results, workspaceRoot) {
|
|
1286
|
-
const root = (0,
|
|
2780
|
+
const root = (0, import_node_path6.resolve)(workspaceRoot ?? ".");
|
|
1287
2781
|
for (const filename of ["tsconfig.json", "jsconfig.json"]) {
|
|
1288
|
-
const configPath = (0,
|
|
1289
|
-
const generated = results.find((r) => (0,
|
|
2782
|
+
const configPath = (0, import_node_path6.join)(root, filename);
|
|
2783
|
+
const generated = results.find((r) => (0, import_node_path6.resolve)(r.targetPath) === configPath);
|
|
1290
2784
|
let raw;
|
|
1291
2785
|
if (generated) {
|
|
1292
2786
|
raw = generated.newContent;
|
|
1293
2787
|
} else {
|
|
1294
2788
|
try {
|
|
1295
|
-
raw = (0,
|
|
2789
|
+
raw = (0, import_node_fs4.readFileSync)(configPath, "utf8");
|
|
1296
2790
|
} catch {
|
|
1297
2791
|
raw = null;
|
|
1298
2792
|
}
|
|
@@ -1365,108 +2859,6 @@ async function fetchGithubOidcToken(env2 = process.env) {
|
|
|
1365
2859
|
return body.value;
|
|
1366
2860
|
}
|
|
1367
2861
|
|
|
1368
|
-
// src/overlapCheck.ts
|
|
1369
|
-
var TEST_PATH_RE = /(\.(test|spec)\.[jt]sx?$)|(^|\/)(__tests__|tests?)\//i;
|
|
1370
|
-
function isTestTarget(path) {
|
|
1371
|
-
return TEST_PATH_RE.test(path);
|
|
1372
|
-
}
|
|
1373
|
-
var STOPWORDS = /* @__PURE__ */ new Set([
|
|
1374
|
-
"a",
|
|
1375
|
-
"an",
|
|
1376
|
-
"the",
|
|
1377
|
-
"is",
|
|
1378
|
-
"are",
|
|
1379
|
-
"was",
|
|
1380
|
-
"were",
|
|
1381
|
-
"be",
|
|
1382
|
-
"been",
|
|
1383
|
-
"being",
|
|
1384
|
-
"of",
|
|
1385
|
-
"to",
|
|
1386
|
-
"in",
|
|
1387
|
-
"on",
|
|
1388
|
-
"for",
|
|
1389
|
-
"with",
|
|
1390
|
-
"at",
|
|
1391
|
-
"by",
|
|
1392
|
-
"from",
|
|
1393
|
-
"as",
|
|
1394
|
-
"and",
|
|
1395
|
-
"or",
|
|
1396
|
-
"not",
|
|
1397
|
-
"no",
|
|
1398
|
-
"nor",
|
|
1399
|
-
"this",
|
|
1400
|
-
"that",
|
|
1401
|
-
"these",
|
|
1402
|
-
"those",
|
|
1403
|
-
"it",
|
|
1404
|
-
"its",
|
|
1405
|
-
"cannot",
|
|
1406
|
-
"can't",
|
|
1407
|
-
"should",
|
|
1408
|
-
"must",
|
|
1409
|
-
"may",
|
|
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;
|
|
1433
|
-
}
|
|
1434
|
-
function normalizedStep(step) {
|
|
1435
|
-
return step.trim().toLowerCase().replace(/\s+/g, " ");
|
|
1436
|
-
}
|
|
1437
|
-
var OVERLAP_THRESHOLD = 0.5;
|
|
1438
|
-
function findOverlappingSteps(targets) {
|
|
1439
|
-
const items = targets.flatMap(
|
|
1440
|
-
(target) => target.planStepsImplemented.map((step) => ({
|
|
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;
|
|
1463
|
-
}
|
|
1464
|
-
function describeOverlapWarnings(warnings) {
|
|
1465
|
-
return warnings.map(
|
|
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
|
-
);
|
|
1468
|
-
}
|
|
1469
|
-
|
|
1470
2862
|
// src/packet.ts
|
|
1471
2863
|
async function fetchPacket(packetUrl, runToken, githubRunId) {
|
|
1472
2864
|
const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
|
|
@@ -1484,30 +2876,30 @@ async function fetchPacket(packetUrl, runToken, githubRunId) {
|
|
|
1484
2876
|
}
|
|
1485
2877
|
|
|
1486
2878
|
// src/phase0.ts
|
|
1487
|
-
var
|
|
2879
|
+
var import_node_fs5 = require("node:fs");
|
|
1488
2880
|
function writePhase0Marker(runId) {
|
|
1489
|
-
(0,
|
|
1490
|
-
(0,
|
|
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}
|
|
1491
2883
|
`);
|
|
1492
2884
|
}
|
|
1493
2885
|
|
|
1494
2886
|
// src/quiktest.ts
|
|
1495
|
-
var
|
|
1496
|
-
var
|
|
2887
|
+
var import_node_fs6 = require("node:fs");
|
|
2888
|
+
var import_node_path7 = require("node:path");
|
|
1497
2889
|
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
|
|
1498
2890
|
function walkForJUnitByName(dir) {
|
|
1499
2891
|
let entries;
|
|
1500
2892
|
try {
|
|
1501
|
-
entries = (0,
|
|
2893
|
+
entries = (0, import_node_fs6.readdirSync)(dir);
|
|
1502
2894
|
} catch {
|
|
1503
2895
|
return null;
|
|
1504
2896
|
}
|
|
1505
2897
|
for (const entry of entries) {
|
|
1506
2898
|
if (SKIP_DIRS.has(entry)) continue;
|
|
1507
|
-
const full = (0,
|
|
2899
|
+
const full = (0, import_node_path7.join)(dir, entry);
|
|
1508
2900
|
let stat;
|
|
1509
2901
|
try {
|
|
1510
|
-
stat = (0,
|
|
2902
|
+
stat = (0, import_node_fs6.statSync)(full);
|
|
1511
2903
|
} catch {
|
|
1512
2904
|
continue;
|
|
1513
2905
|
}
|
|
@@ -1523,23 +2915,23 @@ function walkForJUnitByName(dir) {
|
|
|
1523
2915
|
function firstXmlIn(dir, namePattern) {
|
|
1524
2916
|
let entries;
|
|
1525
2917
|
try {
|
|
1526
|
-
entries = (0,
|
|
2918
|
+
entries = (0, import_node_fs6.readdirSync)(dir);
|
|
1527
2919
|
} catch {
|
|
1528
2920
|
return null;
|
|
1529
2921
|
}
|
|
1530
2922
|
const match = entries.find((e) => namePattern.test(e));
|
|
1531
|
-
return match ? (0,
|
|
2923
|
+
return match ? (0, import_node_path7.join)(dir, match) : null;
|
|
1532
2924
|
}
|
|
1533
2925
|
function readTestReportBytes(cwd = process.cwd()) {
|
|
1534
2926
|
try {
|
|
1535
2927
|
const report = findJUnitReport(cwd);
|
|
1536
|
-
return report ? (0,
|
|
2928
|
+
return report ? (0, import_node_fs6.readFileSync)(report) : null;
|
|
1537
2929
|
} catch {
|
|
1538
2930
|
return null;
|
|
1539
2931
|
}
|
|
1540
2932
|
}
|
|
1541
2933
|
function findJUnitReport(cwd = process.cwd()) {
|
|
1542
|
-
return walkForJUnitByName(cwd) ?? firstXmlIn((0,
|
|
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$/);
|
|
1543
2935
|
}
|
|
1544
2936
|
function buildCiUrl(serverUrl, repository, githubRunId) {
|
|
1545
2937
|
return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;
|
|
@@ -1563,8 +2955,8 @@ async function reportToQuikTest(params) {
|
|
|
1563
2955
|
try {
|
|
1564
2956
|
console.log(`reporting ${report}`);
|
|
1565
2957
|
const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
|
|
1566
|
-
const { readFileSync:
|
|
1567
|
-
const body =
|
|
2958
|
+
const { readFileSync: readFileSync8 } = await import("node:fs");
|
|
2959
|
+
const body = readFileSync8(report);
|
|
1568
2960
|
let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
|
|
1569
2961
|
if (generatedFiles) {
|
|
1570
2962
|
url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
|
|
@@ -1577,7 +2969,7 @@ async function reportToQuikTest(params) {
|
|
|
1577
2969
|
if (!res.ok) {
|
|
1578
2970
|
throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);
|
|
1579
2971
|
}
|
|
1580
|
-
(0,
|
|
2972
|
+
(0, import_node_fs6.rmSync)(report, { force: true });
|
|
1581
2973
|
let unmatched = [];
|
|
1582
2974
|
try {
|
|
1583
2975
|
const json = await res.json();
|
|
@@ -1593,11 +2985,11 @@ async function reportToQuikTest(params) {
|
|
|
1593
2985
|
|
|
1594
2986
|
// src/baselineCheck.ts
|
|
1595
2987
|
var import_node_child_process3 = require("node:child_process");
|
|
1596
|
-
var
|
|
1597
|
-
var
|
|
2988
|
+
var import_node_fs8 = require("node:fs");
|
|
2989
|
+
var import_node_path8 = require("node:path");
|
|
1598
2990
|
|
|
1599
2991
|
// src/regressionCheck.ts
|
|
1600
|
-
var
|
|
2992
|
+
var import_node_fs7 = require("node:fs");
|
|
1601
2993
|
var TESTCASE_RE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
|
|
1602
2994
|
var NAME_ATTR_RE = /\bname="([^"]*)"/;
|
|
1603
2995
|
var CLASSNAME_ATTR_RE = /\bclassname="([^"]*)"/;
|
|
@@ -1683,7 +3075,7 @@ function readJUnitOutcomes(cwd) {
|
|
|
1683
3075
|
const report = findJUnitReport(cwd);
|
|
1684
3076
|
if (!report) return null;
|
|
1685
3077
|
try {
|
|
1686
|
-
return parseJUnitOutcomes((0,
|
|
3078
|
+
return parseJUnitOutcomes((0, import_node_fs7.readFileSync)(report, "utf8"));
|
|
1687
3079
|
} catch {
|
|
1688
3080
|
return null;
|
|
1689
3081
|
}
|
|
@@ -1780,32 +3172,32 @@ function checkableIds(ids, types) {
|
|
|
1780
3172
|
});
|
|
1781
3173
|
}
|
|
1782
3174
|
function insideCheckout(cwd, path) {
|
|
1783
|
-
const abs = (0,
|
|
1784
|
-
const rel = (0,
|
|
1785
|
-
return rel === "" || rel.startsWith("..") || (0,
|
|
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;
|
|
1786
3178
|
}
|
|
1787
3179
|
function writeForCheck(abs, content) {
|
|
1788
|
-
const original = (0,
|
|
3180
|
+
const original = (0, import_node_fs8.existsSync)(abs) ? (0, import_node_fs8.readFileSync)(abs) : null;
|
|
1789
3181
|
const createdDirs = [];
|
|
1790
3182
|
if (original === null) {
|
|
1791
3183
|
const missing = [];
|
|
1792
|
-
for (let d = (0,
|
|
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);
|
|
1793
3185
|
for (const d of missing.reverse()) {
|
|
1794
|
-
(0,
|
|
3186
|
+
(0, import_node_fs8.mkdirSync)(d);
|
|
1795
3187
|
createdDirs.push(d);
|
|
1796
3188
|
}
|
|
1797
3189
|
}
|
|
1798
|
-
(0,
|
|
3190
|
+
(0, import_node_fs8.writeFileSync)(abs, content);
|
|
1799
3191
|
return { abs, original, createdDirs };
|
|
1800
3192
|
}
|
|
1801
3193
|
function restore(written) {
|
|
1802
3194
|
for (const file of [...written].reverse()) {
|
|
1803
3195
|
try {
|
|
1804
|
-
if (file.original !== null) (0,
|
|
1805
|
-
else (0,
|
|
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 });
|
|
1806
3198
|
for (const d of [...file.createdDirs].reverse()) {
|
|
1807
3199
|
try {
|
|
1808
|
-
(0,
|
|
3200
|
+
(0, import_node_fs8.rmdirSync)(d);
|
|
1809
3201
|
} catch {
|
|
1810
3202
|
}
|
|
1811
3203
|
}
|
|
@@ -1829,7 +3221,7 @@ function untrackedFiles(cwd) {
|
|
|
1829
3221
|
}
|
|
1830
3222
|
var mtimeOf = (path) => {
|
|
1831
3223
|
try {
|
|
1832
|
-
return (0,
|
|
3224
|
+
return (0, import_node_fs8.statSync)(path).mtimeMs;
|
|
1833
3225
|
} catch {
|
|
1834
3226
|
return null;
|
|
1835
3227
|
}
|
|
@@ -1843,7 +3235,7 @@ function decideCause(targets, results, cwd) {
|
|
|
1843
3235
|
const abs = insideCheckout(cwd, t.path);
|
|
1844
3236
|
if (next === void 0 || abs === null) return "ALREADY_TRUE";
|
|
1845
3237
|
try {
|
|
1846
|
-
if ((0,
|
|
3238
|
+
if ((0, import_node_fs8.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
|
|
1847
3239
|
} catch {
|
|
1848
3240
|
return "ALREADY_TRUE";
|
|
1849
3241
|
}
|
|
@@ -1919,7 +3311,7 @@ async function runBaselineCheck(params) {
|
|
|
1919
3311
|
for (const file of untrackedAfter) {
|
|
1920
3312
|
if (untrackedBefore.has(file)) continue;
|
|
1921
3313
|
const abs = insideCheckout(cwd, file);
|
|
1922
|
-
if (abs) (0,
|
|
3314
|
+
if (abs) (0, import_node_fs8.rmSync)(abs, { force: true });
|
|
1923
3315
|
}
|
|
1924
3316
|
}
|
|
1925
3317
|
}
|
|
@@ -1940,8 +3332,8 @@ async function runBaselineCheck(params) {
|
|
|
1940
3332
|
}
|
|
1941
3333
|
|
|
1942
3334
|
// src/failureArtifact.ts
|
|
1943
|
-
var
|
|
1944
|
-
var
|
|
3335
|
+
var import_node_fs9 = require("node:fs");
|
|
3336
|
+
var import_node_path9 = require("node:path");
|
|
1945
3337
|
|
|
1946
3338
|
// src/failureReason.ts
|
|
1947
3339
|
var MAX_FAILURE_REASON = 1e3;
|
|
@@ -1982,20 +3374,20 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
|
|
|
1982
3374
|
var REPORT_COPY = "final-test-report.xml";
|
|
1983
3375
|
var MAX_REPORT_BYTES = 5 * 1024 * 1024;
|
|
1984
3376
|
var MAX_FILES = 200;
|
|
1985
|
-
var RUNNER_VERSION = true ? "9.
|
|
3377
|
+
var RUNNER_VERSION = true ? "9.2.0-rc.3" : "dev";
|
|
1986
3378
|
function safeDestination(base, repoPath) {
|
|
1987
|
-
if (!repoPath || (0,
|
|
1988
|
-
const destination = (0,
|
|
1989
|
-
const rel = (0,
|
|
1990
|
-
if (!rel || rel.startsWith("..") || (0,
|
|
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;
|
|
1991
3383
|
return destination;
|
|
1992
3384
|
}
|
|
1993
3385
|
function writeFailureArtifact(input) {
|
|
1994
3386
|
if (input.results.length === 0) return { written: false };
|
|
1995
3387
|
try {
|
|
1996
|
-
const base = (0,
|
|
1997
|
-
(0,
|
|
1998
|
-
(0,
|
|
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 });
|
|
1999
3391
|
const files = [];
|
|
2000
3392
|
const skipped = [];
|
|
2001
3393
|
for (const result of input.results) {
|
|
@@ -2004,8 +3396,8 @@ function writeFailureArtifact(input) {
|
|
|
2004
3396
|
skipped.push(result.targetPath);
|
|
2005
3397
|
continue;
|
|
2006
3398
|
}
|
|
2007
|
-
(0,
|
|
2008
|
-
(0,
|
|
3399
|
+
(0, import_node_fs9.mkdirSync)((0, import_node_path9.dirname)(destination), { recursive: true });
|
|
3400
|
+
(0, import_node_fs9.writeFileSync)(destination, result.newContent);
|
|
2009
3401
|
files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
|
|
2010
3402
|
}
|
|
2011
3403
|
let testReport = "none";
|
|
@@ -2013,7 +3405,7 @@ function writeFailureArtifact(input) {
|
|
|
2013
3405
|
if (input.testReport.byteLength > MAX_REPORT_BYTES) {
|
|
2014
3406
|
testReport = "too-large";
|
|
2015
3407
|
} else {
|
|
2016
|
-
(0,
|
|
3408
|
+
(0, import_node_fs9.writeFileSync)((0, import_node_path9.join)(base, REPORT_COPY), input.testReport);
|
|
2017
3409
|
testReport = "included";
|
|
2018
3410
|
}
|
|
2019
3411
|
}
|
|
@@ -2033,8 +3425,8 @@ function writeFailureArtifact(input) {
|
|
|
2033
3425
|
failureReasons: input.failureReasons
|
|
2034
3426
|
};
|
|
2035
3427
|
const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
|
|
2036
|
-
(0,
|
|
2037
|
-
return { written: (0,
|
|
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")) };
|
|
2038
3430
|
} catch (err) {
|
|
2039
3431
|
console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
|
|
2040
3432
|
return { written: false };
|
|
@@ -2042,7 +3434,7 @@ function writeFailureArtifact(input) {
|
|
|
2042
3434
|
}
|
|
2043
3435
|
|
|
2044
3436
|
// src/scopeCheck.ts
|
|
2045
|
-
var
|
|
3437
|
+
var import_node_fs10 = require("node:fs");
|
|
2046
3438
|
var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
|
|
2047
3439
|
var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
|
|
2048
3440
|
var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
|
|
@@ -2099,7 +3491,7 @@ function checkApiScope(results, targets, apiChanges) {
|
|
|
2099
3491
|
} else {
|
|
2100
3492
|
let currentContent;
|
|
2101
3493
|
try {
|
|
2102
|
-
currentContent = (0,
|
|
3494
|
+
currentContent = (0, import_node_fs10.readFileSync)(targetPath, "utf8");
|
|
2103
3495
|
} catch {
|
|
2104
3496
|
currentContent = "";
|
|
2105
3497
|
}
|
|
@@ -2118,7 +3510,24 @@ function describeScopeViolations(check) {
|
|
|
2118
3510
|
}
|
|
2119
3511
|
|
|
2120
3512
|
// src/targeting.ts
|
|
2121
|
-
var
|
|
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";
|
|
3528
|
+
}
|
|
3529
|
+
|
|
3530
|
+
// src/targeting.ts
|
|
2122
3531
|
var CONTRACT_VERSION2 = "test-targets-1";
|
|
2123
3532
|
function listWorkspaceFiles(workspaceRoot) {
|
|
2124
3533
|
return listFiles(workspaceRoot ?? ".");
|
|
@@ -2126,13 +3535,13 @@ function listWorkspaceFiles(workspaceRoot) {
|
|
|
2126
3535
|
function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
|
|
2127
3536
|
const denied = matchesDeniedPath(target.path, deniedPaths);
|
|
2128
3537
|
if (denied) {
|
|
2129
|
-
throw new
|
|
3538
|
+
throw new DeniedPathError(
|
|
2130
3539
|
`pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`
|
|
2131
3540
|
);
|
|
2132
3541
|
}
|
|
2133
3542
|
const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);
|
|
2134
3543
|
if (deniedContext) {
|
|
2135
|
-
throw new
|
|
3544
|
+
throw new DeniedPathError(
|
|
2136
3545
|
`pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`
|
|
2137
3546
|
);
|
|
2138
3547
|
}
|
|
@@ -2147,15 +3556,15 @@ function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
|
|
|
2147
3556
|
}
|
|
2148
3557
|
return;
|
|
2149
3558
|
}
|
|
2150
|
-
const root = (0,
|
|
2151
|
-
const rel = (0,
|
|
2152
|
-
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)) {
|
|
2153
3562
|
throw new Error(
|
|
2154
3563
|
`pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
|
|
2155
3564
|
);
|
|
2156
3565
|
}
|
|
2157
3566
|
}
|
|
2158
|
-
|
|
3567
|
+
function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope) {
|
|
2159
3568
|
const contextData = {
|
|
2160
3569
|
// NESTED, NOT FLATTENED — a second vocabulary for the design shape is exactly what
|
|
2161
3570
|
// QUIKTR-1034 cost.
|
|
@@ -2174,6 +3583,9 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
|
|
|
2174
3583
|
contextData.outOfScope = outOfScope;
|
|
2175
3584
|
}
|
|
2176
3585
|
contextData.testDiscovery = testDiscovery;
|
|
3586
|
+
return contextData;
|
|
3587
|
+
}
|
|
3588
|
+
async function postTargeting(gateway, contextData, signal) {
|
|
2177
3589
|
const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
|
|
2178
3590
|
method: "POST",
|
|
2179
3591
|
headers: { "content-type": "application/json", "x-run-token": gateway.token },
|
|
@@ -2183,14 +3595,15 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
|
|
|
2183
3595
|
expectedOutputType: "json",
|
|
2184
3596
|
userPrompt: "",
|
|
2185
3597
|
contextData
|
|
2186
|
-
})
|
|
3598
|
+
}),
|
|
3599
|
+
...signal ? { signal } : {}
|
|
2187
3600
|
});
|
|
2188
3601
|
if (!res.ok) {
|
|
2189
|
-
throw new
|
|
3602
|
+
throw new TargetingHttpError(res.status, res.statusText);
|
|
2190
3603
|
}
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
3604
|
+
return res.json();
|
|
3605
|
+
}
|
|
3606
|
+
function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
|
|
2194
3607
|
if (body.outcome === "NO_TARGET") {
|
|
2195
3608
|
return { outcome: "NO_TARGET", reason: body.noTargetReason ?? null };
|
|
2196
3609
|
}
|
|
@@ -2219,6 +3632,66 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
|
|
|
2219
3632
|
...correctedKinds.length > 0 ? { correctedKinds } : {}
|
|
2220
3633
|
};
|
|
2221
3634
|
}
|
|
3635
|
+
async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = []) {
|
|
3636
|
+
const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
|
|
3637
|
+
const envelope = await postTargeting(gateway, contextData);
|
|
3638
|
+
checkHardFailure(envelope, "pilot.targeting");
|
|
3639
|
+
const body = unwrapExecute(envelope, "pilot.targeting");
|
|
3640
|
+
return finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);
|
|
3641
|
+
}
|
|
3642
|
+
var CODE_LIKE = /^[A-Z0-9_]{1,40}$/;
|
|
3643
|
+
async function runTargeting(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], options = {}) {
|
|
3644
|
+
const mode = options.mode ?? resolveTargetingMode();
|
|
3645
|
+
if (mode !== "loop") {
|
|
3646
|
+
return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
|
|
3647
|
+
}
|
|
3648
|
+
const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
|
|
3649
|
+
let summary;
|
|
3650
|
+
let runtimeCode;
|
|
3651
|
+
let reason;
|
|
3652
|
+
try {
|
|
3653
|
+
const looped = await runTargetingLoop(
|
|
3654
|
+
{ baseContext, listing: workspaceListing, deniedPaths },
|
|
3655
|
+
{ ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
|
|
3656
|
+
);
|
|
3657
|
+
summary = looped.summary;
|
|
3658
|
+
const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
|
|
3659
|
+
return { ...result, loop: summary };
|
|
3660
|
+
} catch (err) {
|
|
3661
|
+
if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;
|
|
3662
|
+
if (err instanceof LoopFailure) {
|
|
3663
|
+
reason = err.reason;
|
|
3664
|
+
runtimeCode = err.runtimeCode;
|
|
3665
|
+
summary = err.summary ?? summary;
|
|
3666
|
+
} else {
|
|
3667
|
+
reason = "final_invalid";
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
const fellBack = {
|
|
3671
|
+
turns: summary?.turns ?? 0,
|
|
3672
|
+
toolCalls: summary?.toolCalls ?? 0,
|
|
3673
|
+
readChars: summary?.readChars ?? 0,
|
|
3674
|
+
refused: summary?.refused ?? 0,
|
|
3675
|
+
reads: summary?.reads ?? [],
|
|
3676
|
+
stopReason: "fallback",
|
|
3677
|
+
fellBack: true,
|
|
3678
|
+
fallbackReason: reason
|
|
3679
|
+
};
|
|
3680
|
+
const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
|
|
3681
|
+
log({
|
|
3682
|
+
event: "targeting.loop_fallback",
|
|
3683
|
+
reason,
|
|
3684
|
+
turn: fellBack.turns,
|
|
3685
|
+
toolCalls: fellBack.toolCalls,
|
|
3686
|
+
...runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}
|
|
3687
|
+
});
|
|
3688
|
+
const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
|
|
3689
|
+
return {
|
|
3690
|
+
...single,
|
|
3691
|
+
loop: fellBack,
|
|
3692
|
+
warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`]
|
|
3693
|
+
};
|
|
3694
|
+
}
|
|
2222
3695
|
|
|
2223
3696
|
// src/targetingRecord.ts
|
|
2224
3697
|
var MAX_TARGETS = 25;
|
|
@@ -2228,9 +3701,11 @@ var MAX_ADDED_PATHS = 20;
|
|
|
2228
3701
|
var MAX_SKIPPED_CONTEXT = 20;
|
|
2229
3702
|
var MAX_SKIPPED_CASES = 200;
|
|
2230
3703
|
var MAX_CONTEXT_RECORDS = 25;
|
|
2231
|
-
var
|
|
2232
|
-
var
|
|
3704
|
+
var MAX_PATH_CHARS2 = 300;
|
|
3705
|
+
var MAX_ID_CHARS3 = 100;
|
|
2233
3706
|
var MAX_REASON_CHARS = 300;
|
|
3707
|
+
var MAX_LOOP_READS = 50;
|
|
3708
|
+
var MAX_FALLBACK_REASON_CHARS = 40;
|
|
2234
3709
|
function clampList(values, max, maxChars) {
|
|
2235
3710
|
let cut = false;
|
|
2236
3711
|
const kept = [];
|
|
@@ -2245,6 +3720,41 @@ function clampList(values, max, maxChars) {
|
|
|
2245
3720
|
}
|
|
2246
3721
|
return { kept, cut };
|
|
2247
3722
|
}
|
|
3723
|
+
function wholeNumber(n) {
|
|
3724
|
+
return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
|
|
3725
|
+
}
|
|
3726
|
+
function clampLoop(loop) {
|
|
3727
|
+
let cut = false;
|
|
3728
|
+
const reads = [];
|
|
3729
|
+
for (const r of loop.reads ?? []) {
|
|
3730
|
+
if (reads.length >= MAX_LOOP_READS) {
|
|
3731
|
+
cut = true;
|
|
3732
|
+
break;
|
|
3733
|
+
}
|
|
3734
|
+
const path = typeof r.path === "string" ? r.path.trim() : "";
|
|
3735
|
+
if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
|
|
3736
|
+
cut = true;
|
|
3737
|
+
continue;
|
|
3738
|
+
}
|
|
3739
|
+
reads.push({
|
|
3740
|
+
path,
|
|
3741
|
+
...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
|
|
3742
|
+
...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
|
|
3743
|
+
chars: wholeNumber(r.chars),
|
|
3744
|
+
...r.refused ? { refused: true } : {}
|
|
3745
|
+
});
|
|
3746
|
+
}
|
|
3747
|
+
return {
|
|
3748
|
+
turns: wholeNumber(loop.turns),
|
|
3749
|
+
toolCalls: wholeNumber(loop.toolCalls),
|
|
3750
|
+
refused: wholeNumber(loop.refused),
|
|
3751
|
+
stopReason: loop.stopReason,
|
|
3752
|
+
...loop.fellBack ? { fellBack: true } : {},
|
|
3753
|
+
...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {},
|
|
3754
|
+
reads,
|
|
3755
|
+
...cut ? { truncated: true } : {}
|
|
3756
|
+
};
|
|
3757
|
+
}
|
|
2248
3758
|
function buildTargetingRecord(targeting, contextLog) {
|
|
2249
3759
|
let truncated = false;
|
|
2250
3760
|
const note = (cut) => {
|
|
@@ -2257,6 +3767,7 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
2257
3767
|
record2.noTargetReason = reason.slice(0, MAX_REASON_CHARS);
|
|
2258
3768
|
if (reason.length > MAX_REASON_CHARS) record2.noTargetReasonTruncated = true;
|
|
2259
3769
|
}
|
|
3770
|
+
if (targeting.loop) record2.loop = clampLoop(targeting.loop);
|
|
2260
3771
|
return record2;
|
|
2261
3772
|
}
|
|
2262
3773
|
const targets = [];
|
|
@@ -2266,12 +3777,12 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
2266
3777
|
break;
|
|
2267
3778
|
}
|
|
2268
3779
|
const path = typeof t.path === "string" ? t.path.trim() : "";
|
|
2269
|
-
if (path.length === 0 || path.length >
|
|
3780
|
+
if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
|
|
2270
3781
|
truncated = true;
|
|
2271
3782
|
continue;
|
|
2272
3783
|
}
|
|
2273
|
-
const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS,
|
|
2274
|
-
const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET,
|
|
3784
|
+
const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
|
|
3785
|
+
const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
|
|
2275
3786
|
note(contextPaths.cut);
|
|
2276
3787
|
note(automationIds.cut);
|
|
2277
3788
|
targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });
|
|
@@ -2279,7 +3790,7 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
2279
3790
|
const skipped = clampList(
|
|
2280
3791
|
(targeting.skippedCases ?? []).map((c) => c.automationId),
|
|
2281
3792
|
MAX_SKIPPED_CASES,
|
|
2282
|
-
|
|
3793
|
+
MAX_ID_CHARS3
|
|
2283
3794
|
);
|
|
2284
3795
|
note(skipped.cut);
|
|
2285
3796
|
const codegenContext = [];
|
|
@@ -2289,16 +3800,16 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
2289
3800
|
break;
|
|
2290
3801
|
}
|
|
2291
3802
|
const targetPath = typeof entry.targetPath === "string" ? entry.targetPath.trim() : "";
|
|
2292
|
-
if (targetPath.length === 0 || targetPath.length >
|
|
3803
|
+
if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS2) {
|
|
2293
3804
|
truncated = true;
|
|
2294
3805
|
continue;
|
|
2295
3806
|
}
|
|
2296
|
-
const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS,
|
|
2297
|
-
const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS,
|
|
3807
|
+
const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
|
|
3808
|
+
const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS2);
|
|
2298
3809
|
const skippedPaths = clampList(
|
|
2299
3810
|
(entry.skipped ?? []).map((s) => s.path),
|
|
2300
3811
|
MAX_SKIPPED_CONTEXT,
|
|
2301
|
-
|
|
3812
|
+
MAX_PATH_CHARS2
|
|
2302
3813
|
);
|
|
2303
3814
|
note(contextPaths.cut);
|
|
2304
3815
|
note(addedPaths.cut);
|
|
@@ -2319,6 +3830,7 @@ function buildTargetingRecord(targeting, contextLog) {
|
|
|
2319
3830
|
codegenContext
|
|
2320
3831
|
};
|
|
2321
3832
|
if (truncated) record.truncated = true;
|
|
3833
|
+
if (targeting.loop) record.loop = clampLoop(targeting.loop);
|
|
2322
3834
|
return record;
|
|
2323
3835
|
}
|
|
2324
3836
|
|
|
@@ -2414,6 +3926,7 @@ async function run(env2) {
|
|
|
2414
3926
|
let baselineFindings;
|
|
2415
3927
|
let vanishedTests;
|
|
2416
3928
|
const contextLog = [];
|
|
3929
|
+
const codegenOut = {};
|
|
2417
3930
|
try {
|
|
2418
3931
|
runToken = await exchangeForRunToken(env2.tokenUrl, await fetchGithubOidcToken());
|
|
2419
3932
|
packet = await fetchPacket(env2.packetUrl, runToken, env2.githubRunId);
|
|
@@ -2431,6 +3944,10 @@ async function run(env2) {
|
|
|
2431
3944
|
outOfScope
|
|
2432
3945
|
);
|
|
2433
3946
|
targetingResult = targeting;
|
|
3947
|
+
for (const w of targeting.warnings ?? []) {
|
|
3948
|
+
warnings.push(w);
|
|
3949
|
+
console.warn(`QuikPilot targeting warning (not blocking): ${w}`);
|
|
3950
|
+
}
|
|
2434
3951
|
if (targeting.outcome === "TARGETED") {
|
|
2435
3952
|
for (const path of targeting.correctedKinds ?? []) {
|
|
2436
3953
|
const w = `QuikPilot named ${path} as a new file, but it already exists in the repository. It was treated as an existing file so its current content was kept in view.`;
|
|
@@ -2476,17 +3993,21 @@ async function run(env2) {
|
|
|
2476
3993
|
);
|
|
2477
3994
|
const [baseline, results] = await Promise.all([
|
|
2478
3995
|
captureBaselineSnapshot(packet.commands.test),
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
3996
|
+
runCodegenStep({
|
|
3997
|
+
mode: resolveCodegenMode(),
|
|
3998
|
+
gateway: packet.gateway,
|
|
3999
|
+
targets: targeting.targets,
|
|
2482
4000
|
workspaceListing,
|
|
2483
|
-
packet.requiredTests,
|
|
2484
|
-
packet.guardrails.deniedPaths,
|
|
4001
|
+
requiredTests: packet.requiredTests,
|
|
4002
|
+
deniedPaths: packet.guardrails.deniedPaths,
|
|
2485
4003
|
judgedByPool,
|
|
2486
4004
|
warnings,
|
|
2487
4005
|
contextLog,
|
|
2488
|
-
outOfScope
|
|
2489
|
-
|
|
4006
|
+
outOfScope,
|
|
4007
|
+
testDiscovery: packet.testDiscovery,
|
|
4008
|
+
skippedCases: targeting.skippedCases ?? [],
|
|
4009
|
+
out: codegenOut
|
|
4010
|
+
})
|
|
2490
4011
|
]);
|
|
2491
4012
|
generatedResults = results;
|
|
2492
4013
|
const depCheck = checkImportDependencies(
|
|
@@ -2622,6 +4143,7 @@ async function run(env2) {
|
|
|
2622
4143
|
targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0,
|
|
2623
4144
|
baselineFindings,
|
|
2624
4145
|
vanishedTests,
|
|
4146
|
+
codegenLoop: codegenOut.loop,
|
|
2625
4147
|
unresolved: failureReasons.length > 0 ? failureReasons : void 0
|
|
2626
4148
|
});
|
|
2627
4149
|
return { hardFailure };
|