co-maintainer 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/ai/batch.d.ts +19 -16
  3. package/dist/src/ai/batch.js +68 -46
  4. package/dist/src/cli/args.js +3 -2
  5. package/dist/src/cli/commands/registry.js +66 -17
  6. package/dist/src/cli/commands/set.js +102 -1
  7. package/dist/src/cli/review_args.d.ts +15 -0
  8. package/dist/src/cli/review_args.js +41 -1
  9. package/dist/src/config.d.ts +7 -0
  10. package/dist/src/github/collect.js +19 -1
  11. package/dist/src/knowledge/guide.d.ts +19 -4
  12. package/dist/src/knowledge/guide.js +222 -87
  13. package/dist/src/knowledge/skill.d.ts +4 -5
  14. package/dist/src/knowledge/skill.js +27 -35
  15. package/dist/src/knowledge/synthesis.d.ts +0 -13
  16. package/dist/src/knowledge/synthesis.js +176 -84
  17. package/dist/src/knowledge/types.d.ts +22 -0
  18. package/dist/src/local/review_local.js +4 -1
  19. package/dist/src/pr/reviewer.js +3 -2
  20. package/dist/src/remote/client.js +14 -1
  21. package/dist/src/remote/schema.d.ts +3 -0
  22. package/dist/src/remote/schema.js +3 -0
  23. package/dist/src/remote/validate.js +12 -1
  24. package/dist/src/review/system_prompt.d.ts +19 -0
  25. package/dist/src/review/system_prompt.js +34 -0
  26. package/dist/src/server/api/repos.js +56 -2
  27. package/dist/src/server/pages/client.d.ts +1 -1
  28. package/dist/src/server/pages/client.js +1 -1
  29. package/dist/src/server/pages/repo_settings.js +31 -0
  30. package/dist/src/services/remote_review.js +31 -2
  31. package/dist/src/services/review.js +2 -1
  32. package/dist/src/services/setup.js +63 -53
  33. package/dist/src/store/migrations.js +7 -0
  34. package/dist/src/store/remote_review_inputs.d.ts +2 -0
  35. package/dist/src/store/remote_review_inputs.js +3 -3
  36. package/dist/src/store/rows.d.ts +3 -0
  37. package/dist/src/types.d.ts +11 -0
  38. package/package.json +1 -1
@@ -2,6 +2,7 @@ import { errorResponse } from "../errors.js";
2
2
  import { AppClient, findInstallationForRepo } from "../../github/app.js";
3
3
  import { activateRepo, deactivateRepo, getRepo, listActiveRepos, updateRepoSettings, } from "../../store/repos.js";
4
4
  import { readConfig, writeRepoConfig } from "../../config.js";
5
+ import { checkReviewSystemPrompt, reviewSystemPromptLimit, } from "../../review/system_prompt.js";
5
6
  import { parseRemakeCron } from "../../services/remake_cron.js";
6
7
  import { parsePolicy, policyToStore, describePolicy, } from "../../services/review_policy.js";
7
8
  import { enqueueSetup } from "../../services/setup.js";
@@ -198,6 +199,53 @@ export async function handleReposRoute(request, url, githubApp) {
198
199
  }
199
200
  }
200
201
  const patch = {};
202
+ // The repository's own review instructions live in config.json, not the
203
+ // database, so they go through writeRepoConfig below.
204
+ const promptPatch = {};
205
+ if ("reviewSystemPromptMaxChars" in body) {
206
+ const raw = body.reviewSystemPromptMaxChars;
207
+ if (raw === null || raw === "") {
208
+ promptPatch.reviewSystemPromptMaxChars = undefined;
209
+ }
210
+ else if (typeof raw === "number" && Number.isInteger(raw)) {
211
+ promptPatch.reviewSystemPromptMaxChars = raw;
212
+ }
213
+ else {
214
+ return errorResponse(422, "invalid_review_system_prompt_limit", "reviewSystemPromptMaxChars must be an integer (0 or -1 for no limit) or null");
215
+ }
216
+ }
217
+ if ("reviewSystemPrompt" in body) {
218
+ const raw = body.reviewSystemPrompt;
219
+ if (raw === null || raw === "") {
220
+ promptPatch.reviewSystemPrompt = undefined;
221
+ }
222
+ else if (typeof raw === "string") {
223
+ promptPatch.reviewSystemPrompt = raw.trim() === "" ? undefined : raw;
224
+ }
225
+ else {
226
+ return errorResponse(422, "invalid_review_system_prompt", "reviewSystemPrompt must be text or null");
227
+ }
228
+ }
229
+ // The prompt after this write is the one given here, or the stored one.
230
+ // Lowering the cap re-checks the stored prompt too.
231
+ if ("reviewSystemPrompt" in promptPatch ||
232
+ "reviewSystemPromptMaxChars" in promptPatch) {
233
+ const existing = readConfig().repos?.[fullName] ?? {};
234
+ const effectiveMax = "reviewSystemPromptMaxChars" in promptPatch
235
+ ? promptPatch.reviewSystemPromptMaxChars
236
+ : existing.reviewSystemPromptMaxChars;
237
+ const effectivePrompt = "reviewSystemPrompt" in promptPatch
238
+ ? promptPatch.reviewSystemPrompt
239
+ : existing.reviewSystemPrompt;
240
+ if (effectivePrompt !== undefined) {
241
+ const problem = checkReviewSystemPrompt(effectivePrompt, reviewSystemPromptLimit({
242
+ reviewSystemPromptMaxChars: effectiveMax,
243
+ }));
244
+ if (problem) {
245
+ return errorResponse(422, "invalid_review_system_prompt", `reviewSystemPrompt ${problem}`);
246
+ }
247
+ }
248
+ }
201
249
  if ("reviewPolicy" in body) {
202
250
  const stored = policyToStore(body.reviewPolicy, { allowLegacy: true });
203
251
  if (!stored.ok) {
@@ -248,8 +296,14 @@ export async function handleReposRoute(request, url, githubApp) {
248
296
  init[key] = body[key];
249
297
  }
250
298
  }
251
- if (Object.keys(init).length > 0 || "remakeCron" in cronPatch) {
252
- await writeRepoConfig(fullName, { ...init, ...cronPatch });
299
+ if (Object.keys(init).length > 0 ||
300
+ "remakeCron" in cronPatch ||
301
+ Object.keys(promptPatch).length > 0) {
302
+ await writeRepoConfig(fullName, {
303
+ ...init,
304
+ ...cronPatch,
305
+ ...promptPatch,
306
+ });
253
307
  }
254
308
  return Response.json({ ok: true });
255
309
  }
@@ -1,2 +1,2 @@
1
1
  /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs — do not edit. */
2
- export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. */\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
2
+ export declare const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
@@ -1,2 +1,2 @@
1
1
  /** Generated from src/server/pages/client.js by scripts/embed_assets.mjs — do not edit. */
2
- export const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. */\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
2
+ export const client = "function toast(message) {\n const host = document.getElementById(\"toasts\");\n if (!host) return;\n const el = document.createElement(\"div\");\n el.className = \"toast\";\n el.setAttribute(\"role\", \"status\");\n el.textContent = message;\n host.appendChild(el);\n setTimeout(function () {\n el.remove();\n }, 5000);\n}\n\nfunction fail(card, message, retry) {\n toast(message);\n if (!card) return;\n let box = card.querySelector(\"[data-fail]\");\n if (!box) {\n box = document.createElement(\"div\");\n box.setAttribute(\"data-fail\", \"1\");\n box.className = \"fail\";\n card.appendChild(box);\n }\n box.replaceChildren();\n const p = document.createElement(\"p\");\n p.textContent = message;\n const btn = document.createElement(\"button\");\n btn.className = \"btn sm\";\n btn.type = \"button\";\n btn.textContent = \"Retry\";\n btn.addEventListener(\"click\", retry);\n box.appendChild(p);\n box.appendChild(btn);\n}\n\nfunction clearFail(card) {\n const box = card && card.querySelector(\"[data-fail]\");\n if (box) box.remove();\n}\n\nfunction skeleton(card, on) {\n if (!card) return;\n card.classList.toggle(\"busy\", on);\n}\n\nasync function api(method, url, body) {\n const res = await fetch(url, {\n method: method,\n headers: {\n \"content-type\": \"application/json\",\n \"x-requested-with\": \"co-maintainer\",\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n let message = \"Request failed\";\n let code = \"\";\n let detail;\n try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n if (data.error && data.error.code) code = data.error.code;\n if (data.error) detail = data.error.detail;\n } catch {\n // body was not JSON; keep the generic message\n }\n const error = new Error(message);\n if (code) error.code = code;\n error.detail = detail;\n throw error;\n }\n if (res.status === 204) return null;\n return await res.json();\n}\n\nasync function run(btn, card, fn) {\n if (btn) btn.disabled = true;\n skeleton(card, true);\n clearFail(card);\n try {\n await fn();\n } catch (err) {\n fail(card, err.message, function () {\n run(btn, card, fn);\n });\n } finally {\n if (btn) btn.disabled = false;\n skeleton(card, false);\n }\n}\n\n/** Polls one job until it reaches a terminal status. A running `init`/`remake`\n * ignores the abort signal, so \"wait for the sync\" is the only honest option\n * the clear pages can offer for it. */\nfunction waitForJob(id) {\n return new Promise(function (resolve, reject) {\n let attempts = 0;\n async function tick() {\n attempts++;\n try {\n const res = await fetch(\"/api/jobs/\" + encodeURIComponent(id), {\n headers: { \"x-requested-with\": \"co-maintainer\" },\n });\n if (!res.ok) throw new Error(\"Could not check the running job.\");\n const job = await res.json();\n if (job.status !== \"running\" && job.status !== \"queued\") {\n resolve();\n return;\n }\n if (attempts > 1200) {\n reject(new Error(\"The sync did not finish.\"));\n return;\n }\n setTimeout(tick, 3000);\n } catch (err) {\n reject(err);\n }\n }\n tick();\n });\n}\n\n/** Clears knowledge, asking about pending jobs when the server refuses.\n * Returns false when the user backed out, so the caller does not reload.\n * A running review is abortable and a running setup is not, which is the\n * difference between the two questions. Called from the inline scripts on the\n * knowledge pages, so it looks unused from inside this file. */\n// oxlint-disable-next-line no-unused-vars\nasync function clearKnowledge(url, includeCache) {\n const target = includeCache ? url + \"?includeCache=1\" : url;\n const retry = target.indexOf(\"?\") >= 0 ? \"&\" : \"?\";\n try {\n await api(\"DELETE\", target);\n } catch (err) {\n if (err.code !== \"jobs_running\") throw err;\n const detail = err.detail || { queued: 0, running: [] };\n const running = detail.running || [];\n const setup = running.find(function (job) {\n return job.abortable === false;\n });\n if (setup) {\n if (\n !confirm(\n \"A sync is running and cannot be stopped. Wait for it to finish and then clear?\",\n )\n ) {\n return false;\n }\n await waitForJob(setup.id);\n await api(\"DELETE\", target);\n return;\n }\n const parts = [];\n if (running.length) parts.push(running.length + \" running review(s)\");\n if (detail.queued) parts.push(detail.queued + \" queued job(s)\");\n if (!confirm(\"Stop \" + parts.join(\" and \") + \" and clear?\")) return false;\n try {\n await api(\"DELETE\", target + retry + \"onRunning=abort\");\n } catch (retryError) {\n // A setup job was claimed between the first 409 and this retry. It\n // cannot be aborted, so wait it out like the branch above.\n if (retryError.code !== \"job_not_abortable\") throw retryError;\n const jobId = retryError.detail && retryError.detail.id;\n if (jobId) await waitForJob(jobId);\n await api(\"DELETE\", target);\n }\n }\n}\n\nasync function postAndGo(url, body, next, btn) {\n const card = btn && btn.closest(\"[data-async]\");\n await run(btn, card, async function () {\n await api(\"POST\", url, body);\n location.href = next;\n });\n}\n\n// Called from the inline scripts on the repo list and repo pages, which deno lint\n// cannot see, so it looks unused from inside this file.\n// deno-lint-ignore no-unused-vars\n// oxlint-disable-next-line no-unused-vars\nfunction bindToggle(btn, url, field) {\n btn.addEventListener(\"click\", async function () {\n if (btn.disabled) return;\n const on = !btn.classList.contains(\"on\");\n btn.classList.toggle(\"on\", on);\n btn.setAttribute(\"data-on\", on ? \"1\" : \"0\");\n btn.disabled = true;\n const card = btn.closest(\"[data-async]\");\n try {\n const payload = {};\n payload[field] = on;\n await api(\"PATCH\", url, payload);\n } catch (err) {\n btn.classList.toggle(\"on\", !on);\n btn.setAttribute(\"data-on\", on ? \"0\" : \"1\");\n fail(card, err.message, function () {\n btn.click();\n });\n } finally {\n btn.disabled = false;\n }\n });\n}\n\n// The helper is inlined into `<head>` by `layout.ts`, before any page script\n// runs, so this is the one place that can close over both `toast()` and\n// `bindToggle` without depending on point-in-time globals.\ndocument.addEventListener(\"DOMContentLoaded\", function () {\n // Client errors bubble to `window` from `document`.\n addEventListener(\"error\", function (ev) {\n toast((ev.error && ev.error.message) || \"Something broke\");\n });\n addEventListener(\"unhandledrejection\", function (ev) {\n toast((ev.reason && ev.reason.message) || \"Something broke\");\n });\n\n document.addEventListener(\"click\", function (ev) {\n const btn =\n ev.target && ev.target.closest\n ? ev.target.closest(\"[data-cancel], [data-post]\")\n : null;\n if (!btn) return;\n ev.preventDefault();\n if (btn.hasAttribute(\"data-cancel\")) {\n postAndGo(\n \"/api/jobs/\" + btn.getAttribute(\"data-cancel\") + \"/cancel\",\n {},\n \"/activity\",\n btn,\n );\n return;\n }\n const body = btn.getAttribute(\"data-body\");\n postAndGo(\n btn.getAttribute(\"data-post\"),\n body ? JSON.parse(body) : {},\n \"/activity\",\n btn,\n );\n });\n\n // Reads `activity-root` at call time, so it has to wait for the body even\n // though this file itself is already parsed.\n if (!document.getElementById(\"activity-root\")) return;\n setInterval(async function () {\n if (document.hidden) return;\n if (document.querySelector(\"[data-async].busy\")) return;\n const root = document.getElementById(\"activity-root\");\n if (!root) return;\n try {\n const res = await fetch(location.pathname + location.search, {\n headers: { accept: \"text/html\" },\n });\n if (!res.ok) return;\n const doc = new DOMParser().parseFromString(\n await res.text(),\n \"text/html\",\n );\n const next = doc.getElementById(\"activity-root\");\n if (!next || next.innerHTML === root.innerHTML) return;\n root.replaceWith(next);\n } catch {\n // a failed poll just waits for the next tick\n }\n }, 5000);\n});\n";
@@ -2,6 +2,7 @@ import { html, layout, repoNav, skSlot, text } from "./layout.js";
2
2
  import { parseRemakeCron } from "../../services/remake_cron.js";
3
3
  import { nextCronRun } from "../../util/cron.js";
4
4
  import { policySource } from "../../services/webhook.js";
5
+ import { DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS } from "../../review/system_prompt.js";
5
6
  import { ASSOCIATIONS, TEMPLATES, TEMPLATE_INFO, storedPolicyValue, withDefaults, } from "../../services/review_policy.js";
6
7
  const ASSOCIATION_LABEL = {
7
8
  OWNER: "Owner",
@@ -157,6 +158,19 @@ export function renderRepoSettings(username, repo, config) {
157
158
  </div>
158
159
  <div class="ft"><button class="primary" id="save-auto">Save</button></div>
159
160
  </div>
161
+ <div class="card" data-async>
162
+ ${skSlot()}
163
+ <div class="hd"><h2>Custom review instructions</h2></div>
164
+ <div class="bd">
165
+ <p class="muted" style="margin:0 0 18px">Added to the reviewer's built-in instructions for every review of this repository, as a separate section. Leave blank for none.</p>
166
+ <div class="field wide"><label for="system-prompt">Instructions</label>
167
+ <textarea id="system-prompt" rows="8" placeholder="For example: prefer the project's own helpers over new dependencies.">${text(config.reviewSystemPrompt ?? "")}</textarea></div>
168
+ <div class="field"><label for="system-prompt-max">Maximum characters</label>
169
+ <input id="system-prompt-max" placeholder="${DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS}" value="${text(config.reviewSystemPromptMaxChars ?? "")}">
170
+ <div class="hint">Blank uses ${DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS}. 0 or -1 means no limit.</div></div>
171
+ </div>
172
+ <div class="ft"><button class="primary" id="save-prompt">Save</button></div>
173
+ </div>
160
174
  <div class="card" data-async>
161
175
  ${skSlot()}
162
176
  <div class="hd"><h2>How this repository is analyzed</h2></div>
@@ -462,6 +476,23 @@ document.getElementById("save-init").addEventListener("click", function() {
462
476
  document.getElementById("save-cron").addEventListener("click", function() {
463
477
  save(this, { remakeCron: document.getElementById("cron").value.trim() });
464
478
  });
479
+ document.getElementById("save-prompt").addEventListener("click", function() {
480
+ var maxRaw = document.getElementById("system-prompt-max").value.trim();
481
+ var max;
482
+ if (maxRaw === "") {
483
+ max = null;
484
+ } else {
485
+ max = Number(maxRaw);
486
+ if (!Number.isInteger(max)) {
487
+ toast("Maximum characters must be a whole number, or blank for the default.");
488
+ return;
489
+ }
490
+ }
491
+ save(this, {
492
+ reviewSystemPrompt: document.getElementById("system-prompt").value,
493
+ reviewSystemPromptMaxChars: max
494
+ });
495
+ });
465
496
  document.getElementById("remove").addEventListener("click", function() {
466
497
  if (!confirm("Stop reviewing this repository?")) return;
467
498
  var btn = this;
@@ -11,6 +11,7 @@ import { closeRemoteSession, openRemoteSession, setRemoteSyncResult, } from "../
11
11
  import { readConfig, remoteByokPolicy, resolvedAiToken } from "../config.js";
12
12
  import { dropByokKey, getByokKey, hasByokKey, registerByokKey, } from "../remote/server/byok_keys.js";
13
13
  import { reviewBlockingFrom } from "../review/blocking.js";
14
+ import { checkReviewSystemPrompt, reviewSystemPromptLimit, } from "../review/system_prompt.js";
14
15
  import { loadGuides } from "../review/guides.js";
15
16
  import { withLogSink } from "../util/log.js";
16
17
  import { cancel, registerHandler } from "./jobs.js";
@@ -69,7 +70,7 @@ function reviewOptionsForRepo(repo, useCodegraph, aiToken) {
69
70
  aiToken: aiToken ?? resolvedAiToken(config, config.ai ?? "openrouter"),
70
71
  lowModel: config.lowModel,
71
72
  highModel: config.highModel,
72
- synthesisVersion: 16,
73
+ synthesisVersion: 17,
73
74
  includeCodebase: true,
74
75
  includePullRequests: true,
75
76
  includePullRequestChanges: true,
@@ -77,6 +78,7 @@ function reviewOptionsForRepo(repo, useCodegraph, aiToken) {
77
78
  includeHowRepoWorks: true,
78
79
  onlyRequestChangedPr: false,
79
80
  reviewBlocking: reviewBlockingFrom(config.reviewBlocking),
81
+ reviewSystemPrompt: config.repos?.[repo]?.reviewSystemPrompt,
80
82
  };
81
83
  }
82
84
  function supersedeActiveRemoteJobs(queueKey, supersededBy) {
@@ -159,6 +161,27 @@ export function submitRemoteReview(token, body) {
159
161
  supersedeActiveRemoteJobs(queueKey, jobId);
160
162
  const revision = body.revision ?? {};
161
163
  const capabilities = body.capabilities ?? { tools: [] };
164
+ const config = readConfig();
165
+ const promptLimit = reviewSystemPromptLimit(config.repos?.[repoRow.full_name]);
166
+ const systemPromptAdd = typeof body.systemPromptAdd === "string" ? body.systemPromptAdd : undefined;
167
+ const systemPromptOverride = typeof body.systemPromptOverride === "string"
168
+ ? body.systemPromptOverride
169
+ : undefined;
170
+ for (const [field, value] of [
171
+ ["systemPromptAdd", systemPromptAdd],
172
+ ["systemPromptOverride", systemPromptOverride],
173
+ ]) {
174
+ if (value === undefined)
175
+ continue;
176
+ const problem = checkReviewSystemPrompt(value, promptLimit);
177
+ if (problem) {
178
+ return {
179
+ error: `${field}: ${problem}`,
180
+ status: 400,
181
+ code: "bad_request",
182
+ };
183
+ }
184
+ }
162
185
  insertRemoteReviewInput({
163
186
  jobId,
164
187
  revisionJson: JSON.stringify(revision),
@@ -166,13 +189,14 @@ export function submitRemoteReview(token, body) {
166
189
  requestId,
167
190
  tokenId: token.id,
168
191
  billedTo,
192
+ systemPromptAdd,
193
+ systemPromptOverride,
169
194
  });
170
195
  // The review and job rows go in one transaction so a failure cannot leave a
171
196
  // partially written submission behind: no review with no job, and no queued
172
197
  // job whose input row points a retry at a job that never really started.
173
198
  // The key is registered only after COMMIT, so it never outlives a failed
174
199
  // setup.
175
- const config = readConfig();
176
200
  const db = getAppDb();
177
201
  db.exec("BEGIN");
178
202
  try {
@@ -250,6 +274,11 @@ export function registerRemoteReviewHandler() {
250
274
  .filter((name) => typeof name === "string" && name));
251
275
  const useCodegraph = allowed.size > 0;
252
276
  const options = reviewOptionsForRepo(job.repo, useCodegraph, byokKey);
277
+ // The client's one-run instructions travel with the job, so a retry
278
+ // keeps them. They apply on top of the server's per-repo prompt.
279
+ options.reviewSystemPromptAdd = input.system_prompt_add ?? undefined;
280
+ options.reviewSystemPromptOverride =
281
+ input.system_prompt_override ?? undefined;
253
282
  // A BYOK client brings a key but not models, so a server with no
254
283
  // models cannot run its review either.
255
284
  if (!options.aiToken ||
@@ -147,7 +147,7 @@ export function reviewOptions(repo, prNumber) {
147
147
  aiToken: resolvedAiToken(config, config.ai && config.ai !== "none" ? config.ai : "openrouter"),
148
148
  highModel: config.highModel,
149
149
  lowModel: config.lowModel,
150
- synthesisVersion: 16,
150
+ synthesisVersion: 17,
151
151
  includeCodebase: true,
152
152
  includePullRequests: true,
153
153
  includePullRequestChanges: true,
@@ -156,6 +156,7 @@ export function reviewOptions(repo, prNumber) {
156
156
  onlyRequestChangedPr: false,
157
157
  useCodegraph: getRepo(repo)?.use_codegraph === 1,
158
158
  reviewBlocking: reviewBlockingFrom(config.reviewBlocking),
159
+ reviewSystemPrompt: config.repos?.[repo]?.reviewSystemPrompt,
159
160
  };
160
161
  }
161
162
  export function aiFor(options) {
@@ -2,12 +2,12 @@
2
2
  * directly; it used to re-spawn the CLI as a subprocess, a second
3
3
  * execution path with its own failure modes. */
4
4
  import { createAiProvider } from "../ai/provider.js";
5
- import { enrichFactsWithReport, synthesizeSections, } from "../knowledge/synthesis.js";
5
+ import { enrichFacts, synthesizeSections } from "../knowledge/synthesis.js";
6
6
  import { collectSource } from "../github/collect.js";
7
7
  import { GhClient } from "../github/gh.js";
8
8
  import { PatClient } from "../github/pat.js";
9
9
  import { extractFacts } from "../knowledge/facts.js";
10
- import { buildReviewDocuments, reviewSignalCount } from "../knowledge/guide.js";
10
+ import { reviewSignalCount, synthesizeReviewGuides, } from "../knowledge/guide.js";
11
11
  import { assembleSkill, codebaseBody, factSectionHashes, } from "../knowledge/skill.js";
12
12
  import { validateSkill } from "../knowledge/validate.js";
13
13
  import { readConfig, reposDir, resolvedAiToken, writeRepoConfig, } from "../config.js";
@@ -22,6 +22,7 @@ import { nowIso } from "../util/time.js";
22
22
  import { mkdir, readTextFile, remove } from "../util/runtime.js";
23
23
  import { addResponseCost, emptyTally } from "../util/cost.js";
24
24
  import { costLabel } from "../util/run_summary.js";
25
+ import { formatError } from "../cli/error.js";
25
26
  export function emptyAiMetrics() {
26
27
  return { calls: 0, tokensIn: 0, tokensOut: 0, ...emptyTally() };
27
28
  }
@@ -86,13 +87,20 @@ async function skillPath(repo) {
86
87
  async function writeReviewDocuments(repo, documents, signalCount) {
87
88
  const directory = `${reposDir()}/${repo}`;
88
89
  if (!documents) {
89
- // This used to delete the files without a word. The rule is
90
- // "says why the third file is missing": keep it to one line.
91
- log("write", `PR_REVIEW_GUIDE.md skipped: found ${signalCount} review signals, needs at least 3`);
92
- await Promise.all([
93
- remove(`${directory}/PR_REVIEW_GUIDE.md`).catch(() => { }),
94
- remove(`${directory}/PR_REVIEW_DETAILED_GUIDE.md`).catch(() => { }),
95
- ]);
90
+ // `undefined` means two different things. Below the signal threshold there
91
+ // is nothing to write, so the files are removed and the reason is one line.
92
+ // When the AI produced no usable guide, the existing files are kept: a
93
+ // provider hiccup must not delete a guide the last run wrote.
94
+ if (signalCount <= 2) {
95
+ log("write", `PR_REVIEW_GUIDE.md skipped: found ${signalCount} review signals, needs at least 3`);
96
+ await Promise.all([
97
+ remove(`${directory}/PR_REVIEW_GUIDE.md`).catch(() => { }),
98
+ remove(`${directory}/PR_REVIEW_DETAILED_GUIDE.md`).catch(() => { }),
99
+ ]);
100
+ }
101
+ else {
102
+ log("write", "PR_REVIEW_GUIDE.md not regenerated: the AI produced no guide, keeping any existing file");
103
+ }
96
104
  return;
97
105
  }
98
106
  const { writeTextFileAtomic } = await import("../util/atomic.js");
@@ -104,17 +112,19 @@ async function writeReviewDocuments(repo, documents, signalCount) {
104
112
  await remove(`${directory}/PR_REVIEW_DETAILED_GUIDE.md`).catch(() => { });
105
113
  }
106
114
  }
107
- /** Splits the codebase-description sections (layout/style/tests/devloop) out
108
- * of the assembled skill into their own file, so `review` can check a pull
109
- * request against how this repository's code actually looks, not just the
110
- * review-bar checklist mined from past PR comments. The skill links to this
111
- * file rather than repeating it, so its body is built from
112
- * the facts instead of being scraped back out of the skill. */
113
- async function writeCodebaseDocument(repo, facts, overrides = {}) {
115
+ /** Writes the codebase-description sections (layout/style/tests/devloop) to
116
+ * their own file, so `review` can check a pull request against how this
117
+ * repository's code actually looks, not just the review-bar checklist. Every
118
+ * section body is authored by the synthesis job; the skill links to this file
119
+ * rather than repeating it. */
120
+ async function writeCodebaseDocument(repo, overrides = {}) {
114
121
  const path = `${reposDir()}/${repo}/CODEBASE.md`;
115
- const body = codebaseBody(facts, overrides);
122
+ const body = codebaseBody(overrides);
116
123
  if (!body) {
117
- await remove(path).catch(() => { });
124
+ // Keep any existing file: `SKILL.md` links to it, and removing it would
125
+ // leave that link dangling. A guide the last run wrote is better than a
126
+ // broken link.
127
+ log("write", "CODEBASE.md not regenerated: the AI produced no codebase sections, keeping any existing file");
118
128
  return;
119
129
  }
120
130
  const { writeTextFileAtomic } = await import("../util/atomic.js");
@@ -157,9 +167,11 @@ async function initOrRemake(options) {
157
167
  const client = clientFor(options);
158
168
  const lowAi = createAiProvider(options, options.lowModel ?? "");
159
169
  const highAi = createAiProvider(options, options.highModel ?? "");
160
- if (lowAi || highAi) {
161
- log("ai", `${options.ai} providers configured · low=${options.lowModel} · high=${options.highModel}`);
170
+ // Every guide is AI-authored: with no provider there is nothing to build.
171
+ if (!lowAi || !highAi) {
172
+ throw new Error("init requires an AI provider. Run: co-maintainer set --ai=openrouter --token=... --low-model=... --high-model=...");
162
173
  }
174
+ log("ai", `${options.ai} providers configured · low=${options.lowModel} · high=${options.highModel}`);
163
175
  log("fetch", `${options.repo} via ${options.auth}`);
164
176
  const source = await timed("fetch repository data", options.logTime, () => collectSource(client, options, previous, async (pullRequests, cache) => {
165
177
  checkpoint.source.pullRequests = pullRequests;
@@ -193,17 +205,15 @@ async function initOrRemake(options) {
193
205
  if (options.logTime) {
194
206
  log("time", `extract deterministic facts · ${((performance.now() - factsStarted) / 1000).toFixed(2)}s`);
195
207
  }
208
+ const usage = async (job, response) => {
209
+ addAiMetrics(aiMetrics, response);
210
+ await recordAiCost(options.repo, job, response);
211
+ };
196
212
  let overrides = {};
197
- const skipped = [];
198
- if (lowAi) {
213
+ let reviewDocuments;
214
+ try {
199
215
  log("ai", "starting extract_unit jobs");
200
- const usage = async (job, response) => {
201
- addAiMetrics(aiMetrics, response);
202
- await recordAiCost(options.repo, job, response);
203
- };
204
- const enriched = await timed("extract_unit AI", options.logTime, () => enrichFactsWithReport(lowAi, options.repo, facts, source, options, usage));
205
- facts = enriched.facts;
206
- skipped.push(...enriched.skipped);
216
+ facts = await timed("extract_unit AI", options.logTime, () => enrichFacts(lowAi, options.repo, facts, source, options, usage));
207
217
  log("ai", `extract_unit complete · ${facts.length} facts`);
208
218
  const hashes = await factSectionHashes(facts);
209
219
  const synthesisChanged = previous &&
@@ -217,22 +227,28 @@ async function initOrRemake(options) {
217
227
  .map(([key]) => key))
218
228
  : undefined;
219
229
  log("ai", `starting synth_section jobs${dirtySections ? ` · ${dirtySections.size} dirty sections` : ""}`);
220
- if (highAi) {
221
- const synth = await timed("synth_section AI", options.logTime, () => synthesizeSections(highAi, options.repo, facts, previousMarkdown, options.ai, options.highModel ?? "", options.aiConcurrent, usage, dirtySections));
222
- overrides = synth.overrides;
223
- skipped.push(...synth.skipped);
224
- }
230
+ const synth = await timed("synth_section AI", options.logTime, () => synthesizeSections(highAi, options.repo, facts, previousMarkdown, options.ai, options.highModel ?? "", options.aiConcurrent, usage, dirtySections));
231
+ overrides = synth.overrides;
225
232
  log("ai", `synth_section complete · ${Object.keys(overrides).length} sections`);
233
+ log("ai", "starting synth_guide jobs");
234
+ reviewDocuments = await timed("synth_guide AI", options.logTime, () => synthesizeReviewGuides(highAi, options.repo, options.ai, options.highModel ?? "", options.aiConcurrent, facts, usage));
235
+ log("ai", reviewDocuments
236
+ ? `synth_guide complete · ${reviewDocuments.detailed ? "short + detailed" : "single guide"}`
237
+ : "synth_guide skipped · fewer than 3 review signals");
238
+ }
239
+ catch (error) {
240
+ // Nothing is written on an AI failure. Fetching and extraction are cached,
241
+ // so a rerun picks up where this stopped instead of starting over.
242
+ throw new Error(`AI failed to generate the guides: ${formatError(error)}. ` +
243
+ "Fetching and extraction are cached, so rerunning `co-maintainer sync <owner/repo>` continues without re-fetching.");
226
244
  }
227
245
  let result = await timed("assemble skill", options.logTime, () => assembleSkill(options.repo, facts, previousMarkdown, previous?.sectionHashes ?? {}, overrides));
228
- const reviewDocuments = buildReviewDocuments(facts);
229
246
  result.markdown = addReviewLink(result.markdown, reviewDocuments);
230
247
  const validation = await timed("validate skill", options.logTime, () => validateSkill(result.markdown, source));
231
- if (!validation.valid && Object.keys(overrides).length) {
232
- log("validate", `AI output rejected: ${validation.errors.join("; ")}`);
233
- overrides = {};
234
- result = await timed("reassemble valid skill", options.logTime, () => assembleSkill(options.repo, facts, previousMarkdown, previous?.sectionHashes ?? {}, overrides));
235
- result.markdown = addReviewLink(result.markdown, reviewDocuments);
248
+ // There is no deterministic fallback to reassemble from: a skill the AI could
249
+ // not write correctly is reported rather than rebuilt from facts.
250
+ if (!validation.valid) {
251
+ log("validate", `skill problems kept: ${validation.errors.join("; ")}`);
236
252
  }
237
253
  const finalValidation = await timed("final skill validation", options.logTime, () => validateSkill(result.markdown, source, "warning"));
238
254
  if (finalValidation.warnings.length) {
@@ -246,7 +262,7 @@ async function initOrRemake(options) {
246
262
  const { writeTextFileAtomic } = await import("../util/atomic.js");
247
263
  await withKnowledgeLock(options.repo, async () => {
248
264
  await writeTextFileAtomic(path, result.markdown);
249
- await writeCodebaseDocument(options.repo, facts, overrides);
265
+ await writeCodebaseDocument(options.repo, overrides);
250
266
  await writeReviewDocuments(options.repo, reviewDocuments, reviewSignalCount(facts));
251
267
  const head = source.commits[0];
252
268
  const baseSha = head?.sha ? String(head.sha) : new Date().toISOString();
@@ -290,16 +306,6 @@ async function initOrRemake(options) {
290
306
  ? `updated ${result.changed.join(", ")}`
291
307
  : "already current"}`);
292
308
  log("done", `${facts.length} facts · ${source.pullRequests.length} pull requests · ${source.commits.length} commits`);
293
- if (skipped.length) {
294
- // A skipped unit used to vanish into a log line and recur as a "cache
295
- // hit" forever. Say it in the final line instead, in this shape:
296
- // `1 unit skipped (PR #3: output was not JSON)`.
297
- const parts = skipped.map((unit) => unit.reason);
298
- const line = skipped.length === 1
299
- ? `1 unit skipped (${parts[0]})`
300
- : `${skipped.length} units skipped (${parts.join("; ")})`;
301
- log("done", line);
302
- }
303
309
  printRunSummary(summaryFromMetrics(aiMetrics, performance.now() - operationStarted));
304
310
  if (options.logTime) {
305
311
  log("time", `AI total · calls=${aiMetrics.calls} · input=${aiMetrics.tokensIn} tokens · output=${aiMetrics.tokensOut} tokens · cost=${costLabel(aiMetrics)}`);
@@ -319,7 +325,11 @@ export function optionsFromConfig(repo, command) {
319
325
  const lowModel = repoConfig.lowModel ?? config.lowModel;
320
326
  const highModel = repoConfig.highModel ?? config.highModel;
321
327
  const aiToken = resolvedAiToken(config, ai);
322
- if (ai !== "none" && (!aiToken || !lowModel || !highModel)) {
328
+ // Every guide is AI-authored: init and sync cannot run without a provider.
329
+ if (ai === "none") {
330
+ throw new Error("init and sync need an AI provider. Run: co-maintainer set --ai=openrouter --token=... --low-model=... --high-model=...");
331
+ }
332
+ if (!aiToken || !lowModel || !highModel) {
323
333
  throw new Error("AI is enabled but token/low-model/high-model are not fully configured. Run: " +
324
334
  "co-maintainer set --token=... --low-model=... --high-model=...");
325
335
  }
@@ -337,7 +347,7 @@ export function optionsFromConfig(repo, command) {
337
347
  aiToken,
338
348
  lowModel,
339
349
  highModel,
340
- synthesisVersion: 16,
350
+ synthesisVersion: 17,
341
351
  includeCodebase: repoConfig.includeCodebase ?? true,
342
352
  includePullRequests: repoConfig.includePullRequests ?? true,
343
353
  includePullRequestChanges: repoConfig.includePullRequestChanges ?? true,
@@ -275,4 +275,11 @@ export const migrations = [
275
275
  `ALTER TABLE repos ADD COLUMN review_policy_json TEXT`,
276
276
  `UPDATE repos SET review_policy_json = '"legacy"'`,
277
277
  ],
278
+ // 12 — a remote client's one-run review instructions travel with the job so
279
+ // a retry keeps them. The per-repo prompt stays in config.json and is read
280
+ // on the server where the review runs.
281
+ [
282
+ `ALTER TABLE remote_review_inputs ADD COLUMN system_prompt_add TEXT`,
283
+ `ALTER TABLE remote_review_inputs ADD COLUMN system_prompt_override TEXT`,
284
+ ],
278
285
  ];
@@ -8,6 +8,8 @@ export declare function insertRemoteReviewInput(input: {
8
8
  /** `'byok'` when the client submitted its own key, else `'server'`. The key
9
9
  * itself is never written here. */
10
10
  billedTo: "server" | "byok";
11
+ systemPromptAdd?: string;
12
+ systemPromptOverride?: string;
11
13
  }): void;
12
14
  export declare function findRemoteReviewInputByRequest(tokenId: string, requestId: string): RemoteReviewInputRow | undefined;
13
15
  export declare function getRemoteReviewInput(jobId: string): RemoteReviewInputRow | undefined;
@@ -3,9 +3,9 @@ import { nowIso } from "../util/time.js";
3
3
  export function insertRemoteReviewInput(input) {
4
4
  getAppDb()
5
5
  .prepare(`INSERT INTO remote_review_inputs
6
- (job_id, revision_json, capabilities_json, request_id, token_id, created_at, billed_to)
7
- VALUES (?, ?, ?, ?, ?, ?, ?)`)
8
- .run(input.jobId, input.revisionJson, input.capabilitiesJson, input.requestId, input.tokenId, nowIso(), input.billedTo);
6
+ (job_id, revision_json, capabilities_json, request_id, token_id, created_at, billed_to, system_prompt_add, system_prompt_override)
7
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
8
+ .run(input.jobId, input.revisionJson, input.capabilitiesJson, input.requestId, input.tokenId, nowIso(), input.billedTo, input.systemPromptAdd ?? null, input.systemPromptOverride ?? null);
9
9
  }
10
10
  export function findRemoteReviewInputByRequest(tokenId, requestId) {
11
11
  return getAppDb()
@@ -186,4 +186,7 @@ export type RemoteReviewInputRow = {
186
186
  /** `'byok'` when the client's own key paid for the review, `'server'`
187
187
  * otherwise. A null (pre-0.5.1 row) is treated as `'server'`. */
188
188
  billed_to?: string | null;
189
+ /** The client's one-run review instructions, kept so a retry reuses them. */
190
+ system_prompt_add?: string | null;
191
+ system_prompt_override?: string | null;
189
192
  };
@@ -49,6 +49,17 @@ export type Options = {
49
49
  /** How a review decides a blocking finding. `model` keeps the
50
50
  * 0.4.13 behavior, `severity` uses a fixed P0/P1 threshold. */
51
51
  reviewBlocking?: "model" | "severity";
52
+ /** The repository's own review instructions (config.json
53
+ * `repos[repo].reviewSystemPrompt`). Appended to the built-in reviewer
54
+ * prompt as a `CUSTOM REVIEW INSTRUCTIONS` section. */
55
+ reviewSystemPrompt?: string;
56
+ /** A one-run addition to the custom section
57
+ * (`review --system-prompt-file`). */
58
+ reviewSystemPromptAdd?: string;
59
+ /** A one-run replacement of the repository's custom section
60
+ * (`review --system-prompt-override-file`). The built-in role, diagram
61
+ * rules and guide block are still kept. */
62
+ reviewSystemPromptOverride?: string;
52
63
  };
53
64
  export type GitHubClient = {
54
65
  request<T>(endpoint: string): Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "co-maintainer",
3
- "version": "0.5.3",
3
+ "version": "0.6.0",
4
4
  "description": "An imitator of yours, A PR review tool like co-maintainer.",
5
5
  "keywords": [
6
6
  "ai",