The best way to control Claude Code, Codex and more from any computer or phone

main
ts 545 lines 20.8 KB
Raw
1 /**
2 * Shared schemas of the git-service REST contract (DESIGN.md §5):
3 * primitives, the tagged-error taxonomy, and the domain shapes. The
4 * per-group endpoint declarations live in the sibling modules (`Repos.ts`,
5 * `Refs.ts`, `Objects.ts`, `Pulls.ts`); the assembled `GitApi` lives in
6 * `../Api.ts`.
7 *
8 * The groups carry no middleware and no auth errors of their own: the
9 * `HttpApi` you mount them in decides who may call them, and application handlers
10 * decide which refs may move.
11 */
12 import * as Schema from "effect/Schema";
13 // Pulls in the `httpApiStatus` annotation augmentation used by the error
14 // classes below.
15 import "effect/http-api/HttpApiSchema";
16
17 // ─────────────────────────────────────────────────────────────────────────────
18 // Primitives
19 // ─────────────────────────────────────────────────────────────────────────────
20
21 /**
22 * A 40-hex SHA-1 object id, branded so oids never mix with plain strings.
23 * Widening to SHA-256 later is mechanical because every consumer goes
24 * through this schema (DESIGN.md §1 "Hashing").
25 */
26 export const Oid = Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/)).pipe(
27 Schema.brand("Oid"),
28 );
29
30 /** The decoded (branded) type of {@link Oid}. */
31 export type Oid = typeof Oid.Type;
32
33 /**
34 * A repository name: 1–100 chars, alphanumeric with `._-` separators,
35 * must start and end alphanumeric. Case-insensitive match, stored as given.
36 */
37 export const RepoName = Schema.String.check(
38 Schema.isPattern(/^[a-z0-9](?:[a-z0-9._-]{0,98}[a-z0-9])?$/i),
39 );
40
41 /**
42 * An owner (namespace) name. Same grammar as {@link RepoName}. The literal
43 * owner `api` is reserved (rejected by the Registry at creation) so the
44 * `/api/v1` prefix can never collide with a repo URL.
45 */
46 export const OwnerName = RepoName;
47
48 /**
49 * A full ref name (`refs/heads/main`, `refs/tags/v1.0`). Rejects the
50 * whitespace / `~^:?*[\` characters git itself forbids. HEAD is virtual
51 * (symref to the default branch) and is never a valid `RefName` here.
52 */
53 export const RefName = Schema.String.check(Schema.isPattern(/^refs\/[^\s~^:?*[\\]+$/));
54
55 /**
56 * Lifecycle status of a repo. Async operations (import/fork/delete) flip
57 * this field; clients poll `GET /repos/:owner/:repo` until `ready` (or 404
58 * once a `deleting` repo's purge completes). There is no jobs API.
59 */
60 export const RepoStatus = Schema.Literals(["ready", "importing", "forking", "deleting"]);
61
62 /** The decoded type of {@link RepoStatus}. */
63 export type RepoStatus = typeof RepoStatus.Type;
64
65 // ─────────────────────────────────────────────────────────────────────────────
66 // Error taxonomy (tagged, status-annotated)
67 // ─────────────────────────────────────────────────────────────────────────────
68
69 /** 403 — the repo is flagged `readOnly`; writes are rejected. */
70 export class ReadOnlyRepo extends Schema.TaggedError<ReadOnlyRepo>()(
71 "ReadOnlyRepo",
72 {},
73 { httpApiStatus: 403 },
74 ) {}
75
76 /** 403 — application policy refused a proposed ref update. */
77 export class PushDenied extends Schema.TaggedError<PushDenied>()(
78 "PushDenied",
79 { ref: Schema.String, reason: Schema.String },
80 { httpApiStatus: 403 },
81 ) {}
82
83 /** 404 — no repo at `owner/repo` (or it finished deleting). */
84 export class RepoNotFound extends Schema.TaggedError<RepoNotFound>()(
85 "RepoNotFound",
86 { owner: Schema.String, repo: Schema.String },
87 { httpApiStatus: 404 },
88 ) {}
89
90 /** 409 — a repo already exists at `owner/repo`. */
91 export class RepoAlreadyExists extends Schema.TaggedError<RepoAlreadyExists>()(
92 "RepoAlreadyExists",
93 { owner: Schema.String, repo: Schema.String },
94 { httpApiStatus: 409 },
95 ) {}
96
97 /**
98 * 409 — the repo exists but is not `ready` (importing / forking /
99 * deleting); retry after polling `GET /repos/:owner/:repo`.
100 */
101 export class RepoNotReady extends Schema.TaggedError<RepoNotReady>()(
102 "RepoNotReady",
103 { status: RepoStatus },
104 { httpApiStatus: 409 },
105 ) {}
106
107 /** 404 — the named ref does not exist. */
108 export class RefNotFound extends Schema.TaggedError<RefNotFound>()(
109 "RefNotFound",
110 { ref: Schema.String },
111 { httpApiStatus: 404 },
112 ) {}
113
114 /**
115 * 409 — compare-and-swap failure on a ref write: `expectedOid` did not
116 * match the ref's current value (`currentOid`, `null` when the ref does
117 * not exist).
118 */
119 export class RefConflict extends Schema.TaggedError<RefConflict>()(
120 "RefConflict",
121 { ref: Schema.String, currentOid: Schema.NullOr(Oid) },
122 { httpApiStatus: 409 },
123 ) {}
124
125 /** 404 — no object with the given oid in this repo. */
126 export class ObjectNotFound extends Schema.TaggedError<ObjectNotFound>()(
127 "ObjectNotFound",
128 { oid: Schema.String },
129 { httpApiStatus: 404 },
130 ) {}
131
132 /** 422 — the object exists but has a different type than the endpoint expects. */
133 export class WrongObjectType extends Schema.TaggedError<WrongObjectType>()(
134 "WrongObjectType",
135 { oid: Schema.String, expected: Schema.String, actual: Schema.String },
136 { httpApiStatus: 422 },
137 ) {}
138
139 /**
140 * 422 — the blob is too large for the base64 JSON endpoint (> 1 MiB);
141 * use the raw streaming route `GET .../blobs/:oid/raw` instead.
142 */
143 export class ObjectTooLarge extends Schema.TaggedError<ObjectTooLarge>()(
144 "ObjectTooLarge",
145 { oid: Schema.String, size: Schema.Number },
146 { httpApiStatus: 422 },
147 ) {}
148
149 /**
150 * 422 — the two commits share no common ancestor within the walk bound
151 * (disjoint histories, or divergence beyond the server's 10k-commit cap;
152 * shallow imports can also surface this across the shallow boundary).
153 */
154 export class NoMergeBase extends Schema.TaggedError<NoMergeBase>()(
155 "NoMergeBase",
156 { base: Oid, head: Oid },
157 { httpApiStatus: 422 },
158 ) {}
159
160 /** 502 — the async import job failed against the source remote. */
161 export class ImportFailed extends Schema.TaggedError<ImportFailed>()(
162 "ImportFailed",
163 { reason: Schema.String },
164 { httpApiStatus: 502 },
165 ) {}
166
167 /** 400 — semantically invalid request (e.g. reserved owner name). */
168 export class ValidationError extends Schema.TaggedError<ValidationError>()(
169 "ValidationError",
170 { message: Schema.String },
171 { httpApiStatus: 400 },
172 ) {}
173
174 /** 404 — no pull request with this number. */
175 export class PullNotFound extends Schema.TaggedError<PullNotFound>()(
176 "PullNotFound",
177 { number: Schema.Number },
178 { httpApiStatus: 404 },
179 ) {}
180
181 /** 422 — the PR's base or head branch does not exist (deleted after open). */
182 export class BranchMissing extends Schema.TaggedError<BranchMissing>()(
183 "BranchMissing",
184 { ref: Schema.String },
185 { httpApiStatus: 422 },
186 ) {}
187
188 /** 409 — an open PR for this base/head pair already exists. */
189 export class PullExists extends Schema.TaggedError<PullExists>()(
190 "PullExists",
191 { number: Schema.Number },
192 { httpApiStatus: 409 },
193 ) {}
194
195 /**
196 * 409 — the operation is invalid in the PR's current state (e.g. merge a
197 * merged PR, reopen a merged PR).
198 */
199 export class PullStateConflict extends Schema.TaggedError<PullStateConflict>()(
200 "PullStateConflict",
201 {
202 number: Schema.Number,
203 state: Schema.Literals(["open", "closed", "merged"]),
204 },
205 { httpApiStatus: 409 },
206 ) {}
207
208 /** 422 — head is already reachable from base; there is nothing to merge. */
209 export class NothingToMerge extends Schema.TaggedError<NothingToMerge>()(
210 "NothingToMerge",
211 { number: Schema.Number },
212 { httpApiStatus: 422 },
213 ) {}
214
215 /**
216 * 409 — the three-way merge is not trivial: these paths changed on both
217 * sides relative to the merge base.
218 */
219 export class MergeConflict extends Schema.TaggedError<MergeConflict>()(
220 "MergeConflict",
221 {
222 number: Schema.Number,
223 /** Conflicting paths, capped at 20 (the full set may be larger). */
224 paths: Schema.Array(Schema.String),
225 },
226 { httpApiStatus: 409 },
227 ) {}
228
229 // ─────────────────────────────────────────────────────────────────────────────
230 // Auth middleware
231 // ─────────────────────────────────────────────────────────────────────────────
232
233 // ─────────────────────────────────────────────────────────────────────────────
234 // Domain shapes
235 // ─────────────────────────────────────────────────────────────────────────────
236
237 /**
238 * A repository resource as returned by the management plane.
239 */
240 /**
241 * Where a repo's objects currently live (DESIGN.md §12.1). `loose` rows
242 * hold their bytes in DO SQLite; `packed` objects have been compacted into
243 * immutable R2 packs; `r2` objects are oversize singletons in R2.
244 */
245 export class ObjectStats extends Schema.Class<ObjectStats>("ObjectStats")({
246 /** Objects whose bytes are still in DO SQLite rows. */
247 loose: Schema.Number,
248 /** Commits, trees and tags kept in SQLite rows (never packed). */
249 resident: Schema.Number,
250 /** Objects compacted into R2 packs. */
251 packed: Schema.Number,
252 /** Oversize objects stored as standalone R2 keys. */
253 r2: Schema.Number,
254 /** Total compressed bytes across all locations. */
255 bytes: Schema.Number,
256 }) {}
257
258 /**
259 * Server-side timing of the most recent push (DESIGN.md §19 phase 0).
260 *
261 * Wall-clock `git push` time includes client-side packing and the upload,
262 * so it bounds server cost rather than measuring it. These are measured
263 * inside the Durable Object, around the work itself.
264 */
265 export class PushStats extends Schema.Class<PushStats>("PushStats")({
266 /** Objects in the pushed pack. */
267 objects: Schema.Number,
268 /** Pack bytes received. */
269 bytes: Schema.Number,
270 /** Parsing + staging the pack (inflate, sha1, SQL). */
271 ingestMs: Schema.Number,
272 /**
273 * The SQL staging portion of `ingestMs`. `ingestMs - stageMs` is CPU:
274 * inflate, sha1, delta resolution, commit/tree parsing. The split decides
275 * whether sharding storage or hoisting parsing is the real win
276 * (DESIGN.md §19).
277 */
278 stageMs: Schema.Number,
279 /** The connectivity check. */
280 connectivityMs: Schema.Number,
281 /** The ref CAS transaction. */
282 finalizeMs: Schema.Number,
283 /** Everything the DO did for this push. */
284 totalMs: Schema.Number,
285 /**
286 * Ingest split by phase (ms): inflate, hash, delta, deflate, copy, sink.
287 * Meaningful as CPU only where the clock runs during synchronous work
288 * (local workerd); production workerd freezes `performance.now()` between
289 * awaits, so there only phases that yield to the event loop accumulate —
290 * which is itself diagnostic (an async inflate path shows up, a sync one
291 * reads 0).
292 */
293 phases: Schema.optional(Schema.Record(Schema.String, Schema.Number)),
294 }) {}
295
296 export class Repo extends Schema.Class<Repo>("Repo")({
297 /** Owner (namespace) segment of the repo's URL. */
298 owner: OwnerName,
299 /** Repo name segment of the repo's URL. */
300 name: RepoName,
301 /**
302 * The stable ULID identity of the repo. Renames never move data because
303 * the Repo DO id derives from `repoId`, not `owner/name`.
304 */
305 repoId: Schema.String,
306 /** Short branch name (e.g. `main`) that HEAD symrefs to. */
307 defaultBranch: Schema.String,
308 /** Optional human description. */
309 description: Schema.NullOr(Schema.String),
310 /** When `true`, receive-pack and REST ref writes are rejected. */
311 readOnly: Schema.Boolean,
312 /**
313 * Public repos are readable (REST reads and `git clone`/`fetch`)
314 * without any token; writes always require one.
315 */
316 public: Schema.Boolean,
317 /** Parent `repoId` when this repo is a fork, else `null`. */
318 forkOf: Schema.NullOr(Schema.String),
319 /** Lifecycle status; poll this for async fork/import/delete progress. */
320 status: RepoStatus,
321 /** Creation time, epoch milliseconds. */
322 createdAt: Schema.Number,
323 /** Object storage breakdown (DESIGN.md §12.1). */
324 objects: ObjectStats,
325 /** Server-side timing of the last push, if any (DESIGN.md §19). */
326 lastPush: Schema.NullOr(PushStats),
327 }) {}
328
329 /**
330 * A ref (branch or tag). `peeled` carries the target commit for annotated
331 * tags (the advertisement's `^{}` line).
332 */
333 export class Ref extends Schema.Class<Ref>("Ref")({
334 /** Full ref name, e.g. `refs/heads/main`. */
335 name: RefName,
336 /** The object the ref points at. */
337 oid: Oid,
338 /** For annotated tags: the peeled (commit) oid. */
339 peeled: Schema.optional(Oid),
340 }) {}
341
342 /** An author/committer/tagger signature line. */
343 const Signature = Schema.Struct({
344 name: Schema.String,
345 email: Schema.String,
346 /** Unix timestamp (seconds). */
347 date: Schema.Number,
348 /** Timezone offset as written, e.g. `+0200`. */
349 tz: Schema.String,
350 });
351
352 /** Parsed commit metadata for the REST read surface. */
353 export class CommitInfo extends Schema.Class<CommitInfo>("CommitInfo")({
354 oid: Oid,
355 /** Root tree of the commit. */
356 tree: Oid,
357 /** Parent commit oids in order. */
358 parents: Schema.Array(Oid),
359 author: Signature,
360 committer: Signature,
361 /** Full commit message (verbatim, including trailing newline). */
362 message: Schema.String,
363 }) {}
364
365 /** A single tree entry. `commit` type = gitlink (submodule). */
366 export class TreeEntry extends Schema.Class<TreeEntry>("TreeEntry")({
367 /** Octal mode string as stored, e.g. `100644`, `40000`, `120000`. */
368 mode: Schema.String,
369 /** Entry name (single path segment). */
370 name: Schema.String,
371 oid: Oid,
372 /** Entry kind derived from mode. */
373 type: Schema.Literals(["blob", "tree", "commit"]),
374 }) {}
375
376 /**
377 * File-level change status. v1 has no rename detection (see the DESIGN note
378 * on the `diff` endpoint in `Objects.ts`); a v1.1 exact-oid pass would add
379 * `"renamed"` + an `oldPath`.
380 */
381 export const FileStatus = Schema.Literals(["added", "removed", "modified"]);
382
383 /** The decoded type of {@link FileStatus}. */
384 export type FileStatus = typeof FileStatus.Type;
385
386 /**
387 * One changed file in a commit diff or comparison. Content is NOT included —
388 * clients fetch old/new blobs by oid (`blobs/:oid`, `blobs/:oid/raw`) and
389 * diff locally. `oldSize`/`newSize` let the client gate binary/oversize
390 * files without a round trip. Gitlinks (mode 160000) appear as entries whose
391 * oids are commit oids; clients render "Subproject commit ..." and must not
392 * fetch them as blobs.
393 */
394 export class DiffEntry extends Schema.Class<DiffEntry>("DiffEntry")({
395 /** Full slash-separated path from the repo root. */
396 path: Schema.String,
397 status: FileStatus,
398 /** Blob oid on the old side (absent for `added`). */
399 oldOid: Schema.optional(Oid),
400 /** Blob oid on the new side (absent for `removed`). */
401 newOid: Schema.optional(Oid),
402 /** Octal mode on the old side, e.g. `100644` (absent for `added`). */
403 oldMode: Schema.optional(Schema.String),
404 /** Octal mode on the new side (absent for `removed`). */
405 newMode: Schema.optional(Schema.String),
406 /** Uncompressed byte size of the old blob (absent for `added`/gitlinks). */
407 oldSize: Schema.optional(Schema.Number),
408 /** Uncompressed byte size of the new blob (absent for `removed`/gitlinks). */
409 newSize: Schema.optional(Schema.Number),
410 }) {}
411
412 /** The changed-file list of one commit vs its first parent. */
413 export class CommitDiff extends Schema.Class<CommitDiff>("CommitDiff")({
414 oid: Oid,
415 /** The first parent the diff was computed against; `null` for a root
416 * commit (diffed against the empty tree — every file is `added`). */
417 parent: Schema.NullOr(Oid),
418 files: Schema.Array(DiffEntry),
419 /** `true` when the file list was cut at the server cap (1000 files). */
420 truncated: Schema.Boolean,
421 }) {}
422
423 /** GitHub-style three-dot comparison of two commits. */
424 export class Comparison extends Schema.Class<Comparison>("Comparison")({
425 /** Resolved base commit oid (tags peeled). */
426 base: Oid,
427 /** Resolved head commit oid (tags peeled). */
428 head: Oid,
429 /** Best common ancestor (first both-reachable commit by generation). */
430 mergeBase: Oid,
431 /** Commits reachable from head but not base (`git rev-list --count base..head`). */
432 aheadBy: Schema.Number,
433 /** Commits reachable from base but not head. */
434 behindBy: Schema.Number,
435 /** head-side commits, committer-time descending, capped at 250. */
436 commits: Schema.Array(CommitInfo),
437 commitsTruncated: Schema.Boolean,
438 /** File diff of mergeBase..head (three-dot, like GitHub compare/PR). */
439 files: Schema.Array(DiffEntry),
440 filesTruncated: Schema.Boolean,
441 }) {}
442
443 /** Lifecycle state of a pull request. `merged` is terminal. */
444 export const PullState = Schema.Literals(["open", "closed", "merged"]);
445
446 /** The decoded type of {@link PullState}. */
447 export type PullState = typeof PullState.Type;
448
449 /**
450 * A pull request. PRs track **live** branches by ref name — the row stores
451 * intent + lifecycle, never a diff snapshot. Diff and mergeability are
452 * recomputed from current ref tips on every read (see {@link PullDetail}).
453 */
454 export class Pull extends Schema.Class<Pull>("Pull")({
455 /** Per-repo monotonic PR number (1-based, never reused). */
456 number: Schema.Int,
457 title: Schema.String,
458 body: Schema.NullOr(Schema.String),
459 /** Full base ref name, e.g. `refs/heads/main`. */
460 baseRef: RefName,
461 /** Full head ref name, e.g. `refs/heads/feature`. */
462 headRef: RefName,
463 state: PullState,
464 /** Creation time, epoch milliseconds. */
465 createdAt: Schema.Number,
466 /** Last update (title/body/state) time, epoch milliseconds. */
467 updatedAt: Schema.Number,
468 /** Merge time (epoch milliseconds); `null` unless `state` is `merged`. */
469 mergedAt: Schema.NullOr(Schema.Number),
470 /** FF: the head tip; the merge commit otherwise. Set iff state=merged. */
471 mergeCommit: Schema.NullOr(Oid),
472 }) {}
473
474 /**
475 * PR detail = the row + live computed compare fields. Live fields are
476 * `null` when uncomputable: a missing base/head branch, a saturated
477 * ancestor walk, or a merged PR (its record is `mergeCommit`).
478 */
479 export class PullDetail extends Pull.extend<PullDetail>("PullDetail")({
480 /** Current tip of `baseRef`; `null` if the branch is gone. */
481 baseOid: Schema.NullOr(Oid),
482 /** Current tip of `headRef`; `null` if the branch is gone. */
483 headOid: Schema.NullOr(Oid),
484 mergeBase: Schema.NullOr(Oid),
485 /** Commits on head not on base (`null` when the walk saturates). */
486 aheadBy: Schema.NullOr(Schema.Int),
487 /** Commits on base not on head. */
488 behindBy: Schema.NullOr(Schema.Int),
489 /**
490 * `true` = FF-able or trivially merge-able; `false` = conflicting paths
491 * or up-to-date; `null` = uncomputable.
492 */
493 mergeable: Schema.NullOr(Schema.Boolean),
494 /** Why: `"ff" | "merge-commit" | "conflict" | "up-to-date" | "unknown"`. */
495 mergeableReason: Schema.NullOr(Schema.String),
496 }) {}
497
498 /** Response of a successful PR merge. */
499 export class MergeResult extends Schema.Class<MergeResult>("MergeResult")({
500 /** How the merge landed. */
501 method: Schema.Literals(["ff", "merge-commit"]),
502 /** The oid the base ref now points at. */
503 oid: Oid,
504 /** The PR row after the merge (`state: "merged"`). */
505 pull: Pull,
506 }) {}
507
508 /**
509 * Response of repo create/fork/import: the repo plus a ready-to-use HTTPS
510 * remote URL and a bootstrap `write` token, killing the create-then-mint
511 * round trip.
512 */
513 export class RepoCreated extends Schema.Class<RepoCreated>("RepoCreated")({
514 repo: Repo,
515 /** HTTPS clone URL for the new repo. */
516 remote: Schema.String,
517 }) {}
518
519 /**
520 * Cursor-paginated wrapper used by list endpoints.
521 *
522 * @example
523 * ```typescript
524 * const page = Paginated(Repo); // { items: Repo[], nextCursor, hasMore }
525 * ```
526 */
527 export const Paginated = <A extends Schema.Top>(items: A) =>
528 Schema.Struct({
529 items: Schema.Array(items),
530 nextCursor: Schema.NullOr(Schema.String),
531 hasMore: Schema.Boolean,
532 });
533 // ─────────────────────────────────────────────────────────────────────────────
534 // Shared path-parameter structs
535 // ─────────────────────────────────────────────────────────────────────────────
536
537 /** `(owner, repo)` path segments shared by repo-scoped endpoints. */
538 export const RepoPath = Schema.Struct({ owner: OwnerName, repo: RepoName });
539
540 /** `(owner, repo, oid)` path segments for object read endpoints. */
541 export const RepoOidPath = Schema.Struct({
542 owner: OwnerName,
543 repo: RepoName,
544 oid: Oid,
545 });