co-maintainer 0.5.2 → 0.5.4

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 (50) hide show
  1. package/dist/package.json +2 -4
  2. package/dist/src/cli/args.js +1 -0
  3. package/dist/src/cli/commands/clear.d.ts +1 -0
  4. package/dist/src/cli/commands/clear.js +152 -0
  5. package/dist/src/cli/commands/registry.d.ts +4 -0
  6. package/dist/src/cli/commands/registry.js +81 -0
  7. package/dist/src/cli/commands/set.js +102 -1
  8. package/dist/src/cli/commands/uninstall.d.ts +1 -0
  9. package/dist/src/cli/commands/uninstall.js +43 -0
  10. package/dist/src/cli/main.js +10 -0
  11. package/dist/src/cli/review_args.d.ts +15 -0
  12. package/dist/src/cli/review_args.js +41 -1
  13. package/dist/src/config.d.ts +21 -0
  14. package/dist/src/config.js +38 -1
  15. package/dist/src/local/review_local.js +4 -1
  16. package/dist/src/local/review_lock.js +2 -2
  17. package/dist/src/pr/reviewer.js +3 -2
  18. package/dist/src/remote/client.js +14 -1
  19. package/dist/src/remote/schema.d.ts +3 -0
  20. package/dist/src/remote/schema.js +3 -0
  21. package/dist/src/remote/validate.js +12 -1
  22. package/dist/src/review/system_prompt.d.ts +19 -0
  23. package/dist/src/review/system_prompt.js +34 -0
  24. package/dist/src/server/api/knowledge.d.ts +7 -0
  25. package/dist/src/server/api/knowledge.js +68 -0
  26. package/dist/src/server/api/repos.js +61 -2
  27. package/dist/src/server/app.js +4 -0
  28. package/dist/src/server/pages/client.d.ts +1 -1
  29. package/dist/src/server/pages/client.js +1 -1
  30. package/dist/src/server/pages/knowledge.js +20 -1
  31. package/dist/src/server/pages/repo_settings.js +31 -0
  32. package/dist/src/server/pages/settings.js +18 -0
  33. package/dist/src/services/clear.d.ts +70 -0
  34. package/dist/src/services/clear.js +310 -0
  35. package/dist/src/services/remote_review.js +30 -1
  36. package/dist/src/services/review.js +1 -0
  37. package/dist/src/store/app_db.d.ts +3 -0
  38. package/dist/src/store/app_db.js +5 -0
  39. package/dist/src/store/cache_db.d.ts +11 -0
  40. package/dist/src/store/cache_db.js +60 -1
  41. package/dist/src/store/migrations.js +7 -0
  42. package/dist/src/store/remote_review_inputs.d.ts +2 -0
  43. package/dist/src/store/remote_review_inputs.js +3 -3
  44. package/dist/src/store/repos.d.ts +3 -0
  45. package/dist/src/store/repos.js +8 -0
  46. package/dist/src/store/rows.d.ts +3 -0
  47. package/dist/src/types.d.ts +11 -0
  48. package/dist/src/util/runtime.d.ts +3 -0
  49. package/dist/src/util/runtime.js +6 -1
  50. package/package.json +2 -4
@@ -117,12 +117,26 @@ export function clonesDir() {
117
117
  export function cloneDir(repo) {
118
118
  return `${clonesDir()}/${repoSlug(repo)}`;
119
119
  }
120
+ /** The directory holding one repository's PR worktrees. `clear` removes it
121
+ * whole, so the layout lives in one place instead of at each call site. */
122
+ export function repoWorktreesDir(repo) {
123
+ return `${getCacheDir()}/co-maintainer/wt/${repoSlug(repo)}`;
124
+ }
125
+ /** Every repository's worktrees, for `clear all` and `uninstall`. */
126
+ export function worktreesDir() {
127
+ return `${getCacheDir()}/co-maintainer/wt`;
128
+ }
120
129
  export function worktreeDir(repo, pr) {
121
- return `${getCacheDir()}/co-maintainer/wt/${repoSlug(repo)}/${pr}`;
130
+ return `${repoWorktreesDir(repo)}/${pr}`;
122
131
  }
123
132
  export function cacheDbPath() {
124
133
  return `${getCacheDir()}/co-maintainer/cache.db`;
125
134
  }
135
+ /** Transient pid files that keep one local review per repository root.
136
+ * `uninstall` still takes them: they are co-maintainer data too. */
137
+ export function locksDir() {
138
+ return `${getCacheDir()}/co-maintainer/locks`;
139
+ }
126
140
  export function loadEnvFile(path) {
127
141
  const contents = readTextFileSync(path);
128
142
  for (const line of contents.split(/\r?\n/)) {
@@ -200,6 +214,29 @@ export async function writeRepoConfig(repo, patch) {
200
214
  repos[repo] = Object.fromEntries(Object.entries({ ...repos[repo], ...patch }).filter(([, value]) => value !== undefined));
201
215
  await writeConfig({ ...config, repos });
202
216
  }
217
+ /** Drops `repos[repo]` from config.json. `clear` uses this so the repository
218
+ * goes back to "never inited": the next run resolves its flags again. Returns
219
+ * whether there was an entry to drop. */
220
+ export async function removeRepoConfig(repo) {
221
+ const config = readConfig();
222
+ if (!config.repos || !(repo in config.repos))
223
+ return false;
224
+ const repos = { ...config.repos };
225
+ delete repos[repo];
226
+ await writeConfig({
227
+ ...config,
228
+ repos: Object.keys(repos).length > 0 ? repos : undefined,
229
+ });
230
+ return true;
231
+ }
232
+ /** Drops every per-repo entry. `clear all` forgets every repository it knows. */
233
+ export async function removeAllRepoConfig() {
234
+ const config = readConfig();
235
+ if (!config.repos || Object.keys(config.repos).length === 0)
236
+ return false;
237
+ await writeConfig({ ...config, repos: undefined });
238
+ return true;
239
+ }
203
240
  /** Merges `patch` into the top-level (global, cross-repo) config —
204
241
  * used by `co-maintainer set`. This is the only path allowed to persist
205
242
  * a token. */
@@ -1,5 +1,5 @@
1
1
  import { parseArgs } from "../cli/args.js";
2
- import { filterReviewConfigArgs, } from "../cli/review_args.js";
2
+ import { filterReviewConfigArgs, loadReviewSystemPromptFlags, reviewSystemPromptLimitFor, } from "../cli/review_args.js";
3
3
  import { buildLocalReviewJson, formatHumanLocalReview, humanFindingsFromResolved, resolvedFromFirstReview, reviewExitCodeFromResolved, } from "../cli/review_result.js";
4
4
  import { addAiMetrics, emptyAiMetrics, recordAiCost, runInitOrRemake, } from "../services/setup.js";
5
5
  import { aiFor } from "../services/review.js";
@@ -107,6 +107,9 @@ export async function runLocalReview(cli) {
107
107
  ...filterReviewConfigArgs(cli.rawArgs),
108
108
  ]);
109
109
  options.useCodegraph = cli.disableCodegraph ? false : true;
110
+ const promptFlags = await loadReviewSystemPromptFlags(cli, reviewSystemPromptLimitFor(repo));
111
+ options.reviewSystemPromptAdd = promptFlags.add;
112
+ options.reviewSystemPromptOverride = promptFlags.override;
110
113
  const guides = await loadGuides(repo);
111
114
  if (!guides.shortGuide && !guides.skill) {
112
115
  throw new ReviewCliError("not_initialized", `Review guides are missing for ${repo}.`, `co-maintainer init ${repo}`);
@@ -1,4 +1,4 @@
1
- import { getCacheDir } from "../config.js";
1
+ import { locksDir } from "../config.js";
2
2
  import { ReviewCliError } from "./git_ops.js";
3
3
  import { isNotFound, isProcessAlive, mkdir, readTextFile, remove, removeSync, writeTextFile, } from "../util/runtime.js";
4
4
  async function lockPath(gitRoot) {
@@ -7,7 +7,7 @@ async function lockPath(gitRoot) {
7
7
  .map((b) => b.toString(16).padStart(2, "0"))
8
8
  .join("")
9
9
  .slice(0, 16);
10
- const dir = `${getCacheDir()}/co-maintainer/locks`;
10
+ const dir = locksDir();
11
11
  await mkdir(dir, { recursive: true });
12
12
  return `${dir}/${hex}.lock`;
13
13
  }
@@ -5,6 +5,7 @@ import { loadGuides } from "../review/guides.js";
5
5
  import { computeScope } from "./scope.js";
6
6
  import { prepareCodegraphTools } from "./codegraph_tools.js";
7
7
  import { REVIEW_COPY_RULE, severitySection } from "./review_copy.js";
8
+ import { reviewSystemPromptBlock } from "../review/system_prompt.js";
8
9
  import { needsSummary, READ_FULL_DIFF_TOOL, readFullDiff, summarizeDiff, } from "./diff_summary.js";
9
10
  import { numberPatch } from "./hunks.js";
10
11
  import { FINDINGS_JSON_INSTRUCTIONS, FINDINGS_JSON_SCHEMA, findingsMarkdownFromJson, } from "./findings_json.js";
@@ -370,7 +371,7 @@ ${diff}`;
370
371
  const matrix = clampImproveMatrix(options.improveMatrix);
371
372
  const request = {
372
373
  job: "review_pull_request",
373
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}`,
374
+ system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
374
375
  prompt,
375
376
  maxTokens: 24_000 * matrix,
376
377
  reasoningEffort: "high",
@@ -534,7 +535,7 @@ ${ownDiff}${unchangedListing}`;
534
535
  const matrix = clampImproveMatrix(options.improveMatrix);
535
536
  const request = {
536
537
  job: "review_local",
537
- system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}`,
538
+ system: `${reviewSystemPrompt(diagrams)}\n\n${reviewGuidesBlock(guide, detailed, codebase)}${reviewSystemPromptBlock(options)}`,
538
539
  prompt,
539
540
  maxTokens: 24_000 * matrix,
540
541
  reasoningEffort: "high",
@@ -1,5 +1,6 @@
1
1
  import { VERSION } from "../version.js";
2
- import { CliError, EXIT_USAGE, exitWith } from "../cli/error.js";
2
+ import { loadReviewSystemPromptFlags } from "../cli/review_args.js";
3
+ import { exitWith } from "../cli/error.js";
3
4
  import { formatHumanReview, humanFindingsFromJson, reviewExitCodeFromJsonFindings, } from "../cli/review_result.js";
4
5
  import { baseUrl, die, readApiError, remoteFetch, remoteFromEnv, } from "./http.js";
5
6
  import { readConfig, writeUserConfig } from "../config.js";
@@ -140,6 +141,10 @@ export async function runRemoteReview(cli) {
140
141
  .filter((name) => REMOTE_KNOWN_TOOL_NAMES.has(name))
141
142
  .map((name) => ({ name }));
142
143
  const requestId = crypto.randomUUID();
144
+ // The review runs on the server, so the server's per-repo cap decides. The
145
+ // client only reads the files and sends them, and the server rejects an
146
+ // over-cap value with a 400.
147
+ const promptFlags = await loadReviewSystemPromptFlags(cli, null);
143
148
  const submitBody = {
144
149
  schemaVersion: REMOTE_SCHEMA_VERSION,
145
150
  requestId,
@@ -157,6 +162,14 @@ export async function runRemoteReview(cli) {
157
162
  // Only present when this run turned BYOK on; `byokKey` is
158
163
  // known to be set here because of the earlier `byokEnabled` guard.
159
164
  ...(byokEnabled ? { byok: { key: byokKey } } : {}),
165
+ // The client's one-run instructions, when given. The server applies
166
+ // them on top of its own per-repo prompt.
167
+ ...(promptFlags.add !== undefined
168
+ ? { systemPromptAdd: promptFlags.add }
169
+ : {}),
170
+ ...(promptFlags.override !== undefined
171
+ ? { systemPromptOverride: promptFlags.override }
172
+ : {}),
160
173
  };
161
174
  const serialized = JSON.stringify(submitBody);
162
175
  if (serialized.length > hs.limits.maxBodyBytes) {
@@ -6,6 +6,9 @@ export declare const MIN_SERVER_SCHEMA = 1;
6
6
  export declare const REMOTE_CLI_UPGRADE_COMMAND = "npm install -g co-maintainer@latest";
7
7
  export declare const REMOTE_MAX_BODY_BYTES = 52428800;
8
8
  export declare const REMOTE_SYNC_INTERVAL_SECONDS = 3;
9
+ /** Absolute ceiling on a client's one-run review instructions, before the
10
+ * repository's own cap is applied on the server. Guards the body size. */
11
+ export declare const REMOTE_MAX_SYSTEM_PROMPT_CHARS = 200000;
9
12
  /** SHA-256 of sorted `fixtures/v<N>/*.json` (name + contents, `\r\n` normalized
10
13
  * to `\n`); bump with schema version. */
11
14
  export declare const REMOTE_FIXTURE_HASH: Record<number, string>;
@@ -6,6 +6,9 @@ export const MIN_SERVER_SCHEMA = 1;
6
6
  export const REMOTE_CLI_UPGRADE_COMMAND = "npm install -g co-maintainer@latest";
7
7
  export const REMOTE_MAX_BODY_BYTES = 52_428_800;
8
8
  export const REMOTE_SYNC_INTERVAL_SECONDS = 3;
9
+ /** Absolute ceiling on a client's one-run review instructions, before the
10
+ * repository's own cap is applied on the server. Guards the body size. */
11
+ export const REMOTE_MAX_SYSTEM_PROMPT_CHARS = 200_000;
9
12
  /** SHA-256 of sorted `fixtures/v<N>/*.json` (name + contents, `\r\n` normalized
10
13
  * to `\n`); bump with schema version. */
11
14
  export const REMOTE_FIXTURE_HASH = {
@@ -1,5 +1,5 @@
1
1
  import { rejectEscapingPath } from "../pr/codegraph_tool_args.js";
2
- import { MIN_CLIENT_SCHEMA, REMOTE_KNOWN_TOOL_NAMES, REMOTE_SCHEMA_VERSION, REMOTE_SYNC_STATUSES, } from "./schema.js";
2
+ import { MIN_CLIENT_SCHEMA, REMOTE_KNOWN_TOOL_NAMES, REMOTE_MAX_SYSTEM_PROMPT_CHARS, REMOTE_SCHEMA_VERSION, REMOTE_SYNC_STATUSES, } from "./schema.js";
3
3
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
4
4
  const REVISION_STATUSES = new Set([
5
5
  "added",
@@ -188,6 +188,17 @@ export function validateSubmitRequest(body) {
188
188
  const revisionErr = validateRevisionPayload(body.revision);
189
189
  if (revisionErr)
190
190
  return revisionErr;
191
+ for (const field of ["systemPromptAdd", "systemPromptOverride"]) {
192
+ const value = body[field];
193
+ if (value === undefined)
194
+ continue;
195
+ if (typeof value !== "string") {
196
+ return bad(field, "must be a string");
197
+ }
198
+ if (value.length > REMOTE_MAX_SYSTEM_PROMPT_CHARS) {
199
+ return bad(field, "too long");
200
+ }
201
+ }
191
202
  if (body.capabilities !== undefined) {
192
203
  if (!isRecord(body.capabilities)) {
193
204
  return bad("capabilities", "must be an object");
@@ -0,0 +1,19 @@
1
+ /** The per-repository custom review instructions and the cap on them. The
2
+ * block is appended to the built-in reviewer system prompt (role, diagram
3
+ * rules and guide) as a separate section, so the built-in instructions are
4
+ * always kept. */
5
+ import type { Options } from "../types.ts";
6
+ import type { RepoConfig } from "../config.ts";
7
+ /** Default cap on `reviewSystemPrompt`, in characters. */
8
+ export declare const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
9
+ /** The repository's cap, or `null` for no limit. Unset takes the default; a
10
+ * non-positive value means unlimited. */
11
+ export declare function reviewSystemPromptLimit(repoConfig: Pick<RepoConfig, "reviewSystemPromptMaxChars"> | undefined): number | null;
12
+ /** The problem with a custom prompt, or `null` when it is fine. Blank text is
13
+ * allowed and means "off". */
14
+ export declare function checkReviewSystemPrompt(text: string, limit: number | null): string | null;
15
+ /** The extra system-prompt section for a review, or `""` when none applies.
16
+ * A per-run override replaces the repository's own section, and a per-run add
17
+ * is appended after it. A blank per-run value counts as absent, so an empty
18
+ * override file keeps the repository's own section rather than dropping it. */
19
+ export declare function reviewSystemPromptBlock(options: Pick<Options, "reviewSystemPrompt" | "reviewSystemPromptAdd" | "reviewSystemPromptOverride">): string;
@@ -0,0 +1,34 @@
1
+ /** Default cap on `reviewSystemPrompt`, in characters. */
2
+ export const DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS = 8000;
3
+ /** The repository's cap, or `null` for no limit. Unset takes the default; a
4
+ * non-positive value means unlimited. */
5
+ export function reviewSystemPromptLimit(repoConfig) {
6
+ const raw = repoConfig?.reviewSystemPromptMaxChars;
7
+ if (raw === undefined)
8
+ return DEFAULT_REVIEW_SYSTEM_PROMPT_MAX_CHARS;
9
+ if (!Number.isFinite(raw) || raw <= 0)
10
+ return null;
11
+ const floored = Math.floor(raw);
12
+ return floored > 0 ? floored : null;
13
+ }
14
+ /** The problem with a custom prompt, or `null` when it is fine. Blank text is
15
+ * allowed and means "off". */
16
+ export function checkReviewSystemPrompt(text, limit) {
17
+ if (limit !== null && text.length > limit) {
18
+ return `must be at most ${limit} characters (got ${text.length})`;
19
+ }
20
+ return null;
21
+ }
22
+ /** The extra system-prompt section for a review, or `""` when none applies.
23
+ * A per-run override replaces the repository's own section, and a per-run add
24
+ * is appended after it. A blank per-run value counts as absent, so an empty
25
+ * override file keeps the repository's own section rather than dropping it. */
26
+ export function reviewSystemPromptBlock(options) {
27
+ const override = options.reviewSystemPromptOverride?.trim();
28
+ const base = override ? override : options.reviewSystemPrompt?.trim();
29
+ const add = options.reviewSystemPromptAdd?.trim();
30
+ const parts = [base, add].filter((part) => Boolean(part));
31
+ if (parts.length === 0)
32
+ return "";
33
+ return `\n\nCUSTOM REVIEW INSTRUCTIONS:\n${parts.join("\n\n")}`;
34
+ }
@@ -0,0 +1,7 @@
1
+ /** `undefined` means the clear may go ahead. A 409 carries enough detail for
2
+ * the page to ask the right question: whether to abort reviews and queued
3
+ * jobs, or to wait out a sync. */
4
+ export declare function negotiateJobs(repos: string[], abort: boolean): Response | undefined;
5
+ export declare function handleKnowledgeRoute(request: Request, url: URL): Promise<Response>;
6
+ /** Shared by the per-repo route, which knows exactly one repository. */
7
+ export declare function clearOneRepo(fullName: string, url: URL): Promise<Response>;
@@ -0,0 +1,68 @@
1
+ /** The dashboard's clear routes.
2
+ *
3
+ * `DELETE /api/repos/:owner/:repo/knowledge` forgets one repository,
4
+ * `DELETE /api/knowledge` forgets every stored repository. Both share the job
5
+ * negotiation here: a queued job can be canceled and a running review can be
6
+ * aborted (`?onRunning=abort`), but a running `init`/`remake` cannot be
7
+ * stopped, so the route answers 409 and the page waits for it instead. */
8
+ import { errorResponse } from "../errors.js";
9
+ import { abortRunningReviews, cancelQueuedJobs, clearRepos, clearRepo, listStoredRepos, repoJobs, } from "../../services/clear.js";
10
+ function readClearParams(url) {
11
+ return {
12
+ includeCache: url.searchParams.get("includeCache") === "1",
13
+ abort: url.searchParams.get("onRunning") === "abort",
14
+ };
15
+ }
16
+ /** A running setup job ignores the abort signal and would write the guides
17
+ * again after the clear, so it is the one thing the caller cannot skip. */
18
+ function isSetupType(type) {
19
+ return type !== "review" && type !== "remote_review";
20
+ }
21
+ /** `undefined` means the clear may go ahead. A 409 carries enough detail for
22
+ * the page to ask the right question: whether to abort reviews and queued
23
+ * jobs, or to wait out a sync. */
24
+ export function negotiateJobs(repos, abort) {
25
+ const jobs = repoJobs(repos);
26
+ if (jobs.queued.length === 0 && jobs.running.length === 0)
27
+ return undefined;
28
+ if (!abort) {
29
+ return errorResponse(409, "jobs_running", "Jobs are pending for this target.", {
30
+ queued: jobs.queued.length,
31
+ running: jobs.running.map((job) => ({
32
+ id: job.id,
33
+ type: job.type,
34
+ abortable: !isSetupType(job.type),
35
+ })),
36
+ });
37
+ }
38
+ const setup = jobs.running.find((job) => isSetupType(job.type));
39
+ if (setup) {
40
+ return errorResponse(409, "job_not_abortable", "A sync is running and cannot be stopped.", { id: setup.id, type: setup.type });
41
+ }
42
+ cancelQueuedJobs(repos);
43
+ abortRunningReviews(repos);
44
+ return undefined;
45
+ }
46
+ export async function handleKnowledgeRoute(request, url) {
47
+ if (url.pathname !== "/api/knowledge" || request.method !== "DELETE") {
48
+ return errorResponse(404, "not_found", `no route for ${url.pathname}`);
49
+ }
50
+ const { includeCache, abort } = readClearParams(url);
51
+ // The same snapshot is negotiated and cleared, so a repository added in
52
+ // between cannot slip past the job check.
53
+ const repos = await listStoredRepos();
54
+ const conflict = negotiateJobs(repos, abort);
55
+ if (conflict)
56
+ return conflict;
57
+ const result = await clearRepos(repos, { includeCache });
58
+ return Response.json({ ok: true, ...result });
59
+ }
60
+ /** Shared by the per-repo route, which knows exactly one repository. */
61
+ export async function clearOneRepo(fullName, url) {
62
+ const { includeCache, abort } = readClearParams(url);
63
+ const conflict = negotiateJobs([fullName], abort);
64
+ if (conflict)
65
+ return conflict;
66
+ const result = await clearRepo(fullName, { includeCache });
67
+ return Response.json({ ok: true, ...result });
68
+ }
@@ -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";
@@ -10,6 +11,7 @@ import { probePlan, recommendationPatch } from "../../services/probe.js";
10
11
  import { estimateInit, readJobHistory } from "../../ai/estimate.js";
11
12
  import { loadPrices } from "../../ai/pricing.js";
12
13
  import { prDetail, repoKnowledge, RepoNotFound, repoOverview, repoPulls, requireActiveRepo, } from "../../services/dashboard.js";
14
+ import { clearOneRepo } from "./knowledge.js";
13
15
  const REPO = /^\/api\/repos\/([^/]+)\/([^/]+)(?:\/(remake|knowledge|pulls)(?:\/(\d+)(?:\/(review))?)?)?$/;
14
16
  export async function handleReposRoute(request, url, githubApp) {
15
17
  if (url.pathname === "/api/repos" && request.method === "GET") {
@@ -197,6 +199,53 @@ export async function handleReposRoute(request, url, githubApp) {
197
199
  }
198
200
  }
199
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
+ }
200
249
  if ("reviewPolicy" in body) {
201
250
  const stored = policyToStore(body.reviewPolicy, { allowLegacy: true });
202
251
  if (!stored.ok) {
@@ -247,8 +296,14 @@ export async function handleReposRoute(request, url, githubApp) {
247
296
  init[key] = body[key];
248
297
  }
249
298
  }
250
- if (Object.keys(init).length > 0 || "remakeCron" in cronPatch) {
251
- 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
+ });
252
307
  }
253
308
  return Response.json({ ok: true });
254
309
  }
@@ -264,6 +319,10 @@ export async function handleReposRoute(request, url, githubApp) {
264
319
  if (sub === "knowledge" && request.method === "GET") {
265
320
  return Response.json(await repoKnowledge(fullName));
266
321
  }
322
+ if (sub === "knowledge" && request.method === "DELETE") {
323
+ requireActiveRepo(fullName);
324
+ return await clearOneRepo(fullName, url);
325
+ }
267
326
  if (sub === "pulls" &&
268
327
  pr &&
269
328
  action === "review" &&
@@ -9,6 +9,7 @@ import { aiConfigured, readConfig, resolveAppPrivateKey } from "../config.js";
9
9
  import { listJobs } from "../store/jobs.js";
10
10
  import { handleJobsRoute } from "./api/jobs.js";
11
11
  import { handleReposRoute } from "./api/repos.js";
12
+ import { handleKnowledgeRoute } from "./api/knowledge.js";
12
13
  import { handleInstallationsRoute } from "./api/installations.js";
13
14
  import { handleSettingsRoute } from "./api/settings.js";
14
15
  import { handleActivityRoute } from "./api/activity.js";
@@ -154,6 +155,9 @@ export function createApp(deps) {
154
155
  if (url.pathname.startsWith("/api/repos")) {
155
156
  return await handleReposRoute(request, url, githubApp);
156
157
  }
158
+ if (url.pathname === "/api/knowledge") {
159
+ return await handleKnowledgeRoute(request, url);
160
+ }
157
161
  if (url.pathname === "/api/installations") {
158
162
  return await handleInstallationsRoute(request, githubApp);
159
163
  }
@@ -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 try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n } catch {\n // body was not JSON; keep the generic message\n }\n throw new Error(message);\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\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 try {\n const data = await res.json();\n if (data.error && data.error.message) message = data.error.message;\n } catch {\n // body was not JSON; keep the generic message\n }\n throw new Error(message);\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\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";
@@ -13,7 +13,7 @@ export function renderKnowledge(username, data, viewId) {
13
13
  ? `<div class="notice"><div class="txt">Built ${when(data.repo.knowledge_built_at)}.${drift
14
14
  ? ` Since then: <b>${drift.prs_since} new pull requests</b>, <b>${drift.prs_updated} changed pull requests</b>, <b>${capped(drift.commits_since, MAX_COMMITS_COUNTED)} new commits</b> and <b>${capped(drift.files_changed, COMPARE_FILE_CAP)} changed files</b>. <span class="muted">Checked ${when(drift.as_of)}.</span>`
15
15
  : ""}</div></div>`
16
- : `<div class="notice info"><div class="txt">Knowledge has not been built yet. Run init from the repository list.</div></div>`;
16
+ : `<div class="notice info"><div class="txt">Knowledge has not been built yet. Use Sync to build it.</div></div>`;
17
17
  const viewer = viewing
18
18
  ? `<div class="card"><div class="hd"><h2>${text(viewing.title)}</h2>
19
19
  <a class="btn sm" style="margin-left:auto" href="/repos/${text(name)}/knowledge">Close</a></div>
@@ -53,12 +53,31 @@ export function renderKnowledge(username, data, viewId) {
53
53
  <div class="hd"><h2>History</h2></div>
54
54
  <div class="bd">${empty("Only the current knowledge is kept", "Older versions are not stored yet.")}</div>
55
55
  </div>
56
+ <div class="card" data-async>
57
+ ${skSlot()}
58
+ <div class="hd"><h2>Clear</h2></div>
59
+ <div class="bd">
60
+ <p class="muted" style="margin:0 0 16px">Delete the guides and the saved settings for this repository. The next Sync builds them from scratch.</p>
61
+ <div class="field wide"><label><input type="checkbox" id="clear-cache"> Also delete the cached evidence: pull request listings, costs, clones and worktrees</label>
62
+ <div class="hint">Without it the next build still reuses the files and pull requests it already paid for.</div></div>
63
+ </div>
64
+ <div class="ft"><button id="clear" style="color:var(--red)">Clear knowledge</button></div>
65
+ </div>
56
66
  </div>
57
67
  </div>
58
68
  <script>
59
69
  document.getElementById("update").addEventListener("click", function() {
60
70
  postAndGo("/api/repos/" + ${JSON.stringify(name)} + "/remake", {}, "/activity", this);
61
71
  });
72
+ document.getElementById("clear").addEventListener("click", function() {
73
+ if (!confirm("Delete the guides and saved settings for this repository?")) return;
74
+ var includeCache = document.getElementById("clear-cache").checked;
75
+ var btn = this;
76
+ run(btn, btn.closest("[data-async]"), async function() {
77
+ var done = await clearKnowledge(${JSON.stringify(`/api/repos/${name}/knowledge`)}, includeCache);
78
+ if (done !== false) location.reload();
79
+ });
80
+ });
62
81
  </script>`,
63
82
  }));
64
83
  }
@@ -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;