gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainbd3591c7conductor: gates run on the live day44 binarymremain/lib/runner.hl

17.1 KB

  1. $mode = 'static'
  2. import { run, dir } from 'hl:proc'
  3. import { mkDir, createFile, writeFile, readFile, realPath, remove, exists } from 'hl:fs'
  4. import { randomBytes } from 'hl:crypto'
  5. import { firstReview, withVendored, RULES_VERSION } from './review-prompt.hl'
  6. import { parseEvents, checked, require } from './review-output.hl'
  7. import { vendoredPaths, isVendored, settleVendored, appResult, appDiff } from './review-vendored.hl'
  8. git = (String repo, Hybrid argv) => {
  9. r = run(['git'] + argv, { cwd = repo, timeout = 30 })
  10. require(r.exit == 0, 'git failed (' + r.exit + '): ' + r.stderr.join(' '))
  11. return r.lines
  12. }
  13. // 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.
  14. 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={}']
  15. import { statePath, loadState, threadUpdates, threadUpdatesFrom, mergeOpenFindings, applyResult, reset, addNotes } from './review-memory.hl'
  16. import { connect } from './gitoria-api.hl'
  17. import { getPull, getToken, getThreads } from './gitoria-api.hl'
  18. import { startStatus, errorStatus, threadInput, postReview, postReplies, statusFor, finishStatus } from './review-post.hl'
  19. import { wakePrompt, freshThreads } from './review-wake.hl'
  20. import { buildSpec } from './tickets.hl'
  21. import { cacheRepo, fetchRefs, addWorktree, removeWorktree, worktreePath, prHeadLocal, baseLocal, maxDiffBytes } from './gitcache.hl'
  22. // A worktree that is live right now; the global error handler of the tool removes it on any failure.
  23. live = { cache = null, path = null, tokenFile = null }
  24. cleanup = () => {
  25. if (live.tokenFile != null) { if (exists(live.tokenFile)) { remove(live.tokenFile) } live.tokenFile = null }
  26. if (live.path != null) { removeWorktree(live.cache, live.path) live.path = null }
  27. }
  28. // Where and as whom the model runs (set by tools/runner.hl from --review-user/--codex-bin/--work-dir). reviewUser == null: codex runs as
  29. // 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.
  30. settings = { reviewUser = null, codexBin = 'codex', workDir = null, vendored = [], vendoredLink = null, timeoutSeconds = 900 }
  31. reviewHome = (String user) => { return '/home/' + user }
  32. codexTurn = (String repo, String instructions, String session, String label, Hybrid prefixes) => {
  33. fullPrompt = withVendored(instructions, prefixes)
  34. writeFile(repo + '/.kunibert/' + label + '-prompt.md', fullPrompt)
  35. let prompt = fullPrompt
  36. if (toBytes(prompt).length > 16000) {
  37. writeFile(repo + '/.kunibert/prompt.md', prompt)
  38. prompt = 'Your full instructions for this turn are in the file .kunibert/prompt.md. Read all of it first, then follow it exactly.'
  39. }
  40. schema = dir() + '/../schema.json'
  41. let argv = [settings.codexBin, 'exec']
  42. if (session != null) { argv = argv + ['resume', '--json', '-c', 'sandbox_mode="read-only"'] }
  43. else { argv = argv + ['--json', '-s', 'read-only', '-C', repo] }
  44. argv = argv + ['--skip-git-repo-check', '--output-schema', schema, '-c', 'model="gpt-6.1-sol"', '-c', 'model_reasoning_effort="max"'] + offline
  45. if (session != null) { argv.push(session) }
  46. argv.push(prompt)
  47. // 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):
  48. // 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.
  49. if (settings.reviewUser != null && settings.workDir != null && realPath(settings.workDir) != null && repo.startsWith(realPath(settings.workDir) + '/')) {
  50. require(run(['chmod', '-R', 'a+rX,go-w', repo], { timeout = 60 }).exit == 0, 'chmod of the worktree failed')
  51. require(run(['chmod', 'a+x', repo + '/..', repo + '/../..'], { timeout = 30 }).exit == 0, 'chmod of the worktree parents failed')
  52. }
  53. // the model's own unix user: no environment of the service (env -i), its own HOME (its own ~/.codex login)
  54. 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 }
  55. writeFile(repo + '/.kunibert/' + label + '-argv.json', JSON.stringify(argv))
  56. r = run(argv, { cwd = repo, timeout = settings.timeoutSeconds })
  57. writeFile(repo + '/.kunibert/' + label + '.jsonl', r.lines.join('
  58. ') + '
  59. ')
  60. return { events = parseEvents(r.lines), code = r.exit, stderr = r.stderr.join('
  61. ') }
  62. }
  63. // 'changed' | 'gone' | null: did the spec file differ from the last run's (hash in the state)?
  64. specChange = (String before, String now) => {
  65. if (before == now) { return null }
  66. return now == null ? 'gone' : 'changed'
  67. }
  68. review = (String data, String directory, String base, String head, String threads = null, Boolean forced = false, Hybrid ctx = null) => {
  69. repo = realPath(directory)
  70. require(repo != null, 'repository directory does not exist')
  71. baseSha = git(repo, ['rev-parse', '--verify', '--end-of-options', base + '^{commit}']).join('')
  72. headSha = git(repo, ['rev-parse', '--verify', '--end-of-options', head + '^{commit}']).join('')
  73. require(git(repo, ['rev-parse', 'HEAD']).join('') == headSha, 'working tree HEAD must match head ref')
  74. require(git(repo, ['status', '--porcelain', '--untracked-files=no']).length == 0, 'tracked working tree must be clean')
  75. return runReview(statePath(data, repo, head), repo, repo, baseSha, headSha, threads, forced, null, null, null, ctx)
  76. }
  77. // A PR from a remote: bare cache, forced fetch, worktree only for the model run (removed after, also on failure).
  78. reviewPr = (String data, String url, Number pr, String base, String tokenFile = null, String threads = null, Boolean forced = false) => {
  79. cache = cacheRepo(data, url)
  80. fetchRefs(cache, url, pr, base, tokenFile)
  81. baseSha = git(cache, ['rev-parse', '--verify', '--end-of-options', baseLocal(base) + '^{commit}']).join('')
  82. headSha = git(cache, ['rev-parse', '--verify', '--end-of-options', prHeadLocal(pr) + '^{commit}']).join('')
  83. return runReview(statePath(data, url, '' + pr), cache, worktreePath(data, url, pr), baseSha, headSha, threads, forced, cache, headSha)
  84. }
  85. // gitDir: where git questions are asked (repo or bare cache); work: where .kunibert is written and the model runs.
  86. // checkoutSha != null: work does not exist yet; make it (detached worktree of the cache) once a model run is certain.
  87. // ctx != null: { title, body, tickets (ids), ticketsBase, ticketsTokenFile } (PR text and the tickets the PR links to).
  88. // hooks != null (gitoria mode): { input(state) -> thread array, start(head), post(state, firstNew, result, mergeBase) -> { skipped } | extras, finish(state, result) -> extras }.
  89. 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) => {
  90. repo = gitDir
  91. let state = loadState(path)
  92. generation = state.generation
  93. prefixes = vendoredPaths(gitDir, headSha, settings.vendored)
  94. state = settleVendored(state, prefixes)
  95. let changes = null
  96. if (hooks != null) { changes = threadUpdatesFrom(state, hooks.input(state)) } else { changes = threadUpdates(state, threads) }
  97. state = changes.state
  98. updates = changes.updates
  99. if (state.head == headSha && updates.length == 0 && state.pending.length == 0 && !forced && state.session != null) { return { skipped = true, head = headSha, generation = generation } }
  100. mergeBase = git(repo, ['merge-base', baseSha, headSha]).join('')
  101. let prev = { head = state.head, verdict = state.verdict, =forced }
  102. if (hooks != null) { hooks.start(headSha, state.head != headSha || forced) }
  103. let diff = git(repo, ['diff', '--no-ext-diff', '--no-textconv', mergeBase + '..' + headSha, '--']).join('
  104. ')
  105. // over the limit with vendored paths: review the app part only; the vendored files are named as skipped
  106. omitted = toBytes(diff).length > maxDiffBytes && prefixes.length > 0
  107. if (omitted) { diff = appDiff(repo, mergeBase + '..' + headSha, prefixes) }
  108. if (toBytes(diff).length > maxDiffBytes) { return { error = 'diff too large', bytes = toBytes(diff).length, limit = maxDiffBytes } }
  109. let rewritten = false
  110. let delta = ''
  111. if (state.head != null && state.head != headSha) {
  112. ancestor = run(['git', 'merge-base', '--is-ancestor', state.head, headSha], { cwd = repo, timeout = 30 })
  113. require(ancestor.exit == 0 || ancestor.exit == 1, 'cannot determine ancestry; missing history')
  114. rewritten = ancestor.exit == 1
  115. if (!rewritten) {
  116. nul = JSON.parse('"\u0000"')
  117. names = git(repo, ['diff', '--no-ext-diff', '--no-textconv', '--name-status', '-z', '-M', mergeBase + '..' + headSha, '--']).join('
  118. ').split(nul)
  119. let paths = []
  120. let i = 0
  121. while (i < names.length && names[i] != '') {
  122. status = names[i]
  123. i = i + 1
  124. paths.push(names[i])
  125. i = i + 1
  126. if (status.startsWith('R') || status.startsWith('C')) { paths.push(names[i]) i = i + 1 }
  127. }
  128. if (omitted) { paths = paths.filter((String p) => { return !isVendored(p, prefixes) }) }
  129. if (paths.length > 0) { delta = git(repo, ['--literal-pathspecs', 'diff', '--no-ext-diff', '--no-textconv', state.head + '..' + headSha, '--'] + paths).join('
  130. ') }
  131. }
  132. }
  133. if (checkoutSha != null) { live.cache = cache live.path = work addWorktree(cache, work, checkoutSha) }
  134. mkDir(work + '/.kunibert')
  135. writeFile(work + '/.kunibert/pr.diff', diff + '
  136. ')
  137. writeFile(work + '/.kunibert/delta.diff', delta)
  138. writeFile(work + '/.kunibert/HL-STANDARD.md', readFile(dir() + '/../rules/HL-STANDARD.md'))
  139. // the spec: linked tickets are fetched again on every run; .kunibert/spec.md only when there is something to show
  140. let spec = { text = null, hash = null }
  141. if (ctx != null) { spec = buildSpec(ctx.ticketsBase, ctx.ticketsTokenFile, ctx.tickets) }
  142. if (spec.text != null) { writeFile(work + '/.kunibert/spec.md', spec.text) }
  143. else if (exists(work + '/.kunibert/spec.md')) { remove(work + '/.kunibert/spec.md') }
  144. let prTitle = 'Local branch review'
  145. let prBody = null
  146. if (ctx != null && ctx.title != null) { prTitle = ctx.title.length > 300 ? ctx.title.slice(0, 300) : ctx.title prBody = ctx.body == null ? '' : ctx.body }
  147. let prompt = firstReview(spec.text != null, prTitle, prBody)
  148. if (state.session != null) { prompt = wakePrompt(state, headSha, rewritten, delta == '', updates, forced, specChange(state.specHash, spec.hash)) }
  149. else if (state.threads.length > 0) { prompt = prompt + freshThreads(state, updates) }
  150. skipNote = omitted ? '
  151. 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.' : ''
  152. notes = state.pending.length > 0 ? '
  153. Notes from the author for this review:
  154. ' + state.pending.join('
  155. ') : ''
  156. prompt = prompt + skipNote
  157. if (state.session == null) { prompt = prompt + notes }
  158. // the prompt of a fresh session that replaces a resumed one (missing session, or a resumed run that read no code)
  159. restart = firstReview(spec.text != null, prTitle, prBody) + skipNote + freshThreads(state, updates) + notes
  160. let turn = codexTurn(work, prompt, state.session, 'codex', prefixes)
  161. let attempts = [{ session = state.session, usage = turn.events.usage }]
  162. let fallback = false
  163. if (state.session != null && (turn.code != 0 || turn.events.error != null)) {
  164. reason = (turn.events.error + ' ' + turn.stderr).toLowerCase()
  165. 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'))
  166. if (missing) {
  167. fallback = true
  168. turn = codexTurn(work, restart, null, 'fallback', prefixes)
  169. attempts.push({ session = null, usage = turn.events.usage })
  170. }
  171. }
  172. // A resumed session on a new or forced head that ran no command (it answered from memory, e.g. "previous approval stands"):
  173. // one fresh session reads the code instead. If that run also shows no working tool, checked() still fails it (kunibert#11).
  174. needsCode = state.session == null || fallback || state.head != headSha || forced
  175. if (state.session != null && !fallback && needsCode && turn.code == 0 && turn.events.error == null && turn.events.commandsOk == 0 && turn.events.commandsFailed == 0) {
  176. fallback = true
  177. turn = codexTurn(work, restart, null, 'fresh', prefixes)
  178. attempts.push({ session = null, usage = turn.events.usage })
  179. }
  180. // Record cost even when result validation fails; do not consume thread deltas.
  181. let usageState = loadState(path)
  182. if (usageState.generation == generation) {
  183. for (attempt of attempts) { usageState.usage.push(attempt) }
  184. writeFile(path, JSON.stringify(usageState))
  185. }
  186. cleanup()
  187. output = checked(turn.events, turn.code, needsCode)
  188. if (output.session == null) { output.session = state.session }
  189. require(output.session != null, 'codex produced no session id')
  190. output.result = appResult(output.result, prefixes, state, settings.vendoredLink)
  191. output.result.vendoredOmitted = omitted
  192. mergedResult = mergeOpenFindings(state, output.result)
  193. output.result = mergedResult.result
  194. let firstNew = state.threads.length
  195. state = applyResult(state, output.result)
  196. state.session = output.session
  197. state.head = headSha
  198. state.verdict = output.result.verdict
  199. state.pending = []
  200. state.specHash = spec.hash
  201. state.rules = RULES_VERSION
  202. for (attempt of attempts) { state.usage.push(attempt) }
  203. if (loadState(path).generation != generation) { return { dropped = true, generation = generation, usage = output.usage } }
  204. let posted = null
  205. if (hooks != null) {
  206. posted = hooks.post(state, firstNew, output.result, mergeBase, prev)
  207. if (posted.skipped != null) { return { skipped = posted.skipped, head = headSha, generation = generation, usage = output.usage } }
  208. if (posted.gids != null) { for (g of posted.gids) { state.threads[g.index].gid = g.id } }
  209. }
  210. writeFile(path, JSON.stringify(state))
  211. if (hooks != null) { posted = hooks.finish(state, output.result, posted) }
  212. return { session = output.session, usage = output.usage, result = output.result, merged = mergedResult.merged, fallback = fallback, generation = generation, =posted }
  213. }
  214. // 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
  215. // file in <data> that is removed right after the fetch (cleanup() removes it on any failure too).
  216. 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) => {
  217. connect(api, keyFile)
  218. // reset (Review again / @kunibert reset): a fresh session for this PR first, then the review; notes (@kunibert <text>) go into the next prompt
  219. if (doReset) { reset(data, clone, '' + pr) }
  220. if (notes.length > 0) { addNotes(data, clone, '' + pr, notes) }
  221. pull = getPull(pr)
  222. if (pull.state != 'open') { return { skipped = 'not_open', state = pull.state } }
  223. mkDir(data)
  224. tokenPath = realPath(data) + '/.token-' + pr + '-' + randomBytes(24, 'hex')
  225. require(createFile(tokenPath, getToken() + '\n', 384), 'fetch token file already exists')
  226. live.tokenFile = tokenPath
  227. cache = cacheRepo(data, clone)
  228. fetchRefs(cache, clone, pr, pull.target, live.tokenFile)
  229. remove(live.tokenFile)
  230. live.tokenFile = null
  231. baseSha = git(cache, ['rev-parse', '--verify', '--end-of-options', baseLocal(pull.target) + '^{commit}']).join('')
  232. headSha = git(cache, ['rev-parse', '--verify', '--end-of-options', prHeadLocal(pr) + '^{commit}']).join('')
  233. apiThreads = getThreads(pr)
  234. hooks = {
  235. input = (state) => { return threadInput(state, apiThreads) },
  236. start = (head, willPost) => { startStatus(pr, head, willPost) },
  237. post = (state, firstNew, result, mergeBase, prev) => {
  238. r = postReview(pr, headSha, state, firstNew, result, mergeBase, cache, prev)
  239. return r
  240. },
  241. finish = (state, result, posted) => {
  242. rp = postReplies(pr, state, result)
  243. status = statusFor(result, posted)
  244. return { review = posted, replies = rp.sent, warnings = rp.warnings, status = status }
  245. }
  246. }
  247. 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 })
  248. if (out.error != null) { errorStatus(out.error) }
  249. return out
  250. }

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