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