kunibert
All repositories: gitoria
17.1 KB
$mode = 'static'import { run, dir } from 'hl:proc'import { mkDir, createFile, writeFile, readFile, realPath, remove, exists } from 'hl:fs'import { randomBytes } from 'hl:crypto'import { firstReview, withVendored, RULES_VERSION } from './review-prompt.hl'import { parseEvents, checked, require } from './review-output.hl'import { vendoredPaths, isVendored, settleVendored, appResult, appDiff } from './review-vendored.hl'git = (String repo, Hybrid argv) => {r = run(['git'] + argv, { cwd = repo, timeout = 30 })require(r.exit == 0, 'git failed (' + r.exit + '): ' + r.stderr.join(' '))return r.lines}// Code must never leave the sandbox: no user config (its MCP servers and plugins), no web search, no apps connector (it carries web search), no plugins, no MCP servers, no browser.offline = ['--ignore-user-config', '-c', 'web_search="disabled"', '-c', 'features.apps=false', '-c', 'features.plugins=false', '-c', 'features.remote_plugin=false', '-c', 'features.browser_use=false', '-c', 'features.browser_use_external=false', '-c', 'features.in_app_browser=false', '-c', 'mcp_servers={}']import { statePath, loadState, threadUpdates, threadUpdatesFrom, mergeOpenFindings, applyResult, reset, addNotes } from './review-memory.hl'import { connect } from './gitoria-api.hl'import { getPull, getToken, getThreads } from './gitoria-api.hl'import { startStatus, errorStatus, threadInput, postReview, postReplies, statusFor, finishStatus } from './review-post.hl'import { wakePrompt, freshThreads } from './review-wake.hl'import { buildSpec } from './tickets.hl'import { cacheRepo, fetchRefs, addWorktree, removeWorktree, worktreePath, prHeadLocal, baseLocal, maxDiffBytes } from './gitcache.hl'// A worktree that is live right now; the global error handler of the tool removes it on any failure.live = { cache = null, path = null, tokenFile = null }cleanup = () => {if (live.tokenFile != null) { if (exists(live.tokenFile)) { remove(live.tokenFile) } live.tokenFile = null }if (live.path != null) { removeWorktree(live.cache, live.path) live.path = null }}// Where and as whom the model runs (set by tools/runner.hl from --review-user/--codex-bin/--work-dir). reviewUser == null: codex runs as// the CLI's own user, as before. Set: every codex call (first, resume, fallback) runs as that user with its own HOME and a clean environment.settings = { reviewUser = null, codexBin = 'codex', workDir = null, vendored = [], vendoredLink = null, timeoutSeconds = 900 }reviewHome = (String user) => { return '/home/' + user }codexTurn = (String repo, String instructions, String session, String label, Hybrid prefixes) => {fullPrompt = withVendored(instructions, prefixes)writeFile(repo + '/.kunibert/' + label + '-prompt.md', fullPrompt)let prompt = fullPromptif (toBytes(prompt).length > 16000) {writeFile(repo + '/.kunibert/prompt.md', prompt)prompt = 'Your full instructions for this turn are in the file .kunibert/prompt.md. Read all of it first, then follow it exactly.'}schema = dir() + '/../schema.json'let argv = [settings.codexBin, 'exec']if (session != null) { argv = argv + ['resume', '--json', '-c', 'sandbox_mode="read-only"'] }else { argv = argv + ['--json', '-s', 'read-only', '-C', repo] }argv = argv + ['--skip-git-repo-check', '--output-schema', schema, '-c', 'model="gpt-6.1-sol"', '-c', 'model_reasoning_effort="max"'] + offlineif (session != null) { argv.push(session) }argv.push(prompt)// The worktree is made by this (root) user, hl:fs creates 700/600: open exactly the job worktree for the review user to READ (never write):// dirs 755, files 644, and the two parent dirs (work/<repo key>) 711 so the path can be walked but not listed. Nothing outside workDir is touched.if (settings.reviewUser != null && settings.workDir != null && realPath(settings.workDir) != null && repo.startsWith(realPath(settings.workDir) + '/')) {require(run(['chmod', '-R', 'a+rX,go-w', repo], { timeout = 60 }).exit == 0, 'chmod of the worktree failed')require(run(['chmod', 'a+x', repo + '/..', repo + '/../..'], { timeout = 30 }).exit == 0, 'chmod of the worktree parents failed')}// the model's own unix user: no environment of the service (env -i), its own HOME (its own ~/.codex login)if (settings.reviewUser != null) { argv = ['runuser', '-u', settings.reviewUser, '--', 'env', '-i', 'HOME=' + reviewHome(settings.reviewUser), 'PATH=/usr/local/bin:/usr/bin:/bin', 'LANG=C.UTF-8'] + argv }writeFile(repo + '/.kunibert/' + label + '-argv.json', JSON.stringify(argv))r = run(argv, { cwd = repo, timeout = settings.timeoutSeconds })writeFile(repo + '/.kunibert/' + label + '.jsonl', r.lines.join('') + '')return { events = parseEvents(r.lines), code = r.exit, stderr = r.stderr.join('') }}// 'changed' | 'gone' | null: did the spec file differ from the last run's (hash in the state)?specChange = (String before, String now) => {if (before == now) { return null }return now == null ? 'gone' : 'changed'}review = (String data, String directory, String base, String head, String threads = null, Boolean forced = false, Hybrid ctx = null) => {repo = realPath(directory)require(repo != null, 'repository directory does not exist')baseSha = git(repo, ['rev-parse', '--verify', '--end-of-options', base + '^{commit}']).join('')headSha = git(repo, ['rev-parse', '--verify', '--end-of-options', head + '^{commit}']).join('')require(git(repo, ['rev-parse', 'HEAD']).join('') == headSha, 'working tree HEAD must match head ref')require(git(repo, ['status', '--porcelain', '--untracked-files=no']).length == 0, 'tracked working tree must be clean')return runReview(statePath(data, repo, head), repo, repo, baseSha, headSha, threads, forced, null, null, null, ctx)}// A PR from a remote: bare cache, forced fetch, worktree only for the model run (removed after, also on failure).reviewPr = (String data, String url, Number pr, String base, String tokenFile = null, String threads = null, Boolean forced = false) => {cache = cacheRepo(data, url)fetchRefs(cache, url, pr, base, tokenFile)baseSha = git(cache, ['rev-parse', '--verify', '--end-of-options', baseLocal(base) + '^{commit}']).join('')headSha = git(cache, ['rev-parse', '--verify', '--end-of-options', prHeadLocal(pr) + '^{commit}']).join('')return runReview(statePath(data, url, '' + pr), cache, worktreePath(data, url, pr), baseSha, headSha, threads, forced, cache, headSha)}// gitDir: where git questions are asked (repo or bare cache); work: where .kunibert is written and the model runs.// checkoutSha != null: work does not exist yet; make it (detached worktree of the cache) once a model run is certain.// ctx != null: { title, body, tickets (ids), ticketsBase, ticketsTokenFile } (PR text and the tickets the PR links to).// hooks != null (gitoria mode): { input(state) -> thread array, start(head), post(state, firstNew, result, mergeBase) -> { skipped } | extras, finish(state, result) -> extras }.runReview = (String path, String gitDir, String work, String baseSha, String headSha, String threads, Boolean forced, String cache, String checkoutSha, Hybrid hooks = null, Hybrid ctx = null) => {repo = gitDirlet state = loadState(path)generation = state.generationprefixes = vendoredPaths(gitDir, headSha, settings.vendored)state = settleVendored(state, prefixes)let changes = nullif (hooks != null) { changes = threadUpdatesFrom(state, hooks.input(state)) } else { changes = threadUpdates(state, threads) }state = changes.stateupdates = changes.updatesif (state.head == headSha && updates.length == 0 && state.pending.length == 0 && !forced && state.session != null) { return { skipped = true, head = headSha, generation = generation } }mergeBase = git(repo, ['merge-base', baseSha, headSha]).join('')let prev = { head = state.head, verdict = state.verdict, =forced }if (hooks != null) { hooks.start(headSha, state.head != headSha || forced) }let diff = git(repo, ['diff', '--no-ext-diff', '--no-textconv', mergeBase + '..' + headSha, '--']).join('')// over the limit with vendored paths: review the app part only; the vendored files are named as skippedomitted = toBytes(diff).length > maxDiffBytes && prefixes.length > 0if (omitted) { diff = appDiff(repo, mergeBase + '..' + headSha, prefixes) }if (toBytes(diff).length > maxDiffBytes) { return { error = 'diff too large', bytes = toBytes(diff).length, limit = maxDiffBytes } }let rewritten = falselet delta = ''if (state.head != null && state.head != headSha) {ancestor = run(['git', 'merge-base', '--is-ancestor', state.head, headSha], { cwd = repo, timeout = 30 })require(ancestor.exit == 0 || ancestor.exit == 1, 'cannot determine ancestry; missing history')rewritten = ancestor.exit == 1if (!rewritten) {nul = JSON.parse('"\u0000"')names = git(repo, ['diff', '--no-ext-diff', '--no-textconv', '--name-status', '-z', '-M', mergeBase + '..' + headSha, '--']).join('').split(nul)let paths = []let i = 0while (i < names.length && names[i] != '') {status = names[i]i = i + 1paths.push(names[i])i = i + 1if (status.startsWith('R') || status.startsWith('C')) { paths.push(names[i]) i = i + 1 }}if (omitted) { paths = paths.filter((String p) => { return !isVendored(p, prefixes) }) }if (paths.length > 0) { delta = git(repo, ['--literal-pathspecs', 'diff', '--no-ext-diff', '--no-textconv', state.head + '..' + headSha, '--'] + paths).join('') }}}if (checkoutSha != null) { live.cache = cache live.path = work addWorktree(cache, work, checkoutSha) }mkDir(work + '/.kunibert')writeFile(work + '/.kunibert/pr.diff', diff + '')writeFile(work + '/.kunibert/delta.diff', delta)writeFile(work + '/.kunibert/HL-STANDARD.md', readFile(dir() + '/../rules/HL-STANDARD.md'))// the spec: linked tickets are fetched again on every run; .kunibert/spec.md only when there is something to showlet spec = { text = null, hash = null }if (ctx != null) { spec = buildSpec(ctx.ticketsBase, ctx.ticketsTokenFile, ctx.tickets) }if (spec.text != null) { writeFile(work + '/.kunibert/spec.md', spec.text) }else if (exists(work + '/.kunibert/spec.md')) { remove(work + '/.kunibert/spec.md') }let prTitle = 'Local branch review'let prBody = nullif (ctx != null && ctx.title != null) { prTitle = ctx.title.length > 300 ? ctx.title.slice(0, 300) : ctx.title prBody = ctx.body == null ? '' : ctx.body }let prompt = firstReview(spec.text != null, prTitle, prBody)if (state.session != null) { prompt = wakePrompt(state, headSha, rewritten, delta == '', updates, forced, specChange(state.specHash, spec.hash)) }else if (state.threads.length > 0) { prompt = prompt + freshThreads(state, updates) }skipNote = omitted ? 'The full diff is over the size limit, so the vendored files are left out of .kunibert/pr.diff. Do not review them; review only the app files in .kunibert/pr.diff.' : ''notes = state.pending.length > 0 ? 'Notes from the author for this review:' + state.pending.join('') : ''prompt = prompt + skipNoteif (state.session == null) { prompt = prompt + notes }// the prompt of a fresh session that replaces a resumed one (missing session, or a resumed run that read no code)restart = firstReview(spec.text != null, prTitle, prBody) + skipNote + freshThreads(state, updates) + noteslet turn = codexTurn(work, prompt, state.session, 'codex', prefixes)let attempts = [{ session = state.session, usage = turn.events.usage }]let fallback = falseif (state.session != null && (turn.code != 0 || turn.events.error != null)) {reason = (turn.events.error + ' ' + turn.stderr).toLowerCase()missing = reason.includes('session') && (reason.includes('not found') || reason.includes('no rollout') || reason.includes('does not exist') || reason.includes('no saved session') || reason.includes('unable to find session'))if (missing) {fallback = trueturn = codexTurn(work, restart, null, 'fallback', prefixes)attempts.push({ session = null, usage = turn.events.usage })}}// A resumed session on a new or forced head that ran no command (it answered from memory, e.g. "previous approval stands"):// one fresh session reads the code instead. If that run also shows no working tool, checked() still fails it (kunibert#11).needsCode = state.session == null || fallback || state.head != headSha || forcedif (state.session != null && !fallback && needsCode && turn.code == 0 && turn.events.error == null && turn.events.commandsOk == 0 && turn.events.commandsFailed == 0) {fallback = trueturn = codexTurn(work, restart, null, 'fresh', prefixes)attempts.push({ session = null, usage = turn.events.usage })}// Record cost even when result validation fails; do not consume thread deltas.let usageState = loadState(path)if (usageState.generation == generation) {for (attempt of attempts) { usageState.usage.push(attempt) }writeFile(path, JSON.stringify(usageState))}cleanup()output = checked(turn.events, turn.code, needsCode)if (output.session == null) { output.session = state.session }require(output.session != null, 'codex produced no session id')output.result = appResult(output.result, prefixes, state, settings.vendoredLink)output.result.vendoredOmitted = omittedmergedResult = mergeOpenFindings(state, output.result)output.result = mergedResult.resultlet firstNew = state.threads.lengthstate = applyResult(state, output.result)state.session = output.sessionstate.head = headShastate.verdict = output.result.verdictstate.pending = []state.specHash = spec.hashstate.rules = RULES_VERSIONfor (attempt of attempts) { state.usage.push(attempt) }if (loadState(path).generation != generation) { return { dropped = true, generation = generation, usage = output.usage } }let posted = nullif (hooks != null) {posted = hooks.post(state, firstNew, output.result, mergeBase, prev)if (posted.skipped != null) { return { skipped = posted.skipped, head = headSha, generation = generation, usage = output.usage } }if (posted.gids != null) { for (g of posted.gids) { state.threads[g.index].gid = g.id } }}writeFile(path, JSON.stringify(state))if (hooks != null) { posted = hooks.finish(state, output.result, posted) }return { session = output.session, usage = output.usage, result = output.result, merged = mergedResult.merged, fallback = fallback, generation = generation, =posted }}// A PR from gitoria: the API gives target/head/threads, the clone URL comes from the event. The token for git goes through a 0600 temp// file in <data> that is removed right after the fetch (cleanup() removes it on any failure too).reviewGitoria = (String data, String api, String keyFile, String clone, Number pr, Boolean forced = false, Boolean doReset = false, Hybrid notes = [], String ticketsBase = null, String ticketsTokenFile = null) => {connect(api, keyFile)// reset (Review again / @kunibert reset): a fresh session for this PR first, then the review; notes (@kunibert <text>) go into the next promptif (doReset) { reset(data, clone, '' + pr) }if (notes.length > 0) { addNotes(data, clone, '' + pr, notes) }pull = getPull(pr)if (pull.state != 'open') { return { skipped = 'not_open', state = pull.state } }mkDir(data)tokenPath = realPath(data) + '/.token-' + pr + '-' + randomBytes(24, 'hex')require(createFile(tokenPath, getToken() + '\n', 384), 'fetch token file already exists')live.tokenFile = tokenPathcache = cacheRepo(data, clone)fetchRefs(cache, clone, pr, pull.target, live.tokenFile)remove(live.tokenFile)live.tokenFile = nullbaseSha = git(cache, ['rev-parse', '--verify', '--end-of-options', baseLocal(pull.target) + '^{commit}']).join('')headSha = git(cache, ['rev-parse', '--verify', '--end-of-options', prHeadLocal(pr) + '^{commit}']).join('')apiThreads = getThreads(pr)hooks = {input = (state) => { return threadInput(state, apiThreads) },start = (head, willPost) => { startStatus(pr, head, willPost) },post = (state, firstNew, result, mergeBase, prev) => {r = postReview(pr, headSha, state, firstNew, result, mergeBase, cache, prev)return r},finish = (state, result, posted) => {rp = postReplies(pr, state, result)status = statusFor(result, posted)return { review = posted, replies = rp.sent, warnings = rp.warnings, status = status }}}out = runReview(statePath(data, clone, '' + pr), cache, worktreePath(settings.workDir == null ? data : settings.workDir, clone, pr), baseSha, headSha, null, forced, cache, headSha, hooks, { title = pull.title, body = pull.body, tickets = pull.tickets, =ticketsBase, =ticketsTokenFile })if (out.error != null) { errorStatus(out.error) }return out}
Branches
Latest commits
- bd3591c7conductor: gates run on the live day44 binarymre
- 47f747a7records: jukebox #9 fix livemre
- 0a3169fdMerge branch 'vendored-size' into mainKunibert
- e447bb09Vendored size fix: keep renames with an app side whole; type the filter parameter (L10)mre
- 99ccc742Vendored size fix: no renames in the app diff, filter the resumed delta toomre
- 1a52e100|||PR Diff size limit counts only app files when vendored paths are setmre
- 50a1867estatus: jukebox #9mre
- c57484e6log: jukebox #9 diff sizemre
- 795a20carecords: guard fix live (PR 8)mre
- 6981d96fMerge branch 'fresh-on-nocmd' into mainKunibert
- 37c47840runner: one shared prompt for both fresh-session fallbacks (L16)mre
- f945d2e1|||PR runner: a resumed run with no command on a new head gets one fresh session instead of a tool errormre
- 10b2a49estatus: PR 314, guard fix proposedmre
- e73995a3log: hycon PR 314 approved after fresh reviewmre
- f60427falog: hycon PR 314 false tool errormre
- 481974f7log: Hermes accepts PR 259 findingmre
- bb0976acrecords: hycon PR 259 design findingmre
- 5c637c24records: hycon PR 259 false tool errormre
- a344c406log: routger 132 reviewedmre
- 56e70dcbrecords: review time limit 1800 s (routger 132)mre