@infosupport/huddle-cli 0.0.0-experiment-167.144.1 → 0.0.0-experiment-137.146.1
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 +2 -1
- package/dist/agent-container.js +345 -0
- package/dist/github-app.js +108 -0
- package/dist/images.js +1 -0
- package/dist/index.js +48 -2
- package/dist/start.js +3 -1
- package/dist/triage-agent-guard.js +344 -0
- package/dist/triage-agent.js +373 -0
- package/dist/update-agent-guard.js +268 -0
- package/dist/update-agent.js +436 -0
- package/package.json +4 -3
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.runUpdateAgent = runUpdateAgent;
|
|
7
|
+
const crypto_1 = __importDefault(require("crypto"));
|
|
8
|
+
const fs_1 = __importDefault(require("fs"));
|
|
9
|
+
const path_1 = __importDefault(require("path"));
|
|
10
|
+
const api_1 = require("./api");
|
|
11
|
+
const agent_container_1 = require("./agent-container");
|
|
12
|
+
const config_1 = require("./config");
|
|
13
|
+
const github_app_1 = require("./github-app");
|
|
14
|
+
const runtime_1 = require("./runtime");
|
|
15
|
+
const utils_1 = require("./utils");
|
|
16
|
+
const update_agent_guard_1 = require("./update-agent-guard");
|
|
17
|
+
const MAX_ATTEMPTS = 3;
|
|
18
|
+
const MAX_TURNS = 40;
|
|
19
|
+
const CLAUDE_TIMEOUT_MS = 30 * 60 * 1000;
|
|
20
|
+
const VERIFY_TIMEOUT_MS = 20 * 60 * 1000;
|
|
21
|
+
const PROMPT_PATH = '.github/agent/update-agent.md';
|
|
22
|
+
const PR_FIELDS = 'number,title,author,isCrossRepository,headRefName,headRefOid,labels,statusCheckRollup,commits';
|
|
23
|
+
const AGENT_RULES = [
|
|
24
|
+
{ domain: 'registry.npmjs.org', status: 'allow' },
|
|
25
|
+
{ domain: 'api.anthropic.com', status: 'allow' },
|
|
26
|
+
{ domain: 'huddle', status: 'allow' }, // huddle's own audit forwarder (global rules don't apply under airlock)
|
|
27
|
+
// better-sqlite3 (gateway) downloads its prebuilt native binary from its own
|
|
28
|
+
// GitHub releases during `npm ci`; GitHub redirects that to its asset hosts.
|
|
29
|
+
// Only that path on github.com, nothing else there.
|
|
30
|
+
{ domain: 'github.com', status: 'allow', path_pattern: '/WiseLibs/better-sqlite3/releases/download/*' },
|
|
31
|
+
{ domain: 'release-assets.githubusercontent.com', status: 'allow' },
|
|
32
|
+
{ domain: 'objects.githubusercontent.com', status: 'allow' },
|
|
33
|
+
];
|
|
34
|
+
const ALLOWED_TOOLS = [
|
|
35
|
+
'Read', 'Edit', 'Write', 'Glob', 'Grep',
|
|
36
|
+
'Bash(npm:*)', 'Bash(npx:*)', 'Bash(node:*)', 'Bash(ls:*)', 'Bash(cat:*)',
|
|
37
|
+
'Bash(git status:*)', 'Bash(git diff:*)', 'Bash(git log:*)', 'Bash(git show:*)',
|
|
38
|
+
// To undo an experiment, such as a regenerated lockfile.
|
|
39
|
+
'Bash(git restore:*)',
|
|
40
|
+
].join(',');
|
|
41
|
+
// ── entry point ──────────────────────────────────────────────────────────────
|
|
42
|
+
async function runUpdateAgent(opts) {
|
|
43
|
+
const engine = (0, runtime_1.resolveRuntime)(opts.runtime).name;
|
|
44
|
+
// In CI the CLI acts as a GitHub App; on a developer's machine as their own `gh` login.
|
|
45
|
+
const appConfig = (0, github_app_1.appConfigFromEnv)();
|
|
46
|
+
const app = appConfig ? new github_app_1.GithubApp(appConfig) : null;
|
|
47
|
+
// Read once; no child process (git and gh on PR content, docker) inherits the key.
|
|
48
|
+
delete process.env.HUDDLE_GITHUB_APP_PRIVATE_KEY;
|
|
49
|
+
if (app)
|
|
50
|
+
await app.refresh();
|
|
51
|
+
else if ((0, agent_container_1.run)('gh', ['auth', 'status']).status !== 0)
|
|
52
|
+
throw new Error('GitHub CLI is not logged in. Run `gh auth login` first.');
|
|
53
|
+
const repo = app?.repo ?? (0, agent_container_1.must)('gh', ['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']).trim();
|
|
54
|
+
const credential = (0, agent_container_1.claudeCredential)();
|
|
55
|
+
// Doubles as the "is Huddle running and are we authenticated" check.
|
|
56
|
+
const { imageName } = await (0, api_1.get)('/api/docker/base-image?ide=vscode');
|
|
57
|
+
const prompt = fetchUpdatePrompt(repo);
|
|
58
|
+
const identity = app ? await app.identity() : gitIdentity();
|
|
59
|
+
const refreshGithub = async () => { await app?.refresh(); };
|
|
60
|
+
const prs = listPrs(repo, opts.pr);
|
|
61
|
+
if (prs.length === 0) {
|
|
62
|
+
console.log(opts.pr ? `PR #${opts.pr} not found.` : 'No open Renovate PRs.');
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const results = [];
|
|
66
|
+
await (0, agent_container_1.withInterruptHandler)(() => processAll(prs, { repo, engine, imageName, credential, prompt, identity, opts, refreshGithub }, results));
|
|
67
|
+
console.log(`\n${(0, utils_1.bold)('Update agent summary')}`);
|
|
68
|
+
for (const r of results) {
|
|
69
|
+
const color = r.outcome === 'fixed' || r.outcome === 'dry-run' ? utils_1.green : r.outcome === 'skipped' ? utils_1.dim : utils_1.red;
|
|
70
|
+
console.log(` #${r.pr} ${color(r.outcome.padEnd(8))} ${r.detail}`);
|
|
71
|
+
}
|
|
72
|
+
// A run that broke (not a PR the agent gave up on) fails the CI job.
|
|
73
|
+
if (results.some((r) => r.outcome === 'error'))
|
|
74
|
+
process.exitCode = 1;
|
|
75
|
+
}
|
|
76
|
+
async function processAll(prs, base, results) {
|
|
77
|
+
const { opts } = base;
|
|
78
|
+
for (const pr of prs) {
|
|
79
|
+
if ((0, agent_container_1.isInterrupted)())
|
|
80
|
+
break;
|
|
81
|
+
const decision = (0, update_agent_guard_1.decide)(pr, { skipMajors: opts.skipMajors });
|
|
82
|
+
if (decision.action === 'skip') {
|
|
83
|
+
if (opts.pr)
|
|
84
|
+
console.log((0, utils_1.yellow)(`Skipping #${pr.number}: ${decision.reason}`));
|
|
85
|
+
results.push({ pr: pr.number, outcome: 'skipped', detail: decision.reason });
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
console.log(`\n${(0, utils_1.bold)(`PR #${pr.number}`)} ${pr.title} ${(0, utils_1.dim)(`(${pr.headRefName})`)}`);
|
|
89
|
+
const ctx = { ...base, pr, usage: { costUsd: 0, turns: 0 } };
|
|
90
|
+
try {
|
|
91
|
+
await ctx.refreshGithub();
|
|
92
|
+
results.push(decision.action === 'give-up'
|
|
93
|
+
? await giveUp(ctx, decision.reason, '')
|
|
94
|
+
: await processPr(ctx));
|
|
95
|
+
}
|
|
96
|
+
catch (err) {
|
|
97
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
98
|
+
(0, agent_container_1.printUntrusted)(` error: ${msg}`, utils_1.red, 20_000, true);
|
|
99
|
+
results.push({ pr: pr.number, outcome: 'error', detail: msg });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// ── setup ────────────────────────────────────────────────────────────────────
|
|
104
|
+
/** The prompt always comes from the default branch, so a PR branch cannot rewrite its own instructions. */
|
|
105
|
+
const fetchUpdatePrompt = (repo) => (0, agent_container_1.fetchPrompt)(repo, PROMPT_PATH, 'HUDDLE_UPDATE_AGENT_PROMPT_REF', 'update agent');
|
|
106
|
+
function gitIdentity() {
|
|
107
|
+
const name = (0, agent_container_1.run)('git', ['config', 'user.name']).stdout.trim();
|
|
108
|
+
const email = (0, agent_container_1.run)('git', ['config', 'user.email']).stdout.trim();
|
|
109
|
+
if (!name || !email)
|
|
110
|
+
throw new Error('Set git user.name and user.email: the agent commits under your name.');
|
|
111
|
+
return { name, email };
|
|
112
|
+
}
|
|
113
|
+
function listPrs(repo, only) {
|
|
114
|
+
if (only) {
|
|
115
|
+
const r = (0, agent_container_1.run)('gh', ['pr', 'view', String(only), '--repo', repo, '--json', PR_FIELDS]);
|
|
116
|
+
if (r.status === 0)
|
|
117
|
+
return [JSON.parse(r.stdout)];
|
|
118
|
+
if (/could not resolve|not found/i.test(r.stderr))
|
|
119
|
+
return [];
|
|
120
|
+
throw new Error(`gh pr view ${only} failed: ${r.stderr.trim()}`);
|
|
121
|
+
}
|
|
122
|
+
const out = (0, agent_container_1.must)('gh', ['pr', 'list', '--repo', repo, '--author', (0, update_agent_guard_1.renovatePrAuthor)(), '--state', 'open', '--limit', '100', '--json', PR_FIELDS]);
|
|
123
|
+
return JSON.parse(out);
|
|
124
|
+
}
|
|
125
|
+
/** Who ran the agent, for comments and the commit trailer: the CI run, or the developer. */
|
|
126
|
+
function runner(ctx) {
|
|
127
|
+
const url = (0, agent_container_1.actionsRunUrl)();
|
|
128
|
+
if (url)
|
|
129
|
+
return { markdown: `Run by [GitHub Actions](${url})`, trailer: url };
|
|
130
|
+
return { markdown: `Run by ${ctx.identity.name}`, trailer: 'huddle update-agent' };
|
|
131
|
+
}
|
|
132
|
+
async function processPr(ctx) {
|
|
133
|
+
const { pr, opts } = ctx;
|
|
134
|
+
const name = `update-agent-pr-${pr.number}`;
|
|
135
|
+
const dir = path_1.default.join(config_1.CONFIG_DIR, 'update-agent', `pr-${pr.number}`);
|
|
136
|
+
// A container from an earlier --keep run is someone's debugging session:
|
|
137
|
+
// never delete it (or its folder) implicitly.
|
|
138
|
+
if (await (0, agent_container_1.containerExists)(name)) {
|
|
139
|
+
return { pr: pr.number, outcome: 'skipped', detail: `container ${name} from an earlier --keep run still exists; remove it first` };
|
|
140
|
+
}
|
|
141
|
+
fs_1.default.rmSync(dir, { recursive: true, force: true });
|
|
142
|
+
try {
|
|
143
|
+
return await fixPr(ctx, name, dir);
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
if (opts.out && ctx.container) {
|
|
147
|
+
try {
|
|
148
|
+
await saveUpdateNetworkLog(ctx, opts.out);
|
|
149
|
+
}
|
|
150
|
+
catch (err) {
|
|
151
|
+
// Never in the way of cleanup: the placeholder must be revoked.
|
|
152
|
+
console.log((0, utils_1.yellow)(` could not write the network log: ${err instanceof Error ? err.message : String(err)}`));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (!opts.keep && ctx.container)
|
|
156
|
+
(0, agent_container_1.wipeWorkspace)(ctx.engine, name);
|
|
157
|
+
await (0, agent_container_1.cleanup)(name, opts.keep);
|
|
158
|
+
if (!opts.keep)
|
|
159
|
+
(0, agent_container_1.removeDir)(dir);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* dir/workspace is mounted at /workspace (repo, input, out). Its root holds no
|
|
164
|
+
* .git, so the gateway mounts it as-is instead of creating a worktree.
|
|
165
|
+
* dir/publish is the trusted clone and dir/agent.bundle the copied-out commit;
|
|
166
|
+
* neither is ever mounted.
|
|
167
|
+
*/
|
|
168
|
+
async function fixPr(ctx, name, dir) {
|
|
169
|
+
const { pr } = ctx;
|
|
170
|
+
const ws = path_1.default.join(dir, 'workspace');
|
|
171
|
+
const publish = path_1.default.join(dir, 'publish');
|
|
172
|
+
const prFiles = prepareWorkspace(ctx, ws, publish);
|
|
173
|
+
if (!prFiles)
|
|
174
|
+
return { pr: pr.number, outcome: 'skipped', detail: 'branch moved while starting; run again' };
|
|
175
|
+
ctx.container = name;
|
|
176
|
+
const agent = await startUpdateAgent(ctx, name, ws);
|
|
177
|
+
// Git metadata the agent could use to run code on commit (hooks, filters).
|
|
178
|
+
const gitBaseline = gitMetadata(agent);
|
|
179
|
+
const failure = await runAttempts(ctx, agent, prFiles);
|
|
180
|
+
if (failure) {
|
|
181
|
+
// Its own explanation is what the reviewer needs most, e.g. "hold this
|
|
182
|
+
// update until X widens its peer range".
|
|
183
|
+
const summary = (await agent.readFile('/workspace/out/summary.md')).trim();
|
|
184
|
+
return giveUp(ctx, failure.reason, failure.output, summary);
|
|
185
|
+
}
|
|
186
|
+
// Nothing the agent or a package's install script left running may change
|
|
187
|
+
// the tree between the checks below and the commit.
|
|
188
|
+
agent.stopAll();
|
|
189
|
+
if (gitMetadata(agent) !== gitBaseline) {
|
|
190
|
+
return giveUp(ctx, 'the git configuration or hooks were changed during the run', 'Something in the container changed .git/config, .git/hooks or .git/info/attributes.');
|
|
191
|
+
}
|
|
192
|
+
const bundle = await commitAndBundle(ctx, agent, dir);
|
|
193
|
+
return publishResult(ctx, agent, publish, bundle);
|
|
194
|
+
}
|
|
195
|
+
/** Clones the PR twice and writes the agent's inputs. Returns the PR's files, or null if the branch moved. */
|
|
196
|
+
function prepareWorkspace(ctx, ws, publish) {
|
|
197
|
+
const { pr, repo } = ctx;
|
|
198
|
+
for (const d of ['input', 'out'])
|
|
199
|
+
fs_1.default.mkdirSync(path_1.default.join(ws, d), { recursive: true });
|
|
200
|
+
const clone = (dest, depth) => (0, agent_container_1.must)('gh', ['repo', 'clone', repo, dest, '--', '--config', 'core.autocrlf=false', '--quiet', '--no-tags', '--single-branch', '--depth', depth, '--branch', pr.headRefName]);
|
|
201
|
+
clone(path_1.default.join(ws, 'repo'), '50');
|
|
202
|
+
clone(publish, '1');
|
|
203
|
+
if ((0, agent_container_1.must)('git', ['-C', publish, 'rev-parse', 'HEAD']).trim() !== pr.headRefOid)
|
|
204
|
+
return null;
|
|
205
|
+
return writeInputs(ctx, path_1.default.join(ws, 'input'));
|
|
206
|
+
}
|
|
207
|
+
/** Writes the agent's inputs (before the container exists) and returns the files the PR itself changes. */
|
|
208
|
+
function writeInputs(ctx, input) {
|
|
209
|
+
const { pr, repo } = ctx;
|
|
210
|
+
const view = JSON.parse((0, agent_container_1.must)('gh', ['pr', 'view', String(pr.number), '--repo', repo, '--json', 'title,body,files']));
|
|
211
|
+
fs_1.default.writeFileSync(path_1.default.join(input, 'pr.md'), `# ${view.title}\n\n${view.body ?? ''}\n`);
|
|
212
|
+
const logs = (0, update_agent_guard_1.failedJobs)(pr).map(({ runId, jobId }) => {
|
|
213
|
+
const r = (0, agent_container_1.run)('gh', ['run', 'view', '--job', jobId, '--repo', repo, '--log']);
|
|
214
|
+
return `===== run ${runId}, job ${jobId} =====\n${r.status === 0 ? (0, agent_container_1.tail)(r.stdout, 20_000) : `(could not read log: ${r.stderr.trim()})`}`;
|
|
215
|
+
});
|
|
216
|
+
fs_1.default.writeFileSync(path_1.default.join(input, 'failure.log'), (0, agent_container_1.tail)(logs.join('\n') || 'No GitHub Actions log found for the failing checks.', 60_000));
|
|
217
|
+
return (view.files ?? []).map((f) => f.path);
|
|
218
|
+
}
|
|
219
|
+
// ── the container ────────────────────────────────────────────────────────────
|
|
220
|
+
async function startUpdateAgent(ctx, name, ws) {
|
|
221
|
+
return (0, agent_container_1.startAgent)({
|
|
222
|
+
name, engine: ctx.engine, imageName: ctx.imageName, credential: ctx.credential, rules: AGENT_RULES, workspace: ws,
|
|
223
|
+
description: 'airlocked: npm registry, Anthropic API and better-sqlite3 releases only',
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
/** Snapshot of the git files that can make git run code, read as root and never through git. */
|
|
227
|
+
function gitMetadata(agent) {
|
|
228
|
+
const r = agent.root([
|
|
229
|
+
'cd /workspace/repo',
|
|
230
|
+
'[ -L .git ] && echo "symlinked .git"',
|
|
231
|
+
'cd .git 2>/dev/null || { echo "no .git directory"; exit 0; }',
|
|
232
|
+
// Git reads config and info/attributes from the directory in `commondir`
|
|
233
|
+
// when that file exists, even outside a worktree. The commit pins
|
|
234
|
+
// GIT_COMMON_DIR, so this only makes a planted one visible as a change.
|
|
235
|
+
'[ -e commondir ] && echo "commondir present"',
|
|
236
|
+
'cat config 2>&1; echo "-- attributes"; cat info/attributes 2>&1',
|
|
237
|
+
'echo "-- hooks"; ls -A hooks 2>&1 | grep -v "[.]sample$"',
|
|
238
|
+
'exit 0',
|
|
239
|
+
].join('\n'));
|
|
240
|
+
if (r.status !== 0)
|
|
241
|
+
throw new Error(`could not read the git metadata in ${agent.name}: ${r.stderr.trim()}`);
|
|
242
|
+
return r.stdout;
|
|
243
|
+
}
|
|
244
|
+
/** Runs Claude Code and verifies its work, up to MAX_ATTEMPTS. Returns null on success. */
|
|
245
|
+
async function runAttempts(ctx, agent, prFiles) {
|
|
246
|
+
const { exec, name } = agent;
|
|
247
|
+
// Hash of the whole working tree, untracked files included, via a throwaway
|
|
248
|
+
// index so the real index stays untouched.
|
|
249
|
+
const treeState = async () => {
|
|
250
|
+
const r = await exec(['sh', '-c', 'cp .git/index "$1" && GIT_INDEX_FILE="$1" git add -A && GIT_INDEX_FILE="$1" git write-tree', 'sh', '/tmp/huddle-tree.idx'], '/workspace/repo');
|
|
251
|
+
if (r.status !== 0)
|
|
252
|
+
throw new Error(`could not read the working tree in ${name}: ${r.stderr.trim()}`);
|
|
253
|
+
return r.stdout.trim();
|
|
254
|
+
};
|
|
255
|
+
// Files the agent changed relative to the PR head, untracked ones included.
|
|
256
|
+
const changedFiles = async () => {
|
|
257
|
+
const r = await exec(['sh', '-c', 'cp .git/index "$1" && GIT_INDEX_FILE="$1" git add -A && GIT_INDEX_FILE="$1" git diff --cached --name-only HEAD', 'sh', '/tmp/huddle-changed.idx'], '/workspace/repo');
|
|
258
|
+
if (r.status !== 0)
|
|
259
|
+
throw new Error(`could not list the changed files in ${name}: ${r.stderr.trim()}`);
|
|
260
|
+
return r.stdout.split('\n').map((l) => l.trim()).filter(Boolean);
|
|
261
|
+
};
|
|
262
|
+
let lastFailure = '';
|
|
263
|
+
let feedback = '';
|
|
264
|
+
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
|
265
|
+
console.log((0, utils_1.dim)(` attempt ${attempt}/${MAX_ATTEMPTS}: running Claude Code`));
|
|
266
|
+
const task = feedback ? `${ctx.prompt}\n\nThis is attempt ${attempt}. ${feedback}` : ctx.prompt;
|
|
267
|
+
const before = await treeState();
|
|
268
|
+
// JSON output: only the agent's final answer is printed (a public CI log
|
|
269
|
+
// must not get the whole transcript), plus its cost for the PR comment.
|
|
270
|
+
const model = process.env.HUDDLE_UPDATE_AGENT_MODEL?.trim();
|
|
271
|
+
// Locally, Claude Code's warnings show while it works. In CI its stderr is
|
|
272
|
+
// captured and printed with workflow commands off (printUntrusted).
|
|
273
|
+
const claude = await exec([
|
|
274
|
+
'claude', '-p', task, '--output-format', 'json', '--max-turns', String(MAX_TURNS),
|
|
275
|
+
...(model ? ['--model', model] : []), '--allowedTools', ALLOWED_TOOLS,
|
|
276
|
+
], '/workspace/repo', { timeout: CLAUDE_TIMEOUT_MS, liveStderr: !(0, agent_container_1.inActions)() });
|
|
277
|
+
reportClaude(ctx, claude);
|
|
278
|
+
if ((await treeState()) === before) {
|
|
279
|
+
if (claude.status !== 0) {
|
|
280
|
+
// Not the PR's fault: credential, firewall or Claude Code itself.
|
|
281
|
+
throw new Error(`Claude Code ${claude.timedOut ? 'timed out' : `exited with ${claude.status}`} without changing anything. ` +
|
|
282
|
+
`Check the credential and the requested rules for ${name} in the portal.`);
|
|
283
|
+
}
|
|
284
|
+
// An attempt that changes nothing is the agent's answer: it sees no code
|
|
285
|
+
// fix (an unfixable update, or an environment problem it explains in its
|
|
286
|
+
// summary). Another attempt would only reach the same conclusion, or
|
|
287
|
+
// re-verify the same tree.
|
|
288
|
+
return lastFailure
|
|
289
|
+
? { reason: `the agent found no further fix after verification failed (attempt ${attempt} of ${MAX_ATTEMPTS})`, output: lastFailure }
|
|
290
|
+
: { reason: 'the agent found no code fix', output: '' };
|
|
291
|
+
}
|
|
292
|
+
const projects = (0, update_agent_guard_1.affectedProjects)([...prFiles, ...(await changedFiles())]);
|
|
293
|
+
console.log((0, utils_1.dim)(` verifying: npm ci, build and test in ${projects.join(', ')}`));
|
|
294
|
+
lastFailure = await verify(exec, projects);
|
|
295
|
+
if (!lastFailure)
|
|
296
|
+
return null;
|
|
297
|
+
const verifyLog = `/workspace/input/verify-${attempt}.log`;
|
|
298
|
+
await agent.writeFile(verifyLog, (0, agent_container_1.tail)(lastFailure, 30_000));
|
|
299
|
+
feedback = `Your previous change did not pass verification; the output is in ${verifyLog}. ` +
|
|
300
|
+
'Fix that, keeping the earlier work where it is right.';
|
|
301
|
+
console.log((0, utils_1.yellow)(' verification failed'));
|
|
302
|
+
}
|
|
303
|
+
return { reason: `verification still failed after ${MAX_ATTEMPTS} attempts`, output: lastFailure };
|
|
304
|
+
}
|
|
305
|
+
/** Prints the agent's final answer and adds its cost and turns to ctx.usage. */
|
|
306
|
+
function reportClaude(ctx, r) {
|
|
307
|
+
const out = (0, agent_container_1.parseClaudeOutput)(r.stdout);
|
|
308
|
+
if (out) {
|
|
309
|
+
ctx.usage.costUsd += out.costUsd;
|
|
310
|
+
ctx.usage.turns += out.turns;
|
|
311
|
+
if (out.result)
|
|
312
|
+
(0, agent_container_1.printUntrusted)(out.result.replace(/^/gm, ' '));
|
|
313
|
+
}
|
|
314
|
+
else if (r.stdout.trim()) {
|
|
315
|
+
(0, agent_container_1.printUntrusted)(r.stdout.trim());
|
|
316
|
+
}
|
|
317
|
+
if (r.status !== 0 && r.stderr.trim())
|
|
318
|
+
(0, agent_container_1.printUntrusted)(r.stderr.trim());
|
|
319
|
+
}
|
|
320
|
+
/** Runs what CI runs, for the given projects. Returns '' when everything passes, otherwise the failing output. */
|
|
321
|
+
async function verify(exec, projects) {
|
|
322
|
+
for (const project of projects) {
|
|
323
|
+
// One stream, in order: the end of the output is then the failure itself,
|
|
324
|
+
// not stderr's build warnings appended after it.
|
|
325
|
+
const r = await exec(['bash', '-lc', '{ npm ci --no-audit --no-fund && npm run build --if-present && CI=true npm test --if-present; } 2>&1'], `/workspace/repo/${project}`, { timeout: VERIFY_TIMEOUT_MS });
|
|
326
|
+
if (r.status !== 0)
|
|
327
|
+
return `### ${project} failed (exit ${r.status ?? 'timeout'})\n${r.stdout}${r.stderr ? `\n${r.stderr}` : ''}`;
|
|
328
|
+
}
|
|
329
|
+
return '';
|
|
330
|
+
}
|
|
331
|
+
/** Commits in the container under the developer's name and copies the commit out as a bundle. */
|
|
332
|
+
async function commitAndBundle(ctx, agent, dir) {
|
|
333
|
+
const { pr, identity, engine } = ctx;
|
|
334
|
+
const message = (0, update_agent_guard_1.sanitizeCommitMessage)(await agent.readFile('/workspace/out/commit-msg.txt'), `fix(deps): adapt code for ${pr.title}`, runner(ctx).trailer);
|
|
335
|
+
// A fresh name, so nothing the agent prepared in /tmp can stand in for it.
|
|
336
|
+
const inContainer = `/tmp/huddle-${crypto_1.default.randomBytes(8).toString('hex')}.bundle`;
|
|
337
|
+
const steps = [
|
|
338
|
+
{ args: ['add', '-A'] },
|
|
339
|
+
{ args: ['commit', '-q', '--no-verify', '-F', '-'], input: message },
|
|
340
|
+
{ args: ['bundle', 'create', inContainer, 'HEAD', `^${pr.headRefOid}`] },
|
|
341
|
+
];
|
|
342
|
+
for (const { args, input } of steps) {
|
|
343
|
+
// Only the repo's own config (checked above) applies: the agent can write
|
|
344
|
+
// ~/.gitconfig, where a filter for a .gitattributes in the tree would
|
|
345
|
+
// change the content on `git add`, after it was verified. GIT_DIR and
|
|
346
|
+
// GIT_COMMON_DIR pin the checked .git: otherwise a `.git/commondir` file
|
|
347
|
+
// would make git take its config and attributes (a filter) from elsewhere.
|
|
348
|
+
const r = await agent.exec([
|
|
349
|
+
'env', 'GIT_CONFIG_GLOBAL=/dev/null', 'GIT_CONFIG_NOSYSTEM=1',
|
|
350
|
+
'GIT_DIR=/workspace/repo/.git', 'GIT_COMMON_DIR=/workspace/repo/.git', 'GIT_WORK_TREE=/workspace/repo',
|
|
351
|
+
'git', '-c', 'core.hooksPath=/dev/null', '-c', 'core.fsmonitor=false',
|
|
352
|
+
'-c', `user.name=${identity.name}`, '-c', `user.email=${identity.email}`, ...args,
|
|
353
|
+
], '/workspace/repo', { input });
|
|
354
|
+
if (r.status !== 0)
|
|
355
|
+
throw new Error(`git ${args[0]} in the container failed: ${(r.stderr || r.stdout).trim()}`);
|
|
356
|
+
}
|
|
357
|
+
const bundle = path_1.default.join(dir, 'agent.bundle');
|
|
358
|
+
(0, agent_container_1.must)(engine, ['cp', `${agent.name}:${inContainer}`, bundle]);
|
|
359
|
+
if (!fs_1.default.lstatSync(bundle).isFile())
|
|
360
|
+
throw new Error('the bundle copied out of the container is not a regular file');
|
|
361
|
+
return bundle;
|
|
362
|
+
}
|
|
363
|
+
/** Checks the agent's commit in the trusted clone, then pushes and comments (or prints it for --dry-run). */
|
|
364
|
+
async function publishResult(ctx, agent, publish, bundle) {
|
|
365
|
+
const { pr, repo, opts } = ctx;
|
|
366
|
+
await ctx.refreshGithub();
|
|
367
|
+
(0, agent_container_1.must)('git', ['-C', publish, 'fetch', '--quiet', bundle, 'HEAD']);
|
|
368
|
+
const fixed = (0, agent_container_1.must)('git', ['-C', publish, 'rev-parse', 'FETCH_HEAD']).trim();
|
|
369
|
+
if ((0, agent_container_1.run)('git', ['-C', publish, 'merge-base', '--is-ancestor', pr.headRefOid, fixed]).status !== 0) {
|
|
370
|
+
return giveUp(ctx, 'the result does not build on the PR head', '');
|
|
371
|
+
}
|
|
372
|
+
const files = (0, update_agent_guard_1.parseNameStatus)((0, agent_container_1.must)('git', ['-C', publish, 'diff', '--name-status', pr.headRefOid, fixed]));
|
|
373
|
+
const blocked = (0, update_agent_guard_1.guardViolations)(files.map((f) => f.path));
|
|
374
|
+
if (blocked.length) {
|
|
375
|
+
return giveUp(ctx, 'blocked by the path guard', `The agent changed files only a person may change:\n${blocked.join('\n')}`);
|
|
376
|
+
}
|
|
377
|
+
const flags = (0, update_agent_guard_1.testWeakeningFlags)(files, (0, agent_container_1.must)('git', ['-C', publish, 'diff', '-U0', pr.headRefOid, fixed]));
|
|
378
|
+
const summary = (await agent.readFile('/workspace/out/summary.md')).trim();
|
|
379
|
+
const facts = await (0, agent_container_1.runFacts)(ctx.container, ctx.usage);
|
|
380
|
+
const comment = [
|
|
381
|
+
'### Update agent: fixed the build',
|
|
382
|
+
'',
|
|
383
|
+
'The agent\'s own summary, written after reading untrusted release notes and logs:',
|
|
384
|
+
'',
|
|
385
|
+
summary ? (0, agent_container_1.quoteUntrusted)((0, agent_container_1.tail)(summary, 20_000)) : '> _The agent wrote no summary._',
|
|
386
|
+
'',
|
|
387
|
+
`**Files changed:** ${files.filter((f) => f.status !== 'D').length} changed, ${files.filter((f) => f.status === 'D').length} deleted`,
|
|
388
|
+
flags.length ? `**Check these (possible weakened tests):**\n${flags.map((f) => `- ${f}`).join('\n')}` : '**Test changes:** nothing suspicious found',
|
|
389
|
+
...facts,
|
|
390
|
+
'',
|
|
391
|
+
`<sub>${runner(ctx).markdown} with \`huddle update-agent\` inside an airlocked Huddle devcontainer. A person still reviews and merges.</sub>`,
|
|
392
|
+
].join('\n');
|
|
393
|
+
if (opts.dryRun) {
|
|
394
|
+
(0, agent_container_1.printUntrusted)((0, agent_container_1.must)('git', ['-C', publish, '--no-pager', 'show', '--stat', '--patch', fixed]), (s) => s, 200_000);
|
|
395
|
+
console.log((0, utils_1.dim)('\n--- PR comment that would be posted ---'));
|
|
396
|
+
(0, agent_container_1.printUntrusted)(comment, (s) => s, 40_000);
|
|
397
|
+
return { pr: pr.number, outcome: 'dry-run', detail: `${files.length} file(s) changed; nothing pushed` };
|
|
398
|
+
}
|
|
399
|
+
// A plain push: it fails instead of overwriting if the branch moved meanwhile.
|
|
400
|
+
(0, agent_container_1.must)('git', ['-C', publish, '-c', 'credential.helper=', '-c', 'credential.helper=!gh auth git-credential', 'push', '--quiet', 'origin', `${fixed}:refs/heads/${pr.headRefName}`]);
|
|
401
|
+
(0, agent_container_1.must)('gh', ['pr', 'comment', String(pr.number), '--repo', repo, '--body-file', '-'], { input: comment });
|
|
402
|
+
console.log((0, utils_1.green)(` pushed ${fixed.slice(0, 7)} to ${pr.headRefName}`));
|
|
403
|
+
return { pr: pr.number, outcome: 'fixed', detail: `pushed ${fixed.slice(0, 7)}${flags.length ? `, ${flags.length} flag(s) for review` : ''}` };
|
|
404
|
+
}
|
|
405
|
+
// ── outcome and cleanup ──────────────────────────────────────────────────────
|
|
406
|
+
async function giveUp(ctx, reason, details, summary = '') {
|
|
407
|
+
const { pr, repo, opts } = ctx;
|
|
408
|
+
console.log((0, utils_1.red)(` giving up: ${reason}`));
|
|
409
|
+
if (!opts.dryRun) {
|
|
410
|
+
await ctx.refreshGithub();
|
|
411
|
+
const facts = await (0, agent_container_1.runFacts)(ctx.container, ctx.usage);
|
|
412
|
+
const body = [
|
|
413
|
+
`### Update agent: gave up`,
|
|
414
|
+
'',
|
|
415
|
+
`**Reason:** ${reason}. ${ctx.container ? 'Nothing was pushed; this' : 'This'} PR needs a person.`,
|
|
416
|
+
...(summary
|
|
417
|
+
? ['', 'The agent\'s own explanation, written after reading untrusted release notes and logs:', '', (0, agent_container_1.quoteUntrusted)((0, agent_container_1.tail)(summary, 20_000))]
|
|
418
|
+
: []),
|
|
419
|
+
details ? `\n<details><summary>Last output</summary>\n\n\`\`\`\n${(0, agent_container_1.tail)(details, 6_000).replace(/```/g, "'''")}\n\`\`\`\n</details>` : '',
|
|
420
|
+
...facts,
|
|
421
|
+
'',
|
|
422
|
+
`<sub>${runner(ctx).markdown} with \`huddle update-agent\`. ${ctx.container
|
|
423
|
+
? `Remove the \`${update_agent_guard_1.GAVE_UP_LABEL}\` label to let the agent try again.`
|
|
424
|
+
: `To let the agent start over, tick the rebase checkbox and remove the \`${update_agent_guard_1.GAVE_UP_LABEL}\` label.`}</sub>`,
|
|
425
|
+
].join('\n');
|
|
426
|
+
if ((0, agent_container_1.run)('gh', ['pr', 'edit', String(pr.number), '--repo', repo, '--add-label', update_agent_guard_1.GAVE_UP_LABEL]).status !== 0) {
|
|
427
|
+
console.log((0, utils_1.yellow)(` could not add the ${update_agent_guard_1.GAVE_UP_LABEL} label (does it exist in ${repo}?)`));
|
|
428
|
+
}
|
|
429
|
+
(0, agent_container_1.must)('gh', ['pr', 'comment', String(pr.number), '--repo', repo, '--body-file', '-'], { input: body });
|
|
430
|
+
}
|
|
431
|
+
return { pr: pr.number, outcome: 'gave-up', detail: reason };
|
|
432
|
+
}
|
|
433
|
+
// ── network log ──────────────────────────────────────────────────────────────
|
|
434
|
+
async function saveUpdateNetworkLog(ctx, out) {
|
|
435
|
+
await (0, agent_container_1.saveNetworkLog)(ctx.container, path_1.default.join(out, `pr-${ctx.pr.number}-network.json`), { pr: ctx.pr.number });
|
|
436
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@infosupport/huddle-cli",
|
|
3
|
-
"version": "0.0.0-experiment-
|
|
3
|
+
"version": "0.0.0-experiment-137.146.1",
|
|
4
4
|
"description": "Huddle CLI — start devcontainers and manage firewall rules",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"author": "Info Support B.V.",
|
|
@@ -20,11 +20,12 @@
|
|
|
20
20
|
"build": "tsc",
|
|
21
21
|
"dev": "tsc --watch",
|
|
22
22
|
"install-global": "npm run build && npm install -g .",
|
|
23
|
-
"typecheck": "tsc --noEmit"
|
|
23
|
+
"typecheck": "tsc --noEmit",
|
|
24
|
+
"test": "tsc && node --test"
|
|
24
25
|
},
|
|
25
26
|
"devDependencies": {
|
|
26
27
|
"@types/node": "^22.0.0",
|
|
27
|
-
"typescript": "
|
|
28
|
+
"typescript": "~6.0.3"
|
|
28
29
|
},
|
|
29
30
|
"engines": {
|
|
30
31
|
"node": ">=22"
|