gitoria

kunibert

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainbd3591c7conductor: gates run on the live day44 binarymremain/docs/reviewer-design/2-prompts-and-memory.md

9.8 KB

  1. # The earlier reviewer handover part 2: prompts, runner, memory rules (verbatim from the earlier setup/reference-reviewer)
  2. ## The first-review prompt (verbatim)
  3. ```
  4. export const PROMPT = (repo: string, pr: number, title: string, body: string, hasSpec: boolean) => `You are the earlier reviewer, the code reviewer of the earlier setup. Review pull request #${pr} of ${repo}: "${title}".
  5. The checked-out working tree is the PR head. The unified diff is in the file .reviewer/pr.diff (read it first); read surrounding code as needed. Do not modify files.
  6. Review along three separate axes and tag every finding with its axis. Judge each axis on its own; never let one axis mask or outrank another.
  7. 1. correctness: real problems the author would want to fix: bugs, security issues, data loss, broken edge cases, missing error handling, wrong tests.
  8. 2. spec: ${hasSpec ? 'the originating ticket(s) are in .reviewer/spec.md, each with its comments in chronological order. The spec is the description as amended by the comments: a later comment that drops, changes or adds a requirement overrules the description and earlier comments, so judge against the latest decision and never report a requirement a later comment dropped. Where the comments leave it unclear which version holds, report one minor spec finding naming the conflict instead of a gap. Report (a) acceptance criteria / requirements that are missing or only partial, (b) behaviour the diff adds that the spec did not ask for (scope creep), (c) requirements that look implemented but wrongly. Quote the spec line in every spec finding.' : 'no ticket or issue is linked, so there are no spec findings; say so in axes.spec.'}
  9. 3. standards: the repo's documented rules: AGENTS.md, CLAUDE.md (and files they include with @path), CONTRIBUTING.md, CODING_STANDARDS.md, at the repo root and in the directories of changed files. Report every place the diff breaks a documented rule and cite it (file + the rule's words). Skip anything a linter or formatter already enforces. You may add code smells (e.g. duplicated code, mysterious name, speculative generality, feature envy) only as severity nit, titled "possible <smell>": they are judgement calls, and a documented repo rule always overrides them.
  10. Every finding needs the exact file path and the line number on the NEW side that appears in the diff (for a spec finding about something missing, use the closest relevant changed line). Be concrete and short; say what is wrong and how to fix it.
  11. summary: two sentences overall. axes: one or two sentences per axis (its result, or that it is clean).
  12. verdict: request_changes if any blocker or major finding, approve if there are no findings, otherwise comment.
  13. replies: answers to earlier review threads by key (e.g. T2); empty on a first review without earlier threads.
  14. PR description:
  15. ${body.slice(0, 4000)}`
  16. /**
  17. * One codex turn. Without `session` a new session starts (its id comes back for later wake-ups);
  18. * with it, that session resumes in `dir` (the new checkout) and gets only `prompt`.
  19. */
  20. export async function runCodex(dir: string, prompt: string, files: { diff: string; delta?: string | null; spec?: string | null }, session: string | null = null): Promise<{ result: Result; session: string | null }> {
  21. mkdirSync(join(dir, '.reviewer'), { recursive: true })
  22. if (files.diff) await Bun.write(join(dir, '.reviewer/pr.diff'), files.diff.slice(0, config.maxDiffBytes))
  23. if (files.delta) await Bun.write(join(dir, '.reviewer/delta.diff'), files.delta.slice(0, config.maxDiffBytes))
  24. if (files.spec) await Bun.write(join(dir, '.reviewer/spec.md'), files.spec)
  25. // one argv entry is capped (~128 KB on Linux): a long prompt goes to a file the model reads first
  26. if (Buffer.byteLength(prompt) > 16_000) {
  27. await Bun.write(join(dir, '.reviewer/prompt.md'), prompt)
  28. prompt = 'Your full instructions for this turn are in the file .reviewer/prompt.md. Read all of it first, then follow it exactly.'
  29. }
  30. const schema = resolve(import.meta.dir, 'schema.json')
  31. const args = session
  32. ? ['exec', 'resume', '--json', '-c', 'sandbox_mode="read-only"', '--skip-git-repo-check', '--output-schema', schema, session, prompt]
  33. : ['exec', '--json', '-s', 'read-only', '--skip-git-repo-check', '-C', dir, '--output-schema', schema, prompt]
  34. // events go to stdout as JSONL (progress to stderr), so the codex user needs no write access to our dirs
  35. const [cmd, argv] = config.codexUser ? ['sudo', ['-n', '-H', '-u', config.codexUser, config.codexBin, ...args]] as const : [config.codexBin, args] as const
  36. const r = await run(cmd, [...argv], { cwd: dir, timeoutMs: config.codexTimeoutMs, stdoutOnly: true })
  37. if (r.code) throw new Error(`codex failed (${r.code}): ${codexError(r.out) ?? r.err.slice(-400)}`)
  38. const ev = parseEvents(r.out)
  39. return { result: parseResult(ev.message), session: ev.session ?? session }
  40. }
  41. /** codex --json output: the session id and the last agent message. */
  42. /** The last error codex reported in its --json events (stderr only holds progress). */
  43. export function codexError(out: string): string | null {
  44. let msg: string | null = null
  45. for (const l of out.split('\n')) {
  46. if (!l.startsWith('{')) continue
  47. try {
  48. const e = JSON.parse(l)
  49. if (e.type === 'error' || e.type === 'turn.failed') msg = String(e.message ?? e.error?.message ?? JSON.stringify(e)).slice(0, 400)
  50. } catch {}
  51. }
  52. return msg
  53. }
  54. export function parseEvents(out: string): { session: string | null; message: string } {
  55. let session: string | null = null
  56. let message = ''
  57. for (const l of out.split('\n')) {
  58. if (!l.startsWith('{')) continue
  59. try {
  60. const e = JSON.parse(l)
  61. if (e.type === 'thread.started' && e.thread_id) session = e.thread_id
  62. if (e.type === 'item.completed' && e.item?.type === 'agent_message' && typeof e.item.text === 'string') message = e.item.text
  63. } catch {}
  64. }
  65. if (!message) throw new Error('codex produced no final message')
  66. return { session, message }
  67. }
  68. export function parseResult(out: string): Result {
  69. const t = out.trim()
  70. const j = t.slice(t.indexOf('{'), t.lastIndexOf('}') + 1)
  71. const r = JSON.parse(j) as Result
  72. if (typeof r.summary !== 'string' || !Array.isArray(r.findings)) throw new Error('codex result malformed')
  73. for (const f of r.findings) if (!AXES.includes(f.axis)) f.axis = 'correctness'
  74. if (!Array.isArray(r.replies)) r.replies = []
  75. return r
  76. }
  77. ```
  78. ## Memory rules + wake-up prompt (verbatim)
  79. ```
  80. export const RULES = `Memory rules:
  81. - A thread that is resolved, or where the author replied with a reason you accept, is settled: never raise that point again, not as a new finding and not reworded.
  82. - If a reply does not convince you and the point still matters, answer in that thread through "replies" (thread key, e.g. T3) instead of a new finding. Keep it short.
  83. - If a thread's problem is fixed by the new code, reply briefly with resolve: true.
  84. - "findings" holds only NEW points: problems in the new changes, or ones you missed before.
  85. - verdict reflects the whole PR as it stands now: unresolved blocking points still count.
  86. - Scope is exactly .reviewer/pr.diff (merge base..head). Code that arrived by merging the base branch into the PR is not the author's change: never review it and never report it as scope creep.`
  87. /** Prompt for a resumed session: only what changed since its last run, never the history it already has. */
  88. export function wakePrompt(o: { sha: string; lastSha: string | null; newCommits: boolean; rewritten: boolean; emptyDelta?: boolean; delta: ReturnType<typeof threadDelta>; requested?: boolean; open?: string; spec?: boolean; notes?: string }): string {
  89. const parts = [`Wake-up: pull request head is now ${o.sha.slice(0, 10)}. The working tree is that commit.`]
  90. if (o.requested) parts.push('The author asked for a review again: look again at your open threads and the changes below, still within the memory rules below; a full fresh review is `@reviewer reset`, not this.')
  91. if (o.rewritten) parts.push('The branch history was rewritten since your last review, so there is no reliable delta: re-read .reviewer/pr.diff for what changed.')
  92. else if (o.newCommits && o.emptyDelta) parts.push(`New commits since your last review (${o.lastSha?.slice(0, 10)}..${o.sha.slice(0, 10)}) touch none of this PR's files (e.g. a merge from the base branch): there is no new PR code to review.`)
  93. else if (o.newCommits) parts.push(`Changes since your last review (${o.lastSha?.slice(0, 10)}..${o.sha.slice(0, 10)}, limited to the files of this PR, so changes merged in from the base branch are left out) are in .reviewer/delta.diff. Review those. The whole PR diff, which is the scope, is in .reviewer/pr.diff: a delta hunk that is not part of it came from the base branch.`)
  94. else parts.push('No new commits since your last review; do not re-review code you already reviewed.')
  95. if (o.delta.length) {
  96. parts.push('Updates on your review threads since your last run:')
  97. for (const d of o.delta) {
  98. const bits = [`${d.key} ${where(d.t)} "${titleOf(d.t)}"`]
  99. if (d.flipped) bits.push(d.t.resolved ? 'was RESOLVED' : 'was REOPENED')
  100. for (const c of d.newComments) bits.push(`${c.author} replied: "${c.body.replace(/\s+/g, ' ').trim()}"`)
  101. parts.push(`- ${bits.join('; ')}`)
  102. }
  103. } else parts.push('No updates on your review threads.')
  104. if (o.notes) parts.push(o.notes)
  105. if (o.spec) parts.push('The ticket spec in .reviewer/spec.md was fetched fresh for this run (description plus comments, oldest first). Re-read it: a later comment overrules the description and earlier comments. If a comment dropped a requirement one of your open spec threads asks for, reply on that thread with resolve: true and do not raise it again.')
  106. if (o.open) parts.push(`Keys of the threads your last review posted (for "replies"; resolve those the new code fixes):\n${o.open}`)
  107. parts.push(RULES, 'Answer in the same JSON format as before (summary, axes, verdict, findings, replies).')
  108. return parts.join('\n')
  109. }
  110. ```

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