gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2177f66f2177f66fReview model runs as its own unix user (reviewUser, codexBin, workDir)Kunibert2177f66f/lib/runner.hl

14.3 KB

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

Branches

Latest commits

  • 2177f66fReview model runs as its own unix user (reviewUser, codexBin, workDir)Kunibert
  • 35df8306Records: live service on byrodin, real proof part 1Kunibert
  • 7480a98dkunibert.service: SIGTERM stop is a clean exitKunibert
  • 3a8d93f9gitoria client: parse only JSON answers, accept a plain-text errorKunibert
  • c9b48bfeVendor Hybriel plugins; deploy ships bin/ from zig-outKunibert
  • a41ba15fKunibert: event intake, git cache, review runner, posting, linked tickets, deploy filesKunibert