Skip to content

feat(runtime): admit browser calls as the patch viewer - #213

Merged
allisonmahmood merged 3 commits into
mainfrom
sdk/197-runtime
Sep 12, 2026
Merged

allisonmahmood merged 3 commits into
mainfrom
sdk/197-runtime

Conversation

@allisonmahmood

@allisonmahmood allisonmahmood commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner

Patches need a browser-only operation path that cannot switch acting users mid-page and records mutations before execution.

Adds runtime admission, loaded-version binding, host-supplied dispatch and durable runtime logging. Only me is admitted now; file routes are reserved for the Files ticket. Includes 0006_runtime_baseline, migration wiring, admission/outcome coverage and updated API/domain documentation.

Stacked on #212 (sdk/196-company-database), which is the base branch for this PR.

Closes #197.

Verification

  • Full offline suite: 428 tests passed across 46 files.
  • Focused runtime, migration and real-server checks: 47 tests passed.
  • pnpm typecheck, pnpm lint and pnpm format:check passed.
  • Grok/Astra review findings addressed or explicitly dispositioned in the PR review follow-up comment.

Implemented with OpenAI GPT-6 Astra in the Oh My Pi harness.

@github-actions github-actions Bot added area:server Touches the server area area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area size:l 501-1,000 changed lines labels Sep 10, 2026
@allisonmahmood

Copy link
Copy Markdown
Owner Author

Astra review

Reviewed git diff origin/sdk/196-company-database...HEAD at 082b637fc5d708459358441b3f7df4a3a242ad82 against #197. Commits: e786973, 082b637. One pass, no subagents; merge-blocking findings only.

Standards

  1. [P1 — method] Do not reserve a lower migration ID for a later change. Runtime installs migration 0007, while the development guide reserves 0006 for Integrations. The pinned Effect migrator does not backfill gaps: it takes the highest recorded ID and skips every currentId <= latestMigrationId. Once an instance runs this PR, the later migration promised at 0006 will silently never execute there, although a fresh installation will execute it. This is an incorrect use of the existing migrator, not a stylistic preference.

    Verified on disposable Postgres: starting from this PR's migrated template, adding a stand-in 0006 migration returned [] and left its table absent; migrating an empty database with 0006 and 0007 created the table. Allocate IDs in landing order and remove the promise that 0006 can be filled later—if Runtime remains 0007, Integrations must receive a higher ID. Update the reservation documentation with the coordinated numbering.

No separate merge-blocking YAGNI finding: the dispatcher and runtime-log foundation are explicitly requested by #197.

Spec

No additional merge-blocking intent findings. The me-only admitted registry and refusal-only file routes match “Admitted at merge”; I have not treated operations assigned to later tickets as missing from this PR.

Verification

  • pnpm exec vitest run packages/runtime/src/Runtime.test.ts packages/runtime/src/RuntimeApi.test.ts packages/runtime/src/RuntimeLog.test.ts apps/server/src/Server.test.ts — 32 tests passed.
  • Separate disposable-Postgres upgrade/fresh-install comparison confirmed the migration finding. No repository source changes or live-instance access.

Summary: Standards: 1 blocker, worst: silently skipped reserved migration on upgrade. Spec: 0 blockers, none.

@allisonmahmood allisonmahmood left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code review vs #197

#197 asked for the runtime door: bind a browser call to the loaded version and the viewer, admit only me, log mutations before they run, and leave file routes reserved. That is the product promise behind this PR — a patch never holds a login, never switches acting users mid-page, and every write that later tickets add already has a place to be attributed.

What shipped matches that intent. packages/runtime owns admission, binding, host-supplied dispatch, and runtime_calls. Only me is on the wire. File GET/PUT exist so later tickets walk the same door rather than inventing a second one. The shell, broker, tables, files, and integrations were correctly left to their tickets.


Method

The package cut is the right one. Runtime declares LoadedVersions and never imports Patches; Patches provides the layer; the server wires Runtime.layer({ me }). Admission lives in Runtime.call, not copied across three HTTP handlers, which is what patchy/dev will need to compose later.

That method is sound, with three caveats:

  1. ApiGuard classifies runtime routes as public. Behaviour is correct (skip the bearer guard and the address-level API limiter so Runtime can use 300/viewer/patch). The name is a lie. A later “treat all public /api alike” change would misfire. A runtime kind that still falls through to the app would be the honest twin of publish.
  2. File routes synthesise a RuntimeEnvelope with principal: null. Header principal is still the authority (body matching is POST-only), so #197’s “principal and wire travel as headers” holds. Ticket 6 will feel this: Handler.run only has Binding in R, so PUT bytes are not in args and cannot be read from the request without widening the handler. Name that split before files land.
  3. RequireSession.admission + captured viewerContext. Keeps runtime → auth without importing Companies. Fragile: Auth’s HTML door/deactivation results are now load-bearing for a JSON API and get flattened to session_expired / access_denied.

Inlining admission into RuntimeApi and dropping Binding / handler() would scatter the invariant, not shrink it. Keep this shape.


YAGNI

The door, me, reserved file refusals, the log table, and every §11 error code are the right size. A few things are not.

Cut

  • RuntimeLog.recent and runtime_calls_connection_recent_idx. No production caller. Spec §11’s reader is the /company recent-calls list, which is the integrations ticket. #197’s done-when is find by correlation. Delete both; the recent/isolation tests go with them.
  • File success codec in RuntimeApi.file (decodeBytes → uint8Array). Reserved routes must admit and refuse. They must not pretend a { me } handler map can return file bytes. Keep Origin / size / fetch-site refusals.
  • Write-side postgres.query SQL truncation in RuntimeLog.begin. Runtime.call never passes sql. The column CHECK already enforces 8 KB. Wait for postgres.

Keep

  • runtime_calls columns including credential_kind, connection_id, sql, resource — that is the §11 table, not a hidden discovery API. Production writes 'session' only.
  • Per-op bodyLimit / config defaults from §12, even though only me is admitted.
  • Two LoadedVersions files (tag vs layer). Spec, not duplication.
  • Runtime.call as one request lifecycle. Splitting admit/dispatch/log would thread Binding through extra functions with one consumer.

LoggedFailure is the one piece that is both extra machinery and a conventions miss: it exists to stamp correlationId onto an error that is already in the channel. Fail with the original OperationError after setting that field; wrap only untagged defects as SourceUnavailable.


Standards

Hard — LoggedFailure (packages/runtime/src/Runtime.ts ~140–157, used ~360–367).
.agents/skills/effect-service-conventions/SKILL.md (Errors): pass through a structured domain error already in the target channel; wrap only unknown/lower-level failures; derive message from the wrapper’s own attributes, never cause.message. LoggedFailure wraps OperationError (already in RuntimeError), re-exposes code / status / retryAfterSeconds from cause, and does return this.cause.message. Every OperationError already has optional correlationId. Expected: fail with the original error after setting that field; wrap only untagged defects as SourceUnavailable.

Hard — packages/sql/CONTEXT.md Migration glossary.
Hit every surface (vocabulary): a ledger change follows through to the owning glossary. The entry still names owners of 1–5 only. Runtime added 0007_runtime_baseline (DEVELOPMENT.md records the reserved 0006 gap). The three migrator spreads were updated; this glossary was not.

Judgement — packages/runtime/src/RuntimeApi.ts success encoding.
ADR-0002: the server encodes /api/* bodies through the api schemas. Failures use encodeSync(RuntimeFailure); success is jsonUnsafe({ ok: true, value }) and never RuntimeSuccess. Inner handler encode is not the envelope schema.

Judgement — packages/patches/src/LoadedVersions.ts.
Effect service conventions: a module that owns construction should export a real make, then layer. Construction is inlined in Layer.effect.

UI consistency: N/A. ADR-0004: N/A (no CLI command). ADR-0009: N/A (platform runtime_calls, no company transaction). Effect imports/layers/it.layer look in line.

Baseline smells (judgement)

  • Middle Man — same LoggedFailure hunk; it mostly delegates to cause.
  • Duplicated Code — two decodeWires, different strictness (Runtime.ts requires a positive int; RuntimeApi.ts is NumberFromString only, for file headers).
  • Speculative Generality — RuntimeLog.recent has no production caller. bodyLimit special-cases tables.* / postgres.* though runtimeOperations is only me; those caps are spec §12, so the repo standard wins over the smell.

Spec

(a) Missing or partial

No #197 merge requirement is missing. me on company/public, admission, LoadedVersions, Runtime.layer({ me }), log pending→finish / pending-past-deadline as unknown, HttpApiTest of the stated rules, docs/API.md, CONTEXT.md / CONTEXT-MAP.md / README are present.

File byte I/O is deferred as specified (“ticket 6 fills the handlers”). Reserved PUT/GET share Runtime.call and then invalid_request / not_available_on_public. PUT does not read the raw body (only store / name / Content-Type in args). That is ticket 6, not a hole in #197.

(b) Scope creep

RuntimeLog.recent (and its tests) implement spec §11 “Reader in v1: the recent-calls list per connection on /company”. #197 did not ask for that reader; there is no /company route (correct). Admin/discovery rows (credential_kind: "admin", null patch/version) are the same extra log surface.

Production still wires only me. Test-only tables.insert / postgres.query handlers are for Origin/log coverage, not admitted ops.

(c) Looks implemented but wrong

Nothing material on the admitted me path.

Hardcoded file principal: null does not violate “on the bytes routes principal and wire travel as headers”. Envelope principal: null is only because there is no JSON body. Company admission uses X-Patchy-Principal; body vs header is compared only on POST. Company GET with a matching header principal is admitted (then invalid_request); header null is principal_changed. Wire is X-Patchy-Wire. Content-Type is copied into args, not required (API.md says PUT “requires” it; #197 only says it travels as Content-Type).

0007_runtime_baseline is the coordinated number, not a miss of “migration 0006_runtime_baseline … ticket 8 holds 0005”. Ticket 3 took 0005_company_database_baseline; 0006 is reserved for Integrations.


Tests and surfaces

Admission is covered on both the wrong and right paths for me, including public me null without a session and unknown ops on a public version before principal checks. Handler failure leaves a row that the response correlationId finds; a hang is pending then unknown after the deadline. Historical public versions re-checked as company-scoped on the real server.

Gaps, not merge-blockers: company non-me with principal: null is implemented (principal_changed) but not HttpApiTest’d; unknown version (vs unknown patch) is only on the server suite; successful me is not asserted to leave runtime_calls empty. File routes skip missing-headers / bearer / rate on PUT.

Surfaces: wire, docs/API.md (rendered, not hand-written), migrators (server / dev / vitest), README layout, product.md, patchy-dev-loop, DEVELOPMENT.md are complete. CLI N/A. Stale parentheticals in AGENTS.md and docs/agents/domain.md still list contexts without Runtime. packages/sql/CONTEXT.md as above.


Standards: 2 hard + 3 judgements; worst is LoggedFailure wrapping an in-channel error. Spec: 1 scope-creep finding (RuntimeLog.recent); worst is that unread recent-calls reader, not a miss of #197.

@allisonmahmood

allisonmahmood commented Sep 10, 2026 •

Copy link
Copy Markdown
Owner Author

Reviewed Grok’s submitted review and Astra’s PR comment against #197 and the source.

Fixed

  • Astra: migration ordering. Runtime is now 0006_runtime_baseline; removed the reserved-0006/gap-tolerance claim. Integrations must land after it as 0007. The migration test starts from a real pre-runtime database, applies Runtime 6 then a stand-in Integrations 7, exercises both tables, and compares a fresh install. No live database or ledger was modified. Grok’s earlier acceptance of 0007 is superseded by this correction.
  • Grok: LoggedFailure. Removed the wrapper; logged typed failures retain their original tag, cause, bounds and Retry-After while receiving the persisted correlation ID. Only untyped defects become SourceUnavailable. Coverage now exercises recovery by the original TooLarge tag as well as HTTP correlation/outcome lookup.
  • Grok: unused recent-calls reader. Removed RuntimeLog.recent, its query/index and recent-list assertions. Kept company isolation through correlation lookup; the integrations ticket can add the reader alongside its actual consumer.
  • Grok: reserved-file success handling. Removed the unused byte-success codec. Reserved routes still enforce browser admission and refuse; actual byte I/O belongs to Files. Their synthetic null body principal remains intentional: these routes authenticate the header principal, not a JSON body.
  • Grok: response schemas and duplicate wire parsing. Runtime HTTP success now encodes through RuntimeSuccess; a malformed handler result is refused rather than emitted. File and JSON admission share the same strict positive-integer wire decoder. Corrected the PUT Content-Type prose to describe transport rather than claim an admission check, and regenerated docs/API.md.
  • Grok: service layout and route naming. Added the real make export to Patches’ LoadedVersions implementation; gave ApiGuard a distinct runtime classification without changing its admission/limiting owner.
  • Grok: vocabulary. SQL’s Migration/Ledger glossary now names Runtime 6 and the migrator’s high-water behavior. Agent navigation points to CONTEXT-MAP instead of duplicating stale context lists.
  • Grok: coverage gaps. Added company non-me/null-principal and unknown-version HTTP assertions, proved public/company me leave the runtime log empty, and covered missing/invalid headers, bearer rejection and throttling on reserved PUT. Retained the existing real-server historical-version checks.

Kept as-is, with reasons

  • Query-only SQL truncation and the 8 KiB database constraint: feat(runtime): the runtime operation path: binding, admission, dispatch and the log #197 explicitly requires this RuntimeLog policy. UTF-8-safe truncation enforces that policy without causing a log insert failure; only explicit postgres.query text is retained. This does not admit postgres operations.
  • Attribution columns/types, including admin and nullable patch/version: these are the requested §11 log shape, not an admin/discovery endpoint. Production still writes session attribution and admits only me. Removed the speculative discovery-only field-copy assertions.
  • RequireSession admission and captured viewer context: reuse Auth’s active-viewer/deactivation policy rather than implement a second identity resolver or add runtime→Companies coupling. The JSON error mapping is intentional and the active/inactive/foreign/expired session cases remain covered.
  • Binding, host-supplied handler map, separate LoadedVersions port/implementation, shared Runtime.call lifecycle and per-operation caps: expressly requested by feat(runtime): the runtime operation path: binding, admission, dispatch and the log #197/§12. They remain centralized; no files/tables/integrations operation was added to the production registry.
  • PUT byte access through Handler: deferred to the Files ticket along with the actual file handlers, as feat(runtime): the runtime operation path: binding, admission, dispatch and the log #197 specifies. The present routes make no successful upload/download promise.

Verification

Fix commit: d18e4f9, pushed to sdk/197-runtime.

  • Focused runtime, migration and real-server suites: 47 passed.
  • Full offline suite: 428 passed / 46 files.
  • pnpm typecheck: 27 tasks passed; pnpm lint and pnpm format:check: passed.
  • The first full run alongside typecheck/lint had two startup-test 5-second timeouts. The isolated startup suite passed 8/8, then the complete uncontended suite passed 428/428; no timeout or unrelated source changes.

Latest-commit CI: all seven checks passed — test (22), test (24), lint (including format/typecheck), clerk-live, cli-smoke, dependency-review, and label. CI run 34503787799 reports head SHA d18e4f9aa405cd9b918f91c0040baed6a54ed670 and conclusion success.

GitHub reports MERGEABLE / CLEAN; no unresolved review threads or additional required branch-protection gates were found. No unresolved blockers. The PR remains stacked on #212 with base sdk/196-company-database and is ready to merge into that base; no merge performed.

@allisonmahmood
allisonmahmood merged commit b9c22fa into main Sep 12, 2026
7 checks passed
@allisonmahmood
allisonmahmood deleted the sdk/197-runtime branch September 12, 2026 11:44
allisonmahmood added a commit that referenced this pull request Sep 12, 2026
Patches need structured data that survives new published versions
without breaking older open versions.

This adds patch-owned tables with additive provisioning at publish,
cumulative owner-visible inventory, and seven viewer-bound runtime
operations. Incompatible changes are refused before content writes and
rechecked under the patch lock. Indexed list queries use storage-column
ordering, and reads enforce the 8 MiB limit before materialization.
Index-size feasibility checks run at publish only; runtime writes rely
on PostgreSQL's own B-tree limit, mapped to `too_large`, without
additional CHECK constraints.

Stacked on #213 (`sdk/197-runtime`); this PR intentionally targets that
branch, not `main`. Files, shared-table uses, and higher tiers remain
outside this change.

Closes #198.

### Verification
- `pnpm lint`
- `pnpm typecheck`
- `pnpm test` — 461 tests across 48 files
- `pnpm format:check`
- Actual-handler `EXPLAIN ANALYZE` over 100,000 rows: default pagination
uses a backward index scan reading 101 rows; equality lookup uses an
index scan reading one row.
- Postgres/PGlite contracts cover additive provisioning, old-version
writes after omission/index addition, native index-key overflow and
rollback, bounded reads, readiness upgrades, and claimed-placement
refusals. UUIDv7 coverage checks timestamp, version, variant, and random
fields.
- Real HTTP + CLI smoke over disposable Postgres during implementation.

Implemented with OpenAI GPT-6 Astra in Oh My Pi.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:ci CI, shared testing infrastructure, development scripts and tooling area:docs Touches the docs area area:server Touches the server area size:l 501-1,000 changed lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(runtime): the runtime operation path: binding, admission, dispatch and the log

1 participant