gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7480a98d7480a98dkunibert.service: SIGTERM stop is a clean exitKunibert7480a98d/lib/runner.hl

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

Branches

Latest commits

  • 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