Skip to content

feat: Genesis - #1

Merged
tlgimenes merged 8 commits into
mainfrom
feat/genesis
Apr 3, 2025
Merged

tlgimenes merged 8 commits into
mainfrom
feat/genesis

Conversation

@tlgimenes

Copy link
Copy Markdown
Contributor

This PR adds much of the code that we were doing in webdraw repo. The goal is to make it an open source ai agent creator

@tlgimenes
tlgimenes merged commit 97cdc92 into main Apr 3, 2025
@tlgimenes
tlgimenes deleted the feat/genesis branch April 3, 2025 14:42
@claude claude Bot mentioned this pull request Oct 7, 2025
viktormarinho added a commit that referenced this pull request May 7, 2026
Address review on PR #3307:

#1 — The previous override only patched `credentialId` and `thinking.id`,
leaving stale `capabilities` / `limits` / `provider` / `title` from the
saved snapshot. Downstream code (`ensureModelCompatibility`, the
max-output-tokens cap, telemetry, prompt headers) consumes those fields,
so a tier whose live slot pointed to a different model would get gated
against the wrong capability set. Replace the patch with a typed
`TierOverride` produced by `resolveTierOverride`, which fetches the full
`ModelInfo` via `ctx.aiProviders.listModels` and translates it into the
`thinking` shape — same translation as the chat path's
`toMetadataModelInfo`. Falls back to a slot-only override (with stored
title) if the provider call throws, so a flaky provider doesn't block
the run.

#2 — Saving any edit on a Simple-Mode-enabled legacy automation (e.g.
just renaming it) used to silently write `tier: "smart"` because
`tierToPersist` fell back to the dropdown's display fallback. After
that, the run path would override the user's original snapshot model
with the org's live "smart" slot. Only auto-pin when `slotMatchedTier`
is truthy — i.e. the saved credential/model actually correspond to a
configured slot. Legacy automations with no slot match stay unpinned
on incidental saves; the user has to explicitly pick a tier via the
dropdown to opt in.

Tests: split build-stream-request tests into "tier override" (verifies
full thinking replacement) and add a new resolve-tier-override.test.ts
that exercises ModelInfo translation, the disabled / unset / no-tier
short-circuits, and the listModels-throws fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
viktormarinho added a commit that referenced this pull request May 7, 2026
* feat(automations): resolve simple-mode tier at run time

Stop baking the resolved model into the automation row. When the user
saves with Simple Mode enabled, persist a `tier` intent ("fast" /
"smart" / "thinking") inside `automation.models`; `buildStreamRequest`
then looks up the live tier slot from `organization_settings.simple_mode`
and uses that instead of the stored credentialId / thinking.id snapshot.

Effects:
- Dormant automations now pick up org Simple Mode changes the next time
  they fire — no UI visit needed to reconcile.
- The detail page derives the dropdown label from `models.tier` first
  (truthful even after a slot reconfig), falling back to slot-match for
  legacy automations.
- The form clears `tier` whenever the user explicitly picks via the
  ModelSelector fallback, so an explicit override beats the tier intent.
- Legacy automations (no tier persisted) keep using the stored snapshot
  until next save, at which point Simple Mode is enabled they get pinned
  to the matched / default tier.

Tests cover the four resolution paths (override, simple-mode disabled,
tier slot unset, no tier on legacy row).

This builds on the UI work merged in #3305 — that PR aligned the model
selector with the chat input but kept baking the resolved model into the
row, so dormant automations stayed stale until someone opened them.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(automations): refresh full thinking metadata + safer auto-pin

Address review on PR #3307:

#1 — The previous override only patched `credentialId` and `thinking.id`,
leaving stale `capabilities` / `limits` / `provider` / `title` from the
saved snapshot. Downstream code (`ensureModelCompatibility`, the
max-output-tokens cap, telemetry, prompt headers) consumes those fields,
so a tier whose live slot pointed to a different model would get gated
against the wrong capability set. Replace the patch with a typed
`TierOverride` produced by `resolveTierOverride`, which fetches the full
`ModelInfo` via `ctx.aiProviders.listModels` and translates it into the
`thinking` shape — same translation as the chat path's
`toMetadataModelInfo`. Falls back to a slot-only override (with stored
title) if the provider call throws, so a flaky provider doesn't block
the run.

#2 — Saving any edit on a Simple-Mode-enabled legacy automation (e.g.
just renaming it) used to silently write `tier: "smart"` because
`tierToPersist` fell back to the dropdown's display fallback. After
that, the run path would override the user's original snapshot model
with the org's live "smart" slot. Only auto-pin when `slotMatchedTier`
is truthy — i.e. the saved credential/model actually correspond to a
configured slot. Legacy automations with no slot match stay unpinned
on incidental saves; the user has to explicitly pick a tier via the
dropdown to opt in.

Tests: split build-stream-request tests into "tier override" (verifies
full thinking replacement) and add a new resolve-tier-override.test.ts
that exercises ModelInfo translation, the disabled / unset / no-tier
short-circuits, and the listModels-throws fallback.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* docs(automations): clarify tier snapshot fallback role

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(settings): persist Simple Mode toggle on first enable

The autosave gated on `formState.isDirty`, but RHF's dirty flag was
cleared before the 250ms debounce fired:
- `handleToggle` calls `form.reset(...)` to seed default tier slots,
  which rebases the dirty baseline (even with keepDirty: true, fields
  that weren't already dirty stay clean).
- `useForm({ values: simpleMode })` re-syncs whenever the React Query
  cache emits a new object reference, which `useSimpleMode`'s select
  does on every render.

By the time the timer fired, `isDirty` was false and `save` bailed,
so the mutation never ran and the row was never inserted. First-time
toggle-on on a fresh org silently no-op'd.

Drop the isDirty gate. Each `schedule()` call is the explicit save
intent — only user actions call it, and nothing inside `save`
re-schedules, so there's no feedback loop.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
AriOliv added a commit to AriOliv/studio that referenced this pull request May 20, 2026
- Follow-up decocms#1: mark fixed by c17706d / 14cf5d3 / d357d8a with
  the BUILTIN_ROLES root-cause note. Keep historical context intact.
- Follow-up decocms#8: add a status block summarising the post-Phase-3
  state of the `member` role.
- New "Operating the strict access model" section spelling out the
  owner / admin / member contract for whoever picks this back up.

phdro88 commented May 26, 2026

Copy link
Copy Markdown

I'm starting the analysis of connections. First, I'll list the organizations and connections.

vibegui added a commit that referenced this pull request May 27, 2026
…2,B6,C3,C5,C6,C7)

Track B (production hardening):
- B1 cleanup on vMCP delete: COLLECTION_VIRTUAL_MCP_DELETE now prunes
  the page-preview/* prefix in object storage when the deleted vMCP
  is the org's Page Editor agent. Fire-and-forget so a storage hiccup
  can't block the user's delete intent.
- B2 concurrent-write protection: introduces withStateLock(orgId, ...)
  — a per-org in-process promise chain — and wraps every state
  read-modify-write in setPagePreviewActive / setActiveDesignSystem /
  refreshPagePreview / setPageProgress / createDesignSystem /
  createPage / bumpRefreshVersion. Eliminates the within-pod
  last-writer-wins race on state.json. Multi-pod deployments still
  rely on object-storage put-per-key atomicity (which holds).
- B6 tool handler tests: 4 new tests for appendBlock / updateBlock /
  removeBlock covering section-name validation, duplicate rejection,
  post-Footer rejection, URL sanitization at append time, and the
  update/remove round-trip on the live block list.

Track C (simplifications):
- C3 import types in page-preview-tab.tsx: drop the locally-declared
  PageEntry / DesignSystemEntry / PreviewKind / PagePreviewStatus
  duplicates; import from service.ts so any new field lands here
  automatically.
- C5 parseJsExport helper: collapse parseTokensJsBrand +
  parsePageJsBlocks into a single regex-driven parseJsExport<T>.
- C6 deriveOnColorTokens: replace the 3 identical pickReadableText
  calls in normalizeBrandContrast with one inline `pick` helper.
- C7 theme catalogue: page-editor.ts INSTRUCTIONS no longer
  hand-syncs the 10-row markdown theme table. Now built at module
  load time from DEFAULT_THEMES. KNOWN_SECTION_NAMES exported for
  any future consumer.

Also lands B5 stream-replay dedup hardening: dispatchedBlockPatches
in page-preview-tab.tsx now resets when taskId changes, so
positional-fallback ids ("#0", "#1") from a prior chat can't collide
with the new chat's positions on cross-chat navigation.

Verified:
- bun test apps/mesh/src/page-preview/ → 35/35 pass
- bun test apps/mesh/src/tools/virtual/studio-pack.test.ts → 4/4 pass
- bun run --cwd=apps/mesh check → no new TS errors

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vibegui added a commit that referenced this pull request May 28, 2026
…2,B6,C3,C5,C6,C7)

Track B (production hardening):
- B1 cleanup on vMCP delete: COLLECTION_VIRTUAL_MCP_DELETE now prunes
  the page-preview/* prefix in object storage when the deleted vMCP
  is the org's Page Editor agent. Fire-and-forget so a storage hiccup
  can't block the user's delete intent.
- B2 concurrent-write protection: introduces withStateLock(orgId, ...)
  — a per-org in-process promise chain — and wraps every state
  read-modify-write in setPagePreviewActive / setActiveDesignSystem /
  refreshPagePreview / setPageProgress / createDesignSystem /
  createPage / bumpRefreshVersion. Eliminates the within-pod
  last-writer-wins race on state.json. Multi-pod deployments still
  rely on object-storage put-per-key atomicity (which holds).
- B6 tool handler tests: 4 new tests for appendBlock / updateBlock /
  removeBlock covering section-name validation, duplicate rejection,
  post-Footer rejection, URL sanitization at append time, and the
  update/remove round-trip on the live block list.

Track C (simplifications):
- C3 import types in page-preview-tab.tsx: drop the locally-declared
  PageEntry / DesignSystemEntry / PreviewKind / PagePreviewStatus
  duplicates; import from service.ts so any new field lands here
  automatically.
- C5 parseJsExport helper: collapse parseTokensJsBrand +
  parsePageJsBlocks into a single regex-driven parseJsExport<T>.
- C6 deriveOnColorTokens: replace the 3 identical pickReadableText
  calls in normalizeBrandContrast with one inline `pick` helper.
- C7 theme catalogue: page-editor.ts INSTRUCTIONS no longer
  hand-syncs the 10-row markdown theme table. Now built at module
  load time from DEFAULT_THEMES. KNOWN_SECTION_NAMES exported for
  any future consumer.

Also lands B5 stream-replay dedup hardening: dispatchedBlockPatches
in page-preview-tab.tsx now resets when taskId changes, so
positional-fallback ids ("#0", "#1") from a prior chat can't collide
with the new chat's positions on cross-chat navigation.

Verified:
- bun test apps/mesh/src/page-preview/ → 35/35 pass
- bun test apps/mesh/src/tools/virtual/studio-pack.test.ts → 4/4 pass
- bun run --cwd=apps/mesh check → no new TS errors

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vibegui added a commit that referenced this pull request May 28, 2026
…2,B6,C3,C5,C6,C7)

Track B (production hardening):
- B1 cleanup on vMCP delete: COLLECTION_VIRTUAL_MCP_DELETE now prunes
  the page-preview/* prefix in object storage when the deleted vMCP
  is the org's Page Editor agent. Fire-and-forget so a storage hiccup
  can't block the user's delete intent.
- B2 concurrent-write protection: introduces withStateLock(orgId, ...)
  — a per-org in-process promise chain — and wraps every state
  read-modify-write in setPagePreviewActive / setActiveDesignSystem /
  refreshPagePreview / setPageProgress / createDesignSystem /
  createPage / bumpRefreshVersion. Eliminates the within-pod
  last-writer-wins race on state.json. Multi-pod deployments still
  rely on object-storage put-per-key atomicity (which holds).
- B6 tool handler tests: 4 new tests for appendBlock / updateBlock /
  removeBlock covering section-name validation, duplicate rejection,
  post-Footer rejection, URL sanitization at append time, and the
  update/remove round-trip on the live block list.

Track C (simplifications):
- C3 import types in page-preview-tab.tsx: drop the locally-declared
  PageEntry / DesignSystemEntry / PreviewKind / PagePreviewStatus
  duplicates; import from service.ts so any new field lands here
  automatically.
- C5 parseJsExport helper: collapse parseTokensJsBrand +
  parsePageJsBlocks into a single regex-driven parseJsExport<T>.
- C6 deriveOnColorTokens: replace the 3 identical pickReadableText
  calls in normalizeBrandContrast with one inline `pick` helper.
- C7 theme catalogue: page-editor.ts INSTRUCTIONS no longer
  hand-syncs the 10-row markdown theme table. Now built at module
  load time from DEFAULT_THEMES. KNOWN_SECTION_NAMES exported for
  any future consumer.

Also lands B5 stream-replay dedup hardening: dispatchedBlockPatches
in page-preview-tab.tsx now resets when taskId changes, so
positional-fallback ids ("#0", "#1") from a prior chat can't collide
with the new chat's positions on cross-chat navigation.

Verified:
- bun test apps/mesh/src/page-preview/ → 35/35 pass
- bun test apps/mesh/src/tools/virtual/studio-pack.test.ts → 4/4 pass
- bun run --cwd=apps/mesh check → no new TS errors

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
vibegui added a commit that referenced this pull request May 28, 2026
…2,B6,C3,C5,C6,C7)

Track B (production hardening):
- B1 cleanup on vMCP delete: COLLECTION_VIRTUAL_MCP_DELETE now prunes
  the page-preview/* prefix in object storage when the deleted vMCP
  is the org's Page Editor agent. Fire-and-forget so a storage hiccup
  can't block the user's delete intent.
- B2 concurrent-write protection: introduces withStateLock(orgId, ...)
  — a per-org in-process promise chain — and wraps every state
  read-modify-write in setPagePreviewActive / setActiveDesignSystem /
  refreshPagePreview / setPageProgress / createDesignSystem /
  createPage / bumpRefreshVersion. Eliminates the within-pod
  last-writer-wins race on state.json. Multi-pod deployments still
  rely on object-storage put-per-key atomicity (which holds).
- B6 tool handler tests: 4 new tests for appendBlock / updateBlock /
  removeBlock covering section-name validation, duplicate rejection,
  post-Footer rejection, URL sanitization at append time, and the
  update/remove round-trip on the live block list.

Track C (simplifications):
- C3 import types in page-preview-tab.tsx: drop the locally-declared
  PageEntry / DesignSystemEntry / PreviewKind / PagePreviewStatus
  duplicates; import from service.ts so any new field lands here
  automatically.
- C5 parseJsExport helper: collapse parseTokensJsBrand +
  parsePageJsBlocks into a single regex-driven parseJsExport<T>.
- C6 deriveOnColorTokens: replace the 3 identical pickReadableText
  calls in normalizeBrandContrast with one inline `pick` helper.
- C7 theme catalogue: page-editor.ts INSTRUCTIONS no longer
  hand-syncs the 10-row markdown theme table. Now built at module
  load time from DEFAULT_THEMES. KNOWN_SECTION_NAMES exported for
  any future consumer.

Also lands B5 stream-replay dedup hardening: dispatchedBlockPatches
in page-preview-tab.tsx now resets when taskId changes, so
positional-fallback ids ("#0", "#1") from a prior chat can't collide
with the new chat's positions on cross-chat navigation.

Verified:
- bun test apps/mesh/src/page-preview/ → 35/35 pass
- bun test apps/mesh/src/tools/virtual/studio-pack.test.ts → 4/4 pass
- bun run --cwd=apps/mesh check → no new TS errors

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
tlgimenes added a commit that referenced this pull request Jun 8, 2026
…st-leg republish (TDD, all gates green)

Fixes #3698-follow: cluster-daemon proxy channel now tolerant of transient subscriber gaps.

PART #1 — Per-slot backoff (proxy-poller.ts)
- Root cause: shared errorStreak across proxy concurrency slots. One systemic error (e.g.
  Cloudflare 520 on the 28s long-poll) backed off BOTH slots → 1–30s zero-subscriber gap
  → dispatch publish to links.proxy.req.<userSub> dropped → proxy_no_first_frame 15s later.
- Fix: move errorStreak into each slot(). Each slot backs off only its own failures; one
  recovering slot re-polls immediately while another retries, keeping ≥1 live subscriber
  through intermittent errors.
- Test: new "per-slot backoff" test with concurrency:2 asserts seenStreaks=[0,0] not [0,1].

PART #2 — Request-leg tolerance (link-proxy-routes.ts, proxy-poller.ts)
- Root cause: fire-and-forget core-NATS publish with no buffer. A single blind publish
  is lost if it lands in a daemon poll/backoff gap; no retry, no durability.
- Fix: cluster-side bounded republish + daemon reqId dedup.
  (A) proxy-abort-registry.register() now returns AbortController|null; null if reqId
      already in-flight (duplicate delivery dedup). handleProxyRequest bails on null
      before try/finally, so duplicate copy doesn't unregister the original.
  (B) createProxyDispatch republishes RequestFrame every 1s (injectable republishIntervalMs,
      0=off) until first reply frame. Stopped by markFirstFrame/cleanup/first-frame-timeout
      (never outlives dispatch, bounded by 15s window). Daemon dedup makes double-execution
      impossible (emits first frame only after upstream responds).
- Tests: registry dedup test + "re-publishes...then stops" cluster test.

Verification: 36 affected-test pass, 110 link tests pass, fmt/lint/typecheck clean.

⚠️ Daemon caveat: proxy-abort-registry.ts marked "SHIPPED DAEMON — needs human review
before merge." Small change, well-tested, but shipped in `decocms` CLI.

Remaining: #3 tie proxy-readiness to claim (doc-vs-code defect), infra fix for CF 520,
plus this dedup safety pattern may apply elsewhere (runAbortRegistry in thread-gate-workflow).

Co-Authored-By: Claude Haiku 4.5 <[email protected]>
tlgimenes added a commit that referenced this pull request Jun 8, 2026
…st-leg republish (TDD, all gates green) (#3704)

Fixes #3698-follow: cluster-daemon proxy channel now tolerant of transient subscriber gaps.

PART #1 — Per-slot backoff (proxy-poller.ts)
- Root cause: shared errorStreak across proxy concurrency slots. One systemic error (e.g.
  Cloudflare 520 on the 28s long-poll) backed off BOTH slots → 1–30s zero-subscriber gap
  → dispatch publish to links.proxy.req.<userSub> dropped → proxy_no_first_frame 15s later.
- Fix: move errorStreak into each slot(). Each slot backs off only its own failures; one
  recovering slot re-polls immediately while another retries, keeping ≥1 live subscriber
  through intermittent errors.
- Test: new "per-slot backoff" test with concurrency:2 asserts seenStreaks=[0,0] not [0,1].

PART #2 — Request-leg tolerance (link-proxy-routes.ts, proxy-poller.ts)
- Root cause: fire-and-forget core-NATS publish with no buffer. A single blind publish
  is lost if it lands in a daemon poll/backoff gap; no retry, no durability.
- Fix: cluster-side bounded republish + daemon reqId dedup.
  (A) proxy-abort-registry.register() now returns AbortController|null; null if reqId
      already in-flight (duplicate delivery dedup). handleProxyRequest bails on null
      before try/finally, so duplicate copy doesn't unregister the original.
  (B) createProxyDispatch republishes RequestFrame every 1s (injectable republishIntervalMs,
      0=off) until first reply frame. Stopped by markFirstFrame/cleanup/first-frame-timeout
      (never outlives dispatch, bounded by 15s window). Daemon dedup makes double-execution
      impossible (emits first frame only after upstream responds).
- Tests: registry dedup test + "re-publishes...then stops" cluster test.

Verification: 36 affected-test pass, 110 link tests pass, fmt/lint/typecheck clean.

⚠️ Daemon caveat: proxy-abort-registry.ts marked "SHIPPED DAEMON — needs human review
before merge." Small change, well-tested, but shipped in `decocms` CLI.

Remaining: #3 tie proxy-readiness to claim (doc-vs-code defect), infra fix for CF 520,
plus this dedup safety pattern may apply elsewhere (runAbortRegistry in thread-gate-workflow).

Co-authored-by: Claude Haiku 4.5 <[email protected]>
pedrofrxncx added a commit that referenced this pull request Jun 16, 2026
…palive (#3957)

UX for the 'frozen then everything at once' streaming case:

#1 Waiting state: the empty pre-first-chunk window showed only a silent
'Thinking…'. Add ThinkingState — a live elapsed clock next to the typing
indicator and, after 20s, a 'taking longer than usual' hint + Cancel
(wired to the existing stop()/cancel run). Uses useClockTick (singleton
useSyncExternalStore interval) so the threshold flips without useEffect.

#4 SSE keepalive 15s -> 10s: the tightest proxy idle timeout in the path is
Istio's 15s; a 15s heartbeat lands ON that boundary, so a silent model gap
(slow TTFB / between-step pauses — provider-agnostic, worse with proxied/
liteLLM) can race-lose and drop the socket mid-run. The client reconnects
and the tail replays the whole in-flight run as one burst (the frozen-then-
burst symptom). 10s keeps a ~5s margin.

#2 (surface reasoning + tool steps) needs no code: reasoning already renders
via ThoughtSummary and tool calls via the per-tool part components as soon as
parts stream; the only blank window is pre-first-part, which #1 now covers.

Verified: tsc + oxlint clean on changed files; sse-keepalive tests pass.
tlgimenes added a commit that referenced this pull request Jul 27, 2026
macOS stamps `com.apple.provenance` on every file and directory a
non-App-Store process creates. NFS advertises no native xattrs, so the
kernel spills it into a 4096-byte `._<name>` AppleDouble sidecar for every
file AND every directory the agent writes.

The merged filter accepted those writes (201) and answered reads with 404.
rclone re-reads an object right after uploading it to confirm the write, so
that combination put it in an unbounded retry loop — measured against a
real mount:

  ERROR : adtest3/._h.txt: Failed to copy: object not found
  ERROR : vfs cache: failed to upload try #1, will retry in 2s
  ERROR : vfs cache: failed to upload try #2, will retry in 4s
  … try #4, will retry in 16s — never converging

The file stays pinned in rclone's VFS upload queue and the ERROR noise
buries real failures. `--exclude "._*"` does not help: it hides them from
listings but rclone uploads them anyway.

So the sidecars now round-trip through a bounded in-memory store — writes
recorded, reads served, deletes forgotten — while still never reaching
ORG_FS and still being omitted from directory listings. The test that
encoded the 404 behavior is inverted rather than appended to.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
pedrofrxncx added a commit that referenced this pull request Jul 29, 2026
Any sync fs call in the daemon blocks its single-threaded event loop for every other in-flight request, including the health probe Studio polls to decide whether the sandbox is alive — a missed probe marks the sandbox dead and triggers recovery (CONTRIBUTING.md rule #1). The write route (the daemon's most frequently hit fs handler, backing every file save from the editor) still used mkdirSync/writeFileSync.

Follows the same async cleanup already applied to daemon.json (#5336) and the org-fs config relay (#5367).
pedrofrxncx pushed a commit that referenced this pull request Jul 29, 2026
The shared store grew forever: one archive per (repo, lockfile), no reaper,
while L1 has had a TTL + per-repo cap since it shipped. `pruneRemoteGoldens`
applies the same rule to the remote store (untouched >7d, then newest 5 per
repo) after a successful publish, reusing L1's constants so the two tiers
can't drift apart.

Async throughout, unlike L1's `pruneGoldens` — the store is NFS, where a
readdir is a round trip per entry, and parking the daemon's event loop stalls
its health probe (CONTRIBUTING rule #1). `.tmp.<pid>` entries are skipped:
they are another node's publish in flight.

Prune runs only where publish does, so a read-only tenant mount never prunes
anything — that's now stated at the values.yaml knob, since it means a
filesystem lifecycle policy is the only reaper until the trusted writer lands.

Also written down where someone enabling this will read it: any sandbox can
read any repo's archive. The volume is mounted whole (warm-pool pods are bound
before they know their repo) and the key is sha256 of the clone URL, so read
isolation is guessability, not enforcement. Accepted for public-registry
dependencies — no first-party source, no secrets, nothing writable. Named the
condition that flips it: a private registry puts proprietary package source in
node_modules, which this store would expose fleet-wide.

Chart 0.9.44, above main's 0.9.43 (the publish workflow skips lower versions);
appVersion stays at main's 1.26.1 rather than regressing to the pre-rebase tag.
pedrofrxncx pushed a commit that referenced this pull request Jul 29, 2026
The shared store grew forever: one archive per (repo, lockfile), no reaper,
while L1 has had a TTL + per-repo cap since it shipped. `pruneRemoteGoldens`
applies the same rule to the remote store (untouched >7d, then newest 5 per
repo) after a successful publish, reusing L1's constants so the two tiers
can't drift apart.

Async throughout, unlike L1's `pruneGoldens` — the store is NFS, where a
readdir is a round trip per entry, and parking the daemon's event loop stalls
its health probe (CONTRIBUTING rule #1). `.tmp.<pid>` entries are skipped:
they are another node's publish in flight.

Prune runs only where publish does, so a read-only tenant mount never prunes
anything — that's now stated at the values.yaml knob, since it means a
filesystem lifecycle policy is the only reaper until the trusted writer lands.

Also written down where someone enabling this will read it: any sandbox can
read any repo's archive. The volume is mounted whole (warm-pool pods are bound
before they know their repo) and the key is sha256 of the clone URL, so read
isolation is guessability, not enforcement. Accepted for public-registry
dependencies — no first-party source, no secrets, nothing writable. Named the
condition that flips it: a private registry puts proprietary package source in
node_modules, which this store would expose fleet-wide.

Chart 0.9.44, above main's 0.9.43 (the publish workflow skips lower versions);
appVersion stays at main's 1.26.1 rather than regressing to the pre-rebase tag.
pedrofrxncx added a commit that referenced this pull request Jul 29, 2026
* feat(sandbox): cross-node golden dependency cache (L2 archive)

The golden node_modules cache is NODE-LOCAL: it only hits when the pod
lands on a node already warm for its repo. The sandbox pool churns ~170
nodes/day across three AZs and ~80% of ensures are fresh pods, so a large
share of boots land somewhere cold and pay a full install — and cross-zone
a node-local cache cannot help at all.

Add a second tier keyed identically to the first: a per-(repo, pm,
lockfile) tar.zst on a shared RWX volume, restorable on any node in any
zone. Restore order becomes L1 reflink (~1s) → L2 extract → install. An L2
hit also seeds this node's L1, so the next pod here gets the reflink.

Store a TARBALL, never the tree. EFS/NFS charges per-operation metadata
latency: fatal across ~100k small files, a non-issue for one large
sequential blob. The per-file cost is paid by the local extract.

Transport is an explicit `zstd -dc | tar -xf -` pipe rather than tar's own
compressor flags, which are not portable and fail differently per flavor:
the image ships GNU tar, but a macOS host runner has bsdtar, where `-I`
means --include (so `-I zstd` looks for a file named "zstd") and
--use-compress-program is rejected on read. Both verified before choosing.
Spawned and streamed throughout, no *Sync — a 2 GB tree through the
daemon's single-threaded loop would stall the health probe and get the
sandbox torn down.

Extraction stages into a temp dir and renames into place, so a tar
interrupted mid-write can never leave a partial node_modules that later
code reads as complete (the boot would skip install and fail somewhere
unrelated). Publish writes a temp file and renames, so concurrent
publishers on different nodes cannot produce a truncated archive.

Publish is gated on the same healthy-boot transition as L1, which matters
more here: a broken install published to a shared store would poison every
node in the fleet, not just this one.

Chart mounts the volume READ-ONLY into the sandbox container. That is the
load-bearing control, not a hint — sandboxes run untrusted code and bun
installs cached content as-is, so a writable shared store would widen the
existing node-local RCE surface to a fleet-wide one. Publishing from
tenant pods stays off; a trusted writer comes with the infra work.

Ships dark: no GOLDEN_CACHE_REMOTE means the daemon is L1-only, exactly
today's behavior. Deploying it additionally needs the EFS CSI driver,
which is not installed — that is infra, tracked separately.

* fix(sandbox): wire the L2 archive pipe fd-to-fd so restore stops truncating

Restore never worked on a real-sized tree. `runPiped` relayed the archive
through this process (`p.stdout.pipe(c.stdin)`), and once the consumer applies
backpressure — `tar -x` writing many small files is slower than `zstd -dc`
produces — the tail of the stream was dropped while BOTH children still exited
0. Verified in the sandbox image on a real daemon boot: restore of a
byte-verified-good 2.3 MB archive failed 2/2 with `tar: Unexpected EOF in
archive`; isolated, 5 of 12 runs failed at 2 MB and 12 of 12 pass wired
fd-to-fd. It never fails below ~1 MB, which is why the ~1 KB test fixture
passes.

The same loss hit publish once, and there it is worse: a valid zstd frame
containing a truncated tar (532 of 1069 members) published as a success. Since
publish no-ops when the key exists, that archive is permanent — every node in
the fleet keeps failing restore and paying a full install with nothing to
repair it. Publish now reads the archive back before the rename.

Also:
- Surface the failing side's stderr. "tar exit 2" alone is unactionable; it
  took a hand-run of the pipe to learn it meant a truncated archive rather
  than a permissions or disk problem.
- Render GOLDEN_CACHE_REMOTE whenever `remote.enabled` instead of nesting it
  under `golden`. The volume was already mounted at that scope, so with
  golden off the chart mounted an RWX PVC into every sandbox pod that the
  daemon never read.

Bun.spawn's direct fd wiring also delivers what the old comment claimed:
a multi-GB tree no longer passes through the daemon's single event loop
during a boot.

* test(sandbox): guard the L2 pipe against silent tail truncation

The fd-to-fd fix shipped without a test, and the existing fixtures cannot
catch what it fixed: the relayed pipe never dropped anything below ~1 MB
and every case here used ~1 KB. A revert to `p.stdout.pipe(c.stdin)` stayed
green on all four.

Round-trip a 1500-file / ~9 MB tree of incompressible content, so tar's
many small writes actually fall behind zstd and the transfer has to survive
backpressure. Assert the exact member count and the contents of the LAST
file — the observed failure delivered 532 of 1069 members with both
children exiting 0, so a partial extract looks fine unless you count.

Verified as a guard, not just an addition: reverted to the relayed pipe and
this test fails 3/3 (and only this test), passes with the fix.

* docs(sandbox-env): the L2 volume's root dir must be provisioned externally

Found by running the two-pod shape on a bare RWX volume: publish dies with
`EACCES: mkdir '/golden-cache/golden'`. A fresh volume is root-owned, and
this chart has no way to fix that — the tenant mount is read-only by
design and fsGroup does not apply to it. Every restore then misses
silently, forever, which reads as "the cache just never hits".

Say so where someone setting pvcName will read it, and name the EFS
spelling (an access point with RootDirectory CreationInfo for uid/gid
1000, not the filesystem root).

* feat(sandbox): report L2 hits in the deps-restore metric

L2 shipped blind. `sandbox.deps.restore` only knew `l1` and `miss`, so a
boot the shared archive rescued was indistinguishable from one the
node-local golden served — which makes the one question the tier exists to
answer ("was it worth the shared store?") unanswerable from the data.

Widen the source union with `l2` and emit it at the archive-restore site.
The counter split is then the hit rate per tier, and `duration_ms` on `l2`
against `miss` is the per-boot saving.

Guarded, because a mislabel is worse than no metric — it credits the
node-local cache with work it never did. The new orchestrator test drives a
real archive published from a separate root with L1 switched OFF, so a hit
can only have come from L2; changing the emitted label to `l1` fails it.

* fix(sandbox): prune the L2 archive store, and decide the cross-repo read

The shared store grew forever: one archive per (repo, lockfile), no reaper,
while L1 has had a TTL + per-repo cap since it shipped. `pruneRemoteGoldens`
applies the same rule to the remote store (untouched >7d, then newest 5 per
repo) after a successful publish, reusing L1's constants so the two tiers
can't drift apart.

Async throughout, unlike L1's `pruneGoldens` — the store is NFS, where a
readdir is a round trip per entry, and parking the daemon's event loop stalls
its health probe (CONTRIBUTING rule #1). `.tmp.<pid>` entries are skipped:
they are another node's publish in flight.

Prune runs only where publish does, so a read-only tenant mount never prunes
anything — that's now stated at the values.yaml knob, since it means a
filesystem lifecycle policy is the only reaper until the trusted writer lands.

Also written down where someone enabling this will read it: any sandbox can
read any repo's archive. The volume is mounted whole (warm-pool pods are bound
before they know their repo) and the key is sha256 of the clone URL, so read
isolation is guessability, not enforcement. Accepted for public-registry
dependencies — no first-party source, no secrets, nothing writable. Named the
condition that flips it: a private registry puts proprietary package source in
node_modules, which this store would expose fleet-wide.

Chart 0.9.44, above main's 0.9.43 (the publish workflow skips lower versions);
appVersion stays at main's 1.26.1 rather than regressing to the pre-rebase tag.

* fix(sandbox-env): drop the tiers/emptyDirSizeLimits values this PR never used

91 lines of values that no template reads. `defaultTier`, `tiers` and
`emptyDirSizeLimits` describe a multi-SandboxTemplate feature that does not
exist in this chart — every key is declared, documented, and then ignored at
render time, so the whole block is a lie about what the chart does.

It also has nothing to do with the L2 cache. It rode in on a values.yaml
conflict resolution during an earlier rebase; main never had it. Deleting
rather than implementing: a tiers feature is not this PR, and orphan config
that renders nothing is worse than absent config — it reads as configurable.

values.yaml vs main is now depsCache.remote only. Chart renders identically
off, on, and still fails on a missing pvcName.

* fix(sandbox): let the shell own the L2 pipe so publish stops dying on EPIPE

CI (Linux) failed the 9 MB round-trip: `EPIPE: broken pipe, write` thrown from
inside Bun's stream pump, asynchronously, where the try/catch around the spawn
can't see it. It took out the whole test file and left publish with no archive.

Passing the producer's `stdout` as the consumer's `stdin` reads as an fd
handoff, but Bun relays it through this process once the stream outgrows the
pipe buffer, and then the relay's write races the consumer. That is the same
handoff that previously truncated the stream's tail with both children exiting
0 — two failure modes, one cause. The 1 KB fixtures never reach the buffer's
edge, which is why only the big case caught either.

So hand the pipe to `bash -c` and let the kernel move the bytes: nothing
traverses this process, both failure modes go away, and a multi-GB tree still
stays off the daemon's event loop. `set -o pipefail` keeps the producer's exit
code visible — without it a failed `tar -c` feeding a happy `zstd` would look
like a successful publish. Verified both directions (producer-fails → exit 1,
both-ok → exit 0). Arguments are shell-quoted, since the mount root and install
root come from operator config and a path with a space would otherwise split.

Also fixes why the CI log was so hard to read: `soleArchive` destructured an
empty readdir and threw ERR_INVALID_ARG_TYPE, which reads as a broken helper
rather than "publish produced nothing", and the test passed no `log` so
publish's own diagnostic was discarded. Both now assert with the real reason.

---------

Co-authored-by: Pedro França <[email protected]>
pedrofrxncx added a commit that referenced this pull request Jul 31, 2026
The discard() helper called fs.unlinkSync() while being invoked from an async HTTP handler, blocking the daemon's single-threaded event loop. Convert to async unlink so file deletion no longer stalls the health probe Studio polls (CONTRIBUTING.md rule #1). Behavior-preserving: same error handling and file deletion order, just async.
pedrofrxncx added a commit that referenced this pull request Jul 31, 2026
golden-cache.ts used readFileSync/statSync/mkdirSync/readdirSync/rmSync/
renameSync/utimesSync throughout. tryRestoreGolden, publishGolden, and
pruneGoldens all run from fire-and-forget calls (entry.ts's
`void orchestrator.publishPendingGolden()`, itself invoked off the
`running` health transition) while the daemon's Bun.serve is already
answering requests, so every sync fs call there parks the single-threaded
event loop and can miss the daemon's own health probe (CONTRIBUTING.md
rule #1) — pruneGoldens is the worst offender, since it walks and stats
every golden dir on the node.

Converts every call to node:fs/promises equivalents, matching the async
style remote-golden.ts (L2) already uses. resolveRemote in remote-golden.ts
awaits the now-async lockfileHash it imports from golden-cache.ts.
Behavior-preserving: same logic, same fallbacks, same log lines.
pedrofrxncx added a commit that referenced this pull request Jul 31, 2026
…5481)

publish() blocked the event loop with a synchronous readFileSync while
validating each changed decofile block, on the same single-threaded Bun
loop that answers the daemon's /health probe (CONTRIBUTING rule #1).
Continues the same conversion already done for the daemon's other
routes (discard, glob, URL-transfer).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants