gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit71efaf8471efaf84Merge branch 'design-guard' into mainKunibert71efaf84/lib/runner.hl

15.7 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, settleVendored, appResult } 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 }
  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 = 900 })
  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. diff = git(repo, ['diff', '--no-ext-diff', '--no-textconv', mergeBase + '..' + headSha, '--']).join('
  104. ')
  105. if (toBytes(diff).length > maxDiffBytes) { return { error = 'diff too large', bytes = toBytes(diff).length, limit = maxDiffBytes } }
  106. let rewritten = false
  107. let delta = ''
  108. if (state.head != null && state.head != headSha) {
  109. ancestor = run(['git', 'merge-base', '--is-ancestor', state.head, headSha], { cwd = repo, timeout = 30 })
  110. require(ancestor.exit == 0 || ancestor.exit == 1, 'cannot determine ancestry; missing history')
  111. rewritten = ancestor.exit == 1
  112. if (!rewritten) {
  113. nul = JSON.parse('"\u0000"')
  114. names = git(repo, ['diff', '--no-ext-diff', '--no-textconv', '--name-status', '-z', '-M', mergeBase + '..' + headSha, '--']).join('
  115. ').split(nul)
  116. let paths = []
  117. let i = 0
  118. while (i < names.length && names[i] != '') {
  119. status = names[i]
  120. i = i + 1
  121. paths.push(names[i])
  122. i = i + 1
  123. if (status.startsWith('R') || status.startsWith('C')) { paths.push(names[i]) i = i + 1 }
  124. }
  125. if (paths.length > 0) { delta = git(repo, ['--literal-pathspecs', 'diff', '--no-ext-diff', '--no-textconv', state.head + '..' + headSha, '--'] + paths).join('
  126. ') }
  127. }
  128. }
  129. if (checkoutSha != null) { live.cache = cache live.path = work addWorktree(cache, work, checkoutSha) }
  130. mkDir(work + '/.kunibert')
  131. writeFile(work + '/.kunibert/pr.diff', diff + '
  132. ')
  133. writeFile(work + '/.kunibert/delta.diff', delta)
  134. writeFile(work + '/.kunibert/HL-STANDARD.md', readFile(dir() + '/../rules/HL-STANDARD.md'))
  135. // the spec: linked tickets are fetched again on every run; .kunibert/spec.md only when there is something to show
  136. let spec = { text = null, hash = null }
  137. if (ctx != null) { spec = buildSpec(ctx.ticketsBase, ctx.ticketsTokenFile, ctx.tickets) }
  138. if (spec.text != null) { writeFile(work + '/.kunibert/spec.md', spec.text) }
  139. else if (exists(work + '/.kunibert/spec.md')) { remove(work + '/.kunibert/spec.md') }
  140. let prTitle = 'Local branch review'
  141. let prBody = null
  142. if (ctx != null && ctx.title != null) { prTitle = ctx.title.length > 300 ? ctx.title.slice(0, 300) : ctx.title prBody = ctx.body == null ? '' : ctx.body }
  143. let prompt = firstReview(spec.text != null, prTitle, prBody)
  144. if (state.session != null) { prompt = wakePrompt(state, headSha, rewritten, delta == '', updates, forced, specChange(state.specHash, spec.hash)) }
  145. else if (state.threads.length > 0) { prompt = prompt + freshThreads(state, updates) }
  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', prefixes)
  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) + freshThreads(state, updates)
  159. turn = codexTurn(work, prompt, null, 'fallback', prefixes)
  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, state.session == null || fallback || state.head != headSha || forced)
  171. if (output.session == null) { output.session = state.session }
  172. require(output.session != null, 'codex produced no session id')
  173. output.result = appResult(output.result, prefixes, state, settings.vendoredLink)
  174. mergedResult = mergeOpenFindings(state, output.result)
  175. output.result = mergedResult.result
  176. let firstNew = state.threads.length
  177. state = applyResult(state, output.result)
  178. state.session = output.session
  179. state.head = headSha
  180. state.verdict = output.result.verdict
  181. state.pending = []
  182. state.specHash = spec.hash
  183. state.rules = RULES_VERSION
  184. for (attempt of attempts) { state.usage.push(attempt) }
  185. if (loadState(path).generation != generation) { return { dropped = true, generation = generation, usage = output.usage } }
  186. let posted = null
  187. if (hooks != null) {
  188. posted = hooks.post(state, firstNew, output.result, mergeBase, prev)
  189. if (posted.skipped != null) { return { skipped = posted.skipped, head = headSha, generation = generation, usage = output.usage } }
  190. if (posted.gids != null) { for (g of posted.gids) { state.threads[g.index].gid = g.id } }
  191. }
  192. writeFile(path, JSON.stringify(state))
  193. if (hooks != null) { posted = hooks.finish(state, output.result, posted) }
  194. return { session = output.session, usage = output.usage, result = output.result, merged = mergedResult.merged, fallback = fallback, generation = generation, =posted }
  195. }
  196. // 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
  197. // file in <data> that is removed right after the fetch (cleanup() removes it on any failure too).
  198. 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) => {
  199. connect(api, keyFile)
  200. // reset (Review again / @kunibert reset): a fresh session for this PR first, then the review; notes (@kunibert <text>) go into the next prompt
  201. if (doReset) { reset(data, clone, '' + pr) }
  202. if (notes.length > 0) { addNotes(data, clone, '' + pr, notes) }
  203. pull = getPull(pr)
  204. if (pull.state != 'open') { return { skipped = 'not_open', state = pull.state } }
  205. mkDir(data)
  206. tokenPath = realPath(data) + '/.token-' + pr + '-' + randomBytes(24, 'hex')
  207. require(createFile(tokenPath, getToken() + '\n', 384), 'fetch token file already exists')
  208. live.tokenFile = tokenPath
  209. cache = cacheRepo(data, clone)
  210. fetchRefs(cache, clone, pr, pull.target, live.tokenFile)
  211. remove(live.tokenFile)
  212. live.tokenFile = null
  213. baseSha = git(cache, ['rev-parse', '--verify', '--end-of-options', baseLocal(pull.target) + '^{commit}']).join('')
  214. headSha = git(cache, ['rev-parse', '--verify', '--end-of-options', prHeadLocal(pr) + '^{commit}']).join('')
  215. apiThreads = getThreads(pr)
  216. hooks = {
  217. input = (state) => { return threadInput(state, apiThreads) },
  218. start = (head, willPost) => { startStatus(pr, head, willPost) },
  219. post = (state, firstNew, result, mergeBase, prev) => {
  220. r = postReview(pr, headSha, state, firstNew, result, mergeBase, cache, prev)
  221. return r
  222. },
  223. finish = (state, result, posted) => {
  224. rp = postReplies(pr, state, result)
  225. status = statusFor(result, posted)
  226. return { review = posted, replies = rp.sent, warnings = rp.warnings, status = status }
  227. }
  228. }
  229. 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 })
  230. if (out.error != null) { errorStatus(out.error) }
  231. return out
  232. }

Branches

Latest commits

  • 71efaf84Merge branch 'design-guard' into mainKunibert
  • c0656581|||PR Flag removal of a documented design as major unless his recorded yes is linked; rules version 5mre
  • 901cdd75records: L10 update 2 livemre
  • 4a68016bMerge branch 'hl-standard-l10b' into mainKunibert
  • 246d0f30|||PR HL-STANDARD L10 update (hybriel ab293e5a), rules version 4mre
  • 1aa4d64crecords: HL-STANDARD L10 update livemre
  • 2b04c240Merge branch 'hl-standard-l10' into mainKunibert
  • 88c7b09d|||PR HL-STANDARD L10 update (hybriel 5885d688), rules version 3mre
  • 00869ecbrecords: gitoria#50 step 3 livemre
  • f97a0e5fMerge branch 'hl-standard' into mainKunibert
  • 9710e39fType STANDARD as String (L10, Kunibert review)mre
  • 4140b664|||PR Review against HL-STANDARD and cite rule ids (gitoria#50 step 3)mre
  • 75c6888drecords: gitoria#50 step 1 connected and provenmre
  • aa6d997frecords: gitoria#50 connect plan, Anton reportmre
  • 8a190ba7Records: kunibert#18 and #15 donemre
  • 2eee9dbbMerge branch 'revendor-day44' into mainKunibert
  • e96721cb|||PR Re-vendor plugins from Hybriel day44 (hl:fetch redirect fix)mre
  • 0c67ab8cLog: kunibert repo ping provenmre
  • b6f3039cLog: kunibert repo connectedmre
  • b143c3c7CONDUCTOR: push recipemre