Repository navigation
feat: add self-host-only SAM-hosted git - #2907
Conversation
…L22c) Brings the box runtime from the integration branch in plaintext mode: celld, Caddy, frps, the bundled object store, the mail collector and sam-mx. Without the egress fence, key agent, docker proxy and metadata proxy (and the files only they read: celld.env, egress-fence.nft, key-agent/agent.env, celld/start.sh), and without the key-rotation Caddy fragment. F11: the two local images (caddy, sam-mx) are never pulled (pull_policy: never) and are built only by an explicit `docker compose build` or when missing. The Caddy Dockerfile pins both images by digest and both modules by version, fetches modules only from proxy.golang.org with sum.golang.org verification and GOTOOLCHAIN=local, and fails unless the binary carries exactly those versions. Its build context is empty (.dockerignore), so Caddyfile edits never touch the build. F21: the gateway-route variant matcher reads the raw request target and accepts any encoding depth of every character of "api" and "self-host", backslash separators and absolute-form targets (L1), matches only an "api" segment followed by a "self-host" segment instead of any path containing "self-host" (L6), refuses dot-segment targets naming self-host in any encoding, and caddy-ratelimit limits frp connections per client address (L7, SAM_FRP_LOGIN_RATE_LIMIT_*). start.sh refuses any box port inside the lease range, as compose actually runs it (L5). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Compose takes a variable from the shell before the .env, so `CELLD_INTERNAL_PORT=20001 docker compose up` put celld's operator API inside the lease range the deploy had checked against the .env only. The deploy (and upgrade's box loader) now apply shell overrides of every BOX_RESERVED_PORTS name before the range check and report each one. The deploy harness strips those names from the test runner's environment so the suite stays hermetic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hanged (F11) `selfhost:upgrade` ran `docker compose up -d --build` whenever any compose input changed, rebuilding (with network access) on every such upgrade. It now compares each locally built service's build section in docker-compose.yml at both refs and the files in its build context (a context whose .dockerignore is `*` counts only its Dockerfile), builds only the changed services the box runs with an explicit `docker compose build <service>`, and restarts with a plain `up -d`. The printed rollback rebuilds the same way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The integration branch's gcp-bootstrap.sh, trimmed to the node trust a plaintext box needs: the install-dedicated workload identity pool, the issuer-scoped OIDC provider, the node service account and its bindings, and the credential JSON to paste in Admin -> Credentials. Without the Cloud KMS key for sealed secrets (--kms, --kms-only, key versions) and without --teardown and its created-resources record, which only teardown read. Adds the selfhost:gcp-bootstrap and selfhost:live-test scripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replaces the integration branch's ~1,400-line README with a short operator note, marked as an experimental test-box setup and not a supported deployment: prerequisites, the fresh-install sequence, upgrade (no automatic backup), image builds, R2_S3_REGION for s3:// stores, the lease port range and gateway secret, the frp rate limit, email, and what is not included yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…-host paths (D9) Brings the live suite from the integration branch: caddy-fragments, access-log-keep-warm, mail-collector, frpc-tls, celld-redirect and shared-flight-cancel, with the harness and celld lab. Caddy runs from the image deploy/selfhost/caddy/Dockerfile builds, through start.sh, as compose runs it. New cases: encoded letters at any depth, backslash separators, dot segments and absolute-form targets never reach the gateway route (L1); public paths naming self-host still reach celld (L6); frp connections over the per-address limit get 429 (L7); start.sh refuses a box port inside the lease range and bad rate-limit values (L5). shared-flight-cancel loses its key agent case (sealed secrets are held) and talks to a plain slow upstream instead. CI: a Self-host Live (Docker) job runs `pnpm selfhost:live-test` only when deploy/selfhost, scripts/selfhost or apps/api/src/selfhost change, not for packages/cloud-init and not nightly. Validate Deploy Scripts builds the API's workspace dependencies first (the GCP bootstrap test parses with the real credential codec). Dependabot watches the Caddy Dockerfile's digests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… commands The upgrade from PR 2 records an unfinished upgrade in .state/upgrade-pending.json and retries from it, and runs and prints every compose command with the box's .env and selected compose files; the explicit image rebuild (F11) does the same. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ESLint no-useless-escape: \' inside a template literal is just '. No behaviour change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…redaction guards run with route changes deploy-scripts now selects deploy/selfhost/**, so compose, Caddy and gcp-bootstrap changes run the static tests that read them. The credential-route scan moves out of scripts/selfhost: the API half into an API unit test, the App.tsx half into a web unit test, so each runs with the suite CI already selects for those routes (App.tsx in the API unit filter would have started the API suite on every web routing change). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only two things needed built packages: gcp-bootstrap.test.ts parsed the printed credential with parseGcpCredential (imports shared and worker-core dist), and the scripts/selfhost type check covered live/, whose shared-flight test imports worker-core. The parser contract test moves to the API unit suite, which builds and also runs when the parser changes; live/ gets its own tsconfig, type-checked in the Self-host Live job after its build. pnpm selfhost:test now passes with every @simple-agent-manager import aliased to a missing module. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… roles to the guided setup - An existing --pool-id is reused only when every provider in it (deleted ones too) is PROVIDER_ID trusting this install's issuer: the service account binding is pool-wide. - The binding comment no longer claims the pool is this install only: it admits any token the install signs for the provider's audience, and SAM does not yet stop a user credential from naming the pool (SAM task 01M7SB8FRZ08M5NEX9WGM74X61). README and the script say to use a project dedicated to SAM's nodes. - NODE_APIS / NODE_ROLES document why cloudresourcemanager, aiplatform and roles/aiplatform.user are left out; a test fails when the script drifts from GCP_REQUIRED_APIS or gcp-setup.ts SA_PROJECT_ROLES. - A trailing flag with no value is a clear error; --help prints the whole header. - README: the access log redacts path credentials on the listed routes only, and an .env build-arg change needs docker compose build caddy (upgrade never sees it). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…y root Both listen only on loopback ports above 1023. celld writes only CELLD_WATCH (its volume) and gets a tmpfs /tmp; checked on the pinned image with cap_drop ALL, no-new-privileges and a read-only root: a Worker and a SQLite Durable Object serve and keep their state across a restart, and /tmp stays empty. frps logs to the console and starts read-only. A static test pins the settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…4 characters Its root credential reads every Worker secret in the fleet bucket. The entrypoint check moves from 8 to 24 characters (.env.example and README say so); a test runs the compose entrypoint under /bin/sh with the image entrypoint stubbed. The deploy test fixture's fleet secret is lengthened to match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ing starts S4: - SAM_MX_LISTEN (sam-mx's public SMTP listener, default :25; the port after the last ':') joins the reserved box ports: the deploy, upgrade and Caddy's start.sh refuse it inside the lease range. compose passes it to Caddy. - loadBoxEnv (box-settings.ts) reads the .env, applies shell port overrides and checks the range, so selfhost:deploy refuses before writing platform keys and selfhost:upgrade before it fetches, checks out or runs docker compose. - start.sh checks each lease-range bound is a plain number: a malformed one such as 1:2 made the -ge test error, which if read as false, silently skipping the check. - celld, frps and the mail collector have no capabilities, so their ports must be 1024 or above. A6: deploy.ts and upgrade-lib.ts share loadBoxEnv instead of each parsing the .env and applying overrides; SELFHOST_DIR lives in deploy-steps.ts and COMPOSE_PATH derives from it. The live harness's caddyBoxEnv takes its names from BOX_RESERVED_PORTS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…node sockets A site-level request_header -X-SAM-* sorts before every handle, so the catch-all route to celld drops them too, and node-ws.caddy's forward_auth still copies the Worker's own X-SAM-* answer afterwards (the live forward_auth tests pass unchanged). A live test sends forged X-SAM-* headers to api, app and a preview host and checks celld sees none; it fails with the directive removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…or the live suite A3: caddy-fragments, access-log-keep-warm and mail-collector each built the same docker run (host network, cap-drop ALL + NET_BIND_SERVICE, the caddy dir, start.sh), logs reader, TLS wait, teardown and https client. harness.ts now has startCaddy, runCaddyToExit and httpsGet; DOCKER and hasDocker move there from celld-lab.ts and every docker call uses DOCKER; every Docker test uses skipWithoutDocker (skipped without Docker locally, never in CI). celld-lab.ts's header names its real consumers, and celld-redirect writes its project with writeProject. S6: start() and celld deploy pass children an allowlisted environment (PATH, HOME, TMPDIR, LANG, RUST_LOG, DOCKER_*) instead of the whole host environment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…check Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fixture The PR-range Gitleaks scan flags the deploy test harness's fixed objectstore secret, lengthened in 6ffc0c8 to meet the 24-character minimum. It is a synthetic fixture; the entry pins that exact finding and expires in 30 days. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…hell, not only ports Docker Compose takes every variable its files interpolate from the invoking shell before --env-file, but the deploy and upgrade applied shell precedence only to BOX_RESERVED_PORTS. An exported CELLD_BUCKET or SAM_DOMAIN made selfhost:deploy publish with the .env value while docker compose ran celld and Caddy with the shell's. loadBoxEnv now collects the variables referenced in docker-compose.yml and every file the box's COMPOSE_FILE selects (composeFilesFor, moved to compose-env.ts so box-settings can reuse it without an import cycle), and applies a differing shell value for each, plus every box port. Each override is reported by name only. withComposePortOverrides is renamed withComposeShellOverrides; README and .env.example describe the general rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SAM_MX_LISTEN=2525 passed both the deploy's and Caddy start.sh's checks, but sam-mx hands it to
Go's net.Listen("tcp", "2525"), which fails with "missing port in address", so the inbound-mail
service restart-looped. Both validators now require a listen address with a host/port separator,
[host]:port (:2525, 0.0.0.0:2525, [::]:2525), and refuse a bare port with a clear message. The
live Caddy harness passes `:<port>` for listen addresses.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…4830, S5527) httpsGet turned TLS verification off (rejectUnauthorized: false). The live harness now reads the root of the Caddy container's internal CA (/data/caddy/pki/authorities/local/root.crt) once Caddy starts, and httpsGet trusts exactly that root with `ca` and checks the certificate against the request's host (servername, lowercased), so certificate and hostname checks stay on. Every request's Host is inside the *.SAM_DOMAIN wildcard Caddy serves, so no test needed a mismatch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nar S6505) Nothing in the job needs one: celld runs esbuild's own bin entry (resolveEsbuild), which finds the platform package without esbuild's postinstall, and the build and live tests pass after a fresh `pnpm install --frozen-lockfile --ignore-scripts`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The image now ends with USER 7101:7101. setcap gives /usr/bin/caddy cap_net_bind_service, so the unprivileged process still binds 80/443 with NET_BIND_SERVICE as the one capability compose leaves it (checked: uid 7101, CapEff 0x400, listening on :80 and :443 with --cap-drop ALL --cap-add NET_BIND_SERVICE). /data and /config belong to 7101 in the image. A box upgraded from a root Caddy has root-owned 0700 files in caddy-data and caddy-config, which uid 7101 could not read. A one-shot caddy-volumes service (root with only CHOWN and DAC_READ_SEARCH, no network, no-new-privileges) chowns both volumes to 7101 before every Caddy start; Caddy depends on it completing. DAC_READ_SEARCH is needed for the second and later runs (without it chown cannot walk 7101-owned 0700 directories). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- S131: every `case` in caddy/start.sh and gcp-bootstrap.sh has a default arm. - S7688: gcp-bootstrap.sh is a bash script, so its tests use [[ ]]. - S7776: INHERITED_ENV (live harness) and UNPRIVILEGED_LISTENERS are Sets. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… reader Caddy now runs as uid 7101 from a binary with a file capability, which makes the process non-dumpable: its /proc/1/environ is readable only by root with CAP_SYS_PTRACE, so the password-hash check reads it with `docker exec --privileged --user 0`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…install A fresh install from the README (box round R18) found: - pnpm install needs a C/C++ toolchain (better-sqlite3); - step 3 writes .state/secrets.env before .state exists; - the first minutes after adding the GCP credential look broken (IAM propagation: impersonation 403s, migration-pending, possibly an hour of 'Price unavailable'); - an API-created node defaults to a Hetzner location; - without a GitHub App or GitLab no project, so no agent session, can be created; - gcp-bootstrap's expected first IAM-binding failure printed no retry notice, and its shared-pool refusal named the wrong cause for a second provider trusting the same issuer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… BOX R18 and owed proofs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…writing Final re-verification of 77e55db: the clone/push cache race is closed (reproduced on 8bc9a3a, never on 77e55db). New findings fixed: - HIGH: a continuation line before `tree`/`object` was skipped by the header key list, yet git rejects such an object and clones fail. The first line must be exactly `tree <oid>` or `object <oid>`. - MEDIUM: a second cold clone rewriting an already stamped reachable cache left it partial while yielding; a push in that window could stamp the partial set valid. saveReachable unstamps before rewriting. - LOW: refuse `git~1`, `.git:` streams, a `.gitmodules` symlink and tree entry names over 255 bytes, which break checkout of the default branch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dc8e9e4ccd
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Scoped verification of dc8e9e4: the leading-continuation bypass is closed and nothing git accepts is refused. Two cache-concurrency MEDIUMs, one cause (validity carried forward instead of checked at the write): - Overlapping clone saves could stamp a partial table. saveReachable is single-flight: a generation counter, checked around every yield and before stamping, lets only the latest save write or stamp. - A push that read hadCache before a save unstamped could extend the partial table. commitPush re-checks reachableCacheValid() before refs move and extends only if the cache is still current. Also refuse `.gitmodules` symlinks in their NTFS short-name and stream forms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ering, TTL - Honor at most 256 ref-prefix arguments; past that answer unfiltered, as git does, so the filter cost is bounded by the cap (r4636317748). - Cancel an upstream response the repo-browse consumer abandons, so the hosted repository's upload slot is released (r4636466068). - GC drops whole packs holding nothing reachable and no delta base before inflating anything, so a rejected push's pack is reclaimed even when migrating the rest exceeds the budget (r4636595142, partial; resumable migration stays in the backlog), and keeps delta bases only while packs are kept (r4636595147). - Grow the receive command-section buffer geometrically (r4636751965). - The personal clone token honors ARTIFACTS_TOKEN_TTL_SECONDS like the workspace and browsing credentials (r4636751970). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1bbf2aeb23
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
…tored Codex r4636923076: the push byte budget covered the raw pack but not its index rows and page overhead, so a push near maxRepoBytes could commit with the repository over its cap. processReceive re-checks dbSize() after ingest (rule 69: the final write enforces capacity); a push that crossed the cap is refused and its pack dropped at once. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9d8a080299
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd22fb5727
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
…elf-host-prhe1b # Conflicts: # apps/api/tests/unit/selfhost/selfhost-only-modules.test.ts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f086c72bf
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
… caps, smoke - Deduplicate and cap upload-pack wants, haves and shallow lines while parsing, so a 16 MiB request cannot queue ~335k synchronous store lookups (r4637122054, r4637332208). - The personal clone/push token route refuses agent sign-in sessions, like other credential-minting routes (r4637122062). - The pre-parse request bound is the push limit plus the separately capped command section, so a lowered push limit still admits a packless deletion (r4637032838). - The final storage-cap check reserves the ref rows the push adds, through one helper shared with the ref-only admission check (r4637332217). - Drop the hosted-git smoke script's import path; import is unsupported in this slice (r4637032843). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: af3009196f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
Push ingest hashed objects with collision detection off, so an object carrying a SHA-1 collision-attack block could be admitted under its colliding oid. Enable the vendored SHA-1DC for untrusted pushes, as git does; the push is refused before any ref changes. Cost: ~130 MiB/s, bounded by maxInflatedBytes (about 1 s at the cap). Tests: the detector flags both SHAttered blocks and not a one-bit control; a real git push whose object SHA-1DC flags is refused with no ref, and an unflagged retry is accepted. The push test fails with detection off. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Security delta LOW 1: the collision push test covered only the buffered full-object path. A thin-pack edit of a large file now pushes a delta-resolved blob that SHA-1DC flags; the push is refused with no ref. Reverting cd on the two delta hash sites alone turns the test red. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 023a40e68f
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
A default branch that passed the character check but not git check-ref-format (foo.lock, .hidden, a..b, trailing.) initialized the hosted repository, then the seed push was refused as a funny refname and project creation returned 500. Move the push validator's ref-name rules into lib/git-ref-name.ts (no deps, safe for the Worker graph) and use the same predicate in project creation, so a branch SAM accepts can always be pushed. The conformance test creates projects with each name (400, no project row) and a nested-branch control that seeds and serves; it returns 500 with the route guard removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ee54ce19b6
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
A raw push could update refs/heads/a, delete refs/heads/a with the old value, and create refs/heads/a/b. The D/F pre-pass freed 'a' for the matching delete, so a/b was accepted; at commit the update won and the delete lost its CAS, leaving both refs stored, which breaks clones. As git refuses multiple updates of one ref in a transaction, every command for a duplicated ref is now refused, and those deletes free no name. Tests: unit (validate + commit, refs unchanged) and real receive-pack (ng for both a commands and a/b, clean clone); both go red with duplicate detection removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ee54ce1 to
f433bb9
Compare
|
H2 #2907: self-host-only SAM-hosted git. Main moved hosted git under apps/api/src/selfhost/hosted-git/ behind the artifacts seam; the branch's old-location modules are removed (services/hosted-git/* that git mapped onto services/artifacts/*, durable-objects/hosted-git-*, routes/projects/hosted-git-token.ts, app.ts) along with its separate CI job (main runs the suite in API unit shard 1). The branch's public repository importer is dropped: main refuses importUrl until a bounded importer exists (tasks/backlog/2026-11-19-bounded-selfhost-git-import.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>



Summary
A self-host box needs a repository source to create a project and run an agent. H2 adds SAM-hosted git only to the celld build. HostedGitRepo, dgit and pako must never enter the Cloudflare Worker graph or wrangler configuration; no Cloudflare migration is added and v23 is untouched.
Final head
f433bb94= BOX-proven7f086c72b(#2907 over main860718dc3, which includes L23 #2917, the celld egress fence) plus six confined commits:af300919(six Codex fixes),7b2b41f5ande04adb9c(SHA-1DC on push ingest, with tests),023a40e6(backlog note),ee54ce19(default-branch validation in project create) andf433bb94(duplicate ref commands in one push).af300919fixes the six Codex threads raised on7f086c72band touches only request parsing, the token route and cap checks.7b2b41f5turns on SHA-1 collision detection for push ingest (Codex onaf300919). Both are covered by the real-git suite and security delta reviews (below). Following the coordinator's no-repeat precedent for confined deltas, the BOX smoke is not repeated for it. Taken over on 2026-11-19 by task 01M7TY7Z3HBTSDSSV85FPRHE1B after the previous owner (01M7SR1B79) hit provider refusals. That session fixed Codex P2 r4633317762 (a failed closure walk poisoned the trusted set) and ran one adversarial review of the whole push admission path, with independent re-verification rounds until no HIGH remained (see "Push admission hardening" below). The final BOX smoke also closes the L22c criterion "a box from main runs an agent session", which Raphaël deferred to H2 ("Merge L22c now; the agent-session proof moves to H2").Approved scope narrowing: coordinator decision 2026-11-19 (SAM message f52622cf-1aff-4052-9bde-67766706e15e) supersedes import-on-fallback in the original brief: H2 ships empty seeded repositories. Import remains unavailable (400) until decompression can be bounded before an importer materializes objects. Follow-up:
tasks/backlog/2026-11-19-bounded-selfhost-git-import.md.Validation
pnpm lintpnpm typecheckpnpm test.claude/rules/47-control-loop-io-budget.md)Staging Verification (REQUIRED for all code changes — merge-blocking)
All checkboxes below are mandatory for any PR that changes runtime code (
.ts,.tsx,.go, etc.). WriteN/A: docs-onlyONLY if the PR contains zero runtime code changes. See.claude/rules/13-staging-verification.md.Deploy Stagingworkflow triggered manually and passed for this branchapp.sammy.party(staging) using test credentials and actively tested the applicationN/A: no infra changesONLY if the PR does not touch any infrastructure paths.Staging Verification Evidence
Final BOX smoke, round 2 (closes the deferred L22c criterion), 2026-11-20 01:20-01:55 UTC, exact head
7f086c72bfbf225cdfbd5b573791eecf4fe15769(#2907 over main860718dc3with L23). L24 #2918 was still open at 01:55Z, so per the coordinator this is the final proof on current main:gceto COMPOSE_PROFILES"), leaving the stack untouched..envCOMPOSE_PROFILESwent fromtunnel,mail-collectortotunnel,mail-collector,gce; no other line changed.pnpm selfhost:upgradefinished EXIT=0 and rebuilt egress-fence and gce-metadata-proxy.selfhost:verify-fencereports "egress fence in effect", health is 200, and upgrade-pending is cleared.01M7V8RXRT63QHGFX3BEDR9ATAreplied "pong" and pushedsam/ping-reply-pong-create-dr9ata. A separate cookie-free clone verifiede2e6b14c825544fd87166301c28f6093a3fc3d81,h2-proof.txt=pong, andgit fsck --strict. Unauthenticated access returns 401..envbackup removed; own metadata key absent and firewall rule 404.7f086c72b, clean, with six containers healthy. BOX FREE posted at channel sequence 428.Round 1, on
9d8a0802(#2907 over main20675016f, before L23), passed the same way:Round 1 details, 2026-11-20 00:30-00:45 UTC, head
9d8a08029933863020011b6f0d0e7a62f12b3804:pnpm selfhost:upgradeof app.vmtest.sam2.party frome7ac643b1. EXIT=0, healthy, no D1 migrations. The generated celld config carriesHostedGitRepoandselfhost-hosted-git-v1.01M7V67QTF30PEZ8G8EJ4SM8KXcreated 201 as the test account, signed in by email OTP through the box's mail collector.01M7V681KWFSR8N9H33N5XPB71(OpenCode,opencode/big-pickle, free) ran on a fresh node, replied "pong", and pushedsam/ping-reply-pong-create-5xpb71.e7400ab74a65a152e842a99a2ebc8203d71751ae,h2-proof.txt=pong, andgit fsck --strictpasses. Unauthenticatedinfo/refsreturns 401.9d8a0802with a clean checkout. BOX FREE posted on feature.selfhost-landing at sequence 424.Earlier evidence, unchanged:
BOX final candidatee7ac643b18f4ca864e403d33f7fbcf7a1a5e8fe8: existingf6 upgraded by ordinary bucket-mode pnpm selfhost:upgrade to e7, exit0/healthy, celld selfhost-hosted-git-v1 retained. Hosted project01M7T0482A939BRG0JFFK9VG62 created201; owner token200/unauth401. Normal node/task01M7T0VJHK2381FBXA2VG6PM8Q used OpenCode big-pickle free, replied pong. Cookie-free clone of sam/ping-run-one-shell-g6pm8q verified push164c22e3dc1c52de674718cc3996a31f75833c29 with h2-proof.txt=pong.
Cleanup: session stop/node/project delete200; project404/nodesempty; GCP inventory neither test VM. Test credential removed200, own SSHkeyabsent/firewall404, remote/local access/scratch removed. BOX cleancheckout e7 and four original containers healthy. BOX FREE feature.selfhost-landing sequence405. The first node failed Docker installation due to GCE Ubuntu mirror503; cleaned through SAM, then one coordinator-approved fresh retry passed. Follow-up idea01M7T0W1QW6WGMZGK1RYAXEEB1 contains sanitized diagnostic evidence; no manual VM provisioning workaround was used.
Primary staging 44532452799 passed at0f504c8dc; runtime code is identical at e7ac643 (later changes are docs/tests). Authenticated Playwright/API proof: Artifacts project01M7T0EY1H2F03C1KK3W60DMQ9 and GitHub project01M7T0F97C4V2BNV2M645TFF9M both create201 and branches200. Self-host token and git routes return404, and Cloudflare settings show native ARTIFACTS with no HOSTED_GIT/HostedGitRepo. Both projects deleted200 and verified404. Project overviews and dashboard/projects/settings navigation had zero page/console errors. Browser evidence retained in .tmp/h2-staging-create-final.log and h2-staging-nav.log.
The earlier staging run exposed native RPC property probing;6324f09ca fixed it and the proxy-shaped negative control detects regression. The final replacement proves the fixed native Artifacts and GitHub paths.
UI Screenshot Evidence
N/A: no UI code changes. Live browser verification screenshots are retained under
.tmp/.End-to-End Verification (Required for multi-component changes)
.claude/rules/10-e2e-verification.md)Data Flow Trace
project-create.ts:registerProjectCreateRouteresolves the existing generic backend, creates the repo and seeds README throughseedArtifactsReadme. Native binding uses global HTTP; the self-host fallback injects authenticated internal fetch.selfhost/hosted-git/http.tsvalidates repository/user/workspace/generation before forwarding smart HTTP to the self-host DO.runtime-git-token.tsvalidates current workspace and mints a backend token; the agent clones, commits and pushes. Real git conformance and the BOX agent session exercise this complete path. Deletion fences new work, waits accepted receives, cancels clone streams and removes repo data with a persistent tombstone.Untested Gaps
Deferred with justification to
tasks/backlog/2026-11-19-hosted-git-gc-and-ingest-hardening.md: GC migration past the inflation budget (whole unreferenced packs are already dropped without inflating), delta depth at ingest, GC holding the input gate, heavy history without a cache, alarm error handling and rate limits. Each needs a write token for that repository and stays inside it.Live Cloudflare Artifacts/GitHub creation passed on the replacement deployment. Public import is deliberately unavailable with an explicit400 and a bounded-import backlog. Final BOX proof includes all runtime ref/deletion defenses; real Git/HTTP, SQLite and concurrency controls also cover them.
Post-Mortem
What broke
Pre-merge staging verification found Cloudflare Artifacts README seeding failed after optional fallback transport properties were added.
Root cause
Workers RPC stubs synthesize callables for unknown properties. Probing
nativeBinding.remoteFetchincorrectly selected a nonexistent RPC method instead of global HTTP.Class of bug
Mock-hidden integration failure across an RPC extension boundary.
Why it wasn't caught
Plain object fixtures returned undefined for unknown properties. The real binding synthesizes methods.
Process fix included in this PR
Native transport is chosen from binding presence, and only a registered fallback supplies extensions. Route and browser tests use proxy-shaped native bindings; removing the guard fails the route test. The dedicated hosted suite runs in API CI shard1 after dependency build.
Post-mortem file
tasks/active/2026-11-19-selfhost-hosted-git-h2.mdrecords evidence and discriminating controls.Specialist Review Evidence (Required for agent-authored PRs)
If local subagents were used during Phase 5, list every reviewer below. Do NOT merge until every row shows PASS or ADDRESSED. If any reviewer could not complete (timeout, workspace killed, error), you MUST add the
needs-human-reviewlabel and stop — do not self-merge. CodeRabbit is not a local reviewer: record it in the CodeRabbit section below, not in this table. See.claude/rules/25-review-merge-gate.md.needs-human-reviewlabel added and merge deferred to humanproject-update.tslets an Artifacts project'sdefaultBranchchange after a non-empty check only. It writes D1 alone, so there is no 500, but a later clone with--branchcan fail. LOW: a branch of 245 to 255 characters is rejected by the new check, while the character message still says max 255.CodeRabbit Review Evidence (Required for agent-authored PRs)
When the agent marks the PR ready for review with the first complete candidate, it applies the
coderabbit-reviewlabel (or dispatches the trusted workflow) and waits about 15 minutes, in parallel with CI, local reviewers and staging. The wait ends at once on aReview skipped, rate-limit or quota reply. A CodeRabbit review is not required. If CodeRabbit reviews, its feedback blocks merge until every finding is implemented or explicitly resolved with a reason. If it does not review (silence,Review skipped, rate limit), record what you observed below and merge on the remaining gates. A missing review never calls forneeds-human-reviewor a waiver. See.claude/rules/25-review-merge-gate.md.CodeRabbit Notes
Requested at readiness 2026-11-19 12:33 UTC using coderabbit-review label; trusted workflow44525031212 succeeded. At12:34:24 CodeRabbit replied "Review skipped:136 files exceed the limit of100." Wait ended on the explicit skip, per rule25. No CodeRabbit review findings. No retry loop; PR contains stacked L22c until #2906 lands.
Exceptions (If any)
Approved empty-seeded-repo scope only; bounded public import is tracked in the linked backlog. No Cloudflare migration or implementation import is permitted.
Agent Preflight (Required)
Classification
External References
N/A: existing integrated git protocol implementation is imported and isolated; no new external service API. Vendored dgit provenance and SAM defensive changes are recorded in apps/api/src/vendor/dgit/UPSTREAM.md. L16 backend seam and L22c renderCelldMain/withSelfHostBuild are the existing extension points.
Codebase Impact Analysis
apps/api/src/routes shared handlers use apps/api/src/services/artifacts/backend.ts for token/fetch/import capability selection. Runtime git implementation, tokens, DO and vendored dgit load only from selfhost/build.ts. packages/repo-hosting accepts injected HTTP. scripts/selfhost/celld-config.ts appends a self-host-only binding/tag; Cloudflare wrangler and migrations remain untouched.
Documentation & Specs
Updated deploy/selfhost/README.md with repository creation, empty-seed scope, unavailable public import and repositories.* limits. Updated task acceptance evidence and added bounded-import backlog. No public supported-hosting promise or UI change.
Constitution & Risk Check
Principles X/XI/XIII: reuse fallback seam, typed administrator limits and fail closed. Resource risk is bounded before inflation/allocation, at cumulative output and delta depth, with a per-operation deadline. Auth binds repository/user/workspace generation. Cloudflare import graph is fail-closed and violation-tested. Bucket upgrade and real agent push are proven; Candidate CI, replacement staging and BOX passed; final main reconciliation remains.
Current local evidence
Late failure-path review delta
Two newer Codex findings (r4629428414/r4629428425) applied; the earlier five-thread summary omitted them. Failed ingest could leave rows at quota, preventing the next ingest orphan sweep. GC cleared pending before a failed sweep, losing recovery work. Fixed in c6a45ee.
Touched functions: PackStore.cleanupOrphans/ingest (extract existing sweep); HostedGitRepo.processReceive failed-ingest catch; alarm/runAlarm/gc retry bookkeeping; typed repositories.maxGcAttempts metadata. No auth, deletion or happy-path protocol change. Immediate cleanup precedes alarm scheduling. GC persists retries under its writer slot and carries errors outside the input gate without resetting the DO. Default3 consecutive attempts, five minutes apart, then a durable failed marker/error log; success resets the budget. One repository per alarm, existing30000-object/256MiB/128MiB inflation/120s envelope per attempt, maximum3 failed attempts per episode.
Validation: full real-git/SQLite24/24, focused GC/deletion8/8, API typecheck and focused lint pass. Real SQLite checksum failure at quota recovers and accepts the next safe push; failed-read GC retains its alarm, reclaims unreachable objects on retry and terminates. Independent negative controls fail: orphan2199552bytes==cap and lostGCpending0vs1. Restored suite passes. Security delta PASS, including cleanup-before-schedule failure and serialized retry metadata.
Coordinator decision720e4e43 (2026-11-19) authorizes no BOX repeat for this confined delta if real-git+SQLite/negative controls, security delta, fresh CI and zero open threads pass. Existing BOX pong/push/cleanup proof remains valid on those conditions. Fresh CI is pending; release remains gated.
Ref-name admission review
Codex r4633207972 found intermediate
.lockpath components accepted.protocol.validatePushnow rejects that component suffix. A complete audit against all ten Git ref-format rules also found a missing final-dot check, fixed together. Existing conservative HTML/whitespace/255-character restrictions are retained.Raw smart-HTTP controls: foo.lock/bar, foo.lock and ends-dot. refused; normal, feature/x and foo.lockish/bar accepted through the same real DO/write path. Rule matrix66/66; full conformance25/25. Removing component check makes raw HTTP accept an invalid ref; removing final-dot check yields1failed/65passed matrix cases. Restored suites pass. Security delta PASS includes independent full-rule audit.
Coordinator decision5e57db22 (2026-11-19) extends no BOX repeat to this invalid-name tightening, conditioned on these positive/negative controls, full real-git, security delta, fresh CI and zero open threads. Only validatePush invalid-ref admission changed; ordinary branch pushes/auth/deletion are unchanged. Fresh CI remains pending.
Push admission hardening (takeover, 2026-11-19/20)
Fixed (each with real-git and/or unit tests; each guard mutated once and its test went red):
packCompletetrusted objects from rejected packs.tree <oid>orobject <oid>, headers in order and newline-terminated, tree modes and names valid, no.gitforms and no.gitmodulessymlink.saveReachablestamps only its walk's version, unstamps before rewriting, and only the latest overlapping save stamps.commitPushre-checks validity at commit time. GC invalidates the cache when it deletes objects.ls-refsprefix cap; GC drops whole unreferenced packs before inflating anything and keeps no delta-only bases; storage cap re-checked after the pack is stored.Deferred: see Untested Gaps.
Throughput (rule 81):
Final gates on
7f086c72b(after merging L23):selfhost:test593 passed (3 skipped), hosted git real-git suite 38/38, self-host unit tests 242/242, repo-hosting 148/148, API and repo-hosting typecheck and lint clean. 0 open review threads.Codex findings on
7f086c72b(fixed inaf300919)Each fix has a real-git or unit test, and each test went red when its fix was removed, except two LOW gaps the security delta review recorded. The gzip-path pre-parse bound has no test (a git delete push is never gzipped), and the final-cap call site of
hostedGitNewRefByteshas only a helper unit test. Neither changes behavior outside those paths. Gates: hosted git 39/39, unit 244/244,selfhost:test593/593, typecheck and lint clean. 0 open threads.Codex finding on
af300919(fixed in7b2b41f5, test extended ine04adb9c)collisionDetect: true), as git does. A flagged object fails ingest withSha1CollisionErrorbefore validation and before any ref write; the failed-ingest path reclaims the pack rows and queues GC.maxInflatedBytes(128 MiB default), so the cost is about 1 s at the cap, against the 120 s deadline.tests/unit/selfhost/hosted-git-sha1dc.test.ts: both SHAttered prefixes are flagged with an unchanged SHA-1, and a one-bit-flipped control is not.type size\0header changes the chaining state), so a test-only hook forces the detector's verdict for one blob. WithcollisionDetect: falsethe test goes red.e04adb9cadds a thin-pack delta-resolved blob to the same test; settingcdto false on the two delta hash sites alone turns it red.tests/unit/selfhost221/221 (the 3 new tests included), typecheck and lint clean. 0 open threads.Codex finding on
023a40e6(fixed inee54ce19)git check-ref-format(foo.lock,.hidden,a..b,trailing.) initialized the hosted repository. The seed push was then refused as a funny refname, and creation returned 500.protocol.tsintoapps/api/src/lib/git-ref-name.ts, which has no imports, so the Worker graph can use it without pulling in dgit.validatePushand the Artifacts project-create path now share it, and project creation answers 400 before any repository exists.tests/unit/lib/git-ref-name.test.ts(accept/reject matrix). The real-route conformance test checks each bad name gets 400 with no project row, and that afeature/seededcontrol is created, seeded and served over git. With the route guard disabled, the test fails with the original 500.Codex finding on
ee54ce19(fixed inf433bb94)refs/heads/a, deleterefs/heads/awith its old value, and createrefs/heads/a/bin one request. The directory/file pre-pass freedabecause of the matching delete, soa/bwas accepted. At commit the update won and the delete lost its CAS, leaving both refs stored, which breaks clones.validatePushnow does the same. Every command for a ref named more than once is rejected (multiple updates for ref not allowed), and those deletes free no name. Real git clients never send duplicate refs.nglines andls-remote, then does a clean clone. Both go red with duplicate detection removed: the push then answersok refs/heads/a.