carlos / platform Public

Design source preservation and retrieval for claimed apps

codex agent, operated by paul@keymail.dev pushed by paul@keymail.dev 188c45d254285eec7aeea38083471f38302503ea parent ca027e8
1 file changed, +260 −0
  • docs/superpowers/specs/2026-11-07-claimed-app-source-design.md +260 −0
diff --git a/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md b/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md
new file mode 100644
index 000000000..0df119e9a
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md
@@ -0,0 +1,260 @@
+# Keep source with a claimed app
+
+Proposed design, 2026-11-07. Paul approved preserving and retrieving source;
+the decisions below await controller acceptance and Opus security review.
+Review history: no rounds yet. This change lands as one usable slice: preservation,
+download, CLI and continuation instructions enabled together for new claims.
+
+## Which source
+
+Today `handleDemoPublish`, registered at `POST /api/demo/apps`, accepts
+`application/gzip`, caps compressed input at 5,000,000 bytes and calls
+`demobuild.ValidateSource` (`internal/console/apidemo.go:276`,
+`internal/console/apidemo.go:428`). Validation retains the original archive,
+allows at most 256 files, 2,000,000 bytes per file and 20,000,000 expanded
+file bytes, and separately bounds tar framing (`internal/demobuild/source.go:25`,
+`internal/demobuild/source.go:61`, `internal/demobuild/source.go:187`).
+
+`insertDemoJob` stores it temporarily in SQLite's `demo_job_outbox`;
+`flushDemoOutbox` writes the immutable object at
+`apps/<demo-account>/<demo-app>/demo-build-data/<job-id>/source.tar.gz`, then
+the signed `demo-build/current.json` job and removes the outbox entry
+(`internal/console/demo_jobs.go:83`, `internal/console/demo_jobs.go:144`,
+`internal/console/demo_jobs.go:248`). This uses `Config.Releases`, the
+deployment store: S3 through `CARLOS_DEPLOYMENT_BUCKET`, or a directory through
+`CARLOS_DEPLOYMENT_DIR` (`internal/console/demo_jobs.go:579`,
+`cmd/console/main.go:441`, `cmd/console/main.go:488`, `cmd/console/main.go:933`).
+The worker reads that exact key, validates its digest, and builds under
+`/var/lib/carlos-demo-builds/<job-id>/<attempt>`
+(`internal/host/demo_jobs.go:577`, `internal/demobuild/worker.go:27`,
+`internal/demobuild/worker.go:215`).
+
+**Last accepted means the job for the settled, serving `edge` version.**
+`demoVersion(job)` is `v0.0.0-demo.<generation>`; publication records
+`state='published'` after readiness, while failed publication can roll back
+to an earlier published generation (`internal/console/demo_publish.go:38`,
+`internal/console/demo_publish.go:228`, `internal/console/demo_publish.go:396`,
+`internal/console/demo_publish.go:418`). Extend `pinDemoClaim` to select exactly
+one published job whose `demoVersion` equals its verified channel pointer,
+whose binary digest matches the manifest, and whose demo/account/app/lifetime
+match the source. Persist that job ID and its `SourceSHA256`. Refuse missing
+or ambiguous provenance. Keep its busy/settlement gates
+(`internal/console/demo_claim_transfer.go:220`). Do not select by binary digest
+alone, newest upload, or `demo_apps.source_sha256`: the latter changes at
+enqueue, before success (`internal/console/demo_jobs.go:161`).
+
+Demos expire after 24 hours. Retirement waits for worker and initialization
+cleanup, then purges the demo app prefix; job rows disappear seven days after
+purge (`internal/console/demo_store.go:257`,
+`internal/console/demo_expiry.go:309`, `internal/console/demo_expiry.go:328`,
+`internal/console/demo_store.go:483`). The archive must leave that lifetime.
+
+## Copy before committing the claim
+
+Store the snapshot in the same provider-neutral `release.Store`, at
+`apps/<target-sqid>/<target-app>/source/claims/<claim-op-id>/source.tar.gz`.
+Derive every segment from validated claim records, never a request-supplied key.
+Add an optional, versioned `claimed_source` descriptor to the target **apps
+row**: operation ID, original target lifetime, source job ID, source digest,
+compressed size, serving version and claim timestamp. It is app-owned metadata,
+with no foreign key or lookup dependency on disposable demo rows.
+
+In `advanceDemoClaimLocked`'s **reserved** phase, immediately after pinning and
+before pipeline/seed/binary work or freezing, add `copyDemoClaimSource`.
+The current phase ordering is at `internal/console/demo_claim_transfer.go:109`.
+Persist source identity on the operation and a separate `source_copied` progress
+flag. Stream-read with `release.OpenObjectStreaming`, limited to 5,000,001 bytes;
+check size, SHA-256 and safe archive structure before a create-only `Put`.
+The interface already specifies create-only writes and idempotent deletion
+(`internal/release/store.go:45`, `internal/release/store.go:353`). No AWS API
+belongs in this logic. Normal work is one bounded GET and one PUT; no polling,
+listing or HEAD request is needed. An uncertain PUT may read the destination:
+accept identical bytes, refuse a mismatch, never overwrite it.
+
+**Do not complete a new claim without source.** Retry transient storage failures
+through the existing persisted retry clock, within the original claim deadline;
+missing/corrupt source aborts. This preserves the promise without freezing a demo
+while copying source. Existing abort cleanup removes uncommitted destination
+objects before releasing the app reservation; committed claims cannot abort
+(`internal/console/demo_claim_transfer.go:786`,
+`internal/console/demo_claim_transfer.go:867`,
+`internal/console/demo_claim_transfer.go:896`). Commit must require the pinned
+copy flag and atomically attach the descriptor alongside the current commit
+transaction (`internal/console/demo_claim_transfer.go:650`). Recovery reuses
+the identity and key; a lost progress write cannot select another upload.
+
+Completed snapshots are outside source-demo expiry, retirement and stray sweeps
+(`internal/console/demo_expiry.go:328`, `internal/console/demo_expiry.go:391`).
+Only an aborted, uncommitted claim may remove its destination copy. On rollout,
+uncommitted older operations must establish this prerequisite before proceeding
+or abort safely; already committed legacy claims remain valid with no snapshot.
+Do not invent source or promise backfill after demo purge.
+
+## Download contract and security
+
+Fix these names now:
+
+| Surface | Name |
+| --- | --- |
+| Browser | `GET /a/{sqid}/apps/{app}/source` — **Download source** |
+| CLI API | `GET /api/cli/apps/{account}/{app}/source` |
+| CLI | `carlos apps source pull --app <app> --account <name-or-sqid> --console <origin>` |
+| Start guide | `/start#after-you-keep-it` |
+
+Add the browser route in `server.go` and the API through `cliRoute` in
+`authcli.go`, using `svcrole.Set{}` and `apiPerson` before `apiAccountApp`.
+Those are the existing person-only registration and membership conventions
+(`internal/console/authcli.go:609`, `internal/console/apicli.go:312`,
+`internal/console/apicli.go:228`). Both **owner and member** may download;
+service/app credentials, demo tokens and operators without membership may not.
+Browser authentication follows `accountApp` (`internal/console/server.go:4411`).
+Recheck current membership, live account/app, descriptor ownership and completed
+claim under the lifecycle locks before handing out bytes. A pending claim,
+deleted app, foreign app or guessed ID gives the same non-disclosing 404 on each
+door. Perform these checks before object access; never accept a key, job ID or
+account from query metadata. No public or presigned download URL.
+
+Share one bounded reader between both handlers. Verify the whole archive's size
+and digest before sending bytes, with a 30-second request deadline. Return
+`Content-Type: application/gzip`, validated `Content-Length`,
+`Content-Disposition: attachment; filename="<app>-source.tar.gz"`,
+`Cache-Control: private, no-store`, `X-Content-Type-Options: nosniff`, and
+`X-Carlos-Source-SHA256` and `X-Carlos-Source-Claimed-At` (UTC RFC3339).
+Do not set `Content-Encoding`; no range or conditional
+cache responses. Apply no-store to errors too. Bound downloads to ten per minute
+per person/account/app, and bound concurrent buffering.
+
+Before releasing bytes, require successful `Store.RecordActivity` with action
+`app-source-download`, account, app, actor, UTC time and snapshot identity;
+describe it as a download started, not proof of client receipt. The existing
+audit table carries these fields (`internal/console/store.go:3050`). Use its
+error-returning method directly: `Server.audit` deliberately ignores failures
+(`internal/console/server.go:5265`). Audit failure returns 503 and no source.
+
+Treat archives as untrusted code. Reuse the structural tar checks without
+requiring today's dependency lock: reject traversal, absolute paths, links,
+special files, duplicate paths, oversized expansion and unsupported tar/gzip
+extensions. Existing checks are in `internal/demobuild/source.go:76`,
+`internal/demobuild/source.go:190`, `internal/demobuild/source.go:227`.
+Do not execute, extract or render source in the console. Validation is not
+secret scanning: the submitted bytes already reach storage and the build worker,
+and the validator's file exclusions do not exclude `.env`
+(`internal/console/demo_jobs.go:267`, `internal/host/demo_jobs.go:577`,
+`internal/demobuild/source.go:207`). Claiming additionally transfers the running
+binary and database snapshot (`internal/console/demo_claim_transfer.go:132`,
+`internal/console/demo_claim_transfer.go:182`). Preserve the user's exact source,
+including any embedded secrets, for current account members only; keep it out of
+logs, prompts and telemetry. The build/platform storage operators remain trusted.
+
+## CLI and the fresh-agent handoff
+
+Follow `runAppsCreate`'s API-only flags: `--app`, `--account`, `--account-id`
+(exact sqid, takes precedence), `--console`; no bucket fallback
+(`apps.go:510`). Add optional `--output <path>`, default `<app>-source.tar.gz`.
+Write a mode-0600 file with exclusive creation; refuse existing files/symlinks,
+remove partial output, verify the response digest and cap independently, and
+refuse redirects to another origin. Print the saved path and snapshot timestamp.
+Prefer an archive over automatic extraction: it avoids a new filesystem-write
+surface. Check archive structure before saving; never run its contents.
+
+The three steps below are the fixed contract for both the done-page CLI
+disclosure and the new `/start` section. Substitute shell-quoted app, canonical
+account sqid and console origin; `v1` is an example fresh release label, changed
+for each subsequent deploy. Prerequisites: CLI and Go installed; inspect source,
+including dotfiles/configuration, before building.
+
+```sh
+# 1. Sign in; the person approves the displayed code in their browser.
+carlos auth login --console '<console-origin>'
+
+# 2. Fetch source, then unpack into a new empty directory.
+carlos apps source pull --console '<console-origin>' --account-id '<sqid>' --app '<app>'
+mkdir '<app>'
+tar --no-same-owner --no-same-permissions -xzf '<app>-source.tar.gz' -C '<app>'
+cd '<app>'
+
+# 3. After inspecting and editing, build and deploy to the existing app.
+CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -o app .
+carlos deploy --console '<console-origin>' --account-id '<sqid>' --app '<app>' --channel edge --kind binary --target linux-arm64 --version v1 --swap hold --no-assets ./app
+```
+
+Login's browser approval is implemented in `auth.go:700`. The demo entry package
+is `.` and its build target is linux/arm64 with cgo disabled
+(`internal/demobuild/lock.go:128`, `internal/demobuild/runner.go:36`). Deploy
+accepts these flags and an artifact; zero-argument deployment instead requires
+saved configuration or the interactive wizard (`deploy.go:128`, `deploy.go:278`).
+Claim installs the `edge` pipeline and promotes the copied binary there
+(`internal/console/demo_claim_transfer.go:120`,
+`internal/console/demo_claim_transfer.go:408`). No new app, region, host, AWS
+access or server-side source build is required by this continuation path.
+
+Extend `demoClaimPageData` with canonical account identity and use the trusted
+console origin. The done page already has copyable agent and CLI blocks, but the
+CLI text currently contains only login (`internal/console/demo_claim_page.go:36`,
+`internal/console/demo_claim_page.go:129`,
+`internal/console/templates/demo_claim.html:173`). Proposed agent prompt:
+“Continue app `<app>` in account `<name>` (ID `<sqid>`) on console `<origin>`.
+Follow [https://carlosframework.com/start#after-you-keep-it](https://carlosframework.com/start#after-you-keep-it):
+help me sign in, fetch its claimed source, then build and deploy my changes to
+that existing app.” Populate only after success; a claim-status cookie is never
+download authority. Coordinate the anchor with the website controller.
+
+Copy inventory for later Luna review: “Download source”; “Source saved when you
+kept this app; later deployments do not update it”; “Sign in / Fetch source /
+Deploy changes”; the agent prompt above; CLI usage/flag help and saved-file
+confirmation (“Saved claimed-at source to `<path>` (`<timestamp>`)”). Proposed
+refusals: “Sign in with carlos auth login --console `<origin>`”; “No saved source
+for this app”; “Source download is temporarily unavailable. Try again”; “Source
+failed integrity or size checks; nothing was saved”; “Output already exists;
+choose another --output path”; “Too many source downloads; try again in a
+minute”; “This app has saved source; moving it between accounts is not supported
+yet”. Reuse existing generic authorization errors; show the missing-snapshot
+message only after account/app authorization.
+
+## Retention, rollout and proof
+
+Keep the immutable **claimed-at snapshot** until permanent app deletion. Later
+deploys never replace it. Trash disables download but retains it for restore,
+following the existing 30-day cooloff; permanent purge deletes the prefix and
+app-owned descriptor (`internal/release/trash.go:31`,
+`internal/release/trash.go:325`, `internal/console/ownership.go:607`). Account
+deletion already requires zero app rows, including Trash, so it must follow
+those purges (`internal/console/ownership.go:819`). Storage backup/version
+retention follows the deployment's deletion policy; this is not a promise of
+immediate erasure from backups.
+
+Region changes retain the same account/app key; the current default-region
+setter changes only SQLite placement defaults (`internal/console/appregionset.go:3`).
+Renaming shipped apps is already refused (`internal/console/appsettings.go:903`).
+The account move is a route-mismatch repair that moves the console record
+(`internal/console/appsettings.go:1650`, `internal/console/appsettings.go:1735`).
+Explicitly refuse rename/account repair for snapshot-bearing apps under their
+mutation locks; a future transfer must copy and verify into the destination
+account before changing ownership, then remove the old copy. Never leave a
+cross-account pointer.
+
+Build failing tests first through the **production router**, then implement:
+
+- Publish A, reject/roll back B (including equal binary digests), claim, and
+ retrieve A byte-for-byte after demo expiry and metadata purge.
+- Inject missing/oversized/corrupt source, failed GET/PUT, lost PUT acknowledgment,
+ crashes at copy/progress/commit boundaries, expiry and abort. Prove no new
+ source-less committed app, no wrong-job retry and complete abort cleanup.
+- Exercise both routes as owner/member, removed member, stranger, other-account
+ same-name app, operator-only, service credential and demo capability. Check
+ identical unauthorized responses and zero storage reads. Race deletion and
+ membership removal; check headers, audit attribution and audit failure.
+- Test archive attacks, CLI no-clobber/partial cleanup, size limits and redirects;
+ preserve through deploy/Trash/restore/region change, purge before account
+ deletion, and refuse rename/account repair. Count object operations: no listing
+ or idle polling. Run storage tests with directory and local S3-adapter mocks.
+- Verify copied prompt/anchor and all three steps against the built CLI in an
+ isolated local fixture; add the command to `docs/site/cli.md` when implemented.
+
+Controller decisions, with recommendations: accept abort-on-source-failure,
+member-and-owner access, retention through Trash until purge, and refusal of the
+existing account repair for snapshot-bearing apps. Keep legacy claims without
+source honest. Schedule Opus review before implementation lands, covering these
+trust boundaries and retention; stop at the first round with no P1, fix P2s
+without reopening, and carry any P3s forward. No product code, infrastructure
+changes or security-review verdict is part of this design commit.