gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit268ebfe6268ebfe6Records: #11 proven live and closedmre268ebfe6/lib/runner.hl

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

Branches

Latest commits

  • 268ebfe6Records: #11 proven live and closedmre
  • 88e8aad3Records: K11 verified and deployedmre
  • cd4cb09cNo review and status error when the model's tools did not run (kunibert#11)Kunibert
  • a6b54efaStatus updatemre
  • 5a72268eRecords: #4-#10 done, #11 started, review package on #1mre
  • 194c7da6Records: real proof greenmre
  • cdfa94a9Records: AppArmor profile for the review sandboxmre
  • c1bf02d8Status: sandbox blockermre
  • 88aaacc5Records: real proof part 2 (posting works, sandbox blocked by AppArmor userns)mre
  • 401df4e8Records: review user logged inmre
  • 6ca681b3Records: login command, status cleanupmre
  • 6b8d763cRecords: review user, device login startedKunibert
  • 07025b99Open the job worktree read-only for the review user before each model runKunibert
  • 2a44bd54Runner CLI: --review-user/--codex-bin/--work-dir work in every modeKunibert
  • 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