minga-swarm 0.1.0 → 0.1.2

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.
@@ -0,0 +1,157 @@
1
+ /**
2
+ * `minga sync`: refresh the read-only checkout after an accepted submission.
3
+ *
4
+ * A submit leaves the submitted files in the worktree while the server commits
5
+ * them on the branch, so a plain `git pull` can abort on "untracked working
6
+ * tree files would be overwritten". This command compares local changes with
7
+ * the freshly fetched branch head and only discards paths that are byte-identical
8
+ * to it or belong to this agent's last accepted submission.
9
+ *
10
+ * node:child_process and node:fs only: plain Node 20+, no dependencies.
11
+ */
12
+ import { execFileSync } from "node:child_process";
13
+ import { existsSync, readFileSync } from "node:fs";
14
+ import { resolve } from "node:path";
15
+ import type { CommandResult } from "./commands.ts";
16
+ import { readAgent } from "./store.ts";
17
+
18
+ /** Runs git in the checkout and returns stdout; throws on a non-zero exit. */
19
+ export type GitRunner = (args: string[]) => string;
20
+
21
+ export interface SyncInput {
22
+ dir: string;
23
+ /** Discard every local change, including files that look unrelated. */
24
+ discard?: boolean;
25
+ /** Injectable for tests; defaults to `git` via execFileSync. */
26
+ runner?: GitRunner;
27
+ }
28
+
29
+ export interface SyncData {
30
+ branch: string;
31
+ changed: string[];
32
+ /** Paths reset or cleaned. */
33
+ discarded: string[];
34
+ /** Paths that would not be discarded without --discard. */
35
+ conflicting: string[];
36
+ synced: boolean;
37
+ /** True when --discard was needed and not given. */
38
+ refused: boolean;
39
+ }
40
+
41
+ interface Change {
42
+ code: string;
43
+ path: string;
44
+ }
45
+
46
+ function firstLine(err: unknown): string {
47
+ const text = err instanceof Error ? err.message : String(err);
48
+ return text.split("\n")[0] ?? text;
49
+ }
50
+
51
+ function parseStatus(text: string): Change[] {
52
+ const changes: Change[] = [];
53
+ for (const line of text.split(/\r?\n/)) {
54
+ if (line.length < 4) continue;
55
+ const code = line.slice(0, 2);
56
+ if (code === "!!") continue;
57
+ let path = line.slice(3);
58
+ if ((code.includes("R") || code.includes("C")) && path.includes(" -> ")) {
59
+ path = path.slice(path.indexOf(" -> ") + 4);
60
+ }
61
+ if (path.startsWith('"') && path.endsWith('"')) path = path.slice(1, -1);
62
+ if (path.length > 0) changes.push({ code, path });
63
+ }
64
+ return changes;
65
+ }
66
+
67
+ function branchOf(run: GitRunner): string {
68
+ try {
69
+ // A clone made with -b <branch> tracks origin/<branch>: follow that first.
70
+ const upstream = run(["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]).trim();
71
+ const match = /^origin\/(.+)$/.exec(upstream);
72
+ if (match?.[1]) return match[1];
73
+ } catch {
74
+ // Detached HEAD or no upstream: fall back to origin/HEAD.
75
+ }
76
+ try {
77
+ const ref = run(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]).trim();
78
+ const match = /^refs\/remotes\/origin\/(.+)$/.exec(ref);
79
+ if (match?.[1]) return match[1];
80
+ } catch {
81
+ // Clones without origin/HEAD fall back to main.
82
+ }
83
+ return "main";
84
+ }
85
+
86
+ function headContent(run: GitRunner, branch: string, path: string): string | null {
87
+ try {
88
+ return run(["show", `origin/${branch}:${path}`]);
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+
94
+ function localContent(repoDir: string, path: string): string | null {
95
+ const absolute = resolve(repoDir, path);
96
+ if (!existsSync(absolute)) return null;
97
+ try {
98
+ return readFileSync(absolute, "utf8");
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+
104
+ /** Compare a worktree with origin/<branch> and drop only safe leftovers. */
105
+ export function syncCommand(input: SyncInput): CommandResult<SyncData> {
106
+ const repoDir = resolve(input.dir);
107
+ const run: GitRunner = input.runner ?? ((args) => execFileSync("git", args, {
108
+ cwd: repoDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"],
109
+ }));
110
+
111
+ try {
112
+ run(["fetch", "origin"]);
113
+ } catch (err) {
114
+ throw new Error(`git fetch origin failed: ${firstLine(err)}`);
115
+ }
116
+
117
+ const branch = branchOf(run);
118
+ const remote = `origin/${branch}`;
119
+ const changes = parseStatus(run(["status", "--porcelain"]));
120
+ const accepted = readAgent(repoDir)?.lastAccepted?.files ?? [];
121
+ const data: SyncData = {
122
+ branch, changed: changes.map((c) => c.path), discarded: [], conflicting: [],
123
+ synced: false, refused: false,
124
+ };
125
+
126
+ if (changes.length === 0) {
127
+ return { text: `already on ${remote}; no local changes to sync`, data };
128
+ }
129
+
130
+ for (const change of changes) {
131
+ const inHead = headContent(run, branch, change.path);
132
+ const local = localContent(repoDir, change.path);
133
+ const identical = inHead !== null && local !== null && inHead === local;
134
+ const safe = identical || accepted.includes(change.path);
135
+ if (!safe) data.conflicting.push(change.path);
136
+ if (safe || input.discard === true) data.discarded.push(change.path);
137
+ }
138
+
139
+ if (data.conflicting.length > 0 && input.discard !== true) {
140
+ data.refused = true;
141
+ const lines = [
142
+ `refusing to sync: local changes are not this agent's leftovers:`,
143
+ ...data.conflicting.map((path) => ` ${path}`),
144
+ 're-run "minga sync --discard" to discard them, or move them aside first',
145
+ ];
146
+ return { text: lines.join("\n"), data };
147
+ }
148
+
149
+ if (data.discarded.length > 0) {
150
+ run(["reset", "--hard", remote]);
151
+ run(["clean", "-fd", "--", ...data.discarded]);
152
+ }
153
+ data.synced = true;
154
+ const discarded = data.discarded.join(", ");
155
+ const text = `synced to ${remote}; discarded ${data.discarded.length} path(s): ${discarded}`;
156
+ return { text: input.discard === true && data.conflicting.length > 0 ? `${text} (--discard)` : text, data };
157
+ }
@@ -47,6 +47,8 @@ export interface ProjectInfo {
47
47
  paths: string[];
48
48
  headAgent: AgentId;
49
49
  rules: Rules;
50
+ /** The branch accepted work lands on; clone it with `git clone -b <branch> <url>/repo.git`. */
51
+ branch?: string;
50
52
  }
51
53
 
52
54
  /**
@@ -122,6 +124,11 @@ export interface MetricsResponse {
122
124
  /** Requests handled since start, per route ("POST /api/next"), and responses per status class. */
123
125
  requests: Record<string, number>;
124
126
  statuses: Record<string, number>;
127
+ /**
128
+ * Server-side handling time per route in ms, measured from request arrival to response,
129
+ * excluding time a long-poll spent holding (long-polled requests are not recorded).
130
+ */
131
+ latencyMs: Record<string, { count: number; p50: number; p99: number; max: number }>;
125
132
  }
126
133
 
127
134
  /** GET /api/events?after=<seq>&limit=<n> -> ascending events. */
@@ -171,13 +178,27 @@ export interface Assignment {
171
178
  path: { id: TaskId; title: string }[];
172
179
  /** Newest handoff note on this task, if any. */
173
180
  handoff?: NoteState;
181
+ /** Commit the project branch pointed at when this was assigned: `git pull` until you have it (repo: GET /repo.git, read-only). */
182
+ head?: string;
174
183
  /** Up to 10 newest notes on this task. */
175
184
  notes: NoteState[];
176
185
  /** Other live attempts on the task (overlap), so the agent can pick a different approach. */
177
186
  others: { attempt: AttemptId; agent: AgentId; model: string; role: Role; approach: string }[];
178
187
  }
179
- /** 200 with { assignment } or 200 with { assignment: null, retryAfterSeconds } when nothing is available. */
180
- export interface NextResponse { assignment: Assignment | null; retryAfterSeconds?: number }
188
+ /**
189
+ * 200 with { assignment } or 200 with { assignment: null, retryAfterSeconds } when nothing is free.
190
+ * done: true means the project has no open leaf task left at all (not merely "all busy"):
191
+ * stop asking. The server answers that at once, without holding a long-poll.
192
+ */
193
+ export interface NextResponse { assignment: Assignment | null; retryAfterSeconds?: number; done?: boolean }
194
+
195
+ /** GET /api/tasks -> every task, compact, for agents that want an overview (no bodies). */
196
+ export interface TasksResponse {
197
+ tasks: { id: TaskId; title: string; parent: TaskId | null; status: TaskState["status"]; points: number; live: number; leaf: boolean }[];
198
+ open: number;
199
+ /** True when no open leaf task remains. */
200
+ done: boolean;
201
+ }
181
202
 
182
203
  /** POST /api/beat */
183
204
  export interface BeatRequest { attempt: AttemptId; model?: string; approach?: string }
@@ -245,6 +266,10 @@ export interface HeadRuleResponse { rules: Rules }
245
266
  export interface HeadBanRequest { agent: AgentId; reason: string }
246
267
  export interface HeadBanResponse { ok: true }
247
268
 
269
+ /** POST /api/head/note — the head leaves a note on a task (shown to agents with their assignment, like any note). */
270
+ export interface HeadNoteRequest { task: TaskId; kind?: NoteKind; text: string }
271
+ export interface HeadNoteResponse { note: NoteState }
272
+
248
273
  /** POST /api/head/close — withdraw a task (or mark it solved/impossible by fiat). */
249
274
  export interface HeadCloseRequest { task: TaskId; status: "withdrawn" | "impossible" | "solved"; reason?: string }
250
275
  export interface HeadCloseResponse { ok: true }
@@ -225,6 +225,12 @@ export const reduce: Reduce = (state: State, event: MingaEvent): State => {
225
225
  if (attempt.endedAt === undefined) unindexAttempt(index, attempt);
226
226
  attempt.endedAt = at;
227
227
  attempt.endReason = d.reason;
228
+ // A release means the agent gave up on this task: reuse the rejection
229
+ // counter so the scheduler steers it elsewhere while other work exists.
230
+ if (d.reason === "released") {
231
+ const byTask = (index.failures[attempt.agent] ??= {});
232
+ byTask[attempt.task] = (byTask[attempt.task] ?? 0) + 1;
233
+ }
228
234
  break;
229
235
  }
230
236
 
@@ -86,8 +86,10 @@ function pickRole(roles: Record<Role, number>, rng: () => number): Role {
86
86
  *
87
87
  * Candidates: open leaf tasks with room under `rules.width`, excluding tasks
88
88
  * the agent already holds live, when the agent is under `maxAttemptsPerAgent`
89
- * and not banned. Candidates are scored (same-family avoidance, zero live
90
- * attempts, no prior failure, age) with a small rng tiebreak.
89
+ * and not banned. Tasks with no prior failure from the agent form the first
90
+ * tier; failed tasks are a fallback only when that tier is empty. Within a
91
+ * tier candidates are scored (same-family avoidance, zero live attempts, age)
92
+ * with a small rng tiebreak.
91
93
  */
92
94
  export const pickTask: PickTask = (input) => {
93
95
  const { state, agent, now } = input;
@@ -140,9 +142,20 @@ export const pickTask: PickTask = (input) => {
140
142
  );
141
143
  if (candidates.length === 0) return null;
142
144
 
145
+ // Hard tier: tasks the agent never failed come first. Failed tasks are only
146
+ // considered when no un-failed candidate exists, so a release steers the
147
+ // agent elsewhere while other open work is available.
148
+ const preferred: TaskState[] = [];
149
+ const fallback: TaskState[] = [];
150
+ for (const task of candidates) {
151
+ if (failedTasks.has(task.id)) fallback.push(task);
152
+ else preferred.push(task);
153
+ }
154
+ const tier = preferred.length > 0 ? preferred : fallback;
155
+
143
156
  let oldest = Infinity;
144
157
  let newest = -Infinity;
145
- for (const task of candidates) {
158
+ for (const task of tier) {
146
159
  const postedAt = Date.parse(task.postedAt);
147
160
  if (Number.isFinite(postedAt)) {
148
161
  if (postedAt < oldest) oldest = postedAt;
@@ -153,12 +166,11 @@ export const pickTask: PickTask = (input) => {
153
166
 
154
167
  let bestTask: TaskState | null = null;
155
168
  let bestScore = -Infinity;
156
- for (const task of candidates) {
169
+ for (const task of tier) {
157
170
  let score = 0;
158
171
 
159
172
  if (!liveFamiliesByTask.get(task.id)?.has(agentFamily)) score += 4;
160
173
  if ((liveCountByTask.get(task.id) ?? 0) === 0) score += 2;
161
- if (!failedTasks.has(task.id)) score += 1;
162
174
 
163
175
  const postedAt = Date.parse(task.postedAt);
164
176
  if (Number.isFinite(postedAt) && Number.isFinite(oldest) && Number.isFinite(newest)) {
package/src/server/app.ts CHANGED
@@ -16,9 +16,9 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
16
16
  import { join as pathJoin } from "node:path";
17
17
  import type { BranchHead, ChangedPaths, CheckPool, CheckResult, CommitAccepted, EventStore } from "../core/contracts.ts";
18
18
  import type {
19
- Assignment, BeatRequest, ErrorBody, EventsResponse, HeadBanRequest, HeadCloseRequest, HeadDecideRequest,
19
+ Assignment, BeatRequest, ErrorBody, EventsResponse, HeadBanRequest, HeadCloseRequest, HeadDecideRequest, HeadNoteRequest,
20
20
  HeadPostRequest, HeadRuleRequest, JoinRequest, JoinResponse, MetricsResponse, NextRequest, NextResponse,
21
- NoteRequest, ProjectInfo, ProposeRequest, ReleaseRequest, SubmissionView, SubmitRequest, SubmitResponse,
21
+ NoteRequest, ProjectInfo, ProposeRequest, ReleaseRequest, SubmissionView, SubmitRequest, SubmitResponse, TasksResponse,
22
22
  VoteRequest,
23
23
  } from "../core/protocol.ts";
24
24
  import {
@@ -32,6 +32,7 @@ import { buildView } from "../log/view.ts";
32
32
  import { pathAllowed, parseAcceptPolicy } from "../project/config.ts";
33
33
  import { decideByVotes, expiredAttempts, pickTask } from "../sched/scheduler.ts";
34
34
  import { authenticate, HttpError, NonceCache, RateLimiter } from "./auth.ts";
35
+ import { Latency } from "./latency.ts";
35
36
 
36
37
  export interface AppDeps {
37
38
  cfg: ProjectConfig;
@@ -52,6 +53,8 @@ export interface AppDeps {
52
53
  joinLimitPerHour?: number;
53
54
  /** Re-runs of a passing check after the branch moved, before giving up as stale. Default 3. */
54
55
  recheckLimit?: number;
56
+ /** Branch head at startup; kept current as accepted work lands. Sent with assignments. */
57
+ initialHead?: string;
55
58
  }
56
59
 
57
60
  const MAX_BODY = 3 * 1024 * 1024;
@@ -60,10 +63,16 @@ const NOTE_MAX = 4000;
60
63
  const MAX_WAIT_SECONDS = 30;
61
64
  /** SSE frames a slow viewer may fall behind before it is disconnected (it reconnects with Last-Event-ID). */
62
65
  const MAX_STREAM_BACKLOG = 2000;
63
- /** Event types that can free capacity for a waiting `next`. */
64
- const CAPACITY_EVENTS = new Set<MingaEvent["type"]>(["task.posted", "attempt.ended", "rule.changed"]);
66
+ /** Event types that can free capacity for, or end, a waiting `next`. */
67
+ const CAPACITY_EVENTS = new Set<MingaEvent["type"]>(["task.posted", "attempt.ended", "rule.changed", "task.closed"]);
65
68
 
66
- type Waiter = { agent: AgentId; model: string; approach: string; finish: (a: Assignment | null) => void };
69
+ const KNOWN_ROUTES = new Set([
70
+ "/api/project", "/api/view", "/api/leaderboard", "/api/metrics", "/api/tasks", "/api/events", "/api/stream", "/api/submission/:id",
71
+ "/api/join", "/api/next", "/api/beat", "/api/note", "/api/submit", "/api/release", "/api/propose", "/api/vote",
72
+ "/api/head/post", "/api/head/decide", "/api/head/rule", "/api/head/ban", "/api/head/close", "/api/head/note",
73
+ ]);
74
+
75
+ type Waiter = { agent: AgentId; model: string; approach: string; finish: (a: Assignment | null | "done") => void };
67
76
 
68
77
  export function createApp(deps: AppDeps) {
69
78
  const { cfg, store, repoDir } = deps;
@@ -74,6 +83,7 @@ export function createApp(deps: AppDeps) {
74
83
  const limiter = new RateLimiter(deps.rateLimitPerMinute ?? 120);
75
84
  const joinLimit = deps.joinLimitPerHour ?? 20;
76
85
  const recheckLimit = deps.recheckLimit ?? 3;
86
+ let branchTip = deps.initialHead;
77
87
  const submissionsDir = deps.submissionsDir ?? pathJoin(repoDir, ".minga", "submissions");
78
88
  mkdirSync(submissionsDir, { recursive: true });
79
89
  const startedAt = Date.now();
@@ -85,6 +95,9 @@ export function createApp(deps: AppDeps) {
85
95
  let waitersScheduled = false;
86
96
  const submissionWaiters = new Map<SubmissionId, Set<() => void>>();
87
97
  const statuses: Record<string, number> = {};
98
+ const latency = new Map<string, Latency>();
99
+ /** Requests that long-polled; their wall time is not handling time, so latency skips them. */
100
+ const heldRequests = new WeakSet<AbortSignal>();
88
101
 
89
102
  // ---------------------------------------------------------------- state
90
103
  const state: State = initialState(structuredClone(cfg.rules));
@@ -120,7 +133,7 @@ export function createApp(deps: AppDeps) {
120
133
  // ---------------------------------------------------------------- helpers
121
134
  const leaseUntil = () => new Date(now().getTime() + state.rules.leaseMinutes * 60_000).toISOString();
122
135
  const projectInfo = (): ProjectInfo => ({
123
- name: cfg.name, goal: cfg.goal, scope: cfg.scope, check: cfg.check, paths: cfg.paths, headAgent: headId, rules: state.rules,
136
+ name: cfg.name, goal: cfg.goal, scope: cfg.scope, check: cfg.check, paths: cfg.paths, headAgent: headId, rules: state.rules, branch: cfg.branch,
124
137
  });
125
138
  const json = (data: unknown, status = 200) => Response.json(data, { status });
126
139
  const fail = (status: number, error: string, detail?: string) => json({ error, ...(detail ? { detail } : {}) } satisfies ErrorBody, status);
@@ -223,6 +236,7 @@ export function createApp(deps: AppDeps) {
223
236
  });
224
237
  return {
225
238
  attempt, role: pick.role, leaseUntil: until,
239
+ ...(branchTip ? { head: branchTip } : {}),
226
240
  task: { id: t.id, title: t.title, body: t.body, parent: t.parent, points: t.points },
227
241
  path, notes, others, ...(handoffId ? { handoff: state.notes[handoffId]! } : {}),
228
242
  };
@@ -233,8 +247,17 @@ export function createApp(deps: AppDeps) {
233
247
  waitersScheduled = true;
234
248
  queueMicrotask(serveWaiters);
235
249
  }
250
+ /** True while some open task has no children: there is still work, even if every slot is busy. */
251
+ function hasOpenLeaf(): boolean {
252
+ for (const t of Object.values(state.tasks)) if (t.status === "open" && t.children.length === 0) return true;
253
+ return false;
254
+ }
236
255
  function serveWaiters() {
237
256
  waitersScheduled = false;
257
+ if (!hasOpenLeaf()) {
258
+ for (const w of [...waiters.values()]) w.finish("done");
259
+ return;
260
+ }
238
261
  for (const w of [...waiters.values()]) {
239
262
  const a = state.agents[w.agent];
240
263
  if (!a || a.banned) { w.finish(null); continue; }
@@ -259,7 +282,9 @@ export function createApp(deps: AppDeps) {
259
282
  // Waiters queued earlier are served first.
260
283
  const assignment = waiters.size ? null : tryAssign(agent, model, approach);
261
284
  if (assignment) return { assignment };
285
+ if (!hasOpenLeaf()) return { assignment: null, done: true };
262
286
  if (!wait) return { assignment: null, retryAfterSeconds: 60 };
287
+ if (signal) heldRequests.add(signal);
263
288
  return new Promise<NextResponse>((resolve) => {
264
289
  waiters.get(agent)?.finish(null); // a newer request from the same agent replaces the older one
265
290
  let timer: ReturnType<typeof setTimeout> | undefined;
@@ -268,7 +293,7 @@ export function createApp(deps: AppDeps) {
268
293
  finish(x) {
269
294
  if (timer) clearTimeout(timer);
270
295
  if (waiters.get(agent) === w) waiters.delete(agent);
271
- resolve(x ? { assignment: x } : { assignment: null, retryAfterSeconds: 0 });
296
+ resolve(x === "done" ? { assignment: null, done: true } : x ? { assignment: x } : { assignment: null, retryAfterSeconds: 0 });
272
297
  },
273
298
  };
274
299
  waiters.set(agent, w);
@@ -425,7 +450,7 @@ export function createApp(deps: AppDeps) {
425
450
  "Minga-Task": s.task, "Minga-Attempt": s.attempt, "Minga-Claim": s.claim,
426
451
  },
427
452
  });
428
- if (out.ok) return finalize(id, { base, result, commit: out.commit });
453
+ if (out.ok) { branchTip = out.commit; return finalize(id, { base, result, commit: out.commit }); }
429
454
  // The branch moved. With recheck = "on-overlap", land on the new head when nothing
430
455
  // committed since the check's base touched these paths.
431
456
  if (cfg.recheck === "on-overlap" && hops < 20) {
@@ -479,6 +504,7 @@ export function createApp(deps: AppDeps) {
479
504
  const s = state.submissions[id];
480
505
  if (!s) throw new HttpError(404, `no submission ${id}`);
481
506
  if (isFinal(s) || !wait) return submissionView(id);
507
+ if (signal) heldRequests.add(signal);
482
508
  return new Promise((resolve) => {
483
509
  let set = submissionWaiters.get(id);
484
510
  if (!set) submissionWaiters.set(id, (set = new Set()));
@@ -603,6 +629,16 @@ export function createApp(deps: AppDeps) {
603
629
  return { ok: true as const };
604
630
  }
605
631
 
632
+ function headNote(b: HeadNoteRequest) {
633
+ const task = str(b.task, "task", 32);
634
+ if (!state.tasks[task]) throw new HttpError(404, `no task ${task}`);
635
+ const kind = b.kind ?? "result";
636
+ if (!NOTE_KINDS.includes(kind)) throw new HttpError(400, `kind must be one of ${NOTE_KINDS.join(", ")}`);
637
+ const id = nextId(state, "note");
638
+ emit({ type: "note.added", actor: headId, data: { note: id, task, agent: headId, kind, text: str(b.text, "text", NOTE_MAX) } });
639
+ return { note: state.notes[id]! };
640
+ }
641
+
606
642
  function headClose(b: HeadCloseRequest) {
607
643
  const task = str(b.task, "task", 32);
608
644
  if (state.tasks[task]?.status !== "open") throw new HttpError(409, `task ${task} is not open`);
@@ -633,6 +669,15 @@ export function createApp(deps: AppDeps) {
633
669
  return new Response(v.body, { headers });
634
670
  }
635
671
 
672
+ function tasksOverview(): TasksResponse {
673
+ const tasks = Object.values(state.tasks).map((t) => ({
674
+ id: t.id, title: t.title, parent: t.parent, status: t.status, points: t.points,
675
+ live: liveAttempts(state, t.id, now()).length, leaf: t.children.length === 0,
676
+ }));
677
+ const open = tasks.filter((t) => t.status === "open" && t.leaf).length;
678
+ return { tasks, open, done: open === 0 };
679
+ }
680
+
636
681
  function metrics(): MetricsResponse {
637
682
  const cpu = process.cpuUsage();
638
683
  const mem = process.memoryUsage();
@@ -654,6 +699,7 @@ export function createApp(deps: AppDeps) {
654
699
  waiting: waiters.size,
655
700
  requests: { ...requests },
656
701
  statuses: { ...statuses },
702
+ latencyMs: Object.fromEntries([...latency].map(([route, h]) => [route, h.summary()])),
657
703
  };
658
704
  }
659
705
 
@@ -688,7 +734,7 @@ export function createApp(deps: AppDeps) {
688
734
  };
689
735
  const head: Record<string, (body: any) => unknown> = {
690
736
  "/api/head/post": headPost, "/api/head/decide": headDecide, "/api/head/rule": headRule,
691
- "/api/head/ban": headBan, "/api/head/close": headClose,
737
+ "/api/head/ban": headBan, "/api/head/close": headClose, "/api/head/note": headNote,
692
738
  };
693
739
 
694
740
  async function handleApi(req: Request, url: URL, ip: string | undefined): Promise<Response> {
@@ -698,6 +744,7 @@ export function createApp(deps: AppDeps) {
698
744
  if (path === "/api/view") return viewResponse(req);
699
745
  if (path === "/api/leaderboard") return json(computeLeaderboard(state, 1000));
700
746
  if (path === "/api/metrics") return json(metrics());
747
+ if (path === "/api/tasks") return json(tasksOverview());
701
748
  if (path === "/api/events") {
702
749
  const after = Number(url.searchParams.get("after") ?? 0) || 0;
703
750
  const limit = Math.min(5000, Number(url.searchParams.get("limit") ?? 1000) || 1000);
@@ -743,8 +790,11 @@ export function createApp(deps: AppDeps) {
743
790
 
744
791
  /** `ip` is the client address (Bun: server.requestIP(req)?.address); used for the join limit. */
745
792
  async function fetch(req: Request, ip?: string): Promise<Response> {
793
+ const t0 = performance.now();
746
794
  const url = new URL(req.url);
747
- const route = `${req.method} ${url.pathname.startsWith("/api/submission/") ? "/api/submission/:id" : url.pathname}`;
795
+ // Bounded keys: arbitrary paths must not grow the metrics maps.
796
+ const path = url.pathname.startsWith("/api/submission/") ? "/api/submission/:id" : url.pathname;
797
+ const route = KNOWN_ROUTES.has(path) ? `${req.method} ${path}` : "other";
748
798
  requests[route] = (requests[route] ?? 0) + 1;
749
799
  let res: Response;
750
800
  try {
@@ -756,6 +806,11 @@ export function createApp(deps: AppDeps) {
756
806
  res = fail(500, "internal error", (err as Error).message);
757
807
  }
758
808
  }
809
+ if (!heldRequests.has(req.signal) && !url.pathname.startsWith("/api/stream")) {
810
+ let h = latency.get(route);
811
+ if (!h) latency.set(route, (h = new Latency()));
812
+ h.record(performance.now() - t0);
813
+ }
759
814
  const cls = `${Math.floor(res.status / 100)}xx`;
760
815
  statuses[cls] = (statuses[cls] ?? 0) + 1;
761
816
  return res;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Read-only git over HTTP for the project repository, so volunteers can
3
+ * git clone <server>/repo.git && git pull
4
+ * and work on the real files (check script, tests, code) before submitting.
5
+ *
6
+ * Wraps `git http-backend` (smart HTTP, CGI). Only fetch is served: git-upload-pack.
7
+ * Pushes (git-receive-pack) are refused — accepted work reaches the branch only through
8
+ * the check queue. `.minga/` is git-ignored, so server state never leaves the machine.
9
+ */
10
+ const PREFIX = "/repo.git";
11
+
12
+ export function isGitRequest(pathname: string): boolean {
13
+ return pathname === PREFIX || pathname.startsWith(`${PREFIX}/`);
14
+ }
15
+
16
+ const forbidden = (msg: string) => new Response(`${msg}\n`, { status: 403, headers: { "content-type": "text/plain" } });
17
+
18
+ export async function serveGit(req: Request, repoDir: string): Promise<Response> {
19
+ const url = new URL(req.url);
20
+ const rest = url.pathname.slice(PREFIX.length) || "/";
21
+ const service = url.searchParams.get("service");
22
+ if (service === "git-receive-pack" || rest.endsWith("/git-receive-pack")) {
23
+ return forbidden("this repository is read-only: submit work with `minga submit`");
24
+ }
25
+ const allowed = (rest === "/info/refs" && service === "git-upload-pack") || (rest === "/git-upload-pack" && req.method === "POST");
26
+ if (!allowed) return forbidden("only smart-HTTP fetch is served (git clone / git fetch)");
27
+
28
+ const body = req.method === "POST" ? new Uint8Array(await req.arrayBuffer()) : undefined;
29
+ const proc = Bun.spawn(["git", "http-backend"], {
30
+ cwd: repoDir,
31
+ stdin: body ?? "ignore",
32
+ stdout: "pipe",
33
+ stderr: "pipe",
34
+ env: {
35
+ PATH: process.env.PATH ?? process.env.Path ?? "",
36
+ ...(process.env.SYSTEMROOT ? { SYSTEMROOT: process.env.SYSTEMROOT } : {}),
37
+ GIT_PROJECT_ROOT: repoDir,
38
+ GIT_HTTP_EXPORT_ALL: "1",
39
+ PATH_INFO: `/.git${rest}`,
40
+ QUERY_STRING: url.search.slice(1),
41
+ REQUEST_METHOD: req.method,
42
+ CONTENT_TYPE: req.headers.get("content-type") ?? "",
43
+ CONTENT_LENGTH: body ? String(body.byteLength) : "",
44
+ HTTP_CONTENT_ENCODING: req.headers.get("content-encoding") ?? "",
45
+ GIT_PROTOCOL: req.headers.get("git-protocol") ?? "",
46
+ REMOTE_ADDR: "127.0.0.1",
47
+ },
48
+ });
49
+ const out = new Uint8Array(await new Response(proc.stdout).arrayBuffer());
50
+ await proc.exited;
51
+
52
+ // CGI output: headers, a blank line, then the body.
53
+ let split = -1;
54
+ for (let i = 0; i + 3 < out.length; i++) {
55
+ if (out[i] === 13 && out[i + 1] === 10 && out[i + 2] === 13 && out[i + 3] === 10) { split = i; break; }
56
+ }
57
+ let sep = 4;
58
+ if (split < 0) {
59
+ for (let i = 0; i + 1 < out.length; i++) if (out[i] === 10 && out[i + 1] === 10) { split = i; sep = 2; break; }
60
+ }
61
+ if (split < 0) {
62
+ const err = await new Response(proc.stderr).text();
63
+ return new Response(`git http-backend failed: ${err.slice(0, 500)}\n`, { status: 500 });
64
+ }
65
+ const headers = new Headers();
66
+ let status = 200;
67
+ for (const line of new TextDecoder().decode(out.subarray(0, split)).split(/\r?\n/)) {
68
+ const i = line.indexOf(":");
69
+ if (i < 0) continue;
70
+ const name = line.slice(0, i).trim();
71
+ const value = line.slice(i + 1).trim();
72
+ if (name.toLowerCase() === "status") status = Number.parseInt(value, 10) || 200;
73
+ else headers.append(name, value);
74
+ }
75
+ return new Response(out.subarray(split + sep), { status, headers });
76
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Fixed-memory latency histogram: log-spaced buckets from 0.05 ms to ~2 min (about 12% wide),
3
+ * so p50/p99 stay accurate to a bucket without keeping samples.
4
+ */
5
+ const MIN = 0.05;
6
+ const GROWTH = 1.12;
7
+ const BUCKETS = 140;
8
+ const LOG_GROWTH = Math.log(GROWTH);
9
+
10
+ export class Latency {
11
+ private counts = new Uint32Array(BUCKETS);
12
+ count = 0;
13
+ max = 0;
14
+
15
+ record(ms: number): void {
16
+ const i = ms <= MIN ? 0 : Math.min(BUCKETS - 1, Math.floor(Math.log(ms / MIN) / LOG_GROWTH) + 1);
17
+ this.counts[i]! += 1;
18
+ this.count += 1;
19
+ if (ms > this.max) this.max = ms;
20
+ }
21
+
22
+ /** Upper edge of the bucket holding quantile q (0..1). */
23
+ quantile(q: number): number {
24
+ if (!this.count) return 0;
25
+ const target = Math.ceil(q * this.count);
26
+ let seen = 0;
27
+ for (let i = 0; i < BUCKETS; i++) {
28
+ seen += this.counts[i]!;
29
+ if (seen >= target) return Math.min(this.max, i === 0 ? MIN : MIN * GROWTH ** i);
30
+ }
31
+ return this.max;
32
+ }
33
+
34
+ summary(): { count: number; p50: number; p99: number; max: number } {
35
+ const r = (n: number) => Math.round(n * 100) / 100;
36
+ return { count: this.count, p50: r(this.quantile(0.5)), p99: r(this.quantile(0.99)), max: r(this.max) };
37
+ }
38
+ }