@sagentlab/navarch-runtime 0.1.173 → 0.1.174

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.
@@ -6,14 +6,17 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEPENDENCY_CACHE_DIRNAME = void 0;
7
7
  exports.npmEnvironment = npmEnvironment;
8
8
  exports.prepareDependencyCache = prepareDependencyCache;
9
+ exports.pullRequestNumberInRepository = pullRequestNumberInRepository;
9
10
  exports.dependencyCacheKey = dependencyCacheKey;
10
11
  exports.renderDependencyCacheNote = renderDependencyCacheNote;
11
12
  exports.lockfileRefusal = lockfileRefusal;
12
13
  exports.npmrcRefusal = npmrcRefusal;
13
14
  exports.copyTree = copyTree;
15
+ const node_child_process_1 = require("node:child_process");
14
16
  const node_crypto_1 = require("node:crypto");
15
17
  const node_fs_1 = require("node:fs");
16
18
  const node_path_1 = __importDefault(require("node:path"));
19
+ const node_util_1 = require("node:util");
17
20
  const logger_cjs_1 = require("./logger.cjs");
18
21
  const sandbox_cjs_1 = require("./sandbox.cjs");
19
22
  /**
@@ -47,6 +50,10 @@ const sandbox_cjs_1 = require("./sandbox.cjs");
47
50
  * become part of a commit or replace files the checkout already has.
48
51
  * - npm workspaces are skipped: their install also writes into the
49
52
  * workspace packages, which a root-level copy does not reproduce.
53
+ * - A session that checks another commit (a verify or review of a pull
54
+ * request) passes that commit as `inputsCommit`. The install inputs are
55
+ * then read from that commit's tree, so the prepared tree matches the pull
56
+ * request's lockfile and not the claim commit's. The same refusals apply.
50
57
  *
51
58
  * Every step degrades to a recorded `skipped`/`failed` result. Dependency
52
59
  * preparation never fails the session.
@@ -87,12 +94,19 @@ function npmEnvironment(env) {
87
94
  return out;
88
95
  }
89
96
  async function prepareDependencyCache(options) {
97
+ if (options.signal?.aborted)
98
+ return [];
90
99
  const runner = options.runner ?? sandbox_cjs_1.nodeCommandRunner;
91
100
  const npmBin = options.npmBin ?? "npm";
92
101
  const env = npmEnvironment(options.env ?? process.env);
93
- const dirs = await trackedLockfileDirs(runner, options.worktreePath);
102
+ const commitDirs = options.inputsCommit && /^[0-9a-f]{40,64}$/i.test(options.inputsCommit)
103
+ ? await commitLockfileDirs(runner, options.worktreePath, options.inputsCommit)
104
+ : null;
105
+ const inputsCommit = commitDirs ? options.inputsCommit : undefined;
106
+ const dirs = commitDirs ?? await trackedLockfileDirs(runner, options.worktreePath);
94
107
  if (dirs.length === 0)
95
108
  return [];
109
+ const source = inputsCommit ? { inputsCommit } : {};
96
110
  let npmVersion = null;
97
111
  const results = [];
98
112
  for (const dir of dirs) {
@@ -104,34 +118,42 @@ async function prepareDependencyCache(options) {
104
118
  results.push({ dir, status: "present" });
105
119
  continue;
106
120
  }
121
+ // A package directory the other commit adds has no place in this checkout.
122
+ if (inputsCommit && !(await exists(node_path_1.default.join(options.worktreePath, dir)))) {
123
+ results.push({ dir, status: "skipped", detail: "this directory is not in the session checkout", ...source });
124
+ continue;
125
+ }
107
126
  if (!(await isIgnored(runner, options.worktreePath, node_path_1.default.join(dir, "node_modules")))) {
108
127
  results.push({ dir, status: "skipped", detail: "node_modules is not ignored by git in this checkout" });
109
128
  continue;
110
129
  }
111
- const packageJson = await readInput(node_path_1.default.join(options.worktreePath, dir, "package.json"));
112
- const lockfile = await readInput(node_path_1.default.join(options.worktreePath, dir, LOCKFILE));
113
- const npmrc = await readInput(node_path_1.default.join(options.worktreePath, dir, ".npmrc"));
130
+ const read = (name) => inputsCommit
131
+ ? readCommitInput(options.worktreePath, inputsCommit, dir === "." ? name : `${dir}/${name}`)
132
+ : readInput(node_path_1.default.join(options.worktreePath, dir, name));
133
+ const packageJson = await read("package.json");
134
+ const lockfile = await read(LOCKFILE);
135
+ const npmrc = await read(".npmrc");
114
136
  const unreadable = [packageJson, lockfile, npmrc].find((input) => input.state === "invalid");
115
137
  if (unreadable?.state === "invalid") {
116
- results.push({ dir, status: "skipped", detail: unreadable.detail });
138
+ results.push({ dir, status: "skipped", detail: unreadable.detail, ...source });
117
139
  continue;
118
140
  }
119
141
  if (packageJson.state !== "file" || lockfile.state !== "file") {
120
- results.push({ dir, status: "skipped", detail: "no package.json next to package-lock.json" });
142
+ results.push({ dir, status: "skipped", detail: "no package.json next to package-lock.json", ...source });
121
143
  continue;
122
144
  }
123
145
  if (usesWorkspaces(packageJson.data)) {
124
- results.push({ dir, status: "skipped", detail: "npm workspaces are not supported by the dependency cache" });
146
+ results.push({ dir, status: "skipped", detail: "npm workspaces are not supported by the dependency cache", ...source });
125
147
  continue;
126
148
  }
127
149
  const refusal = lockfileRefusal(lockfile.data) ?? (npmrc.state === "file" ? npmrcRefusal(npmrc.data) : null);
128
150
  if (refusal) {
129
- results.push({ dir, status: "skipped", detail: refusal });
151
+ results.push({ dir, status: "skipped", detail: refusal, ...source });
130
152
  continue;
131
153
  }
132
154
  npmVersion ??= await readNpmVersion(runner, npmBin, env);
133
155
  if (!npmVersion) {
134
- results.push({ dir, status: "failed", detail: "npm is not available to the runtime" });
156
+ results.push({ dir, status: "failed", detail: "npm is not available to the runtime", ...source });
135
157
  continue;
136
158
  }
137
159
  const inputs = {
@@ -197,19 +219,32 @@ async function prepareDependencyCache(options) {
197
219
  }
198
220
  }
199
221
  if (failure) {
200
- results.push({ dir, status: "failed", key, detail: failure });
222
+ results.push({ dir, status: "failed", key, detail: failure, ...source });
201
223
  continue;
202
224
  }
203
- results.push({ dir, status, key });
225
+ results.push({ dir, status, key, ...source });
204
226
  await pruneEntries(options.cacheRoot, options.repository, dir, options.keepPerLockfile ?? DEFAULT_KEEP_PER_LOCKFILE)
205
227
  .catch((error) => log.warn(`dependency cache prune failed: ${String(error)}`));
206
228
  }
207
229
  catch (error) {
208
- results.push({ dir, status: "failed", detail: `unexpected error: ${error.message ?? String(error)}` });
230
+ results.push({ dir, status: "failed", detail: `unexpected error: ${error.message ?? String(error)}`, ...source });
209
231
  }
210
232
  }
211
233
  return results;
212
234
  }
235
+ /**
236
+ * The pull request number when `url` is a pull request of `repository`
237
+ * ("owner/name"), else null. A verify or review task carries its pull
238
+ * request in `github_issue_url`; a task that links an issue has no head to
239
+ * prepare for.
240
+ */
241
+ function pullRequestNumberInRepository(url, repository) {
242
+ const match = /^https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/(\d{1,10})(?:[/?#]|$)/i.exec(url ?? "");
243
+ if (!match || match[1].toLowerCase() !== repository.toLowerCase())
244
+ return null;
245
+ const number = Number(match[2]);
246
+ return number > 0 ? number : null;
247
+ }
213
248
  function dependencyCacheKey(input) {
214
249
  return sha256(Buffer.from(JSON.stringify({
215
250
  v: KEY_VERSION,
@@ -229,7 +264,9 @@ function dependencyCacheKey(input) {
229
264
  * Prompt section that tells the agent what the runtime prepared. Returns null
230
265
  * when the worktree has no tracked lockfile, so unrelated sessions see nothing.
231
266
  */
232
- function renderDependencyCacheNote(results) {
267
+ function renderDependencyCacheNote(results,
268
+ /** The pull request under check, even when its head could not be read. */
269
+ pullRequestNumber) {
233
270
  if (results.length === 0)
234
271
  return null;
235
272
  const label = (dir) => (dir === "." ? "`node_modules`" : `\`${dir}/node_modules\``);
@@ -237,10 +274,20 @@ function renderDependencyCacheNote(results) {
237
274
  const notReady = results.filter((r) => r.status === "skipped" || r.status === "failed");
238
275
  const lines = ["## Prepared dependencies", ""];
239
276
  if (ready.length > 0) {
240
- lines.push(`Navarch installed locked dependencies before this session started: ${ready.map((r) => `${label(r.dir)} (cache ${r.status === "hit" ? "hit" : "built"}, key \`${r.key.slice(0, 12)}\`)`).join(", ")}.`, "The runtime ran `npm ci --ignore-scripts` outside the sandbox, keyed on the repository, `package-lock.json`, `package.json`, `.npmrc`, Node, npm, and platform, and copied the result into this checkout.", "Use these directories for local tests, type checks, and builds. Do not run `npm ci` or `npm install`: the sandbox has no registry access.", "Lifecycle scripts did not run. If a step fails because a package needs its install script (for example a native addon build), report that exact package and command as a capability gap.");
277
+ lines.push(`Navarch installed locked dependencies before this session started: ${ready.map((r) => `${label(r.dir)} (cache ${r.status === "hit" ? "hit" : "built"}, key \`${r.key.slice(0, 12)}\`)`).join(", ")}.`, "The runtime ran `npm ci --ignore-scripts` outside the sandbox, keyed on the repository, `package-lock.json`, `package.json`, `.npmrc`, Node, npm, and platform, and copied the result into this checkout.", "Use these directories for local tests, type checks, and builds when their install inputs match. Do not run `npm ci` or `npm install`: the sandbox has no registry access.", "Lifecycle scripts did not run. If a step fails because a package needs its install script (for example a native addon build), report that exact package and command as a capability gap.");
278
+ const commit = ready.find((r) => r.inputsCommit)?.inputsCommit;
279
+ if (commit) {
280
+ const subject = pullRequestNumber ? `pull request #${pullRequestNumber}'s head` : "the commit under check,";
281
+ lines.push(`The install inputs (\`package.json\`, \`package-lock.json\`, \`.npmrc\`) came from ${subject} \`${commit.slice(0, 12)}\`, not from this checkout's claim commit, so the packages match the change you check.`, "Link or copy these directories into the detached worktree where you check that commit out. If the head moved and any install input changed, record the affected checks as `NOT RUN (prepared dependencies are for an older head)`.");
282
+ }
283
+ else if (pullRequestNumber) {
284
+ lines.push(`The runtime could not read the head of pull request #${pullRequestNumber} and used the session checkout's install inputs.`, "Before reusing these packages in the detached worktree, compare `package.json`, `package-lock.json`, and `.npmrc` for each package directory. If any input differs, record the affected checks as `NOT RUN (prepared dependencies use different install inputs)`.");
285
+ }
241
286
  }
242
287
  for (const r of results.filter((result) => result.status === "present")) {
243
288
  lines.push(`${label(r.dir)} was already in the checkout, so the runtime left it unchanged.`);
289
+ if (pullRequestNumber)
290
+ lines.push("Confirm that these existing packages match the pull request's install inputs before using them.");
244
291
  }
245
292
  for (const r of notReady) {
246
293
  lines.push(`${label(r.dir)} was not prepared (${r.status}): ${r.detail ?? "no detail"}.`);
@@ -251,14 +298,30 @@ async function trackedLockfileDirs(runner, worktreePath) {
251
298
  const listed = await runner.run("git", ["-C", worktreePath, "ls-files", "-z", "--", LOCKFILE, `*/${LOCKFILE}`], { timeoutMs: 30_000 });
252
299
  if (listed.code !== 0)
253
300
  return [];
254
- const dirs = listed.stdout
255
- .split("\0")
256
- .filter(Boolean)
301
+ return selectLockfileDirs(listed.stdout.split("\0").filter(Boolean));
302
+ }
303
+ /** Root and first-level directories only, root first, never a vendored node_modules copy. */
304
+ function selectLockfileDirs(files) {
305
+ const dirs = files
257
306
  .map((file) => node_path_1.default.posix.dirname(file))
258
- // Root and first-level packages only, never a vendored node_modules copy.
259
307
  .filter((dir) => dir === "." || (!dir.includes("/") && dir !== "node_modules"));
260
308
  return [...new Set(dirs)].sort((a, b) => (a === "." ? -1 : b === "." ? 1 : a.localeCompare(b))).slice(0, MAX_LOCKFILES);
261
309
  }
310
+ /**
311
+ * Lockfile directories in a commit's tree, or null when git cannot read the
312
+ * commit. `ls-tree` takes literal paths, so the first-level directories are
313
+ * listed first and each one's lockfile path is then looked up by name.
314
+ */
315
+ async function commitLockfileDirs(runner, worktreePath, commit) {
316
+ const top = await runner.run("git", ["-C", worktreePath, "ls-tree", "-d", "-z", "--name-only", `${commit}^{commit}`], { timeoutMs: 30_000 });
317
+ if (top.code !== 0)
318
+ return null;
319
+ const candidates = [LOCKFILE, ...top.stdout.split("\0").filter(Boolean).map((dir) => `${dir}/${LOCKFILE}`)];
320
+ const listed = await runner.run("git", ["-C", worktreePath, "ls-tree", "-z", "--name-only", commit, "--", ...candidates], { timeoutMs: 30_000 });
321
+ if (listed.code !== 0)
322
+ return null;
323
+ return selectLockfileDirs(listed.stdout.split("\0").filter(Boolean));
324
+ }
262
325
  async function isIgnored(runner, worktreePath, relativePath) {
263
326
  const result = await runner.run("git", ["-C", worktreePath, "check-ignore", "-q", "--", `${relativePath.split(node_path_1.default.sep).join("/")}/`], { timeoutMs: 30_000 });
264
327
  return result.code === 0;
@@ -553,6 +616,40 @@ async function readInput(file) {
553
616
  await handle.close();
554
617
  }
555
618
  }
619
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
620
+ /**
621
+ * Reads an install input from a commit's tree. Only a regular blob counts: a
622
+ * symlink or submodule entry is refused, as `readInput` refuses a link. The
623
+ * bytes come straight from git, so the cache key equals the one computed from
624
+ * the same file in a checkout.
625
+ */
626
+ async function readCommitInput(worktreePath, commit, file) {
627
+ const name = node_path_1.default.posix.basename(file);
628
+ const unreadable = { state: "invalid", detail: `${name} could not be read from commit ${commit.slice(0, 12)}` };
629
+ let line;
630
+ try {
631
+ const listed = await execFileAsync("git", ["-C", worktreePath, "ls-tree", "-l", "-z", commit, "--", file], { encoding: "buffer", timeout: 30_000 });
632
+ line = listed.stdout.toString("utf8").split("\0").find(Boolean);
633
+ }
634
+ catch {
635
+ return unreadable;
636
+ }
637
+ if (!line)
638
+ return { state: "absent" };
639
+ const match = /^(\d{6}) (\w+) ([0-9a-f]{40,64}) +(\d+|-)\t/.exec(line);
640
+ if (!match || match[2] !== "blob" || (match[1] !== "100644" && match[1] !== "100755")) {
641
+ return { state: "invalid", detail: `${name} is not a regular file` };
642
+ }
643
+ if (Number(match[4]) > MAX_INPUT_BYTES)
644
+ return { state: "invalid", detail: `${name} is larger than 64 MB` };
645
+ try {
646
+ const blob = await execFileAsync("git", ["-C", worktreePath, "cat-file", "blob", match[3]], { encoding: "buffer", timeout: 30_000, maxBuffer: MAX_INPUT_BYTES + 1 });
647
+ return { state: "file", data: blob.stdout };
648
+ }
649
+ catch {
650
+ return unreadable;
651
+ }
652
+ }
556
653
  async function touch(file) {
557
654
  const now = new Date();
558
655
  await node_fs_1.promises.utimes(file, now, now).catch(() => undefined);
@@ -427,6 +427,28 @@ class GitWorktree {
427
427
  return null;
428
428
  }
429
429
  }
430
+ /**
431
+ * Fetches a pull request's head for dependency preparation. The worktree-local
432
+ * ref keeps the commit reachable for this session and avoids races with other
433
+ * sessions fetching the same pull request into the shared repository.
434
+ */
435
+ async fetchPullRequestHead(pullRequestNumber, signal) {
436
+ if (!Number.isSafeInteger(pullRequestNumber) || pullRequestNumber <= 0)
437
+ return null;
438
+ if (signal?.aborted)
439
+ return null;
440
+ const localRef = `refs/worktree/navarch/pull/${pullRequestNumber}/head`;
441
+ const options = { signal, timeoutMs: 30_000 };
442
+ try {
443
+ await this.runGit(["-C", this.worktreePath, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "origin", `+refs/pull/${pullRequestNumber}/head:${localRef}`], true, options);
444
+ const resolved = await this.runGit(["-C", this.worktreePath, "rev-parse", "--verify", `${localRef}^{commit}`], false, options);
445
+ const sha = resolved.stdout.trim();
446
+ return /^[0-9a-f]{40,64}$/i.test(sha) ? sha : null;
447
+ }
448
+ catch {
449
+ return null;
450
+ }
451
+ }
430
452
  /**
431
453
  * Puts the snapshot's files in the working tree as uncommitted edits on top
432
454
  * of the branch, which already sits on the hosted agent's HEAD: the state the
@@ -858,11 +880,11 @@ class GitWorktree {
858
880
  throw error;
859
881
  }
860
882
  }
861
- async runGit(args, authenticated) {
883
+ async runGit(args, authenticated, options) {
862
884
  if (authenticated && this.gitGrant) {
863
885
  // The helper reads the grant file the runtime refreshes; no token enters
864
886
  // argv or the environment.
865
- const grantResult = await this.runner.run("git", ["-c", "credential.helper=", "-c", `credential.helper=${this.gitGrant.credentialHelper}`, ...args], { env: gitEnvWithoutGithubTokens() });
887
+ const grantResult = await this.runner.run("git", ["-c", "credential.helper=", "-c", `credential.helper=${this.gitGrant.credentialHelper}`, ...args], { ...options, env: gitEnvWithoutGithubTokens() });
866
888
  if (grantResult.code !== 0) {
867
889
  throw new Error(`git ${args[0] ?? "command"} failed: ${grantResult.stderr || grantResult.stdout}`);
868
890
  }
@@ -878,6 +900,7 @@ class GitWorktree {
878
900
  ]
879
901
  : [];
880
902
  const result = await this.runner.run("git", [...credentialArgs, ...args], {
903
+ ...options,
881
904
  env: githubToken
882
905
  ? { ...process.env, GITHUB_TOKEN: githubToken, GIT_TERMINAL_PROMPT: "0" }
883
906
  : { ...process.env, GIT_TERMINAL_PROMPT: "0" },
package/dist/session.cjs CHANGED
@@ -851,6 +851,20 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
851
851
  activeAbortController = dependencyAbort;
852
852
  if (leaseLost || deps.shutdownSignal?.aborted)
853
853
  dependencyAbort.abort();
854
+ // A verify or review checks the pull request's head in a detached
855
+ // worktree, not this checkout's claim commit. When the pull request
856
+ // changes the lockfile, dependencies from the claim commit are the wrong
857
+ // packages (sagentlab/navarch#3266: verify had an SDK without the new
858
+ // API and ended BLOCKED). Install from the head's lockfile instead.
859
+ const checkedPullRequest = task.task_type === "verify" || task.task_type === "review"
860
+ ? (0, dependency_cache_cjs_1.pullRequestNumberInRepository)(task.github_issue_url, bundle.repository?.full_name ?? task.repo)
861
+ : null;
862
+ const checkedHeadSha = checkedPullRequest
863
+ ? await gitWorktree.fetchPullRequestHead(checkedPullRequest, dependencyAbort.signal)
864
+ : null;
865
+ if (checkedPullRequest && !checkedHeadSha && !dependencyAbort.signal.aborted) {
866
+ log.warn(`dependency cache for ${leaseId}: pull request #${checkedPullRequest} head could not be fetched; using the checkout's lockfile.`);
867
+ }
854
868
  const dependencyResults = await (0, dependency_cache_cjs_1.prepareDependencyCache)({
855
869
  cacheRoot: node_path_1.default.join(config.workspaceRoot, dependency_cache_cjs_1.DEPENDENCY_CACHE_DIRNAME),
856
870
  worktreePath: gitWorktree.worktreePath,
@@ -858,6 +872,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
858
872
  repository: task.repo,
859
873
  timeoutMs: config.dependencyCacheTimeoutMs,
860
874
  signal: dependencyAbort.signal,
875
+ ...(checkedHeadSha ? { inputsCommit: checkedHeadSha } : {}),
861
876
  }).catch((error) => {
862
877
  log.warn(`dependency cache for ${leaseId} failed: ${(0, redact_cjs_1.redactText)(String(error), registry.list())}`);
863
878
  return [];
@@ -871,7 +886,7 @@ async function runClaimedSession(deps, claimed, sessionId, lifecycle) {
871
886
  else
872
887
  log.info(message);
873
888
  }
874
- const dependencyNote = (0, dependency_cache_cjs_1.renderDependencyCacheNote)(dependencyResults);
889
+ const dependencyNote = (0, dependency_cache_cjs_1.renderDependencyCacheNote)(dependencyResults, checkedPullRequest ?? undefined);
875
890
  if (dependencyNote) {
876
891
  promptText = `${promptText}\n\n${dependencyNote}`;
877
892
  await node_fs_1.promises.writeFile(node_path_1.default.join(workDir, "prompt.md"), promptText, "utf8");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sagentlab/navarch-runtime",
3
- "version": "0.1.173",
3
+ "version": "0.1.174",
4
4
  "description": "Navarch machine-side session manager: claims delivery tasks and runs them through local coding agents.",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",