co-maintainer 0.6.12 → 0.7.0-beta.1

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 (159) hide show
  1. package/README.md +1 -1
  2. package/dist/package.json +1 -1
  3. package/dist/src/ai/anthropic.js +2 -0
  4. package/dist/src/ai/batch.d.ts +3 -1
  5. package/dist/src/ai/batch.js +23 -2
  6. package/dist/src/ai/mermaid_loop.js +1 -1
  7. package/dist/src/ai/oauth/sign-in-with-chatgpt.js +8 -10
  8. package/dist/src/ai/openai.js +2 -0
  9. package/dist/src/ai/openrouter.js +2 -0
  10. package/dist/src/cli/args.js +47 -0
  11. package/dist/src/cli/command_json.d.ts +20 -1
  12. package/dist/src/cli/command_json.js +4 -0
  13. package/dist/src/cli/commands/config.d.ts +1 -1
  14. package/dist/src/cli/commands/config.js +1 -0
  15. package/dist/src/cli/commands/registry.js +226 -1
  16. package/dist/src/cli/commands/review.js +50 -9
  17. package/dist/src/cli/commands/serve.js +5 -0
  18. package/dist/src/cli/commands/set.js +75 -17
  19. package/dist/src/cli/commands/view.js +46 -5
  20. package/dist/src/cli/commands/view_sources.d.ts +11 -0
  21. package/dist/src/cli/commands/view_sources.js +40 -0
  22. package/dist/src/cli/main.js +5 -0
  23. package/dist/src/cli/pr_carry.d.ts +25 -0
  24. package/dist/src/cli/pr_carry.js +128 -0
  25. package/dist/src/cli/prompt.js +26 -1
  26. package/dist/src/cli/review_args.d.ts +8 -0
  27. package/dist/src/cli/review_args.js +18 -0
  28. package/dist/src/cli/review_carry.d.ts +32 -0
  29. package/dist/src/cli/review_carry.js +60 -0
  30. package/dist/src/cli/review_github.d.ts +16 -2
  31. package/dist/src/cli/review_github.js +49 -12
  32. package/dist/src/cli/review_intent.d.ts +25 -0
  33. package/dist/src/cli/review_intent.js +87 -0
  34. package/dist/src/cli/review_result.d.ts +53 -2
  35. package/dist/src/cli/review_result.js +90 -23
  36. package/dist/src/config.d.ts +30 -0
  37. package/dist/src/config.js +20 -12
  38. package/dist/src/extensions/command.d.ts +1 -0
  39. package/dist/src/extensions/command.js +355 -0
  40. package/dist/src/extensions/contexts.d.ts +65 -0
  41. package/dist/src/extensions/contexts.js +134 -0
  42. package/dist/src/extensions/cost.d.ts +8 -0
  43. package/dist/src/extensions/cost.js +6 -0
  44. package/dist/src/extensions/local_tracking.d.ts +7 -0
  45. package/dist/src/extensions/local_tracking.js +29 -0
  46. package/dist/src/extensions/mock.d.ts +29 -0
  47. package/dist/src/extensions/mock.js +67 -0
  48. package/dist/src/extensions/process.d.ts +43 -0
  49. package/dist/src/extensions/process.js +244 -0
  50. package/dist/src/extensions/registry.d.ts +79 -0
  51. package/dist/src/extensions/registry.js +240 -0
  52. package/dist/src/extensions/render_actions.d.ts +6 -0
  53. package/dist/src/extensions/render_actions.js +50 -0
  54. package/dist/src/extensions/render_cli.d.ts +18 -0
  55. package/dist/src/extensions/render_cli.js +88 -0
  56. package/dist/src/extensions/render_json.d.ts +51 -0
  57. package/dist/src/extensions/render_json.js +144 -0
  58. package/dist/src/extensions/render_markdown.d.ts +22 -0
  59. package/dist/src/extensions/render_markdown.js +96 -0
  60. package/dist/src/extensions/render_review.d.ts +44 -0
  61. package/dist/src/extensions/render_review.js +167 -0
  62. package/dist/src/extensions/report.d.ts +57 -0
  63. package/dist/src/extensions/report.js +97 -0
  64. package/dist/src/extensions/review_result.d.ts +2 -0
  65. package/dist/src/extensions/review_result.js +14 -0
  66. package/dist/src/extensions/run_folder.d.ts +74 -0
  67. package/dist/src/extensions/run_folder.js +172 -0
  68. package/dist/src/extensions/runner.d.ts +66 -0
  69. package/dist/src/extensions/runner.js +251 -0
  70. package/dist/src/extensions/schema.d.ts +103 -0
  71. package/dist/src/extensions/schema.js +539 -0
  72. package/dist/src/extensions/session.d.ts +56 -0
  73. package/dist/src/extensions/session.js +173 -0
  74. package/dist/src/github/collect.d.ts +7 -2
  75. package/dist/src/github/collect.js +66 -6
  76. package/dist/src/github/gh.d.ts +7 -0
  77. package/dist/src/github/gh.js +24 -29
  78. package/dist/src/knowledge/guide.js +3 -2
  79. package/dist/src/knowledge/instruction_files.d.ts +45 -0
  80. package/dist/src/knowledge/instruction_files.js +91 -0
  81. package/dist/src/knowledge/instructions.d.ts +78 -0
  82. package/dist/src/knowledge/instructions.js +280 -0
  83. package/dist/src/knowledge/rule_changes.d.ts +39 -0
  84. package/dist/src/knowledge/rule_changes.js +90 -0
  85. package/dist/src/knowledge/rules.d.ts +44 -0
  86. package/dist/src/knowledge/rules.js +82 -0
  87. package/dist/src/knowledge/synthesis.d.ts +1 -0
  88. package/dist/src/knowledge/synthesis.js +12 -5
  89. package/dist/src/knowledge/types.d.ts +4 -0
  90. package/dist/src/local/carry_over_store.d.ts +10 -0
  91. package/dist/src/local/carry_over_store.js +17 -0
  92. package/dist/src/local/review_local.js +100 -62
  93. package/dist/src/local/review_lock.js +15 -4
  94. package/dist/src/pr/diff_plan.d.ts +110 -0
  95. package/dist/src/pr/diff_plan.js +429 -0
  96. package/dist/src/pr/diff_summary.d.ts +17 -1
  97. package/dist/src/pr/diff_summary.js +87 -13
  98. package/dist/src/pr/review_diff.d.ts +47 -0
  99. package/dist/src/pr/review_diff.js +112 -0
  100. package/dist/src/pr/reviewer.d.ts +44 -19
  101. package/dist/src/pr/reviewer.js +114 -142
  102. package/dist/src/remote/client.js +67 -8
  103. package/dist/src/remote/http.d.ts +12 -0
  104. package/dist/src/remote/http.js +31 -0
  105. package/dist/src/remote/push_client.js +14 -3
  106. package/dist/src/remote/server/guides.js +12 -1
  107. package/dist/src/remote/server/routes.js +4 -2
  108. package/dist/src/remote/server/sessions.js +4 -1
  109. package/dist/src/remote/validate.js +11 -0
  110. package/dist/src/review/carry_over.d.ts +6 -1
  111. package/dist/src/review/carry_over.js +10 -2
  112. package/dist/src/review/coverage.d.ts +57 -0
  113. package/dist/src/review/coverage.js +186 -0
  114. package/dist/src/review/diagram.d.ts +73 -0
  115. package/dist/src/review/diagram.js +309 -0
  116. package/dist/src/review/engine.d.ts +2 -6
  117. package/dist/src/review/engine.js +1 -1
  118. package/dist/src/review/guides.d.ts +6 -0
  119. package/dist/src/review/guides.js +8 -1
  120. package/dist/src/review/intent.d.ts +24 -0
  121. package/dist/src/review/intent.js +28 -0
  122. package/dist/src/review/not_initialized.d.ts +13 -0
  123. package/dist/src/review/not_initialized.js +18 -0
  124. package/dist/src/review/system_prompt.d.ts +6 -0
  125. package/dist/src/review/system_prompt.js +13 -0
  126. package/dist/src/review/visible_paths.d.ts +22 -0
  127. package/dist/src/review/visible_paths.js +41 -0
  128. package/dist/src/server/auth.js +8 -1
  129. package/dist/src/server/pages/extensions.d.ts +5 -0
  130. package/dist/src/server/pages/extensions.js +72 -0
  131. package/dist/src/server/pages/pr.js +3 -2
  132. package/dist/src/services/dashboard.d.ts +8 -0
  133. package/dist/src/services/dashboard.js +8 -0
  134. package/dist/src/services/push_review.js +14 -5
  135. package/dist/src/services/remote_review.js +81 -26
  136. package/dist/src/services/replies.js +15 -8
  137. package/dist/src/services/review.d.ts +9 -3
  138. package/dist/src/services/review.js +109 -28
  139. package/dist/src/services/rules_build.d.ts +46 -0
  140. package/dist/src/services/rules_build.js +155 -0
  141. package/dist/src/services/setup.d.ts +31 -0
  142. package/dist/src/services/setup.js +120 -25
  143. package/dist/src/services/watch_comments.js +2 -0
  144. package/dist/src/store/app_db.d.ts +3 -1
  145. package/dist/src/store/app_db.js +7 -2
  146. package/dist/src/store/cache_db.js +3 -0
  147. package/dist/src/store/extensions.d.ts +51 -0
  148. package/dist/src/store/extensions.js +132 -0
  149. package/dist/src/store/migrations.js +40 -0
  150. package/dist/src/types.d.ts +22 -1
  151. package/dist/src/util/atomic.d.ts +15 -1
  152. package/dist/src/util/atomic.js +59 -29
  153. package/dist/src/util/interrupt.d.ts +6 -0
  154. package/dist/src/util/interrupt.js +27 -0
  155. package/dist/src/util/runtime.d.ts +3 -1
  156. package/dist/src/util/runtime.js +2 -2
  157. package/dist/src/util/test_location_guard.d.ts +6 -0
  158. package/dist/src/util/test_location_guard.js +47 -0
  159. package/package.json +1 -1
@@ -0,0 +1,172 @@
1
+ /** The folder one review shares with its extensions.
2
+ *
3
+ * <config dir>/co-maintainer/extensions/<run-id>/details.json context
4
+ * <config dir>/co-maintainer/extensions/<run-id>/cm-review.json AI results
5
+ * <config dir>/co-maintainer/extensions/<run-id>/diff.patch the diff
6
+ *
7
+ * The folder is removed however the review ends. A process that dies cannot
8
+ * remove its own, so `serve` removes the folders of jobs no longer running at
9
+ * startup and the CLI removes the folders of CLI runs whose process is gone.
10
+ *
11
+ * `state.json` records which extensions started. A `serve` job that runs again
12
+ * after a restart finds its folder still there and learns from it which
13
+ * extensions were cut off mid-run. */
14
+ import { dirname } from "node:path";
15
+ import { configPath } from "../config.js";
16
+ import { getEnv, isNotFound, isProcessAlive, mkdir, readDir, readTextFile, remove, writeTextFile, } from "../util/runtime.js";
17
+ import { writeTextFileAtomic } from "../util/atomic.js";
18
+ /** `<config dir>/co-maintainer/extensions`. A `config.json` moved elsewhere
19
+ * with `CM_CONFIG_PATH` may sit in a folder that holds anything, such as the
20
+ * home folder, so the run folders go under a name of their own there:
21
+ * `co-maintainer-extensions` next to that file. */
22
+ export function extensionsRoot() {
23
+ if (getEnv("CM_CONFIG_PATH") === undefined) {
24
+ return `${dirname(configPath())}/extensions`;
25
+ }
26
+ return `${dirname(configPath())}/co-maintainer-extensions`;
27
+ }
28
+ /** Every run id is a UUID, or `debug-` and a UUID. Nothing else is ever made
29
+ * or removed under the extensions folder. */
30
+ const RUN_ID = /^(?:debug-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
31
+ export function isRunId(value) {
32
+ return value !== undefined && RUN_ID.test(value);
33
+ }
34
+ function safeRunId(runId) {
35
+ if (!RUN_ID.test(runId)) {
36
+ throw new Error(`invalid extension run id: ${runId}`);
37
+ }
38
+ return runId;
39
+ }
40
+ /** Marks `owner.json` as co-maintainer's own. */
41
+ const OWNER_TOOL = "co-maintainer-extension-run";
42
+ async function readJson(path) {
43
+ try {
44
+ return JSON.parse(await readTextFile(path));
45
+ }
46
+ catch {
47
+ return undefined;
48
+ }
49
+ }
50
+ export async function openRunFolder(input) {
51
+ const dir = `${extensionsRoot()}/${safeRunId(input.runId)}`;
52
+ const state = await readJson(`${dir}/state.json`);
53
+ await mkdir(dir, { recursive: true });
54
+ const folder = {
55
+ runId: input.runId,
56
+ dir,
57
+ detailsPath: `${dir}/details.json`,
58
+ reviewResultPath: `${dir}/cm-review.json`,
59
+ diffPath: `${dir}/diff.patch`,
60
+ restarted: state !== undefined,
61
+ startedBefore: new Set(state?.started ?? []),
62
+ finishedBefore: new Set(state?.finished ?? []),
63
+ details: { ...input.details, reviewResultPath: "", diffPath: "" },
64
+ };
65
+ folder.details.diffPath = folder.diffPath;
66
+ const owner = {
67
+ tool: OWNER_TOOL,
68
+ pid: process.pid,
69
+ kind: input.owner,
70
+ };
71
+ await writeTextFile(`${dir}/owner.json`, JSON.stringify(owner));
72
+ await writeTextFile(folder.diffPath, input.diff);
73
+ await writeDetails(folder);
74
+ // A rerun keeps the old record until each extension starts again, so a
75
+ // second restart still knows what the first one cut off.
76
+ if (!state)
77
+ await writeState(folder, { started: [], finished: [] });
78
+ return folder;
79
+ }
80
+ /** Written through a temporary file and a rename: an extension that is
81
+ * already running may read it while it is rewritten. */
82
+ async function writeDetails(folder) {
83
+ await writeTextFileAtomic(folder.detailsPath, `${JSON.stringify(folder.details, null, 2)}\n`);
84
+ }
85
+ async function writeState(folder, state) {
86
+ await writeTextFileAtomic(`${folder.dir}/state.json`, JSON.stringify(state));
87
+ }
88
+ /** Calls for one folder are serialised, so two extensions starting or
89
+ * finishing together cannot drop each other's entry. */
90
+ const startedLocks = new Map();
91
+ function updateState(folder, change) {
92
+ const previous = startedLocks.get(folder.dir) ?? Promise.resolve();
93
+ const next = previous.then(async () => {
94
+ const stored = await readJson(`${folder.dir}/state.json`);
95
+ const state = {
96
+ started: stored?.started ?? [],
97
+ finished: stored?.finished ?? [],
98
+ };
99
+ change(state);
100
+ await writeState(folder, state);
101
+ });
102
+ const settled = next.catch(() => { });
103
+ startedLocks.set(folder.dir, settled);
104
+ return next;
105
+ }
106
+ /** Records that an extension started. A rerun clears its earlier finish. */
107
+ export function markStarted(folder, name) {
108
+ return updateState(folder, (state) => {
109
+ if (!state.started.includes(name))
110
+ state.started.push(name);
111
+ state.finished = state.finished.filter((entry) => entry !== name);
112
+ });
113
+ }
114
+ /** Records that an extension finished, so a restart after it does not count
115
+ * it as cut off. */
116
+ export function markFinished(folder, name) {
117
+ return updateState(folder, (state) => {
118
+ if (!state.finished.includes(name))
119
+ state.finished.push(name);
120
+ });
121
+ }
122
+ /** Writes the AI review results and points `details.json` at them. */
123
+ export async function writeReviewResult(folder, result) {
124
+ await writeTextFileAtomic(folder.reviewResultPath, `${JSON.stringify(result, null, 2)}\n`);
125
+ folder.details.reviewResultPath = folder.reviewResultPath;
126
+ await writeDetails(folder);
127
+ }
128
+ export async function removeRunFolder(folder) {
129
+ startedLocks.delete(folder.dir);
130
+ await remove(folder.dir, { recursive: true }).catch(() => { });
131
+ }
132
+ /** Removes the run folders `keep` does not claim. Only a folder named like a
133
+ * run id that holds co-maintainer's own `owner.json` is ever a candidate:
134
+ * anything else under the folder is someone else's and stays. */
135
+ export async function removeStaleRunFolders(keep) {
136
+ const root = extensionsRoot();
137
+ let removed = 0;
138
+ try {
139
+ for await (const entry of readDir(root)) {
140
+ if (!entry.isDirectory || entry.isSymlink)
141
+ continue;
142
+ if (!RUN_ID.test(entry.name))
143
+ continue;
144
+ const owner = await readJson(`${root}/${entry.name}/owner.json`);
145
+ if (owner?.tool !== OWNER_TOOL)
146
+ continue;
147
+ if (keep(entry.name, owner))
148
+ continue;
149
+ await remove(`${root}/${entry.name}`, { recursive: true }).catch(() => { });
150
+ removed++;
151
+ }
152
+ }
153
+ catch (error) {
154
+ if (!isNotFound(error))
155
+ throw error;
156
+ }
157
+ return removed;
158
+ }
159
+ /** `serve`'s cleanup at startup: every folder of a job no longer running, and
160
+ * every CLI run whose process is gone. */
161
+ export function removeServeRunFolders(running) {
162
+ return removeStaleRunFolders((runId, owner) => owner.kind === "cli"
163
+ ? owner.pid === process.pid || isProcessAlive(owner.pid)
164
+ : running.has(runId));
165
+ }
166
+ /** The CLI's cleanup on its next review: a CLI run whose process is gone.
167
+ * Folders `serve` owns are left to `serve`, which may still rerun them. */
168
+ export function removeDeadCliRunFolders() {
169
+ return removeStaleRunFolders((_, owner) => owner.kind !== "cli" ||
170
+ owner.pid === process.pid ||
171
+ isProcessAlive(owner.pid));
172
+ }
@@ -0,0 +1,66 @@
1
+ /** Runs the extensions of one review.
2
+ *
3
+ * The AI review is the start point and never waits for an extension. An
4
+ * extension with no run-after starts with the review, one with `--run-after`
5
+ * starts when its target finishes, and `--parallelism=false` with no run-after
6
+ * waits for the review. Every extension that becomes ready at the same moment
7
+ * starts in priority order, 3 first, ties in registration order. There is no
8
+ * other limit: `max-concurrent-jobs` already bounds the reviews.
9
+ *
10
+ * A run ends in one of three states. `retry` is never final: it is honoured up
11
+ * to the registration's limit and then becomes Failed. */
12
+ import { type ExtensionRegistration } from "./registry.ts";
13
+ import { type ExtensionData, type ExtensionFindingInput, type ExtensionUsage, type ExtensionVerdict } from "./schema.ts";
14
+ import { type RunFolder } from "./run_folder.ts";
15
+ export type ExtensionResult = {
16
+ /** The registered name, which is the extension's id in every output. */
17
+ name: string;
18
+ status: "ok" | "failed" | "skipped";
19
+ verdict: ExtensionVerdict | null;
20
+ reason: string | null;
21
+ markdown: string;
22
+ findings: ExtensionFindingInput[];
23
+ data: ExtensionData;
24
+ extraData: unknown;
25
+ usage: ExtensionUsage | null;
26
+ /** stdout and stderr with the exit code, kept for a failure. */
27
+ details: string | null;
28
+ durationMs: number;
29
+ attempts: number;
30
+ };
31
+ export type RunnerInput = {
32
+ /** The registrations that apply to this review, in registration order. */
33
+ registrations: ExtensionRegistration[];
34
+ folder: RunFolder;
35
+ /** The working directory a local review's extensions run in. */
36
+ cwd?: string;
37
+ /** Resolves true once the review results are written, false when the
38
+ * review did not finish. */
39
+ reviewDone: Promise<boolean>;
40
+ signal?: AbortSignal;
41
+ rerunOnRestart: (registration: ExtensionRegistration) => boolean;
42
+ killGraceMs?: number;
43
+ /** Waits out a `retryAfterSeconds`. Tests pass a shorter one. */
44
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
45
+ log?: (message: string) => void;
46
+ };
47
+ /** A Failed result for an extension that never ran. */
48
+ export declare function failedResult(name: string, reason: string): ExtensionResult;
49
+ /** The target an extension waits for: its run-after, or the review when it
50
+ * may not run alongside it. */
51
+ export declare function dependencyOf(registration: Pick<ExtensionRegistration, "runAfter" | "parallelism">): string | undefined;
52
+ /** Orders a set that becomes ready together: priority 3 first, ties in
53
+ * registration order. */
54
+ export declare function startOrder(registrations: ExtensionRegistration[]): ExtensionRegistration[];
55
+ /** One extension from its first attempt to its final state: schema retries,
56
+ * requested retries, the timeout and a cancel. */
57
+ export declare function runAttempts(input: {
58
+ registration: ExtensionRegistration;
59
+ command: string;
60
+ cwd?: string;
61
+ signal?: AbortSignal;
62
+ killGraceMs?: number;
63
+ sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
64
+ log?: (message: string) => void;
65
+ }): Promise<ExtensionResult>;
66
+ export declare function runExtensions(input: RunnerInput): Promise<ExtensionResult[]>;
@@ -0,0 +1,251 @@
1
+ /** Runs the extensions of one review.
2
+ *
3
+ * The AI review is the start point and never waits for an extension. An
4
+ * extension with no run-after starts with the review, one with `--run-after`
5
+ * starts when its target finishes, and `--parallelism=false` with no run-after
6
+ * waits for the review. Every extension that becomes ready at the same moment
7
+ * starts in priority order, 3 first, ties in registration order. There is no
8
+ * other limit: `max-concurrent-jobs` already bounds the reviews.
9
+ *
10
+ * A run ends in one of three states. `retry` is never final: it is honoured up
11
+ * to the registration's limit and then becomes Failed. */
12
+ import { formatTimeout, REVIEW_TARGET, } from "./registry.js";
13
+ import { runCommandOnce, substitute } from "./process.js";
14
+ import { parseResponse, } from "./schema.js";
15
+ import { markFinished, markStarted } from "./run_folder.js";
16
+ const EMPTY_DATA = { media: [], metrics: [] };
17
+ function blank(name, status, reason) {
18
+ return {
19
+ name,
20
+ status,
21
+ verdict: null,
22
+ reason,
23
+ markdown: "",
24
+ findings: [],
25
+ data: EMPTY_DATA,
26
+ extraData: null,
27
+ usage: null,
28
+ details: null,
29
+ durationMs: 0,
30
+ attempts: 0,
31
+ };
32
+ }
33
+ /** A Failed result for an extension that never ran. */
34
+ export function failedResult(name, reason) {
35
+ return blank(name, "failed", reason);
36
+ }
37
+ function defaultSleep(ms, signal) {
38
+ return new Promise((resolve) => {
39
+ if (signal?.aborted)
40
+ return resolve();
41
+ const timer = setTimeout(done, ms);
42
+ function done() {
43
+ clearTimeout(timer);
44
+ signal?.removeEventListener("abort", done);
45
+ resolve();
46
+ }
47
+ signal?.addEventListener("abort", done, { once: true });
48
+ });
49
+ }
50
+ /** The target an extension waits for: its run-after, or the review when it
51
+ * may not run alongside it. */
52
+ export function dependencyOf(registration) {
53
+ if (registration.runAfter)
54
+ return registration.runAfter;
55
+ return registration.parallelism === false ? REVIEW_TARGET : undefined;
56
+ }
57
+ /** Names whose run-after chain loops. `register` refuses a cycle, so this
58
+ * only catches a config edited by hand, which would otherwise wait forever. */
59
+ function namesInCycles(registrations) {
60
+ const next = new Map(registrations.map((entry) => [entry.name, entry]));
61
+ const looping = new Set();
62
+ for (const start of registrations) {
63
+ const seen = new Set([start.name]);
64
+ let current = start.runAfter;
65
+ while (current && current !== REVIEW_TARGET && next.has(current)) {
66
+ if (seen.has(current)) {
67
+ looping.add(start.name);
68
+ break;
69
+ }
70
+ seen.add(current);
71
+ current = next.get(current).runAfter;
72
+ }
73
+ }
74
+ return looping;
75
+ }
76
+ /** Orders a set that becomes ready together: priority 3 first, ties in
77
+ * registration order. */
78
+ export function startOrder(registrations) {
79
+ return registrations
80
+ .map((entry, index) => ({ entry, index }))
81
+ .sort((a, b) => (b.entry.priority ?? 0) - (a.entry.priority ?? 0) || a.index - b.index)
82
+ .map(({ entry }) => entry);
83
+ }
84
+ function failureReason(outcome, problem) {
85
+ if (outcome.spawnError)
86
+ return `the command could not start: ${outcome.spawnError}`;
87
+ if (outcome.stdoutTooLarge)
88
+ return "stdout was larger than 16 MiB";
89
+ if (outcome.stdout.trim() === "" && outcome.exitCode !== 0) {
90
+ return outcome.signal
91
+ ? `the command was killed by ${outcome.signal} and printed no response`
92
+ : `the command exited with code ${outcome.exitCode} and printed no response`;
93
+ }
94
+ return `the response does not match the schema: ${problem}`;
95
+ }
96
+ function fromResponse(name, response, outcome, started, attempts) {
97
+ const status = response.status === "ok" ? "ok" : response.status;
98
+ return {
99
+ name,
100
+ status: status,
101
+ verdict: response.verdict ?? null,
102
+ reason: response.reason ??
103
+ (status === "failed" ? "the extension reported a failure" : null),
104
+ markdown: response.markdown,
105
+ findings: response.findings,
106
+ data: response.data,
107
+ extraData: response.extraData,
108
+ usage: response.usage ?? null,
109
+ details: status === "failed" ? outcome.details : null,
110
+ durationMs: Math.round(performance.now() - started),
111
+ attempts,
112
+ };
113
+ }
114
+ /** One extension from its first attempt to its final state: schema retries,
115
+ * requested retries, the timeout and a cancel. */
116
+ export async function runAttempts(input) {
117
+ const { registration } = input;
118
+ const sleep = input.sleep ?? defaultSleep;
119
+ const log = input.log ?? (() => { });
120
+ const started = performance.now();
121
+ let attempts = 0;
122
+ let schemaRetries = 0;
123
+ let requested = 0;
124
+ const failed = (reason, details) => ({
125
+ ...blank(registration.name, "failed", reason),
126
+ details,
127
+ durationMs: Math.round(performance.now() - started),
128
+ attempts,
129
+ });
130
+ while (true) {
131
+ attempts++;
132
+ log(`extension ${registration.name}: attempt ${attempts}`);
133
+ const outcome = await runCommandOnce({
134
+ command: input.command,
135
+ cwd: input.cwd,
136
+ timeoutMs: registration.timeoutSeconds * 1000,
137
+ signal: input.signal,
138
+ killGraceMs: input.killGraceMs,
139
+ });
140
+ if (outcome.canceled) {
141
+ return failed("the review was cancelled", outcome.details);
142
+ }
143
+ if (outcome.timedOut) {
144
+ return failed(`timed out after ${formatTimeout(registration.timeoutSeconds)}`, outcome.details);
145
+ }
146
+ const parsed = outcome.stdoutTooLarge
147
+ ? { ok: false, reason: "stdout too large" }
148
+ : parseResponse(outcome.stdout);
149
+ if (!parsed.ok) {
150
+ const unsupported = parsed.reason.startsWith("unsupported schemaVersion");
151
+ const reason = unsupported
152
+ ? parsed.reason
153
+ : failureReason(outcome, parsed.reason);
154
+ if (!unsupported && schemaRetries < registration.retryOnFailTimes) {
155
+ schemaRetries++;
156
+ log(`extension ${registration.name}: ${reason}, retrying`);
157
+ continue;
158
+ }
159
+ return failed(reason, outcome.details);
160
+ }
161
+ const response = parsed.response;
162
+ if (response.status === "retry") {
163
+ if (requested >= registration.maxRequestedRetries) {
164
+ return failed(`asked for a retry more than ${registration.maxRequestedRetries} time${registration.maxRequestedRetries === 1 ? "" : "s"}. Last reason: ${response.reason}`, outcome.details);
165
+ }
166
+ requested++;
167
+ log(`extension ${registration.name}: asked to retry in ${response.retryAfterSeconds}s (${response.reason})`);
168
+ await sleep((response.retryAfterSeconds ?? 0) * 1000, input.signal);
169
+ if (input.signal?.aborted) {
170
+ return failed("the review was cancelled", outcome.details);
171
+ }
172
+ continue;
173
+ }
174
+ return fromResponse(registration.name, response, outcome, started, attempts);
175
+ }
176
+ }
177
+ export async function runExtensions(input) {
178
+ const byName = new Map(input.registrations.map((entry) => [entry.name, entry]));
179
+ const looping = namesInCycles(input.registrations);
180
+ const results = new Map();
181
+ let reviewFinished = false;
182
+ void input.reviewDone.then((done) => {
183
+ reviewFinished = done;
184
+ });
185
+ const runOne = async (registration) => {
186
+ const name = registration.name;
187
+ if (looping.has(name)) {
188
+ return blank(name, "skipped", "its run-after chain is a cycle");
189
+ }
190
+ const target = dependencyOf(registration);
191
+ if (target === REVIEW_TARGET) {
192
+ if (!(await input.reviewDone)) {
193
+ return blank(name, "failed", "the review did not finish");
194
+ }
195
+ reviewFinished = true;
196
+ }
197
+ else if (target !== undefined) {
198
+ const waitedOn = byName.get(target);
199
+ const pending = results.get(target);
200
+ if (!waitedOn || !pending) {
201
+ return blank(name, "skipped", `it runs after ${target}, which does not run for this review`);
202
+ }
203
+ const outcome = await pending;
204
+ if (outcome.status === "skipped") {
205
+ return blank(name, "skipped", `it runs after ${target}, which was skipped`);
206
+ }
207
+ if (outcome.status === "failed" && waitedOn.failFast) {
208
+ return blank(name, "skipped", `it runs after ${target}, which failed`);
209
+ }
210
+ }
211
+ if (input.signal?.aborted) {
212
+ return blank(name, "failed", "the review was cancelled");
213
+ }
214
+ if (input.folder.restarted &&
215
+ input.folder.startedBefore.has(name) &&
216
+ !input.folder.finishedBefore.has(name) &&
217
+ !input.rerunOnRestart(registration)) {
218
+ return blank(name, "failed", "co-maintainer restarted while it was running, and it is set not to run again");
219
+ }
220
+ await markStarted(input.folder, name);
221
+ const command = substitute(registration.command, {
222
+ details_path: input.folder.detailsPath,
223
+ review_result_path: reviewFinished ? input.folder.reviewResultPath : "",
224
+ diff_path: input.folder.diffPath,
225
+ });
226
+ const result = await runAttempts({
227
+ registration,
228
+ command,
229
+ cwd: input.cwd,
230
+ signal: input.signal,
231
+ killGraceMs: input.killGraceMs,
232
+ sleep: input.sleep,
233
+ log: input.log,
234
+ });
235
+ // A cancel is not a finish: a restart after it reruns the extension.
236
+ if (!input.signal?.aborted) {
237
+ await markFinished(input.folder, name).catch(() => { });
238
+ }
239
+ return result;
240
+ };
241
+ // Every promise is in the map before any of them looks a target up, and the
242
+ // ones that become ready together resume in the order they were made, which
243
+ // is priority order.
244
+ for (const registration of startOrder(input.registrations)) {
245
+ results.set(registration.name, Promise.resolve()
246
+ .then(() => runOne(registration))
247
+ .catch((error) => blank(registration.name, "failed", `co-maintainer could not run it: ${error instanceof Error ? error.message : String(error)}`)));
248
+ }
249
+ const settled = await Promise.all(input.registrations.map((entry) => results.get(entry.name)));
250
+ return settled;
251
+ }
@@ -0,0 +1,103 @@
1
+ /** The JSON an extension prints on stdout, as data.
2
+ *
3
+ * One list of field specs drives two things: the validator that decides
4
+ * whether a response is usable, and the schema table in the extensions docs
5
+ * page. A field cannot be checked one way and documented another, and the docs
6
+ * test fails when the table on the page is older than this list. The rules
7
+ * that tie one field to another (a verdict only with `ok`, a reason with
8
+ * `skipped`) are written out in `crossFieldProblem` and named in the table's
9
+ * rule column. */
10
+ export declare const EXTENSION_SCHEMA_VERSION = 1;
11
+ /** The longest wait a `retry` response may ask for. */
12
+ export declare const MAX_RETRY_AFTER_SECONDS = 180;
13
+ export declare const MAX_MARKDOWN_CHARS = 200000;
14
+ export declare const SEVERITIES: readonly ["P0", "P1", "P2", "P3"];
15
+ export declare const STATUSES: readonly ["ok", "failed", "skipped", "retry"];
16
+ export declare const VERDICTS: readonly ["request_changes", "comment"];
17
+ export declare const MEDIA_KINDS: readonly ["image", "video", "link"];
18
+ export type ExtensionStatus = (typeof STATUSES)[number];
19
+ export type ExtensionVerdict = (typeof VERDICTS)[number];
20
+ export type Severity = (typeof SEVERITIES)[number];
21
+ export type ExtensionFindingInput = {
22
+ key?: string;
23
+ severity: Severity;
24
+ blocking: boolean;
25
+ title: string;
26
+ body: string;
27
+ path?: string;
28
+ lineFrom?: number;
29
+ lineTo?: number;
30
+ };
31
+ export type ExtensionMedia = {
32
+ kind: (typeof MEDIA_KINDS)[number];
33
+ label: string;
34
+ url: string;
35
+ };
36
+ export type ExtensionMetric = {
37
+ name: string;
38
+ value: number;
39
+ unit?: string;
40
+ };
41
+ export type ExtensionData = {
42
+ media: ExtensionMedia[];
43
+ metrics: ExtensionMetric[];
44
+ };
45
+ export type ExtensionUsage = {
46
+ costUsd?: number;
47
+ tokensIn?: number;
48
+ tokensOut?: number;
49
+ cachedIn?: number;
50
+ cachedOut?: number;
51
+ };
52
+ /** A response after validation, with every optional list filled in. */
53
+ export type ExtensionResponse = {
54
+ schemaVersion: number;
55
+ name: string;
56
+ status: ExtensionStatus;
57
+ verdict?: ExtensionVerdict;
58
+ reason?: string;
59
+ retryAfterSeconds?: number;
60
+ markdown: string;
61
+ findings: ExtensionFindingInput[];
62
+ data: ExtensionData;
63
+ extraData: unknown;
64
+ usage?: ExtensionUsage;
65
+ };
66
+ type FieldType = "string" | "url" | "number" | "integer" | "boolean" | "object" | "array" | "any";
67
+ export type FieldSpec = {
68
+ name: string;
69
+ type: FieldType;
70
+ /** `yes`, `no`, or the rule that decides it, as the docs table prints it. */
71
+ required: string;
72
+ enum?: readonly string[];
73
+ min?: number;
74
+ /** For a string, its longest length in characters. */
75
+ maxLength?: number;
76
+ max?: number;
77
+ /** The fields of an object, or of each object in an array. */
78
+ fields?: FieldSpec[];
79
+ description: string;
80
+ };
81
+ export declare const RESPONSE_FIELDS: FieldSpec[];
82
+ export type ValidationResult = {
83
+ ok: true;
84
+ response: ExtensionResponse;
85
+ } | {
86
+ ok: false;
87
+ reason: string;
88
+ };
89
+ /** Checks one parsed response. An unsupported `schemaVersion` is reported on
90
+ * its own, before anything else, so an extension built for a later version
91
+ * gets a reason that says so instead of a complaint about a field it renamed. */
92
+ export declare function validateResponse(value: unknown): ValidationResult;
93
+ /** stdout as a response. Only the whole of stdout counts: no streaming, no
94
+ * log lines around the JSON. */
95
+ export declare function parseResponse(stdout: string): ValidationResult;
96
+ /** The response schema as the Markdown table the docs page carries between
97
+ * its `extension-schema` markers. */
98
+ export declare function responseSchemaTable(): string;
99
+ export declare const SCHEMA_BLOCK_START = "<!-- extension-schema:start -->";
100
+ export declare const SCHEMA_BLOCK_END = "<!-- extension-schema:end -->";
101
+ /** Rewrites the schema block in a docs page from the code. */
102
+ export declare function applySchemaBlock(md: string): string;
103
+ export {};